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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.settle.*;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.commonmapper.CountMapper;
import com.gree.mall.manager.enums.SettleCategoryTypEnum;
import com.gree.mall.manager.enums.SettleWagesStatusEnum;
import com.gree.mall.manager.enums.UserTypeEnum;
import com.gree.mall.manager.enums.workorder.PoolStatusEnum;
import com.gree.mall.manager.enums.workorder.SettleExpenseStatusEnum;
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.SettleExpenseItemService;
import com.gree.mall.manager.plus.service.SettleExpenseService;
import com.gree.mall.manager.plus.service.SettleMonthWagesWorkerService;
import com.gree.mall.manager.plus.service.UserService;
import com.gree.mall.manager.zfire.bean.QueryParamBean;
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 javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class WorkerSettleExpenseLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final SettleExpenseService settleExpenseService;
    private final SettleExpenseItemService settleExpenseItemService;
    private final UserService userService;
    private final SettleMonthWagesWorkerService settleMonthWagesWorkerService;
    private final CountMapper countMapper;

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

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

    }

    public IPage<SettleExpenseItemVO> list(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        String workerOrParam = null;
        int removeIndex = -1;
        if (CollectionUtil.isNotEmpty(zfireParamBean.getParams())) {
            for (int i = 0; i < zfireParamBean.getParams().size(); i++) {
                final QueryParamBean param = zfireParamBean.getParams().get(i);
                if (param.getParam().equals("month_settle_worker_id")) {
                    workerOrParam = param.getValue().toString();
                    removeIndex = i;
                }
            }
            if (removeIndex > -1) {
                zfireParamBean.getParams().remove(removeIndex);
            }
        }
        FieldUtils.supplyParam(zfireParamBean, SettleExpenseItemVO.class, adminUser);
        return commonMapper.workerSettleExpenseList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, workerOrParam);

    }

    public void importData(AdminUserCom adminUser, InputStream inputStream, HttpServletRequest request,String createWebsitId, String createWebsitName) throws Exception {

        //读取excel数据
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("网点名称", "importWebsitName");
        reader.addHeaderAlias("发放月份", "sendMonth");
        reader.addHeaderAlias("费用类型", "typeName");
        reader.addHeaderAlias("安装/维修品类", "category");
        reader.addHeaderAlias("维修自编号", "repairCustomCode");
        reader.addHeaderAlias("内机条码", "insideCode");
        reader.addHeaderAlias("内机名称", "insideName");
        reader.addHeaderAlias("基础安装/维修费用", "baseAmount");
        reader.addHeaderAlias("辅材达标", "materialAmount");
        reader.addHeaderAlias("评价数据达标", "appraiseAmount");
        reader.addHeaderAlias("旧机回收达标", "recoveryAmount");
        reader.addHeaderAlias("合计金额", "totalAmount");
        reader.addHeaderAlias("工单编号", "orderNo");
        reader.addHeaderAlias("销售单号", "salesOrderNo");
        reader.addHeaderAlias("安装/维修日期", "workDate");
        reader.addHeaderAlias("销售类型", "salesType");
        reader.addHeaderAlias("维修内容", "repairContent");
        reader.addHeaderAlias("用户姓名", "userName");
        reader.addHeaderAlias("用户电话", "userMobile");
        reader.addHeaderAlias("用户地址", "userAddress");
        reader.addHeaderAlias("工程师1名称", "workerName1");
        reader.addHeaderAlias("工程师1结算比例", "workerSettleRate1");
        reader.addHeaderAlias("工程师1结算金额", "workerSettleAmount1");
        reader.addHeaderAlias("工程师2名称", "workerName2");
        reader.addHeaderAlias("工程师2结算比例", "workerSettleRate2");
        reader.addHeaderAlias("工程师2结算金额", "workerSettleAmount2");
        reader.addHeaderAlias("备注", "remark");

        List<ImportSettleExpenseItem> itemList = reader.readAll(ImportSettleExpenseItem.class);

        if (CollectionUtil.isEmpty(itemList)) {
            throw new RemoteServiceException("导入数据不能空");
        }

        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("平台账号不能导入");
        }
        String companyWechatId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        String companyWechatName = adminUser.getAdminCompanyWechat().getCompanyName();

        Map<String, User> userMap = this.getUserMap(companyWechatId);

        Set<String> byCount = new HashSet<>();
        BigDecimal settleAmount = BigDecimal.ZERO;
        for (int i = 0; i < itemList.size(); i++) {
            final ImportSettleExpenseItem item = itemList.get(i);
            item.setCompanyWechatId(companyWechatId)
                    .setCompanyWechatName(companyWechatName)
                   .setWebsitId(createWebsitId)
                    .setWebsitName(createWebsitName)
                    .setTypeName(StrUtil.trim(item.getTypeName()))
                    .setCategory(StrUtil.trim(item.getCategory()));

            this.checkRequireParams((i+2), item, userMap, item.getId());

            byCount.add(item.getWorkerName1());
            if (StringUtils.isNotBlank(item.getWorkerName2())) {
                byCount.add(item.getWorkerName2());
            }
            settleAmount = settleAmount.add(item.getWorkerSettleAmount1());
            if (Objects.nonNull(item.getWorkerSettleAmount2())) {
                settleAmount = settleAmount.add(item.getWorkerSettleAmount2());
            }
        }

        // 检查当前导入内容安装是否有重复品类相同内机条码
        final Map<String, List<ImportSettleExpenseItem>> groupInsideCodeMap = itemList.stream()
                .filter(v -> v.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_HOME.getKey())
                        || v.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_OTHER.getKey()))
                .collect(Collectors.groupingBy(v -> v.getCategory() + "|" + v.getInsideCode()));

        for (Map.Entry<String, List<ImportSettleExpenseItem>> entry : groupInsideCodeMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new RemoteServiceException("导入数据发现重复内机条码：" + entry.getKey());
            }
        }

        // 检查导入历史是否重复品类相同内机条码
        final List<String> insideCodeList = itemList.stream()
                .filter(v -> v.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_HOME.getKey())
                        || v.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_OTHER.getKey()))
                .map(v -> v.getTypeName() + "|" + v.getCategory() + "|" + v.getRepairCustomCode())
                .collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(insideCodeList)) {
            final List<SettleExpenseItem> installExpenseItems = settleExpenseItemService.lambdaQuery()
                    .eq(SettleExpenseItem::getCompanyWechatId, companyWechatId)
                    .in(SettleExpenseItem::getCategoryType, SettleCategoryTypEnum.INSTALL_HOME.getKey(), SettleCategoryTypEnum.INSTALL_OTHER.getKey())
                    .in(SettleExpenseItem::getUniqueJoinCode, insideCodeList)
                    .list();

            if (CollectionUtil.isNotEmpty(installExpenseItems)) {
                for (SettleExpenseItem expenseItem : installExpenseItems) {
                    throw new RemoteServiceException("历史导入记录与本次导入数据有重复: " + expenseItem.getUniqueJoinCode());
                }
            }
        }

        // 检查当前导入内容维修是否有重复品类相同维修自编号
        final Map<String, List<ImportSettleExpenseItem>> groupRepairMap = itemList.stream()
                .filter(v -> v.getCategoryType().equals(SettleCategoryTypEnum.REPAIR.getKey()))
                .collect(Collectors.groupingBy(v -> v.getCategory() + "|" + v.getRepairCustomCode()));

        for (Map.Entry<String, List<ImportSettleExpenseItem>> entry : groupRepairMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new RemoteServiceException("导入数据发现重复维修自编号：" + entry.getKey());
            }
        }

        // 检查导入历史是否重复品类相同维修自编号
        final List<String> repairCustomCodeList = itemList.stream()
                .filter(v -> v.getCategoryType().equals(SettleCategoryTypEnum.REPAIR.getKey()))
                .map(v -> v.getTypeName() + "|" + v.getCategory() + "|" + v.getRepairCustomCode())
                .collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(repairCustomCodeList)) {
            final List<SettleExpenseItem> repairExpenseItems = settleExpenseItemService.lambdaQuery()
                    .eq(SettleExpenseItem::getCompanyWechatId, companyWechatId)
                    .eq(SettleExpenseItem::getCategoryType, SettleCategoryTypEnum.REPAIR.getKey())
                    .in(SettleExpenseItem::getUniqueJoinCode, repairCustomCodeList)
                    .list();

            if (CollectionUtil.isNotEmpty(repairExpenseItems)) {
                for (SettleExpenseItem expenseItem : repairExpenseItems) {
                    throw new RemoteServiceException("历史导入记录与本次导入数据有重复: " + expenseItem.getUniqueJoinCode());
                }
            }
        }


        SettleExpense expense = new SettleExpense();
        expense.setCompanyWechatId(companyWechatId);
        expense.setCompanyWechatName(companyWechatName);
        expense.setWebsitId(createWebsitId);
        expense.setWebsitName(createWebsitName);
        expense.setImportBatchNo(IdWorker.getIdStr());
        expense.setSettleByCount(byCount.size());
        expense.setSettleOrderCount(itemList.size());
        expense.setSettleAmount(settleAmount);
        expense.setStatus(SettleExpenseStatusEnum.NO.getKey());
        expense.insert();

        List<SettleExpenseItem> items = itemList.stream().map(v -> {
            SettleExpenseItem item = new SettleExpenseItem();
            BeanUtils.copyProperties(v, item);
            item.setSettleExpenseId(expense.getId());
            if (!item.getCategoryType().equals(SettleCategoryTypEnum.OTHER.getKey())) {
                if (item.getCategoryType().equals(SettleCategoryTypEnum.REPAIR.getKey())) {
                    item.setUniqueJoinCode(item.getTypeName() + "|" + item.getCategory() + "|" + item.getRepairCustomCode());
                } else {
                    item.setUniqueJoinCode(item.getTypeName() + "|" + item.getCategory() + "|" + item.getInsideCode());
                }
            }
            return item;
        }).collect(Collectors.toList());

        settleExpenseItemService.saveBatch(items);
    }

    private void checkRequireParams(Integer row, SettleExpenseItem item, Map<String, User> userMap, String itemId) {
        String rowStr = Objects.nonNull(row) ? "第" + row + "行，" : "";
        if (StringUtils.isBlank(item.getSendMonth())) {
            throw new RemoteServiceException(rowStr + "发放月份不能为空");
        }
        if (StringUtils.isBlank(item.getTypeName())) {
            throw new RemoteServiceException(rowStr + "费用类型不能为空");
        }
        if ((item.getTypeName().equals("安装费用")
                || item.getTypeName().equals("维修费用"))
                && StringUtils.isNotBlank(item.getCategory())) {
            if (item.getTypeName().equals("安装费用") && !item.getCategory().equals("家用空调")) {
                item.setCategoryType(SettleCategoryTypEnum.INSTALL_OTHER.getKey());
            } else if (item.getTypeName().equals("维修费用")) {
                item.setCategoryType(SettleCategoryTypEnum.REPAIR.getKey());
            } else {
                item.setCategoryType(SettleCategoryTypEnum.INSTALL_HOME.getKey());
            }

        } else {
            item.setCategoryType(SettleCategoryTypEnum.OTHER.getKey());
        }
        if (Objects.isNull(item.getWorkerSettleAmount1())) {
            throw new RemoteServiceException(rowStr + "工程师1结算金额不能为空");
        }

        if (item.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_HOME.getKey())) {
            if (StringUtils.isBlank(item.getInsideCode())) {
                throw new RemoteServiceException(rowStr + "内机条码不能为空");
            }
            if (StringUtils.isBlank(item.getInsideName())) {
                throw new RemoteServiceException(rowStr + "内机名称不能为空");
            }
            if (Objects.isNull(item.getBaseAmount())) {
                throw new RemoteServiceException(rowStr + "基础安装/维修费用不能为空");
            }
            if (Objects.isNull(item.getMaterialAmount())) {
                throw new RemoteServiceException(rowStr + "辅材达标不能为空");
            }
            if (Objects.isNull(item.getAppraiseAmount())) {
                throw new RemoteServiceException(rowStr + "评价数据达标不能为空");
            }
            if (Objects.isNull(item.getRecoveryAmount())) {
                throw new RemoteServiceException(rowStr + "回收旧机达标不能为空");
            }
            if (Objects.isNull(item.getTotalAmount())) {
                throw new RemoteServiceException(rowStr + "合计金额不能为空");
            }
            if (Objects.isNull(item.getOtherAmount())) {
                item.setOtherAmount(BigDecimal.ZERO);
            }
            final BigDecimal computeAmount = item.getBaseAmount().add(item.getMaterialAmount()).add(item.getAppraiseAmount()).add(item.getRecoveryAmount()).add(item.getOtherAmount());
            if (computeAmount.compareTo(item.getTotalAmount()) != 0) {
                throw new RemoteServiceException(rowStr + "必要四种费用金额未等于合计金额");
            }
            if (item.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RemoteServiceException("合计金额必须大于0");
            }
            if (StringUtils.isBlank(item.getOrderNo())) {
                throw new RemoteServiceException(rowStr + "工单编号不能为空");
            }
            if (StringUtils.isBlank(item.getSalesOrderNo())) {
                throw new RemoteServiceException(rowStr + "销售单号不能为空");
            }
            if (StringUtils.isBlank(item.getSalesType())) {
                throw new RemoteServiceException(rowStr + "销售类型不能为空");
            }
            if (Objects.isNull(item.getWorkDate())) {
                throw new RemoteServiceException(rowStr + "安装/维修日期不能为空");
            }
            if (StringUtils.isBlank(item.getUserName())) {
                throw new RemoteServiceException(rowStr + "用户姓名不能为空");
            }
            if (StringUtils.isBlank(item.getUserMobile())) {
                throw new RemoteServiceException(rowStr + "用户电话不能为空");
            }
            if (StringUtils.isBlank(item.getUserAddress())) {
                throw new RemoteServiceException(rowStr + "用户地址不能为空");
            }
            if (item.getWorkerSettleAmount1().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RemoteServiceException(rowStr + "工程师1结算金额必须大于0");
            }
            if (StringUtils.isBlank(item.getWorkerSettleRate1())) {
                throw new RemoteServiceException(rowStr + "工程师1结算比例不能为空");
            }
//            if (StringUtils.isBlank(item.getWorkerName2())) {
//                throw new RemoteServiceException(rowStr + "工程师2名称不能为空");
//            }
//            item.setWorkerName2(StrUtil.trim(item.getWorkerName2()));
//            if (StringUtils.isBlank(item.getWorkerSettleRate2())) {
//                throw new RemoteServiceException(rowStr + "工程师2结算比例不能为空");
//            }
//            if (Objects.isNull(item.getWorkerSettleAmount2())) {
//                throw new RemoteServiceException(rowStr + "工程师2结算金额不能为空");
//            }
//            if (!userMap.containsKey(item.getWorkerName2())) {
//                throw new RemoteServiceException(rowStr + "系统未找到工程师2名称");
//            }
//            final BigDecimal settleAmount = item.getWorkerSettleAmount1().add(item.getWorkerSettleAmount2());
//            if (settleAmount.compareTo(item.getTotalAmount()) != 0) {
//                throw new RemoteServiceException(rowStr + "工程师1结算金额和工程师2结算金额合计不等于合计金额");
//            }
//            if (!userMap.containsKey(item.getWorkerName2())) {
//                throw new RemoteServiceException(rowStr + "系统未找到工程师2名称");
//            }
//            item.setWorkerId2(userMap.get(item.getWorkerName2()).getUserId());
//            item.setWorkerMobile2(userMap.get(item.getWorkerName2()).getMobile());
            Integer count = settleExpenseItemService.lambdaQuery()
                    .eq(SettleExpenseItem::getCompanyWechatId, item.getCompanyWechatId())
                    .eq(SettleExpenseItem::getCategoryType, SettleCategoryTypEnum.INSTALL_HOME.getKey())
                    .eq(SettleExpenseItem::getInsideCode, item.getInsideCode())
                    .ne(StringUtils.isNotBlank(itemId), SettleExpenseItem::getId, itemId)
                    .count();
            if (count > 0) {
                throw new RemoteServiceException(rowStr + "内机条码已重复存在，请检查");
            }
        } else if (item.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_OTHER.getKey())) {
            if (StringUtils.isBlank(item.getInsideCode())) {
                throw new RemoteServiceException(rowStr + "内机条码不能为空");
            }
            if (Objects.isNull(item.getWorkDate())) {
                throw new RemoteServiceException(rowStr + "安装/维修日期不能为空");
            }
            if (StringUtils.isBlank(item.getUserName())) {
                throw new RemoteServiceException(rowStr + "用户姓名不能为空");
            }
            if (StringUtils.isBlank(item.getUserMobile())) {
                throw new RemoteServiceException(rowStr + "用户电话不能为空");
            }
            if (StringUtils.isBlank(item.getUserAddress())) {
                throw new RemoteServiceException(rowStr + "用户地址不能为空");
            }
            if (item.getWorkerSettleAmount1().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RemoteServiceException(rowStr + "工程师1结算金额必须大于0");
            }
            Integer count = settleExpenseItemService.lambdaQuery()
                    .eq(SettleExpenseItem::getCompanyWechatId, item.getCompanyWechatId())
                    .eq(SettleExpenseItem::getCategoryType, SettleCategoryTypEnum.INSTALL_OTHER.getKey())
                    .eq(StringUtils.isNotBlank(item.getCategory()), SettleExpenseItem::getCategory, item.getCategory())
                    .eq(SettleExpenseItem::getInsideCode, item.getInsideCode())
                    .ne(StringUtils.isNotBlank(itemId), SettleExpenseItem::getId, itemId)
                    .count();
            if (count > 0) {
                throw new RemoteServiceException(rowStr + "内机条码已重复存在，请检查");
            }
        } else if (item.getCategoryType().equals(SettleCategoryTypEnum.REPAIR.getKey())) {
            if (StringUtils.isBlank(item.getRepairCustomCode())) {
                throw new RemoteServiceException(rowStr + "维修自编号不能为空");
            }
            if (StringUtils.isBlank(item.getInsideCode())) {
                throw new RemoteServiceException(rowStr + "内机条码不能为空");
            }
            if (Objects.isNull(item.getWorkDate())) {
                throw new RemoteServiceException(rowStr + "安装/维修日期不能为空");
            }
            if (StringUtils.isBlank(item.getRepairContent())) {
                throw new RemoteServiceException(rowStr + "维修内容不能为空");
            }
//            if (StringUtils.isBlank(item.getUserName())) {
//                throw new RemoteServiceException(rowStr + "用户姓名不能为空");
//            }
            if (StringUtils.isBlank(item.getUserMobile())) {
                throw new RemoteServiceException(rowStr + "用户电话不能为空");
            }
            if (StringUtils.isBlank(item.getUserAddress())) {
                throw new RemoteServiceException(rowStr + "用户地址不能为空");
            }
            if (item.getWorkerSettleAmount1().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RemoteServiceException(rowStr + "工程师1结算金额必须大于0");
            }
            Integer count = settleExpenseItemService.lambdaQuery()
                    .eq(SettleExpenseItem::getCompanyWechatId, item.getCompanyWechatId())
                    .eq(SettleExpenseItem::getCategoryType, SettleCategoryTypEnum.REPAIR.getKey())
                    .eq(SettleExpenseItem::getRepairCustomCode, item.getRepairCustomCode())
                    .eq(StringUtils.isNotBlank(item.getCategory()), SettleExpenseItem::getCategory, item.getCategory())
                    .ne(StringUtils.isNotBlank(itemId), SettleExpenseItem::getId, itemId)
                    .count();
            if (count > 0) {
                throw new RemoteServiceException(rowStr + "维修自编号已重复存在，请检查");
            }
        }
        if (StringUtils.isBlank(item.getWorkerName1()) && StringUtils.isBlank(item.getWorkerId1())) {
            throw new RemoteServiceException(rowStr + "工程师1名称不能为空");
        } else {
            // 去左右空格
            item.setWorkerId1(StrUtil.trim(item.getWorkerId1()));
            item.setWorkerName1(StrUtil.trim(item.getWorkerName1()));

            if (StringUtils.isNotBlank(item.getWorkerId1()) && userMap.containsKey(item.getWorkerId1())) {
                // 师傅id1不为空并且有系统师傅信息
                final User user = userMap.get(item.getWorkerId1());
                item.setWorkerName1(item.getWorkerId1());
                item.setWorkerId1(user.getUserId());
                item.setWorkerMobile1(user.getMobile());
            } else if (StringUtils.isNotBlank(item.getWorkerName1()) && userMap.containsKey(item.getWorkerName1())) {
                // 师傅名称1不为空并且有系统师傅信息
                final User user = userMap.get(item.getWorkerName1());
                item.setWorkerId1(user.getUserId());
                item.setWorkerMobile1(user.getMobile());
            } else if (StringUtils.isNotBlank(item.getWorkerId1()) && !userMap.containsKey(item.getWorkerId1())) {
                item.setWorkerId1(null);
            }
        }
        if (StringUtils.isNotBlank(item.getWorkerName2()) || StringUtils.isNotBlank(item.getWorkerId2())) {
            // 去左右空格
            item.setWorkerId2(StrUtil.trim(item.getWorkerId2()));
            item.setWorkerName2(StrUtil.trim(item.getWorkerName2()));

            if (userMap.containsKey(item.getWorkerId2())) {
                // 师傅id2不为空并且有系统师傅信息
                final User user = userMap.get(item.getWorkerId2());
                item.setWorkerName2(item.getWorkerId2());
                item.setWorkerId2(user.getUserId());
                item.setWorkerMobile2(user.getMobile());
            } else if (userMap.containsKey(item.getWorkerName2())) {
                // 师傅名称2不为空并且有系统师傅信息
                final User user = userMap.get(item.getWorkerName2());
                item.setWorkerId2(user.getUserId());
                item.setWorkerMobile2(user.getMobile());
            } else if (StringUtils.isNotBlank(item.getWorkerId2()) && !userMap.containsKey(item.getWorkerId2())) {
                item.setWorkerId2(null);
            }
        }
//        item.setWorkerName1(StrUtil.trim(item.getWorkerName1()));
//        if (!userMap.containsKey(item.getWorkerName1())) {
//            throw new RemoteServiceException(rowStr + "系统未找到工程师1名称");
//        }

//        item.setWorkerId1(userMap.get(item.getWorkerName1()).getUserId());
//        item.setWorkerMobile1(userMap.get(item.getWorkerName1()).getMobile());
//        if (StringUtils.isNotBlank(item.getWorkerName2())) {
//            if (!userMap.containsKey(item.getWorkerName2())) {
//                throw new RemoteServiceException(rowStr + "系统未找到工程师2名称");
//            }
//            item.setWorkerName2(StrUtil.trim(item.getWorkerName2()));
//            item.setWorkerId2(userMap.get(item.getWorkerName2()).getUserId());
//            item.setWorkerMobile2(userMap.get(item.getWorkerName2()).getMobile());
//        }
    }

    private Map<String, User> getUserMap(String companyWechatId) {
        final List<User> userList = userService.lambdaQuery()
                .eq(User::getCompanyWechatId, companyWechatId)
                .eq(User::getType, UserTypeEnum.WORKER.getKey())
                .list();
        if (CollectionUtil.isEmpty(userList)) {
            throw new RemoteServiceException("系统暂无师傅信息");
        }
        Map<String, User> userMap;
        try {
            userMap = userList.stream().collect(Collectors.toMap(User::getNickName, Function.identity()));
        } catch (Exception e) {
            throw new RemoteServiceException("系统存在的师傅名称有重复，请检查");
        }
        return userMap;
    }

    @Transactional
    public void save(AdminUserCom adminUser, SettleExpenseItem item) {

        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("平台账号不能新增");
        }
        if (StringUtils.isBlank(item.getSettleExpenseId())) {
            throw new RemoteServiceException("汇总单号不能为空");
        }
        String companyWechatId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        String companyWechatName = adminUser.getAdminCompanyWechat().getCompanyName();

        item.setCompanyWechatId(companyWechatId)
                .setCompanyWechatName(companyWechatName);
               // .setWebsitId(adminUser.getAdminWebsit().getWebsitId())
              //  .setWebsitName(adminUser.getAdminWebsit().getName());

        Map<String, User> userMap = this.getUserMap(companyWechatId);

        this.checkRequireParams(null, item, userMap, item.getId());

        if (!item.getCategoryType().equals(SettleCategoryTypEnum.OTHER.getKey())) {
            if (item.getCategoryType().equals(SettleCategoryTypEnum.REPAIR.getKey())) {
                item.setUniqueJoinCode(item.getTypeName() + "|" + item.getCategory() + "|" + item.getRepairCustomCode());

                final List<SettleExpenseItem> repairExpenseItems = settleExpenseItemService.lambdaQuery()
                        .eq(SettleExpenseItem::getCompanyWechatId, companyWechatId)
                        .eq(SettleExpenseItem::getCategoryType, SettleCategoryTypEnum.REPAIR.getKey())
                        .in(SettleExpenseItem::getUniqueJoinCode, item.getUniqueJoinCode())
                        .ne(StringUtils.isNotBlank(item.getId()), SettleExpenseItem::getId, item.getId())
                        .list();

                if (CollectionUtil.isNotEmpty(repairExpenseItems)) {
                    for (SettleExpenseItem expenseItem : repairExpenseItems) {
                        throw new RemoteServiceException("历史记录与本次数据有重复: " + expenseItem.getUniqueJoinCode());
                    }
                }
            } else {
                item.setUniqueJoinCode(item.getTypeName() + "|" + item.getCategory() + "|" + item.getInsideCode());

                final List<SettleExpenseItem> installExpenseItems = settleExpenseItemService.lambdaQuery()
                        .eq(SettleExpenseItem::getCompanyWechatId, companyWechatId)
                        .in(SettleExpenseItem::getCategoryType, SettleCategoryTypEnum.INSTALL_HOME.getKey(), SettleCategoryTypEnum.INSTALL_OTHER.getKey())
                        .in(SettleExpenseItem::getUniqueJoinCode, item.getUniqueJoinCode())
                        .ne(StringUtils.isNotBlank(item.getId()), SettleExpenseItem::getId, item.getId())
                        .list();

                if (CollectionUtil.isNotEmpty(installExpenseItems)) {
                    for (SettleExpenseItem expenseItem : installExpenseItems) {
                        throw new RemoteServiceException("历史记录与本次数据有重复: " + expenseItem.getUniqueJoinCode());
                    }
                }
            }
        }

        item.insertOrUpdate();

        final List<SettleExpenseItem> itemList = settleExpenseItemService.lambdaQuery()
                .eq(SettleExpenseItem::getSettleExpenseId, item.getSettleExpenseId())
                .list();
        Set<String> byCount = new HashSet<>();
        BigDecimal settleAmount = BigDecimal.ZERO;
        for (SettleExpenseItem expenseItem : itemList) {
            byCount.add(expenseItem.getWorkerName1());
            if (StringUtils.isNotBlank(expenseItem.getWorkerName2())) {
                byCount.add(expenseItem.getWorkerName2());
            }
            settleAmount = settleAmount.add(expenseItem.getWorkerSettleAmount1());
            if (Objects.nonNull(expenseItem.getWorkerSettleAmount2())) {
                settleAmount = settleAmount.add(expenseItem.getWorkerSettleAmount2());
            }
        }
        SettleExpense settleExpense = settleExpenseService.getById(item.getSettleExpenseId());
        settleExpense.setSettleAmount(settleAmount)
                .setSettleByCount(byCount.size())
                .setSettleOrderCount(itemList.size())
                .updateById();
    }

    @Transactional
    public void gatherBatchDel(AdminUserCom adminUser, List<String> ids) {
        final List<SettleExpense> expenseList = settleExpenseService.lambdaQuery()
                .eq(SettleExpense::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleExpense::getId, ids)
                .in(SettleExpense::getStatus, SettleExpenseStatusEnum.NO.getKey(), SettleExpenseStatusEnum.NOT.getKey())
                .list();
        if (CollectionUtil.isNotEmpty(expenseList)) {
            final List<String> idList = expenseList.stream().map(SettleExpense::getId).collect(Collectors.toList());
            settleExpenseService.lambdaUpdate()
                    .in(SettleExpense::getId, idList)
                    .remove();
            settleExpenseItemService.lambdaUpdate()
                    .in(SettleExpenseItem::getSettleExpenseId, idList)
                    .remove();
        }
    }

    @Transactional
    public void batchDel(AdminUserCom adminUser, List<String> ids) {
        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("非商户账号，删除失败");
        }

        final List<SettleExpenseItem> expenseItemList = settleExpenseItemService.lambdaQuery()
                .eq(SettleExpenseItem::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleExpenseItem::getId, ids)
                .groupBy(SettleExpenseItem::getSettleExpenseId)
                .list();

        if (CollectionUtil.isEmpty(expenseItemList)) {
            throw new RemoteServiceException("汇总明细为空，删除失败");
        }

        List<SettleExpense> expenseList = settleExpenseService.lambdaQuery()
                .eq(SettleExpense::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .in(SettleExpense::getId, expenseItemList.stream()
                        .map(SettleExpenseItem::getSettleExpenseId)
                        .collect(Collectors.toList()))
                .list();
        final List<SettleExpense> settleExpenses = expenseList.stream()
                .filter(v -> v.getStatus().equals(PoolStatusEnum.YES.getKey()))
                .collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(settleExpenses)) {
            final List<String> batchNoList = settleExpenses.stream().map(SettleExpense::getImportBatchNo).collect(Collectors.toList());
            throw new RemoteServiceException(StrUtil.join(",", batchNoList) + "发现导入批次号已汇总，删除失败");
        }

        settleExpenseItemService.removeByIds(ids);


        // 更新汇总记录人数、单数量、结算金额

        for (SettleExpense expense : expenseList) {
            final List<SettleExpenseItem> expenseItems = settleExpenseItemService.lambdaQuery()
                    .eq(SettleExpenseItem::getSettleExpenseId, expense.getId())
                    .list();
            if (CollectionUtil.isEmpty(expenseItems)) {
                settleExpenseService.lambdaUpdate()
                        .set(SettleExpense::getSettleByCount, 0)
                        .set(SettleExpense::getSettleOrderCount, 0)
                        .set(SettleExpense::getSettleAmount, BigDecimal.ZERO)
                        .eq(SettleExpense::getId, expense.getId())
                        .update();
            }

            int settleByCount = 0;
            int settleOrderCount = expenseItems.size();
            BigDecimal settleAmount = BigDecimal.ZERO;
            for (SettleExpenseItem expenseItem : expenseItems) {
                settleByCount++;
                settleAmount = settleAmount.add(expenseItem.getWorkerSettleAmount1());
                if (StringUtils.isNotBlank(expenseItem.getWorkerId2())
                        && Objects.nonNull(expenseItem.getWorkerSettleAmount2())
                        && expenseItem.getWorkerSettleAmount2().compareTo(BigDecimal.ZERO) > 0) {
                    settleByCount++;
                    settleAmount = settleAmount.add(expenseItem.getWorkerSettleAmount2());
                }
            }
            settleExpenseService.lambdaUpdate()
                    .set(SettleExpense::getSettleByCount, settleByCount)
                    .set(SettleExpense::getSettleOrderCount, settleOrderCount)
                    .set(SettleExpense::getSettleAmount, settleAmount)
                    .eq(SettleExpense::getId, expense.getId())
                    .update();
        }


    }

    @Transactional
    public void monthGather(AdminUserCom adminUser, MonthGatherBean bean) {
        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("非商户账号，汇总失败");
        }

        String companyWechatId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        String companyWechatName = adminUser.getAdminCompanyWechat().getCompanyName();

        final Integer count = settleMonthWagesWorkerService.lambdaQuery()
                .eq(SettleMonthWagesWorker::getCompanyWechatId, companyWechatId)
                .eq(SettleMonthWagesWorker::getName, bean.getName())
                .count();

        if (count > 0) {
            throw new RemoteServiceException("已存在重复的汇总名称，汇总失败");
        }


        final List<SettleExpense> expenseList = settleExpenseService.lambdaQuery()
                .eq(SettleExpense::getCompanyWechatId, companyWechatId)
                .in(SettleExpense::getId, bean.getIds())
                .in(SettleExpense::getStatus, SettleExpenseStatusEnum.NO.getKey(), SettleExpenseStatusEnum.NOT.getKey())
                .list();

        final List<String> ids = expenseList.stream().map(SettleExpense::getId).collect(Collectors.toList());

        final List<SettleExpenseItem> expenseItemList = settleExpenseItemService.lambdaQuery()
                .eq(SettleExpenseItem::getCompanyWechatId, companyWechatId)
                .in(SettleExpenseItem::getSettleExpenseId, ids)
                .list();

        String settleMonthWagesId = IdWorker.getIdStr();
        List<SettleMonthWagesWorker> wagesWorker1List = new ArrayList<>();
        // 师傅1分组
        final Map<String, List<SettleExpenseItem>> worker1GroupMap = expenseItemList.stream()
                .collect(Collectors.groupingBy(SettleExpenseItem::getWorkerName1));

        // 师傅2分组
        final Map<String, List<SettleExpenseItem>> worker2GroupMap = expenseItemList.stream()
                .filter(v ->
                        StringUtils.isNotBlank(v.getWorkerName2())
                                && Objects.nonNull(v.getWorkerSettleAmount2())
                                && v.getWorkerSettleAmount2().compareTo(BigDecimal.ZERO) > 0
                ).collect(Collectors.groupingBy(SettleExpenseItem::getWorkerName2));

        for (Map.Entry<String, List<SettleExpenseItem>> entry : worker1GroupMap.entrySet()) {
            BigDecimal installAmount = BigDecimal.ZERO;
            BigDecimal installHomeAmount = BigDecimal.ZERO;
            BigDecimal installOtherAmount = BigDecimal.ZERO;
            BigDecimal repairAmount = BigDecimal.ZERO;
            BigDecimal otherAmount = BigDecimal.ZERO;
            int installHomeCount = 0;
            int installOtherCount = 0;
            int repairCount = 0;
            int otherCount = 0;
            if (CollectionUtil.isNotEmpty(worker2GroupMap) && worker2GroupMap.containsKey(entry.getKey())) {
                // 师傅2分组里存在师傅1分组的师傅名称，合并到师傅1分组处理
                entry.getValue().addAll(worker2GroupMap.get(entry.getKey()));
                worker2GroupMap.remove(entry.getKey());
            }
            for (SettleExpenseItem expenseItem : entry.getValue()) {
                if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_HOME.getKey())
                        || expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_OTHER.getKey()) ) {
                    installAmount = installAmount.add(expenseItem.getWorkerSettleAmount1());
                    if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_HOME.getKey())) {
                        installHomeAmount = installHomeAmount.add(expenseItem.getWorkerSettleAmount1());
                        installHomeCount++;
                    }
                    if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_OTHER.getKey())) {
                        installOtherAmount = installOtherAmount.add(expenseItem.getWorkerSettleAmount1());
                        installOtherCount++;
                    }
                }
                if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.REPAIR.getKey()) ) {
                    repairAmount = repairAmount.add(expenseItem.getWorkerSettleAmount1());
                    repairCount++;
                }
                if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.OTHER.getKey()) ) {
                    otherAmount = otherAmount.add(expenseItem.getWorkerSettleAmount1());
                    otherCount++;
                }
            }
            if (installAmount.compareTo(BigDecimal.ZERO) == 0
                    && repairAmount.compareTo(BigDecimal.ZERO) == 0
                    && otherAmount.compareTo(BigDecimal.ZERO) == 0) {
                // 三大结算费用都为0忽略此师傅
                continue;
            }
            SettleMonthWagesWorker wagesWorker = new SettleMonthWagesWorker();
            wagesWorker.setSettleMonthWagesId(settleMonthWagesId)
                    .setCompanyWechatId(companyWechatId)
                    .setCompanyWechatName(companyWechatName)
                    .setWorkerId(entry.getValue().get(0).getWorkerId1())
                    .setWorkerName(entry.getValue().get(0).getWorkerName1())
                    .setWorkerMobile(entry.getValue().get(0).getWorkerMobile1())
                    .setInstallAmount(installAmount)
                    .setRepairAmount(repairAmount)
                    .setOtherAmount(otherAmount)
                    .setSettleAmount(installAmount.add(repairAmount).add(otherAmount))
                    .setInstallHomeAmount(installHomeAmount)
                    .setInstallOtherAmount(installOtherAmount)
                    .setInstallHomeCount(installHomeCount)
                    .setInstallOtherCount(installOtherCount)
                    .setRepairCount(repairCount)
                    .setOtherCount(otherCount);
            wagesWorker1List.add(wagesWorker);
        }

        // 剩余师傅2分组
        if (CollectionUtil.isNotEmpty(worker2GroupMap)) {
            for (Map.Entry<String, List<SettleExpenseItem>> entry : worker2GroupMap.entrySet()) {
                BigDecimal installAmount = BigDecimal.ZERO;
                BigDecimal installHomeAmount = BigDecimal.ZERO;
                BigDecimal installOtherAmount = BigDecimal.ZERO;
                BigDecimal repairAmount = BigDecimal.ZERO;
                BigDecimal otherAmount = BigDecimal.ZERO;
                int installHomeCount = 0;
                int installOtherCount = 0;
                int repairCount = 0;
                int otherCount = 0;
                for (SettleExpenseItem expenseItem : entry.getValue()) {
                    if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_HOME.getKey())
                            || expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_OTHER.getKey()) ) {
                        installAmount = installAmount.add(expenseItem.getWorkerSettleAmount2());
                        if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_HOME.getKey())) {
                            installHomeAmount = installHomeAmount.add(expenseItem.getWorkerSettleAmount2());
                            installHomeCount++;
                        }
                        if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.INSTALL_OTHER.getKey())) {
                            installOtherAmount = installOtherAmount.add(expenseItem.getWorkerSettleAmount2());
                            installOtherCount++;
                        }
                    }
                    if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.REPAIR.getKey()) ) {
                        repairAmount = repairAmount.add(expenseItem.getWorkerSettleAmount2());
                        repairCount++;
                    }
                    if (expenseItem.getCategoryType().equals(SettleCategoryTypEnum.OTHER.getKey()) ) {
                        otherAmount = otherAmount.add(expenseItem.getWorkerSettleAmount2());
                        otherCount++;
                    }
                }

                // 师傅id添加对象
                SettleMonthWagesWorker wagesWorker = new SettleMonthWagesWorker();
                wagesWorker.setSettleMonthWagesId(settleMonthWagesId)
                        .setCompanyWechatId(companyWechatId)
                        .setCompanyWechatName(companyWechatName)
                        .setWorkerId(entry.getValue().get(0).getWorkerId2())
                        .setWorkerName(entry.getValue().get(0).getWorkerName2())
                        .setWorkerMobile(entry.getValue().get(0).getWorkerMobile2())
                        .setInstallAmount(installAmount)
                        .setRepairAmount(repairAmount)
                        .setOtherAmount(otherAmount)
                        .setSettleAmount(installAmount.add(repairAmount).add(otherAmount))
                        .setInstallHomeAmount(installHomeAmount)
                        .setInstallOtherAmount(installOtherAmount)
                        .setInstallHomeCount(installHomeCount)
                        .setInstallOtherCount(installOtherCount)
                        .setRepairCount(repairCount)
                        .setOtherCount(otherCount);

                wagesWorker1List.add(wagesWorker);
            }
        }

        int byCount = wagesWorker1List.size();
        BigDecimal settleAmount = BigDecimal.ZERO;
        for (SettleMonthWagesWorker wagesWorker : wagesWorker1List) {
            settleAmount = settleAmount.add(wagesWorker.getSettleAmount());
            wagesWorker.setName(bean.getName());
        }

        SettleMonthWages wages = new SettleMonthWages();
        wages.setId(settleMonthWagesId);
        wages.setCompanyWechatId(companyWechatId);
        wages.setCompanyWechatName(companyWechatName);
        wages.setName(bean.getName());
        wages.setSettleByCount(byCount);
        wages.setSettleAmount(settleAmount);
        wages.setWaitByCount(byCount);
        wages.setWaitAmount(settleAmount);
        wages.setStatus(SettleWagesStatusEnum.NOT.getKey());
        wages.insert();

        // 保存汇总明细
        settleMonthWagesWorkerService.saveBatch(wagesWorker1List);

        // 填充师傅结算汇总
        settleExpenseService.lambdaUpdate()
                .set(SettleExpense::getRejectBy, null)
                .set(SettleExpense::getRejectTime, null)
                .set(SettleExpense::getName, wages.getName())
                .set(SettleExpense::getGatherBatchNo, wages.getId())
                .set(SettleExpense::getGatherBy, wages.getCreateBy())
                .set(SettleExpense::getGatherTime, wages.getCreateTime())
                .set(SettleExpense::getStatus, SettleExpenseStatusEnum.YES.getKey())
                .eq(SettleExpense::getCompanyWechatId, companyWechatId)
                .in(SettleExpense::getId, ids)
                .update();

        settleExpenseItemService.lambdaUpdate()
                .set(SettleExpenseItem::getSettleMonthWagesId, wages.getId())
                .eq(SettleExpenseItem::getCompanyWechatId, companyWechatId)
                .in(SettleExpenseItem::getSettleExpenseId, ids)
                .update();
    }

    public DataBoardBean dataBoard() {
        DataBoardBean bean = new DataBoardBean();
        AdminUserCom adminUser = commonLogic.getAdminUser();
        // 网点权限
        String websitId = adminUser.getType() == 0 ? adminUser.getAdminWebsitIds().get(0) : null;

        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            // 侍汇总
            DataBoardBean waitBean = countMapper.countTotalSettleExpense(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId);
            if (Objects.nonNull(waitBean)) {
                bean.setWaitGatherAmount(waitBean.getWaitGatherAmount());
                bean.setWaitGatherCount(waitBean.getWaitGatherCount());

                // 侍汇总明细
                DataBoardBean waitItemBean = countMapper.countTotalSettleExpenseItem(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId);
                if (Objects.nonNull(waitItemBean)) {
                    bean.setWaitGatherInstallHomeAmount(waitItemBean.getWaitGatherInstallHomeAmount());
                    bean.setWaitGatherInstallAmount(waitItemBean.getWaitGatherInstallAmount());
                    bean.setWaitGatherRepairAmount(waitItemBean.getWaitGatherRepairAmount());
                    bean.setWaitGatherOtherAmount(waitItemBean.getWaitGatherOtherAmount());
                    bean.setWaitGatherInstallHomeCount(waitItemBean.getWaitGatherInstallHomeCount());
                    bean.setWaitGatherInstallCount(waitItemBean.getWaitGatherInstallCount());
                    bean.setWaitGatherRepairCount(waitItemBean.getWaitGatherRepairCount());
                    bean.setWaitGatherOtherCount(waitItemBean.getWaitGatherOtherCount());
                }
            }

            // 侍发放
            DataBoardBean sendBean = countMapper.countTotalSettleSend(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId);
            if (Objects.nonNull(sendBean)) {
                bean.setWaitSendByCount(sendBean.getWaitSendByCount());
                bean.setWaitSendAmount(sendBean.getWaitSendAmount());
                // 侍发放明细
                DataBoardBean waitSendAmountBean = countMapper.countTotalSettleSendItemAmount(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId);
                if (Objects.nonNull(waitSendAmountBean)) {
                    bean.setWaitSendInstallHomeAmount(waitSendAmountBean.getWaitSendInstallHomeAmount());
                    bean.setWaitSendInstallAmount(waitSendAmountBean.getWaitSendInstallAmount());
                    bean.setWaitSendRepairAmount(waitSendAmountBean.getWaitSendRepairAmount());
                    bean.setWaitSendOtherAmount(waitSendAmountBean.getWaitSendOtherAmount());
                }
                DataBoardBean waitSendCount1Bean = countMapper.countTotalSettleSendItemCount(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId, "installHome");
                DataBoardBean waitSendCount2Bean = countMapper.countTotalSettleSendItemCount(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId, "installOther");
                DataBoardBean waitSendCount3Bean = countMapper.countTotalSettleSendItemCount(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId, "repair");
                DataBoardBean waitSendCount4Bean = countMapper.countTotalSettleSendItemCount(adminUser.getAdminCompanyWechat().getCompanyWechatId(), websitId, "other");
                if (Objects.nonNull(waitSendCount1Bean)) {
                    bean.setWaitSendByInstallHomeCount(waitSendCount1Bean.getWaitSendByInstallHomeCount());
                }
                if (Objects.nonNull(waitSendCount2Bean)) {
                    bean.setWaitSendByInstallCount(waitSendCount2Bean.getWaitSendByInstallCount());
                }
                if (Objects.nonNull(waitSendCount3Bean)) {
                    bean.setWaitSendByRepairCount(waitSendCount3Bean.getWaitSendByRepairCount());
                }
                if (Objects.nonNull(waitSendCount4Bean)) {
                    bean.setWaitSendByOtherCount(waitSendCount4Bean.getWaitSendByOtherCount());
                }
            }
        }


        return bean;
    }

    public MonthSendDataBean monthSendData(String startMonth, String endMonth) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        MonthSendDataBean bean = new MonthSendDataBean();
        bean.setDataList(new ArrayList<>());
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            String startDate = startMonth + "-01 00:00:00";

            String endDate = endMonth + "-01 00:00:00";
            final DateTime endOfMonth = DateUtil.endOfMonth(DateUtil.parseDateTime(endDate));
            endDate = DateUtil.formatDateTime(endOfMonth);
            List<MonthSendWorkerBean> workers = countMapper.monthSendData(adminUser.getAdminCompanyWechat().getCompanyWechatId(), startDate, endDate);

            if (CollectionUtil.isNotEmpty(workers)) {
                List<MonthSendWorkerBean> workerBeanList = workers.stream()
                        .peek(v -> v.setSendDate(StrUtil.sub(v.getSendDate(), 0, 7)))
                        .collect(Collectors.toList());

                Set<String> yearMonthSet = workerBeanList.stream()
                        .map(MonthSendWorkerBean::getSendDate)
                        .collect(Collectors.toSet());

                List<MonthSendItemBean> itemBeanList = new ArrayList<>();
                for (String yearMonth : yearMonthSet) {
                    MonthSendItemBean itemBean = new MonthSendItemBean();
                    Set<String> workerSet = new HashSet<>();
                    BigDecimal settleAmount = BigDecimal.ZERO;
                    for (MonthSendWorkerBean workerBean : workerBeanList) {
                        if (StrUtil.equals(workerBean.getSendDate(), yearMonth)) {
                            workerSet.add(workerBean.getWorkerId());
                            settleAmount = settleAmount.add(workerBean.getSettleAmount());
                        }
                    }
                    itemBean.setYearMonth(yearMonth);
                    itemBean.setEndSendByCount(workerSet.size());
                    itemBean.setEndSendAmount(settleAmount);
                    itemBeanList.add(itemBean);
                }

                final List<MonthSendItemBean> beanList = itemBeanList.stream()
                        .sorted(Comparator.comparing(v -> Integer.parseInt(v.getYearMonth().replace("-", ""))))
                        .collect(Collectors.toList());
                bean.setDataList(beanList);
            }
        }
        return bean;
    }
}
