package com.gree.mall.manager.controller.workerorder;

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.annotation.ZfireList;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.workorder.*;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.workorder.SettleOrderLogic;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@RequiredArgsConstructor
@Slf4j
@RestController
@Api(value = "结算单API", tags = {"结算单API"})
@RequestMapping(value = "/settle/order", produces = "application/json; charset=utf-8")
public class SettleOrderController {

    private final SettleOrderLogic settleOrderLogic;
    private final RedisLockRegistry redisLockRegistry;
    private final CommonLogic commonLogic;

    @ZfireList
    @PostMapping("/list")
    @ApiOperation(value = "结算单-列表")
    public ResponseHelper<Page<SettleOrderVO>> list(
            @RequestBody ZfireParamBean zfireParamBean
    ) {
        IPage<SettleOrderVO> orderSmallTypeVO = settleOrderLogic.list(zfireParamBean);
        return ResponseHelper.success(orderSmallTypeVO, new TypeReference<SettleOrderVO>() {});
    }

    @PostMapping("/list/export")
    @ApiOperation(value = "结算单-导出")
    public void listExport(@RequestBody ZfireParamBean zfireParamBean, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //2.查询要导出的内容
        IPage<SettleOrderVO> page = settleOrderLogic.list(zfireParamBean);
        //3.导出
        FieldUtils.exportData(page.getRecords(), zfireParamBean.getExportFields(), request, response);
    }

    @ZfireList
    @PostMapping("/pool/list")
    @ApiOperation(value = "汇总结算单-列表")
    public ResponseHelper<Page<SettlePoolVO>> poolList(
            @RequestBody ZfireParamBean zfireParamBean
    ) {
        IPage<SettlePoolVO> orderSmallTypeVO = settleOrderLogic.poolList(zfireParamBean);
        return ResponseHelper.success(orderSmallTypeVO, new TypeReference<SettlePoolVO>() {});
    }

    @PostMapping("/pool/detail/list")
    @ApiOperation(value = "汇总结算单-明细")
    public ResponseHelper<List<SettlePoolWorkerVO>> poolDetailList(
            @ApiParam(value = "id", required = true) @RequestParam String id,
            @ApiParam(value = "师傅信息", required = true) @RequestParam String workerName,
            @ApiParam(value = "联系电话", required = true) @RequestParam String mobile,
            @ApiParam(value = "身份证", required = true) @RequestParam String idcard,
            @ApiParam(value = "工单单号", required = true) @RequestParam String orderBaseId,
            @ApiParam(value = "客户名称", required = true) @RequestParam String customerName,
            @ApiParam(value = "客户电话", required = true) @RequestParam String customerMobile,
            @ApiParam(value = "工单类型", required = true) @RequestParam String orderSmallType,
            @ApiParam(value = "结算单类型 INSTALL=安装 REPAIR=维修 OTHER=其它 EXAMINE=奖罚单", required = true) @RequestParam String settleOrderType
    ) {
        List<SettlePoolWorkerVO> orderSmallTypeVO = settleOrderLogic.poolDetailList(id, workerName, mobile, idcard,
                orderBaseId, customerName, customerMobile, orderSmallType, settleOrderType);
        return ResponseHelper.success(orderSmallTypeVO);
    }

    @GetMapping("export/pool/detail")
    @ApiOperation(value = "汇总结算单-明细导出")
    public void exportPoolDetail(
            @RequestParam String id,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        ExcelData excelData = settleOrderLogic.exportPoolDetail(id);
        ExcelUtils.exportExcel(request, response, "账单明细.xlsx", excelData);
    }

    @PostMapping("/pool")
    @ApiOperation(value = "结算单-月度汇总")
    public ResponseHelper pool(
            @ApiParam(value = "单号", required = true) @RequestBody SettleOrderBean bean
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":" + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                settleOrderLogic.pool(bean, adminUser);
            }
        } catch(Exception e) {
            log.error("【结算单汇总处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/batch/pool")
    @ApiOperation(value = "结算单-批量汇总")
    public ResponseHelper batchPool(
            @ApiParam(value = "单号", required = true) @RequestBody SettleOrderBean bean
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":" + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                settleOrderLogic.batchPool(bean, adminUser);
            }
        } catch(Exception e) {
            log.error("【结算单汇总处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/batch/confirm")
    @ApiOperation(value = "结算单-发放")
    public ResponseHelper batchConfirm(
            @ApiParam(value = "ids", required = true) @RequestBody List<String> ids
    ) throws Exception {
        settleOrderLogic.batchConfirm(ids);
        return ResponseHelper.success();
    }

    @PostMapping("/batch/cancel")
    @ApiOperation(value = "结算单-驳回")
    public ResponseHelper batchCancel(
            @ApiParam(value = "ids", required = true) @RequestBody List<String> ids
    ) throws Exception {
        settleOrderLogic.batchCancel(ids);
        return ResponseHelper.success();
    }

    @PostMapping("/batch/item/cancel")
    @ApiOperation(value = "结算单-明细驳回")
    public ResponseHelper batchItemCancel(
            @ApiParam(value = "ids", required = true) @RequestBody PoolSettleItemBean bean
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":pool:item");
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                settleOrderLogic.batchItemCancel(bean);
            }
        } catch(Exception e) {
            log.error("【账单明细驳回处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }

    @PostMapping("/reset/ywg")
    @ApiOperation(value = "重新生成已完工待结算处理")
    public ResponseHelper ywg(
            @ApiParam(value = "单号", required = true) @RequestBody List<String> ids
    ) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String lockKey = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            lockKey = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":" + lockKey);
        try {
            if (obtain.tryLock(5, TimeUnit.SECONDS)) {
                settleOrderLogic.ywg(ids);
            }
        } catch(Exception e) {
            log.error("【重新生成已完工待结算处理】失败", e);
            throw e;
        } finally {
            obtain.unlock();
        }

        return ResponseHelper.success();
    }
}
