package com.gree.mall.manager.logic.settle.repair;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.settle.repair.*;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.commonmapper.DailyMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.constant.DailyConstant;
import com.gree.mall.manager.constant.SysDictConstant;
import com.gree.mall.manager.enums.repair.settle.DictCodeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.DateUtils;
import com.gree.mall.manager.utils.RedisUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class DailyImportSummaryLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final SettleDailyImportSummaryItemService settleDailyImportSummaryItemService;
    private final SettleDailyReduceCostService settleDailyReduceCostService;
    private final DailyMapper dailyMapper;
    private final SettleWebsitWorkerDirectorService settleWebsitWorkerDirectorService;
    private final SettleDailyIssueSummaryRecordService settleDailyIssueSummaryRecordService;
    private final SysDictCompanyService sysDictCompanyService;
    private final SettleDailyWithholdService settleDailyWithholdService;
    private final SettleDailyResidualInsuranceService settleDailyResidualInsuranceService;
    private final SettleDailyRemaineBuckleService settleDailyRemaineBuckleService;
    private final SettleDailyIncrDecrCostService settleDailyIncrDecrCostService;
    private final RedisUtil redisUtil;
    private final DailyTransferLogic dailyTransferLogic;
    private final SettleDailyIssueSummaryMonthRecordService settleDailyIssueSummaryMonthRecordService;


    public IPage<DailyImportSummaryVO> page(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, DailyImportSummaryVO.class, adminUser);

        return commonMapper.repairSettleDailyImportSummaryList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    /**
     * 导入结算/工单扣回数据
     */
    @Transactional
    public String importOrderData(String type, String importBatchNo, List<Object> datas, HttpServletRequest request) throws Exception {
        StringBuffer errorData = new StringBuffer();
        AdminUserCom adminUser = commonLogic.getAdminUser();
        log.info("【导入结算】:{}", DateUtils.formatDate(new Date()));
        List<SettleDailyReduceCost> reduceList = new ArrayList<>();
        //生成导入批次号
        List<SettleDailyImportSummaryItem> summaryItemList = new ArrayList<>();
        String batchNo = commonLogic.generateNo("reduce".equals(type) ? "HK" : "JS", "repair_daily", 11);
        //传入批次号删除数据
        if (StringUtils.isNotEmpty(importBatchNo)) {
            if ("reduce".equals(type)) {
                Integer count = settleDailyReduceCostService.lambdaQuery()
                        .eq(SettleDailyReduceCost::getImportBatchNo, importBatchNo)
                        .eq(SettleDailyReduceCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                        .count();

                if (count > 0) {
                    throw new RemoteServiceException("存在已执行的数据");
                }
                settleDailyReduceCostService.lambdaUpdate().eq(SettleDailyReduceCost::getImportBatchNo, importBatchNo).remove();
            } else {
                Integer count = settleDailyImportSummaryItemService.lambdaQuery()
                        .eq(SettleDailyImportSummaryItem::getImportBatchNo, importBatchNo)
                        .eq(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_HAS)
                        .count();
                if (count > 0) {
                    throw new RemoteServiceException("存在已汇总的数据");
                }
                settleDailyImportSummaryItemService.lambdaUpdate().eq(SettleDailyImportSummaryItem::getImportBatchNo, importBatchNo)
                        .remove();
            }
        }

        for (int i = 0; i < datas.size(); i++) {
            List<String> row = (List<String>) datas.get(i);
            CommonUtils.initList(row, 100);
//            DailyWorkerNumberBean workerNumberBean = dailyMapper.queryWorkerNumber(row.get(33),row.get(34),row.get(44));
//            if(workerNumberBean == null){
//                throw new RemoteServiceException("行数" + row.get(0) + "姓名："+row.get(33) +"找不到对应的工号");
//            }
            SettleDailyReduceCost bean = new SettleDailyReduceCost();
//            bean.setWorkerNumber(workerNumberBean.getWorkerNumber());
//            bean.setBelongCompany(workerNumberBean.getBelongCompany());
//            bean.setBelongCompanyId(workerNumberBean.getBelongCompanyId());
            bean.setImportBatchNo(batchNo);
            bean.setDispatchOrderNo(row.get(1));
            bean.setSelfNo(row.get(2));
            bean.setOrderStatus(row.get(3));
            bean.setSummaryNumber(row.get(4));
            bean.setOldSummaryNumber(row.get(5));
            bean.setSummaryName(row.get(6));
            bean.setRepairType(row.get(7));
            bean.setInOutMachine(row.get(8));
            bean.setMachineCode(row.get(9));
            bean.setOutMachineType(row.get(10));
            bean.setOutMachineDescribe(row.get(11));
            bean.setInMachineCode(row.get(12));
            bean.setInMachineType(row.get(13));
            bean.setInMachineDescribe(row.get(14));
            bean.setUserName(row.get(15));
            bean.setAreaCode(row.get(16));
            bean.setMobile(row.get(17));
            bean.setTel(row.get(18));
            bean.setProvince(row.get(19));
            bean.setCity(row.get(20));
            bean.setCounty(row.get(21));
            bean.setUserAddr(row.get(22));
            bean.setGpsAddr(row.get(23));
            bean.setPostalCode(row.get(24));
            bean.setSaleDeptNo(row.get(25));
            bean.setSaleDeptName(row.get(26));
            bean.setInvoiceCode(row.get(27));

            if (StringUtils.isNotBlank(row.get(28))) {
                bean.setBuyDate(new SimpleDateFormat("yyyy年MM月dd日").parse(row.get(28)));
            }
            if (StringUtils.isNotBlank(row.get(29))) {
                bean.setInstallDate(new SimpleDateFormat("yyyy年MM月dd日").parse(row.get(29)));
            }

            if (StringUtils.isNotBlank(row.get(30))) {
                bean.setReportDate(new SimpleDateFormat("yyyy年MM月dd日").parse(row.get(30)));
            }
            if (StringUtils.isNotBlank(row.get(31))) {
                bean.setRepairDate(new SimpleDateFormat("yyyy年MM月dd日").parse(row.get(31)));
            }
            bean.setRepairWorkerId(row.get(32));
            bean.setRepairWorkerName(row.get(33));
            bean.setRepairWorkerMobile(row.get(34));
            if (StringUtils.isNotBlank(row.get(35))) {
                bean.setRepairFee(new BigDecimal(row.get(35)));
            }
            if (StringUtils.isNotBlank(row.get(36))) {
                bean.setTrafficFee(new BigDecimal(row.get(36)));
            }
            if (StringUtils.isNotBlank(row.get(37))) {
                bean.setAccommodationFee(new BigDecimal(row.get(37)));
            }
            if (StringUtils.isNotBlank(row.get(38))) {
                bean.setLiftingFee(new BigDecimal(row.get(38)));
            }
            if (StringUtils.isNotBlank(row.get(39))) {
                bean.setOtherFee(new BigDecimal(row.get(39)));
            }
            if (StringUtils.isNotBlank(row.get(40))) {
                bean.setTotalFee(new BigDecimal(row.get(40)));
            }
            bean.setSettlementBatchNo(row.get(41));
            bean.setInstallWebsitNo(row.get(42));
            bean.setInstallWebsitName(row.get(43));
            bean.setRepairUnit(row.get(44));
            bean.setOldRepairUnit(row.get(45));
            bean.setRepairName(row.get(46));
            bean.setFaultPhenomenon(row.get(47));
            bean.setFaultAnalysis(row.get(48));
            bean.setRepairDetail(row.get(49));
            bean.setRemark(row.get(50));
            bean.setImportBy(adminUser.getNickName());
            bean.setImportTime(new Date());
            bean.setCreateTime(new Date());
            bean.setWebsitName(row.get(46));
            bean.setWebsitNumber(row.get(44));
            bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
            if (StringUtils.isNotBlank(row.get(51))) {
                bean.setSettlementTime(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").parse(row.get(51)));
            }
            if (("reduce").equals(type)) {
                //设置执行状态未未执行
                bean.setDoStatus(DailyConstant.DO_STATUS_NOT);
                reduceList.add(bean);
            } else {
                SettleDailyImportSummaryItem item = new SettleDailyImportSummaryItem();
                BeanUtils.copyProperties(bean, item);
                item.setSummaryStatus(DailyConstant.SUMMARY_STATUS_NOT);
                summaryItemList.add(item);
                //查询在系统中已存在的
//                Integer count = dailyImportSummaryItemService.lambdaQuery()
//                            .eq(DailyImportSummaryItem::getDispatchOrderNo,item.getDispatchOrderNo())
//                            .eq(DailyImportSummaryItem::getSelfNo,item.getSelfNo())
//                            .in(DailyImportSummaryItem::getOrderStatus,DailyConstant.SUMMARY_STATUS_ARRAY).count();
//                if(count > 0){
//                    errorData.append("工单"+ item.getDispatchOrderNo());
//                }
            }

        }
        if (("reduce").equals(type)) {
            settleDailyReduceCostService.saveBatch(reduceList);
            dailyMapper.bindWorkerNumber2(adminUser.getAdminCompanyWechat().getCompanyWechatId(), batchNo);
            //判断是否有匹配失败的师傅编号的
            List<SettleDailyReduceCost> list = settleDailyReduceCostService.lambdaQuery()
                    .eq(SettleDailyReduceCost::getWorkerNumber, "")
                    .eq(SettleDailyReduceCost::getImportBatchNo, batchNo)
                    .last("limit 1")
                    .list();
            if (list.size() > 0)
                throw new RemoteServiceException("姓名：" + list.get(0).getRepairName() + ",派工序号:" + list.get(0).getDispatchOrderNo() + "找不到对应的师傅编号");
            //判断是否存在导入重复的工单号
        } else {
            settleDailyImportSummaryItemService.saveBatch(summaryItemList);
            dailyMapper.bindWorkerNumber(adminUser.getAdminCompanyWechat().getCompanyWechatId(), batchNo);
            //判断是否有匹配失败的师傅编号的
            List<SettleDailyImportSummaryItem> list = settleDailyImportSummaryItemService.lambdaQuery()
                    .eq(SettleDailyImportSummaryItem::getWorkerNumber, "")
                    .eq(SettleDailyImportSummaryItem::getImportBatchNo, batchNo)
                    .last("limit 1")
                    .list();
            if (list.size() > 0)
                throw new RemoteServiceException("姓名：" + list.get(0).getRepairName() + ",派工序号:" + list.get(0).getDispatchOrderNo() + "找不到对应的师傅编号");
            //判断是否存在导入重复的工单号
            List<String> errList = dailyMapper.queryDistinctOrderNo(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            if (!CollectionUtils.isEmpty(errList)) {
                errorData = errorData.append(StringUtils.join(errList, ","));
            }
        }

        if (errorData.length() > 0) {
            errorData.append("已存在,导入失败");
            throw new RemoteServiceException(errorData.toString());
        }
        return errorData.toString();
    }

    /**
     * 结算数据导入 -删除
     */
    public void repairDelete(String importBatchNo) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        Integer count = settleDailyImportSummaryItemService.lambdaQuery()
                .eq(SettleDailyImportSummaryItem::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyImportSummaryItem::getImportBatchNo, importBatchNo)
                .eq(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_HAS).count();
        if (count > 0) {
            throw new RemoteServiceException("已汇总,无法删除");
        }

        settleDailyImportSummaryItemService.lambdaUpdate()
                .eq(SettleDailyImportSummaryItem::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyImportSummaryItem::getImportBatchNo, importBatchNo)
                .in(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_CAN_DEL).remove();
    }

    @Transactional
    public void repairSummary(String importBatchNo, Boolean install) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        //不结算主管的身份证
        List<SettleWebsitWorkerDirector> list = settleWebsitWorkerDirectorService.lambdaQuery().list();
        List<String> notSettleIdcards = list.stream().map(SettleWebsitWorkerDirector::getIdcard).collect(Collectors.toList());
        //结算数据导入明细
        List<SettleDailyImportSummaryItem> updateList = settleDailyImportSummaryItemService.lambdaQuery()
                .eq(SettleDailyImportSummaryItem::getImportBatchNo, importBatchNo)
                .in(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_CAN_DO)
                .in(SettleDailyImportSummaryItem::getOrderStatus, DailyConstant.SUMMARY_STATUS_ARRAY)
                .list();

        if (updateList.size() <= 0) {
            throw new RemoteServiceException("该批次已汇总,请勿重复汇总。");
        }
        String opName = adminUser.getNickName();
        String summaryBatchNo = updateList.get(0).getSummaryBatchNo();
        if (StringUtils.isEmpty(summaryBatchNo)) {
            summaryBatchNo = commonLogic.generateNo("HZ", "dailyBatch", 13);
        }
        settleDailyIssueSummaryRecordService.lambdaUpdate().eq(SettleDailyIssueSummaryRecord::getSummaryBatchNo, summaryBatchNo).remove();
        //查询统计数据
        List<DailyTotalCostBean> costBeans = dailyMapper.queryDailyTotalCost(adminUser.getAdminCompanyWechat().getCompanyWechatId(), importBatchNo, DailyConstant.SUMMARY_STATUS_CAN_DO, DailyConstant.SUMMARY_STATUS_ARRAY);

        String nowMonth = DateUtil.format(new Date(), "yyyyMM");
        List<SettleDailyIssueSummaryRecord> issueList = new ArrayList<>();
        SysDictCompany dict = sysDictCompanyService.lambdaQuery()
                .eq(SysDictCompany::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SysDictCompany::getDictType, SysDictConstant.REPAIR_DAILY)
                .last("limit 1")
                .one();
        if (dict == null) {
            throw new RemoteServiceException("未配置暂扣比例。");
        }
        List<SettleDailyWithhold> withholds = settleDailyWithholdService.lambdaQuery().list();

        //1.标记为非新的历史待扣费用(防止驳回的时候误删)
//        dailyRemaineBuckleService.lambdaUpdate()
//                .set(DailyRemaineBuckle::getSummaryBatchNo,summaryBatchNo)
//                .set(DailyRemaineBuckle::getUpdateTime,new Date())
//                .set(DailyRemaineBuckle::getUpdateBy,opName)
//                .eq(DailyRemaineBuckle::getSummaryBatchNo,"").update();

        //1.应发金额 = 维修费用 + 增减费用 - 扣回费用
        //2.应发金额 = 应发金额 - 工伤残保
        //3.应发金额 = 应发金额 - 暂扣款
        //ps.如果不够扣，则有多少扣多少，然后留给下次扣。一个身份证只扣1次工伤残保
        for (DailyTotalCostBean cost : costBeans) {
            SettleDailyIssueSummaryRecord issue = new SettleDailyIssueSummaryRecord();
            String BatchNo = commonLogic.generateNo("SF", "dailySalaryNo", 16);
            //维修费
            BigDecimal totalFee = cost.getTotalFee();
            if (totalFee.doubleValue() < 0) {
                continue;
            }
            //不结算主管过滤直接成0
            if (notSettleIdcards.contains(cost.getIdCard()) && (install == null || !install)) {
                issue.setRemark("安维主管结算费用0,原可结算金额：" + totalFee);
                totalFee = BigDecimal.valueOf(0);
            }

            //获取身份证
            issue.setMobile(cost.getMobile());
            issue.setIdCard(cost.getIdCard());
            issue.setRepairCount(cost.getRepairCount());
            issue.setWebsitName(cost.getWebsitName());
            issue.setWebsitNumber(cost.getWebsitNumber());
            issue.setCompanyWechatId(cost.getCompanyWechatId());
            issue.setCompanyWechatName(cost.getCompanyWechatName());
            issue.setMonth(nowMonth);
            issue.setServiceName(cost.getRepairWorkerName());
            issue.setServiceNumber(cost.getWorkerNumber());
            issue.setSummaryName(cost.getSummaryName());
            issue.setSummaryNumber(cost.getSummaryNumber());
            issue.setSalaryNo(BatchNo);
            issue.setStatus(DailyConstant.SUMMARY_STATUS_HAS);
            issue.setRepairTotalAmount(totalFee);
            issue.setCreateTime(new Date());
            issue.setCreateBy(opName);
            issue.setSummaryBatchNo(summaryBatchNo);
            issue.setSummaryTime(new Date());
            issue.setSummaryBy(opName);
            issue.setIsMonthSummary(false);
            issue.setReduceCost(new BigDecimal(0));
            issue.setIncrDecrCost(new BigDecimal(0));
            issue.setShouldResidualInsuranceCost(BigDecimal.valueOf(0));
            issue.setShouldEmpInsuranceCost(BigDecimal.valueOf(0));
            issue.setEmpInsuranceCost(BigDecimal.valueOf(0));
            issue.setResidualInsuranceCost(BigDecimal.valueOf(0));
            issue.setShouldReduceCost(BigDecimal.valueOf(0));
            issue.setWithholdTotalCost(BigDecimal.valueOf(0));
            issue.setWithholdCost(BigDecimal.valueOf(0));
            issue.setIssueCost(totalFee);
            issue.setInstall(install);
            issue.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            issue.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());

            if (install == null || !install) {
                //暂扣金额
                if (issue.getIssueCost().doubleValue() >= 0) {
                    BigDecimal withholdCost = issue.getIssueCost()
                            .multiply(new BigDecimal(dict.getDictValue()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (withholdCost.doubleValue() > 0) {
                        issue.setWithholdCost(withholdCost);
                        issue.setWithholdTotalCost(withholdCost);

                        issue.setIssueCost(issue.getIssueCost().subtract(withholdCost));
                    }
                }
                //处理本月要扣的工伤残保金，扣不完则留到历史费用
                //2.扣工伤残保，并产生新的待扣记录
                issue = this.deductGscb(opName, nowMonth, summaryBatchNo, issue, cost, withholds, adminUser);
                //3.处理历史待扣
                issue = this.historyAmount(issue, summaryBatchNo, opName, adminUser);
            }
            issueList.add(issue);
        }
        //生成数据到日结发放表
        settleDailyIssueSummaryRecordService.saveOrUpdateBatch(issueList);

        for (SettleDailyIssueSummaryRecord issueSummaryRecord : issueList) {
            for (SettleDailyImportSummaryItem importSummaryItem : updateList) {
                importSummaryItem.setSummaryBy(opName);
                importSummaryItem.setSummaryTime(new Date());
                importSummaryItem.setSummaryStatus(DailyConstant.SUMMARY_STATUS_HAS);
                importSummaryItem.setSummaryBatchNo(summaryBatchNo);
                importSummaryItem.setMonth(nowMonth);
                importSummaryItem.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
                importSummaryItem.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
                if (issueSummaryRecord.getServiceNumber().equals(importSummaryItem.getWorkerNumber())
                        && issueSummaryRecord.getSummaryNumber().equals(importSummaryItem.getSummaryNumber())) {
                    importSummaryItem.setIssueSalaryId(issueSummaryRecord.getId());
                }
            }
        }
        settleDailyImportSummaryItemService.updateBatchById(updateList, 500);
    }

    /**
     * 扣本月的工伤残保
     */
    public SettleDailyIssueSummaryRecord deductGscb(String opName, String nowMonth, String summaryBatchNo, SettleDailyIssueSummaryRecord issue, DailyTotalCostBean cost, List<SettleDailyWithhold> withholds, AdminUserCom adminUser) {

        BigDecimal issueCost = issue.getIssueCost();
        //查询本月是否有扣除记录
        Integer count = settleDailyResidualInsuranceService.lambdaQuery()
                .eq(SettleDailyResidualInsurance::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyResidualInsurance::getSendMonth, nowMonth)
                .eq(SettleDailyResidualInsurance::getIdcard, cost.getIdCard())
//                .eq(DailyResidualInsurance::getMobile,cost.getMobile())
                .eq(SettleDailyResidualInsurance::getName, cost.getRepairWorkerName())
                .count();
        if (count == 0) {
            //残保金月份扣除记录表
            SettleDailyResidualInsurance insurance = new SettleDailyResidualInsurance();
            insurance.setServiceNumber(cost.getWorkerNumber());
            insurance.setMobile(cost.getMobile());
            insurance.setIdcard(cost.getIdCard());
            insurance.setName(cost.getRepairWorkerName());
            insurance.setSendMonth(nowMonth);
            insurance.setCreateTime(new Date());
            insurance.setCreateBy(opName);
            insurance.setSummaryBatchNo(summaryBatchNo);
            insurance.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            insurance.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
            insurance.insert();

            for (SettleDailyWithhold withhold : withholds) {
                BigDecimal withholdAmount = withhold.getAmount();
                //减掉本次要扣的钱之后的钱
                BigDecimal subAmount = issueCost.subtract(withholdAmount);
                //处理工伤
                if (DictCodeEnum.EMP_RESIDUAL_DAILY.getName().equals(withhold.getName())) {
                    issue.setShouldEmpInsuranceCost(withholdAmount);

                    if (subAmount.doubleValue() < 0) {
                        //本次扣的工伤(所有钱)
                        issue.setEmpInsuranceCost(issueCost);
                        //不够扣，应发金额为0
                        issueCost = BigDecimal.valueOf(0);
                        //记录下次要扣的钱
                        SettleDailyRemaineBuckle dailyRemaineBuckle = supplyRemaineBuckle(subAmount, DictCodeEnum.EMP_RESIDUAL_DAILY.toString(),
                                cost.getWorkerNumber(), Constant.DAILY_PREFIX + summaryBatchNo,
                                cost.getWebsitName(), cost.getWebsitNumber(), opName, cost.getIdCard(),
                                adminUser.getAdminCompanyWechat().getCompanyWechatId(), adminUser.getAdminCompanyWechat().getCompanyName());

                        log.info("【产生历史待扣费用11】:{}", JSONObject.toJSONString(dailyRemaineBuckle));

                        dailyRemaineBuckle.insert();
                    } else {
                        // 应发金额 = 应发金额 - 扣掉该扣的钱
                        issueCost = subAmount;
                        // 已扣完工伤
                        issue.setEmpInsuranceCost(withholdAmount);
                    }
                }
                //处理残保金
                if (DictCodeEnum.INSURANCE_DAILY.getName().equals(withhold.getName())) {
                    issue.setShouldResidualInsuranceCost(withhold.getAmount());
                    issue.setResidualInsuranceCost(new BigDecimal(0));

                    if (subAmount.doubleValue() < 0) {
                        //本次已扣残保金
                        issue.setResidualInsuranceCost(issueCost);
                        //不够扣，应发金额为0
                        issueCost = BigDecimal.valueOf(0);
                        //记录下次要扣的钱
                        SettleDailyRemaineBuckle dailyRemaineBuckle = this.supplyRemaineBuckle(subAmount, DictCodeEnum.INSURANCE_DAILY.toString(), cost.getWorkerNumber(),
                                Constant.DAILY_PREFIX + summaryBatchNo, cost.getWebsitName(), cost.getWebsitNumber(), opName, cost.getIdCard(),
                                adminUser.getAdminCompanyWechat().getCompanyWechatId(), adminUser.getAdminCompanyWechat().getCompanyName());

                        log.info("【产生历史待扣费用12】:{}", JSONObject.toJSONString(dailyRemaineBuckle));

                        dailyRemaineBuckle.insert();
                    } else {
                        // 应发金额 = 应发金额 - 扣掉该扣的钱
                        issueCost = subAmount;
                        // 已扣完残保金
                        issue.setResidualInsuranceCost(withholdAmount);
                    }
                }
            }
        }
        issue.setIssueCost(issueCost);
        return issue;
    }


    /**
     * 处理历史费用
     *
     * @param issue     汇总数据
     * @param adminUser
     */
    @Transactional
    public SettleDailyIssueSummaryRecord historyAmount(SettleDailyIssueSummaryRecord issue, String summaryBatchNo, String opName, AdminUserCom adminUser) {
        if (issue.getIssueCost().doubleValue() == 0) {
            return issue;
        }
        List<SettleDailyRemaineBuckle> buckles = settleDailyRemaineBuckleService.lambdaQuery()
                .eq(SettleDailyRemaineBuckle::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyRemaineBuckle::getIdcard, issue.getIdCard())
                .eq(SettleDailyRemaineBuckle::getIsBuckle, false)
                .list();
        if (CollectionUtils.isEmpty(buckles)) {
            return issue;
        }

        //将所有未处理的历史数据都标记为本次已处理，后续逻辑将会产生新的历史待扣记录
        List<String> buckleIds = buckles.stream().map(SettleDailyRemaineBuckle::getId).collect(Collectors.toList());
        settleDailyRemaineBuckleService.lambdaUpdate()
                .set(SettleDailyRemaineBuckle::getSummaryBatchNo, summaryBatchNo)
                .set(SettleDailyRemaineBuckle::getIsBuckle, true)
                .set(SettleDailyRemaineBuckle::getUpdateTime, new Date())
                .set(SettleDailyRemaineBuckle::getUpdateBy, opName)
                .in(SettleDailyRemaineBuckle::getId, buckleIds).update();

        String summaryBatchNoTmp = Constant.DAILY_PREFIX + summaryBatchNo;

        //增减费用
        for (SettleDailyRemaineBuckle remaine : buckles) {
            //历史费用
            BigDecimal amount = remaine.getBuckleAmount();
            if (DictCodeEnum.INCR_DECR_DAILY.toString().equals(remaine.getCostType())) {

                BigDecimal sum = issue.getIssueCost().add(amount);
                if (sum.doubleValue() > 0) {
                    //记录增减费用
                    issue.setIncrDecrCost(issue.getIncrDecrCost().add(amount));
                    //还剩多少钱
                    issue.setIssueCost(sum);
                } else {
                    issue.setIncrDecrCost(issue.getIncrDecrCost().add(issue.getIssueCost()));
                    issue.setIssueCost(BigDecimal.valueOf(0));
                    //产生历史费用
                    //记录下次要扣的钱(这里不需要生成临时的批次号，驳回的时候也依据这个临时的批次号删除)
                    SettleDailyRemaineBuckle dailyRemaineBuckle = this.supplyRemaineBuckle(sum, remaine.getCostType(), remaine.getWorkerNumber(),
                            summaryBatchNoTmp, remaine.getWebsitName(), remaine.getWebsitNumber(), opName, remaine.getIdcard(),
                            adminUser.getAdminCompanyWechat().getCompanyWechatId(), adminUser.getAdminCompanyWechat().getCompanyName());
                    dailyRemaineBuckle.insert();
                }
            }
        }

        if (issue.getIssueCost().doubleValue() == 0) {
            return issue;
        }

        //处理扣回费用
        for (SettleDailyRemaineBuckle remaine : buckles) {
            //历史费用
            BigDecimal amount = remaine.getBuckleAmount();
            if (DictCodeEnum.REDUCE_DAILY.toString().equals(remaine.getCostType())) {
                if (amount.doubleValue() > 0) {
                    amount = BigDecimal.valueOf(0).subtract(amount);
                }
                BigDecimal sum = issue.getIssueCost().add(amount);
                if (sum.doubleValue() > 0) {
                    //应扣回费用
                    issue.setShouldReduceCost(issue.getShouldReduceCost().add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));
                    //实际已扣回费用
                    issue.setReduceCost(issue.getReduceCost().add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));

                    issue.setIssueCost(sum);
                } else {
                    issue.setReduceCost(issue.getReduceCost().add(issue.getIssueCost()));
                    issue.setIssueCost(BigDecimal.valueOf(0));
                    //产生历史费用
                    //记录下次要扣的钱(这里不需要生成临时的批次号，驳回的时候也依据这个临时的批次号删除)
                    SettleDailyRemaineBuckle dailyRemaineBuckle = this.supplyRemaineBuckle(sum, remaine.getCostType(), remaine.getWorkerNumber(),
                            summaryBatchNoTmp, remaine.getWebsitName(), remaine.getWebsitNumber(), opName, remaine.getIdcard(),
                            adminUser.getAdminCompanyWechat().getCompanyWechatId(), adminUser.getAdminCompanyWechat().getCompanyName());
                    dailyRemaineBuckle.insert();
                }
            }
        }

        if (issue.getIssueCost().doubleValue() == 0) {
            return issue;
        }

        //处理历史的工伤残保金
        for (SettleDailyRemaineBuckle remaine : buckles) {
            //历史费用
            BigDecimal amount = remaine.getBuckleAmount();

            BigDecimal sum = issue.getIssueCost().add(amount);
            if (DictCodeEnum.INSURANCE_DAILY.toString().equals(remaine.getCostType())
                    || DictCodeEnum.EMP_RESIDUAL_DAILY.toString().equals(remaine.getCostType())) {

                if (sum.doubleValue() > 0) {
                    if (DictCodeEnum.INSURANCE_DAILY.toString().equals(remaine.getCostType())) {
                        //残保金应扣
                        issue.setShouldResidualInsuranceCost(issue.getShouldResidualInsuranceCost()
                                .add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));
                        //残保金已扣
                        issue.setResidualInsuranceCost(issue.getResidualInsuranceCost()
                                .add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));

                    } else {
                        //工伤保险应扣
                        issue.setShouldEmpInsuranceCost(issue.getShouldEmpInsuranceCost()
                                .add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));
                        //工伤保险已扣
                        issue.setEmpInsuranceCost(issue.getEmpInsuranceCost()
                                .add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));
                    }
                    issue.setIssueCost(sum);
                } else {
                    //不够扣
                    if (DictCodeEnum.INSURANCE_DAILY.toString().equals(remaine.getCostType())) {
                        //残保金应扣
                        issue.setShouldResidualInsuranceCost(issue.getShouldResidualInsuranceCost()
                                .add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));
                        //残保金已扣
                        issue.setResidualInsuranceCost(issue.getResidualInsuranceCost()
                                .add(issue.getIssueCost()));
                    } else {
                        //工伤保险应扣
                        issue.setShouldEmpInsuranceCost(issue.getShouldEmpInsuranceCost()
                                .add(amount.doubleValue() < 0 ? BigDecimal.valueOf(0).subtract(amount) : amount));
                        //工伤保险已扣
                        issue.setEmpInsuranceCost(issue.getEmpInsuranceCost().add(issue.getIssueCost()));
                    }
                    issue.setIssueCost(BigDecimal.valueOf(0));
                    //产生历史费用
                    //记录下次要扣的钱(这里不需要生成临时的批次号，驳回的时候也依据这个临时的批次号删除)
                    SettleDailyRemaineBuckle dailyRemaineBuckle = this.supplyRemaineBuckle(sum, remaine.getCostType(), remaine.getWorkerNumber(),
                            summaryBatchNoTmp, remaine.getWebsitName(), remaine.getWebsitNumber(), opName, remaine.getIdcard(),
                            adminUser.getAdminCompanyWechat().getCompanyWechatId(), adminUser.getAdminCompanyWechat().getCompanyName());

                    log.info("【产生历史待扣费用2】:{}", JSONObject.toJSONString(dailyRemaineBuckle));

                    dailyRemaineBuckle.insert();
                }

                remaine.setSummaryBatchNo(summaryBatchNo);
                remaine.setIsBuckle(true);
                remaine.setUpdateTime(new Date());
                remaine.updateById();
            }
        }

        return issue;
    }

    public SettleDailyRemaineBuckle supplyRemaineBuckle(BigDecimal buckle, String type, String workerNumber,
                                                        String summaryBatchNo, String websiteName, String websiteNumber,
                                                        String opName, String idcard, String companyId, String companyName) {
        SettleDailyRemaineBuckle bean = new SettleDailyRemaineBuckle();
        bean.setCostType(type);
        bean.setBuckleAmount(buckle);
        bean.setIsBuckle(false);
        bean.setWorkerNumber(workerNumber);
        bean.setSummaryBatchNo(summaryBatchNo);
        bean.setCreateBy(opName);
        bean.setCreateTime(new Date());
        bean.setWebsitName(websiteName);
        bean.setIdcard(idcard);
        bean.setWebsitNumber(websiteNumber);
        bean.setCompanyWechatId(companyId);
        bean.setCompanyWechatName(companyName);
        //bean.insert();
        return bean;
    }

    public IPage<DailyImportSummaryItemVO> repairDetailList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, DailyImportSummaryItemVO.class, adminUser);

        return commonMapper.repairDetailList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    /**
     * 删除结算导入明细
     *
     * @param ids
     */
    @Transactional
    public void repairItemDelete(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        Integer count = settleDailyImportSummaryItemService.lambdaQuery()
                .eq(SettleDailyImportSummaryItem::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(SettleDailyImportSummaryItem::getId, ids)
                .eq(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_HAS)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("存在已汇总的数据,无法删除");
        }

        settleDailyImportSummaryItemService.lambdaUpdate()
                .eq(SettleDailyImportSummaryItem::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(SettleDailyImportSummaryItem::getId, ids)
                .in(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_CAN_DEL)
                .remove();
    }

    public void batchWaitSummary(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        settleDailyImportSummaryItemService.lambdaUpdate()
                .set(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_WAIT)
                .in(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_CAN_DO)
                .in(SettleDailyImportSummaryItem::getId, ids)
                .update();
    }

    public void batchSummary(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        settleDailyImportSummaryItemService.lambdaUpdate()
                .set(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_NOT)
                .eq(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_WAIT)
                .in(SettleDailyImportSummaryItem::getId, ids)
                .update();
    }

    public IPage<DailyIncrDecrCostCountVO> reduceCountPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, DailyIncrDecrCostCountVO.class, adminUser);

        return commonMapper.reduceCountList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    @Transactional
    public void reduceCountDel(String importBatchNo) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        Integer count = settleDailyIncrDecrCostService.lambdaQuery()
                .eq(SettleDailyIncrDecrCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyIncrDecrCost::getImportBatchNo, importBatchNo)
                .eq(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("该批次已执行,无法删除。");
        }
        settleDailyIncrDecrCostService.lambdaUpdate()
                .eq(SettleDailyIncrDecrCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyIncrDecrCost::getImportBatchNo, importBatchNo)
                .eq(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_NOT)
                .remove();
    }

    /**
     * 批量执行 -增减费用数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void reduceCountDo(String importBatchNo) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        String opName = adminUser.getNickName();
        String doBatchNo = commonLogic.generateNo("JZ", "reduceBatchNo", 13);
        String nowMonth = DateUtil.format(new Date(), "yyyyMM");
        List<DailyIncrDecrCostCountBean> beans = dailyMapper.queryIncrDecrByBatch(adminUser.getAdminCompanyWechat().getCompanyWechatId(), importBatchNo, DailyConstant.DO_STATUS_NOT);
        if (beans.size() == 0) {
            throw new RemoteServiceException("没有可扣减的数据");
        }
        List<SettleDailyIssueSummaryRecord> records = new ArrayList<>();
        List<String> serviceNumberList = new ArrayList<>();
        List<String> websiteNumberList = new ArrayList<>();
        for (DailyIncrDecrCostCountBean bean : beans) {
            SettleDailyIssueSummaryRecord issueRecord = settleDailyIssueSummaryRecordService
                    .getOne(Wrappers.<SettleDailyIssueSummaryRecord>lambdaQuery()
                            .eq(SettleDailyIssueSummaryRecord::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                            .eq(SettleDailyIssueSummaryRecord::getStatus, DailyConstant.ISSUE_STATUS_NOT)
                            .eq(SettleDailyIssueSummaryRecord::getServiceNumber, bean.getServiceNumber())
                            .eq(SettleDailyIssueSummaryRecord::getWebsitNumber, bean.getWebsitNumber())
                            .orderByDesc(SettleDailyIssueSummaryRecord::getIssueCost)
                            .last("limit 1"));
            if (issueRecord != null) {
                BigDecimal incrDecrCost = new BigDecimal(0);
                if (issueRecord.getIncrDecrCost() != null) {
                    incrDecrCost = incrDecrCost.add(issueRecord.getIncrDecrCost());
                }
                incrDecrCost = incrDecrCost.add(bean.getTotalAmount());
                BigDecimal issueCost = issueRecord.getIssueCost().add(bean.getTotalAmount());
                issueRecord.setIncrDecrCost(incrDecrCost);
                issueRecord.setIssueCost(issueCost);
                issueRecord.setUpdateBy(opName);
                issueRecord.setUpdateTime(new Date());
                if (issueCost.doubleValue() < 0) {
                    //设置为0
                    issueCost = BigDecimal.valueOf(0);
                    issueRecord.setIssueCost(issueCost);
                    BigDecimal extra = BigDecimal.valueOf(0).subtract(issueCost);
                    saveRemaineBuckle(extra, DictCodeEnum.INCR_DECR_DAILY.toString(), bean.getServiceNumber(),
                            Constant.DAILY_PREFIX + issueRecord.getSummaryNumber(), bean.getWebsitName(),
                            bean.getWebsitNumber(), issueRecord.getIdCard(), opName);
                }
                records.add(issueRecord);
                serviceNumberList.add(bean.getServiceNumber());
                websiteNumberList.add(bean.getWebsitNumber());
            }
        }
        if (records.size() == 0) {
            throw new RemoteServiceException("暂无可扣回费用");
        }
        settleDailyIssueSummaryRecordService.updateBatchById(records);
        //修改增减费用执行记录
        settleDailyIncrDecrCostService.lambdaUpdate()
                .set(SettleDailyIncrDecrCost::getDoTime, new Date())
                .set(SettleDailyIncrDecrCost::getDoBy, opName)
                .set(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                .set(SettleDailyIncrDecrCost::getUpdateBy, opName)
                .set(SettleDailyIncrDecrCost::getUpdateTime, new Date())
                .set(SettleDailyIncrDecrCost::getDoBatchNo, doBatchNo)
                .set(SettleDailyIncrDecrCost::getReduceMonth, nowMonth)
                .eq(SettleDailyIncrDecrCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyIncrDecrCost::getImportBatchNo, importBatchNo)
                .eq(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_NOT)
                .in(SettleDailyIncrDecrCost::getWebsitNumber, websiteNumberList)
                .in(SettleDailyIncrDecrCost::getServiceNumber, serviceNumberList)
                .update();
    }

    public void saveRemaineBuckle(BigDecimal buckle, String type, String workerNumber, String summaryBatchNo,
                                  String websiteName, String websiteNumber, String idCard, String opName) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        SettleDailyRemaineBuckle bean = new SettleDailyRemaineBuckle();
        bean.setCostType(type);
        bean.setBuckleAmount(buckle);
        bean.setIsBuckle(false);
        bean.setWorkerNumber(workerNumber);
        bean.setSummaryBatchNo(summaryBatchNo);
        bean.setCreateBy(opName);
        bean.setCreateTime(new Date());
        bean.setWebsitName(websiteName);
        bean.setWebsitNumber(websiteNumber);
        bean.setIdcard(idCard);
        bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
        bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        bean.insert();
    }

    public void reduceBatchDo(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        Integer count = settleDailyIncrDecrCostService.lambdaQuery()
                .eq(SettleDailyIncrDecrCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleDailyIncrDecrCost::getId, ids)
                .eq(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("存在已执行的数据,请重新选择.");
        }

        String opName = adminUser.getNickName();



        settleDailyIncrDecrCostService.lambdaUpdate()
                .set(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                .set(SettleDailyIncrDecrCost::getDoTime, new Date())
                .set(SettleDailyIncrDecrCost::getDoBy, opName)
                .eq(SettleDailyIncrDecrCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleDailyIncrDecrCost::getId, ids)
                .eq(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_NOT).update();
    }

    @Transactional
    public void reduceBatchDel(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        Integer count = settleDailyIncrDecrCostService.lambdaQuery()
                .eq(SettleDailyIncrDecrCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleDailyIncrDecrCost::getId, ids)
                .eq(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("存在已执行的数据,请重新选择.");
        }
        settleDailyIncrDecrCostService.lambdaUpdate()
                .eq(SettleDailyIncrDecrCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleDailyIncrDecrCost::getId, ids)
                .eq(SettleDailyIncrDecrCost::getDoStatus, DailyConstant.DO_STATUS_NOT).remove();
    }

    @Transactional
    public void reduceUpdate(SettleDailyIncrDecrCost cost) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        SettleDailyIncrDecrCost queryCost = settleDailyIncrDecrCostService.getById(cost.getId());
        if (queryCost == null) {
            throw new RemoteServiceException("当前数据不存在.");
        }
        if (queryCost.getDoStatus() != null && queryCost.getDoStatus() == 1) {
            throw new RemoteServiceException("已经执行无法编编辑.");
        }
        queryCost.setCostAmount(cost.getCostAmount());
        queryCost.updateById();
    }

    /**
     * 导入增减费用数据
     *
     * @param importBatchNo
     * @param datas
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    public void importIncrDecrCost(String importBatchNo, List<Object> datas, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        String opName = adminUser.getNickName();
        log.info("【导入增减费用】:{}", DateUtils.formatDate(new Date()));
        List<SettleDailyIncrDecrCost> incrDecrCostList = new ArrayList<>();
        //传入批次号删除数据
        if (importBatchNo != null) {
            settleDailyIncrDecrCostService.lambdaUpdate()
                    .eq(SettleDailyIncrDecrCost::getImportBatchNo, importBatchNo)
                    .remove();
        }

        String batchNo = commonLogic.generateNo("JM", "IncrDecr", 11);
        for (int i = 0; i < datas.size(); i++) {
            List<String> row = (List<String>) datas.get(i);
            SettleDailyIncrDecrCost bean = new SettleDailyIncrDecrCost();
            bean.setImportBatchNo(batchNo);
            bean.setServiceName(row.get(1));
            bean.setServiceNumber(row.get(2));
            bean.setWebsitNumber(row.get(3));
            bean.setWebsitName(row.get(4));
            bean.setSummaryNumber(row.get(5));
            bean.setSummaryName(row.get(6));
            bean.setIdCard(row.get(7));
            bean.setMobile(row.get(8));
            bean.setCostType(row.get(9));
            if (null != row.get(10)) {
                bean.setCostAmount(new BigDecimal(row.get(10)));
            }
            bean.setRemark(row.get(11));
            bean.setReduceMonth(row.get(12));
            bean.setDoStatus(DailyConstant.DO_STATUS_NOT);
            bean.setImportBy(opName);
            bean.setImportTime(new Date());
            bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
            incrDecrCostList.add(bean);
        }
        settleDailyIncrDecrCostService.saveBatch(incrDecrCostList);
    }

    public IPage<DailyIncrDecrCostVO> incrDecrCostList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, DailyIncrDecrCostVO.class, adminUser);

        return commonMapper.repairSettleDailyincrDecrCostList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public IPage<DailyReduceCostGatherVO> reduceTotalPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, DailyReduceCostGatherVO.class, adminUser);

        return commonMapper.reduceTotalList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public IPage<DailyReduceCostVO> reducePage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, DailyReduceCostVO.class, adminUser);

        return commonMapper.reduceList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    @Transactional
    public void reduceListDelete(String importBatchNo) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        Integer count = settleDailyReduceCostService.lambdaQuery()
                .eq(SettleDailyReduceCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyReduceCost::getImportBatchNo, importBatchNo)
                .eq(SettleDailyReduceCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                .count();

        if (count > 0) {
            throw new RemoteServiceException("存在已执行的数据，无法删除。");
        }
        settleDailyReduceCostService.lambdaUpdate()
                .eq(SettleDailyReduceCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyReduceCost::getImportBatchNo, importBatchNo)
                .eq(SettleDailyReduceCost::getDoStatus, DailyConstant.DO_STATUS_NOT)
                .remove();
    }

    @Transactional
    public void reduceItemDelete(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        Integer count = settleDailyReduceCostService.lambdaQuery()
                .eq(SettleDailyReduceCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleDailyReduceCost::getId, ids)
                .eq(SettleDailyReduceCost::getDoStatus, DailyConstant.DO_STATUS_HAS)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("存在已执行的数据，无法删除。");
        }
        settleDailyReduceCostService.lambdaUpdate()
                .eq(SettleDailyReduceCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleDailyReduceCost::getId, ids)
                .eq(SettleDailyReduceCost::getDoStatus, DailyConstant.DO_STATUS_NOT)
                .remove();
    }


    @Transactional
    public void reduceListDo(String importBatchNo) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }

        String opName = adminUser.getNickName();

        List<SettleDailyReduceCost> reduceList = settleDailyReduceCostService.lambdaQuery()
                .eq(SettleDailyReduceCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyReduceCost::getImportBatchNo, importBatchNo)
                .eq(SettleDailyReduceCost::getDoStatus, DailyConstant.DO_STATUS_NOT)
                .list();

        if (reduceList.size() == 0) {
            throw new RemoteServiceException("暂无可扣回的数据");
        }
        summaryReduce(reduceList, opName, importBatchNo, null, adminUser);
    }

    @Transactional
    public void summaryReduce(List<SettleDailyReduceCost> reduceList, String opName, String importBatchNo, List<String> ids, AdminUserCom adminUser) {
        String doBatchNo = commonLogic.generateNo("ZX", "dailyDoBatch", 13);
        List<SettleDailyIssueSummaryRecord> records = new ArrayList<>();

        List<SettleDailyReduceCost> reduceUpdateList = new ArrayList<>();

        for (SettleDailyReduceCost bean : reduceList) {
            SettleDailyIssueSummaryRecord issueRecord = settleDailyIssueSummaryRecordService.getOne(
                    Wrappers.<SettleDailyIssueSummaryRecord>lambdaQuery()
                            .eq(SettleDailyIssueSummaryRecord::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                            .eq(SettleDailyIssueSummaryRecord::getStatus, DailyConstant.ISSUE_STATUS_NOT)
                            .eq(SettleDailyIssueSummaryRecord::getServiceNumber, bean.getWorkerNumber())
                            .eq(SettleDailyIssueSummaryRecord::getWebsitNumber, bean.getWebsitNumber())
                            .orderByDesc(SettleDailyIssueSummaryRecord::getIssueCost)
                            .last("limit 1"));
            if (Objects.nonNull(issueRecord)) {
                BigDecimal reduceCost = new BigDecimal(0);
                if (Objects.nonNull(issueRecord.getShouldReduceCost())) {
                    reduceCost = reduceCost.add(issueRecord.getShouldReduceCost());
                }
                reduceCost = reduceCost.add(bean.getTotalFee());
                BigDecimal subAmount = issueRecord.getIssueCost().subtract(bean.getTotalFee());
                issueRecord.setShouldReduceCost(reduceCost);
                issueRecord.setReduceCost(new BigDecimal(0));
                issueRecord.setUpdateBy(opName);
                issueRecord.setUpdateTime(new Date());
                bean.setDoBatchNo(doBatchNo);
                bean.setReduceDate(new Date());
                bean.setDoTime(new Date());
                bean.setDoBy(opName);
                bean.setIssueSalaryId(issueRecord.getId());
                bean.setDoStatus(DailyConstant.DO_STATUS_HAS);
                bean.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
                bean.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
                reduceUpdateList.add(bean);

                if (subAmount.doubleValue() < 0) {
                    //不够扣的处理
                    saveRemaineBuckle(subAmount, DictCodeEnum.REDUCE_DAILY.toString(), bean.getWorkerNumber(),
                            bean.getSummaryNumber(), bean.getWebsitName(), bean.getWebsitNumber(),
                            issueRecord.getIdCard(), opName);
                    //设置为0
                    issueRecord.setReduceCost(issueRecord.getIssueCost());
                    issueRecord.setIssueCost(BigDecimal.valueOf(0));
                } else {
                    //够扣的处理
                    issueRecord.setReduceCost(reduceCost);
                    issueRecord.setIssueCost(subAmount);
                }
                records.add(issueRecord);
            }
        }
        if (CollectionUtil.isEmpty(records)) {
            throw new RemoteServiceException("暂无可扣回的数据");
        }
        settleDailyIssueSummaryRecordService.updateBatchById(records);
        settleDailyReduceCostService.updateBatchById(reduceUpdateList);

    }

    @Transactional
    public void reduceItemDo(List<String> ids) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        String opName = adminUser.getNickName();
        List<SettleDailyReduceCost> reduceList = settleDailyReduceCostService.lambdaQuery()
                .eq(SettleDailyReduceCost::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleDailyReduceCost::getId, ids)
                .eq(SettleDailyReduceCost::getDoStatus, DailyConstant.DO_STATUS_NOT)
                .list();

        if (CollectionUtil.isEmpty(reduceList)) {
            throw new RemoteServiceException("暂无可扣回的数据");
        }
        summaryReduce(reduceList, opName, null, ids, adminUser);
    }

    public IPage<WorkerWaitBuckleVO> buckleList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, WorkerWaitBuckleVO.class, adminUser);

        return commonMapper.buckleList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }


    /**
     * 发放日结工资
     */
    @Transactional
    public void issueSalary(String summaryBatchNo, List<String> summaryNumberList, String mobile, String code) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        //验证手机验证码
        Object validMessageCode = redisUtil.get(Constant.RedisPrefix.ISSUE_SAL_MOBILE_SMS + mobile);
        if (validMessageCode == null || code == null) {
            throw new RemoteServiceException("请先发送验证码");
        }
        if (!code.equals(validMessageCode.toString())) {
            throw new RemoteServiceException("短信验证码输入错误");
        }
        summaryNumberList = dailyTransferLogic.issueCheck(summaryBatchNo, summaryNumberList, false, adminUser);
        dailyTransferLogic.issueSalary(summaryBatchNo, summaryNumberList, false, adminUser);

        redisUtil.del(Constant.RedisPrefix.ISSUE_SAL_MOBILE_SMS + mobile);
    }

    @Transactional
    public void rejectSalary(String summaryBatchNo, List<String> summaryWebsiteNumber) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() == 2) {
            throw new RemoteServiceException("平台账号禁止操作");
        }
        Integer count = settleDailyIssueSummaryRecordService.lambdaQuery()
                .eq(SettleDailyIssueSummaryRecord::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyIssueSummaryRecord::getSummaryBatchNo, summaryBatchNo)
                .in(CollectionUtil.isNotEmpty(summaryWebsiteNumber), SettleDailyIssueSummaryRecord::getSummaryNumber, summaryWebsiteNumber)
                .and(wrapper ->
                        wrapper.ne(SettleDailyIssueSummaryRecord::getStatus, DailyConstant.ISSUE_STATUS_NOT)
                                .or()
                                .ne(SettleDailyIssueSummaryRecord::getShouldReduceCost, 0).or()
                                .ne(SettleDailyIssueSummaryRecord::getIncrDecrCost, 0)
                ).count();
        // todo 存在驳回 增减费用 ,扣回费用

        if (count > 0) {
            throw new RemoteServiceException("存在已发放或扣减和增减费用数据");
        }

        settleDailyIssueSummaryRecordService.lambdaUpdate()
                .set(SettleDailyIssueSummaryRecord::getStatus, DailyConstant.ISSUE_STATUS_REJECT)
                .set(SettleDailyIssueSummaryRecord::getUpdateTime, new Date())
                .set(SettleDailyIssueSummaryRecord::getUpdateBy, adminUser.getNickName())
                .eq(SettleDailyIssueSummaryRecord::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(SettleDailyIssueSummaryRecord::getSummaryBatchNo, summaryBatchNo)
                .in(CollectionUtil.isNotEmpty(summaryWebsiteNumber), SettleDailyIssueSummaryRecord::getSummaryNumber, summaryWebsiteNumber)
                .eq(SettleDailyIssueSummaryRecord::getStatus, DailyConstant.SUMMARY_STATUS_HAS)
                .update();

        settleDailyImportSummaryItemService.lambdaUpdate()
                .set(SettleDailyImportSummaryItem::getSummaryStatus, DailyConstant.SUMMARY_STATUS_REJECT)
                .eq(SettleDailyImportSummaryItem::getSummaryBatchNo, summaryBatchNo)
                .in(CollectionUtil.isNotEmpty(summaryWebsiteNumber), SettleDailyImportSummaryItem::getSummaryNumber, summaryWebsiteNumber)
                .update();

        settleDailyResidualInsuranceService.lambdaUpdate().eq(SettleDailyResidualInsurance::getSummaryBatchNo, summaryBatchNo).remove();

        //删掉新产生的历史数据
        settleDailyRemaineBuckleService.lambdaUpdate().eq(SettleDailyRemaineBuckle::getSummaryBatchNo, Constant.DAILY_PREFIX + summaryBatchNo).remove();
        //将本次批次号处理的数据还原
        settleDailyRemaineBuckleService.lambdaUpdate()
                .set(SettleDailyRemaineBuckle::getIsBuckle, false)
                .eq(SettleDailyRemaineBuckle::getSummaryBatchNo, summaryBatchNo)
                .update();
    }

    public List<DailySummaryDataBean> summaryList(String summaryBatchNo) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<DailySummaryDataBean> list = dailyMapper.summaryDayList(summaryBatchNo, adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds());
        return list;

    }

    public IPage<DailySummaryDataBean> cwSummaryList(String summaryBatchNo, String summaryStartTime, String summaryEndTime, String issueStartTime, String issueEndTime, Integer status, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        IPage<DailySummaryDataBean> page = dailyMapper.cwSummaryList(new Page(pageNum, pageSize), summaryBatchNo, summaryStartTime, summaryEndTime, issueStartTime, issueEndTime, status,
                adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds());
        return page;
    }

    public IPage<SettleDailyIssueSummaryRecord> workerSummaryList(String summaryBatchNo, String summaryCommpany, String month, String status,
                                                                  String websiteName, String serviceName, String idCard, String mobile, String websitNumber, Integer pageNo, Integer pageSize) {
        if (StringUtils.isNotEmpty(month)) {
            month = month.replaceAll("-", "");
        }
        AdminUserCom adminUser = commonLogic.getAdminUser();

        return settleDailyIssueSummaryRecordService.lambdaQuery()
                .in(CollectionUtil.isNotEmpty(adminUser.getCompanyWechatIds()), SettleDailyIssueSummaryRecord::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .in(CollectionUtil.isNotEmpty(adminUser.getAdminWebsitIds()), SettleDailyIssueSummaryRecord::getWebsitNumber, adminUser.getAdminWebsitIds())
                .eq(StringUtils.isNotEmpty(summaryBatchNo), SettleDailyIssueSummaryRecord::getSummaryBatchNo, summaryBatchNo)
                .eq(StringUtils.isNotEmpty(summaryCommpany), SettleDailyIssueSummaryRecord::getSummaryNumber, summaryCommpany)
                .eq(StringUtils.isNotEmpty(month), SettleDailyIssueSummaryRecord::getMonth, month)
                .eq(StringUtils.isNotEmpty(status), SettleDailyIssueSummaryRecord::getStatus, status)
                .eq(StringUtils.isNotEmpty(websiteName), SettleDailyIssueSummaryRecord::getWebsitName, websiteName)
                .eq(StringUtils.isNotEmpty(serviceName), SettleDailyIssueSummaryRecord::getServiceName, serviceName)
                .eq(StringUtils.isNotEmpty(mobile), SettleDailyIssueSummaryRecord::getMobile, mobile)
                .eq(StringUtils.isNotEmpty(idCard), SettleDailyIssueSummaryRecord::getIdCard, idCard)
                .orderByDesc(SettleDailyIssueSummaryRecord::getCreateTime, SettleDailyIssueSummaryRecord::getServiceName)
                .page(new Page<>(pageNo, pageSize));
    }

    public ExcelData workerSummaryExport(List<SettleDailyIssueSummaryRecord> dailyIssueSummaryRecords) {
        String[] titles = new String[]{"工资条编号", "发放月份", "状态", "所属网点", "网点编号", "服务人员", "服务人员编号",
                "身份证", "手机号", "本次维修结算费用", "需扣回费用(应扣)", "需扣回费用(已扣)", "增减费用",
                "工伤保险(应扣)", "工伤保险(已扣)", "残保金(应扣)", "残保金(已扣)", "暂扣款应扣", "应发金额", "备注"};
        List<List<Object>> rows = new ArrayList<>();
        for (SettleDailyIssueSummaryRecord bean : dailyIssueSummaryRecords) {
            List<Object> row = new ArrayList<>();
            row.add(bean.getSalaryNo());
            row.add(bean.getMonth());
            row.add(CommonUtils.getIssueStatus(bean.getStatus()));
            row.add(bean.getWebsitName());
            row.add(bean.getWebsitNumber());
            row.add(bean.getServiceName());
            row.add(bean.getServiceNumber());
            row.add(bean.getIdCard());
            row.add(bean.getMobile());
            row.add(bean.getRepairTotalAmount());
            row.add(bean.getShouldReduceCost());
            row.add(bean.getReduceCost());
            row.add(bean.getIncrDecrCost());
            row.add(bean.getShouldEmpInsuranceCost());
            row.add(bean.getEmpInsuranceCost());
            row.add(bean.getShouldResidualInsuranceCost());
            row.add(bean.getResidualInsuranceCost());
            row.add(bean.getWithholdCost());
            row.add(bean.getIssueCost());
            row.add(bean.getRemark());
            // row.add(bean.getWithholdTotalCost());
            // row.add(DateUtils.formatDate(bean.getCreateTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public IPage<DailyWorkerIssueSalaryBean> workerDetailList(String issueSalaryId, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        return dailyMapper.workerDetailList(new Page(pageNum, pageSize), issueSalaryId, adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds());
    }

    public IPage<SettleDailyIssueSummaryMonthRecord> workerSummaryMonthList(String summaryBatchNo, String summaryNumber,
                                                                            Integer status, String websiteNumber, String serviceName, String idCard, String mobile, String websiteName, Integer pageNo, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        IPage<SettleDailyIssueSummaryMonthRecord> page = settleDailyIssueSummaryMonthRecordService.lambdaQuery()
                .in(CollectionUtil.isNotEmpty(adminUser.getCompanyWechatIds()), SettleDailyIssueSummaryMonthRecord::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .in(CollectionUtil.isNotEmpty(adminUser.getAdminWebsitIds()), SettleDailyIssueSummaryMonthRecord::getWebsitNumber, adminUser.getAdminWebsitIds())
                .eq(StringUtils.isNotEmpty(summaryBatchNo), SettleDailyIssueSummaryMonthRecord::getSummaryBatchNo, summaryBatchNo)
                .eq(StringUtils.isNotEmpty(summaryNumber), SettleDailyIssueSummaryMonthRecord::getSummaryNumber, summaryNumber)
                .eq(Objects.isNull(status), SettleDailyIssueSummaryMonthRecord::getStatus, status)
                .eq(StringUtils.isNotEmpty(websiteName), SettleDailyIssueSummaryMonthRecord::getWebsitName, websiteName)
                .eq(StringUtils.isNotEmpty(serviceName), SettleDailyIssueSummaryMonthRecord::getServiceName, serviceName)
                .eq(StringUtils.isNotEmpty(idCard), SettleDailyIssueSummaryMonthRecord::getIdCard, idCard)
                .eq(StringUtils.isNotEmpty(mobile), SettleDailyIssueSummaryMonthRecord::getMobile, mobile)
                .orderByDesc(SettleDailyIssueSummaryMonthRecord::getCreateTime, SettleDailyIssueSummaryMonthRecord::getServiceName)
                .page(new Page<>(pageNo, pageSize));
        return page;
    }

    public IPage<DailyNotMonthSummaryCountBean> cwSummaryMonthList(String summaryBatchNo, String summaryStartTime, String summaryEndTime,
                                                                   String issueStartTime, String issueEndTime, Integer status, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        IPage<DailyNotMonthSummaryCountBean> page = dailyMapper.cwSummaryMonthList(new Page(pageNum, pageSize), summaryBatchNo, summaryStartTime, summaryEndTime, issueStartTime, issueEndTime, status,
                adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds());
        return page;
    }

    public ExcelData workerDetailExport(List<DailyWorkerIssueSalaryBean> list) {
        String[] titles = new String[]{"序号", "状态", "发放月份", "发放时间", "银行卡账号", "户名", "开户行", "派工序号", "自编号码", "工单状态", "新结算单位号", "旧结算单位号", "结算单位名", "维修类型", "内外机",
                "机器条码", "外机型", "外机型描述", "内机条码", "内机型", "内机型描述", "用户姓名", "区号", "移动电话", "电话号码",
                "省份", "市县", "区县", "用户地址", "GPS定位", "邮政编码", "销售单位号", "销售单位", "发票编号", "购买日期", "安装日期",
                "报修日期", "修复日期", "维修工ID", "维修工姓名", "维修工电话", "维修费用", "交通费", "住宿费用", "吊装费用", "其他费用", "总费用",
                "结算单批号", "安装网点号", "安装网点名", "新维修单位号", "旧维修单位号", "维修单位名", "故障现象", "故障分析", "维修内容",
                "备注", "转结算时间"
        };
        List<List<Object>> rows = new ArrayList<>();
        for (DailyWorkerIssueSalaryBean bean : list) {
            List<Object> row = new ArrayList<>();
            row.add(list.indexOf(bean) + 1);
            row.add(CommonUtils.getIssueStatus(bean.getIssueStatus()));
            row.add(bean.getMonth());
            row.add(bean.getIssueTime());
            row.add(bean.getBankAccount());
            row.add(bean.getBankAccountName());
            row.add(bean.getDepositBank());
            row.add(bean.getDispatchOrderNo());
            row.add(bean.getSelfNo());
            row.add(bean.getOrderStatus());
            row.add(bean.getSummaryNumber());
            row.add(bean.getOldSummaryNumber());
            row.add(bean.getSummaryName());
            row.add(bean.getRepairType());
            row.add(bean.getInOutMachine());
            row.add(bean.getMachineCode());
            row.add(bean.getOutMachineType());
            row.add(bean.getOutMachineDescribe());
            row.add(bean.getInMachineCode());
            row.add(bean.getInMachineType());
            row.add(bean.getInMachineDescribe());
            row.add(bean.getUserName());
            row.add(bean.getAreaCode());
            row.add(bean.getMobile());
            row.add(bean.getTel());
            row.add(bean.getProvince());
            row.add(bean.getCity());
            row.add(bean.getCounty());
            row.add(bean.getUserAddr());
            row.add(bean.getGpsAddr());
            row.add(bean.getPostalCode());
            row.add(bean.getSaleDeptNo());
            row.add(bean.getSaleDeptName());
            row.add(bean.getInvoiceCode());
            row.add(DateUtils.formatDate(bean.getBuyDate()));
            row.add(DateUtils.formatDate(bean.getInstallDate()));
            row.add(DateUtils.formatDate(bean.getRepairDate()));
            row.add(DateUtils.formatDate(bean.getReportDate()));
            row.add(bean.getRepairWorkerId());
            row.add(bean.getRepairWorkerName());
            row.add(bean.getRepairWorkerMobile());
            row.add(bean.getRepairFee());
            row.add(bean.getTrafficFee());
            row.add(bean.getAccommodationFee());
            row.add(bean.getLiftingFee());
            row.add(bean.getOtherFee());
            row.add(bean.getTotalFee());
            row.add(bean.getSettlementBatchNo());
            row.add(bean.getInstallWebsitNo());
            row.add(bean.getInstallWebsitName());
            row.add(bean.getRepairUnit());
            row.add(bean.getOldRepairUnit());
            row.add(bean.getRepairName());
            row.add(bean.getFaultPhenomenon());
            row.add(bean.getFaultAnalysis());
            row.add(bean.getRepairDetail());
            row.add(bean.getRemark());
            row.add(DateUtils.formatDate(bean.getSettlementTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public IPage<AllDailyImportSummaryItemVO> repairAllList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, DailyImportSummaryItemVO.class, adminUser);

        return commonMapper.repairAllList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, adminUser.getCompanyWechatIds());
    }

    public DailyCountBean repairAllCount() {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        DailyCountBean bean = new DailyCountBean();
        bean.setWaitCount(commonMapper.repairAllCount(adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds(), 1));
        bean.setEndCount(commonMapper.repairAllCount(adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds(), 2));
        bean.setIngCount(commonMapper.repairAllCount(adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds(), 3));
        bean.setErrCount(commonMapper.repairAllCount(adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds(), 4));
        bean.setRejectCount(commonMapper.repairAllCount(adminUser.getCompanyWechatIds(), adminUser.getAdminWebsitIds(), 5));
        return bean;
    }
}
