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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.order.OldProductManagerAdd;
import com.gree.mall.manager.bean.order.OrderOldProductAdd;
import com.gree.mall.manager.bean.workorder.OrderSettleDetailBean;
import com.gree.mall.manager.bean.workorder.OrderSettleNormBean;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.NoticeEnum;
import com.gree.mall.manager.enums.workorder.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.WxPubNoticeLogic;
import com.gree.mall.manager.logic.engin.OrderEnginBaseLogic;
import com.gree.mall.manager.logic.trade.OldProdctManagerLogic;
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.StringUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class OrderLogLogic {

    private final CommonLogic commonLogic;
    private final OrderFlagLogic orderFlagLogic;
    private final PgOrderOperatorLogService pgOrderOperatorLogService;
    private final PgOrderBaseService pgOrderBaseService;
    private final PgOrderSettleNormService pgOrderSettleNormService;
    private final PgSettleOrderService pgSettleOrderService;
    private final NoticeRecordService noticeRecordService;
    private final PgOrderWorkerService pgOrderWorkerService;
    private final PgOrderProductService pgOrderProductService;
    private final SettleOrderLogic settleOrderLogic;
    private final WxPubNoticeLogic wxPubNoticeLogic;
    private final PgOrderSettleWorkerService pgOrderSettleWorkerService;
    private final PgSettleOrderBakService pgSettleOrderBakService;
    private final OrderEnginBaseLogic orderEnginBaseLogic;
    private final OldProductManagerService oldProductManagerService;
    private final OldProductManagerItemService oldProductManagerItemService;
    private final OldProductManagerItemAttributeService oldProductManagerItemAttributeService;
    private final OrderInfoService orderInfoService;
    private final OrderOldProductService orderOldProductService;
    private final OrderOldProductItemService orderOldProductItemService;
    private final OldProdctManagerLogic oldProdctManagerLogic;

    /**
     * 工单操作明细
     * @param orderBaseId
     * @return
     */
    public List<PgOrderOperatorLog> operatorLogList(String orderBaseId){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<PgOrderOperatorLog> list = pgOrderOperatorLogService.lambdaQuery()
                .eq(PgOrderOperatorLog::getOrderBaseId, orderBaseId)
                .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()),
                        PgOrderOperatorLog::getCompanyWechatId,
                        adminUser.getCompanyWechatId())
                .orderByDesc(PgOrderOperatorLog::getId)
                .list();
        return list;
    }

    /**
     * 过程反馈-添加操作明细
     */
    @Transactional
    public void addLog(PgOrderOperatorLog pgOrderOperatorLog){
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(pgOrderOperatorLog.getOrderBaseId());
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YUYUE.getKey())
                ||pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.GAIYUE.getKey())
        || pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YUYUEY.getKey())) {
            //预约和改约需要记录操作明细，并变更工单预约时间
            pgOrderBaseService.lambdaUpdate()
                    .set(PgOrderBase::getAppointmentTime, pgOrderOperatorLog.getAppointmentTime())
                    .set(PgOrderBase::getAppointmentEndTime,pgOrderOperatorLog.getAppointmentEndTime() )
                    .set(PgOrderBase::getLastOperatorAppointmentTime, new Date())
                    .eq(PgOrderBase::getId, pgOrderOperatorLog.getOrderBaseId())
                    .update();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH");
        SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm");



        Integer index = 1;

        String context ="";

        if (pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.DAIJIAN.getRemark())){

            if (pgOrderBase.getAppointmentTime() == null)
                throw new RemoteServiceException("未操作预约，请先操作预约");


            String[] split = pgOrderOperatorLog.getApplyNum().split(",|，");

            for (String s : split) {

                context = context+"("+"待件"+index+"：申请编号："+s.replace("|",",物料编号：")+")";


                index ++ ;
            }

            pgOrderBaseService.lambdaUpdate()
                    .set(PgOrderBase::getAppointmentTime, pgOrderOperatorLog.getAppointmentTime())
                    .set(PgOrderBase::getAppointmentEndTime,pgOrderOperatorLog.getAppointmentEndTime() )
                    .set(PgOrderBase::getLastOperatorAppointmentTime, new Date())
                    .eq(PgOrderBase::getId, pgOrderOperatorLog.getOrderBaseId())
                    .update();

            String format = sdf3.format(pgOrderOperatorLog.getAppointmentTime());
            String format1 = sdf3.format(pgOrderOperatorLog.getAppointmentEndTime());

            context =context+"；申请时间："+DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss")+"；反馈内容："+pgOrderOperatorLog.getContent()
                    +",改约上门时间："+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1;

            pgOrderOperatorLog.setContent(context);

        }

        if (pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.LAXIU.getRemark())){
            String format = sdf3.format(pgOrderOperatorLog.getAppointmentTime());
            String format1 = sdf3.format(pgOrderOperatorLog.getAppointmentEndTime());

            if (pgOrderBase.getAppointmentTime() == null)
                throw new RemoteServiceException("未操作预约，请先操作预约");

            pgOrderOperatorLog.setContent("改约上门时间："+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1
                    +"；反馈内容："+pgOrderOperatorLog.getContent());

            pgOrderBaseService.lambdaUpdate()
                    .set(PgOrderBase::getAppointmentTime, pgOrderOperatorLog.getAppointmentTime())
                    .set(PgOrderBase::getAppointmentEndTime,pgOrderOperatorLog.getAppointmentEndTime() )
                    .set(PgOrderBase::getLastOperatorAppointmentTime, new Date())
                    .eq(PgOrderBase::getId, pgOrderOperatorLog.getOrderBaseId())
                    .update();

        }


        if (pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.NOCALL.getRemark())){
            String format = sdf3.format(pgOrderOperatorLog.getAppointmentTime());
            String format1 = sdf3.format(pgOrderOperatorLog.getAppointmentEndTime());

            if (pgOrderBase.getAppointmentTime() == null)
                throw new RemoteServiceException("未操作预约，请先操作预约");

            pgOrderOperatorLog.setContent("改约上门时间："+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1
                    +"；反馈内容："+pgOrderOperatorLog.getContent());

            pgOrderBaseService.lambdaUpdate()
                    .set(PgOrderBase::getAppointmentTime, pgOrderOperatorLog.getAppointmentTime())
                    .set(PgOrderBase::getAppointmentEndTime,pgOrderOperatorLog.getAppointmentEndTime() )
                    .set(PgOrderBase::getLastOperatorAppointmentTime, new Date())
                    .eq(PgOrderBase::getId, pgOrderOperatorLog.getOrderBaseId())
                    .update();

        }

        if (pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YANWU.getRemark())){
            String format = sdf3.format(pgOrderOperatorLog.getAppointmentTime());
            String format1 = sdf3.format(pgOrderOperatorLog.getAppointmentEndTime());

            if (pgOrderBase.getAppointmentTime() == null)
                throw new RemoteServiceException("未操作预约，请先操作预约");

            pgOrderOperatorLog.setContent("延误类型："+pgOrderOperatorLog.getYwType()+",改约上门时间："+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1
                    +"；反馈内容："+pgOrderOperatorLog.getContent());

            pgOrderBaseService.lambdaUpdate()
                    .set(PgOrderBase::getAppointmentTime, pgOrderOperatorLog.getAppointmentTime())
                    .set(PgOrderBase::getAppointmentEndTime,pgOrderOperatorLog.getAppointmentEndTime() )
                    .set(PgOrderBase::getLastOperatorAppointmentTime, new Date())
                    .eq(PgOrderBase::getId, pgOrderOperatorLog.getOrderBaseId())
                    .update();

        }


        if (pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.ZHILIANG.getRemark())){

            pgOrderOperatorLog.setContent("质量反馈编号："+pgOrderOperatorLog.getZlNumber()+",反馈时间："+DateUtil.format(pgOrderOperatorLog.getFkTime(),"yyyy-MM-dd HH:mm:ss")
                    +"；反馈内容："+pgOrderOperatorLog.getContent());
        }


        //预约
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YUYUEY.getKey())){
            if(pgOrderBase.getAppointmentTime() != null){
                throw new RemoteServiceException("已预约工单请操作改约");
            }
/*
            if(pgOrderOperatorLog.getAppointmentTime().getTime() < new Date().getTime()){
                throw new RemoteServiceException("预约时间不可小于当前时间");
            }
*/

            String format = sdf3.format(pgOrderOperatorLog.getAppointmentTime());
            String format1 = sdf3.format(pgOrderOperatorLog.getAppointmentEndTime());

            int hour = Integer.parseInt(sdf2.format(pgOrderOperatorLog.getAppointmentTime()));
            String s = hour >= 12 ? "下午" : "上午";

            String text = StringUtil.isEmpty(pgOrderOperatorLog.getContent())?"":(pgOrderOperatorLog.getContent()+"，");

            pgOrderOperatorLog.setContent(text+"预约时间:"+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1);
        }
        //改约
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.GAIYUE.getKey())){

            if (pgOrderBase.getAppointmentTime() == null)
                throw new RemoteServiceException("未操作预约，请先操作预约");

            if(pgOrderBase.getOrderStatus().equals(OrderBaseStatusEnum.YWG.getKey()) || pgOrderBase.getOrderStatus().equals(OrderBaseStatusEnum.YJS.getKey())){
                throw new RemoteServiceException("已完工工单请勿操作改约");
            }
            if(pgOrderOperatorLog.getAppointmentTime().getTime() < DateUtil.beginOfDay(new Date()).getTime()){
                throw new RemoteServiceException("改约时间不可小于当前时间");
            }

            String format = sdf3.format(pgOrderOperatorLog.getAppointmentTime());
            String format1 = sdf3.format(pgOrderOperatorLog.getAppointmentEndTime());

            int hour = Integer.parseInt(sdf2.format(pgOrderOperatorLog.getAppointmentTime()));
            String s = hour >= 12 ? "下午" : "上午";
            String text = StringUtil.isEmpty(pgOrderOperatorLog.getContent())?"":(pgOrderOperatorLog.getContent()+"，");

            pgOrderOperatorLog.setContent(text+"改约时间:"+sdf.format(pgOrderOperatorLog.getAppointmentTime())+" "+format+"-"+format1);
        }
        //已完工
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.WGFK.getKey())){
            if(OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())){
                throw new RemoteServiceException("当前状态不可操作报完工");
            }
            //网点和师傅不能为空
            if(StringUtils.isBlank(pgOrderBase.getWebsitId())){
                throw new RemoteServiceException("网点为空不能报完工");
            }
            if(StringUtils.isBlank(pgOrderBase.getWorkerId())){
                throw new RemoteServiceException("师傅为空不能报完工");
            }
            pgOrderBase.setOrderStatus(OrderBaseStatusEnum.YWG.getKey());
            pgOrderBase.setOrderStatusText(OrderBaseStatusEnum.YWG.getRemark());
            pgOrderBase.setOverTime(new Date());
            pgOrderBase.setOverDate(DateUtil.beginOfDay(pgOrderBase.getOverTime()));
            pgOrderBase.setWebsitOverTime(new Date());
            pgOrderBase.setOverRemark(pgOrderOperatorLog.getContent());
            pgOrderBase.updateById();

            // 插入费用结算
            List<PgOrderProduct> orderProducts = pgOrderProductService.lambdaQuery()
                    .eq(PgOrderProduct::getOrderBaseId, pgOrderBase.getId())
                    .list();

            //生成待结算数据
            settleOrderLogic.insertSettleOrderMethod(pgOrderBase, orderProducts);
            //生成已完工标签
            orderFlagLogic.saveOrderFlag(Lists.newArrayList(pgOrderBase.getId()),OrderFlagEnum.YWG);

            // 销售类型=工程 更新结束时间
            if (pgOrderBase.getSaleType().equals(2)) {
                orderEnginBaseLogic.updateEndTime(pgOrderBase.getProjectNo());
            }

            if (pgOrderBase.getIsCj())
                this.addOldManager(pgOrderBase.getId());
        }
        //异常反馈
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.YCFK.getKey())){
            if(OrderBaseStatusEnum.isOver().contains(pgOrderBase.getOrderStatus())){
                throw new RemoteServiceException("当前状态不可操作异常反馈");
            }
            orderFlagLogic.saveOrderFlag(Lists.newArrayList(pgOrderBase.getId()),OrderFlagEnum.YI_CHANGE);

            pgOrderOperatorLog.setContent("异常类型："+pgOrderOperatorLog.getExType()+",异常原因："+pgOrderOperatorLog.getExNote()+",反馈内容："+pgOrderOperatorLog.getContent());

        }

        //pgOrderOperatorLog.insert();
        pgOrderOperatorLog.setCreateWebsit(pgOrderBase.getWebsitName());
        this.addLog(pgOrderOperatorLog.getOrderBaseId(),pgOrderOperatorLog.getType(),pgOrderOperatorLog.getContent(),
                pgOrderOperatorLog.getCreateWebsit(),pgOrderOperatorLog.getImgSrc());
    }

    private void addOldManager(String id) {
        if (oldProductManagerService.lambdaQuery().eq(OldProductManager::getPgOrderId,id).count() > 0) {
            return;
        }

        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        OrderInfo orderInfo = orderInfoService.getById(pgOrderBase.getSaleOrderId());

        List<OrderOldProduct> list = orderOldProductService.lambdaQuery().eq(OrderOldProduct::getOrderId, pgOrderBase.getSaleOrderId()).list();

        List<OrderOldProductItem> orderOldProductItems = orderOldProductItemService.lambdaQuery().eq(OrderOldProductItem::getOrderId, pgOrderBase.getSaleOrderId()).list();

        OldProductManagerAdd oldProductManagerAdd = new OldProductManagerAdd();
        oldProductManagerAdd.setCompanyName(orderInfo.getCompanyName());
        oldProductManagerAdd.setCompanyWechatId(orderInfo.getCompanyWechatId());
        oldProductManagerAdd.setOrderId(orderInfo.getOrderId());
        oldProductManagerAdd.setPgOrderId(pgOrderBase.getId());
        oldProductManagerAdd.setStatus("IN");
        oldProductManagerAdd.setUserName(pgOrderBase.getUserName());
        oldProductManagerAdd.setUserPhone(pgOrderBase.getUserMobile());
        oldProductManagerAdd.setUserAddress(pgOrderBase.getAddress());
        oldProductManagerAdd.setSaleType(orderInfo.getSaleType());
        oldProductManagerAdd.setOverTime(pgOrderBase.getOverTime());
        oldProductManagerAdd.setRemark(pgOrderBase.getRemark());
        oldProductManagerAdd.setProvince(pgOrderBase.getProvince());
        oldProductManagerAdd.setProvinceId(pgOrderBase.getProvinceId());
        oldProductManagerAdd.setCityId(pgOrderBase.getCityId());
        oldProductManagerAdd.setCity(pgOrderBase.getCity());
        oldProductManagerAdd.setArea(pgOrderBase.getArea());
        oldProductManagerAdd.setAreaId(pgOrderBase.getAreaId());
        oldProductManagerAdd.setStreet(pgOrderBase.getStreet());
        oldProductManagerAdd.setStreetId(pgOrderBase.getStreetId());
        oldProductManagerAdd.setOrderSmallType(pgOrderBase.getOrderSmallType());
        oldProductManagerAdd.setOrderSmallTypeText(pgOrderBase.getOrderSmallTypeText());

        OrderOldProductAdd orderOldProductAdd = new OrderOldProductAdd();

        orderOldProductAdd.setId(list.get(0).getSpecId());
        orderOldProductAdd.setNum(1);
        orderOldProductAdd.setPayAmount(list.get(0).getPayAmount());
        List<String> collect = orderOldProductItems.stream().map(OrderOldProductItem::getGoodsCategoryItemId).collect(Collectors.toList());
        orderOldProductAdd.setItemIds(collect);

        List<OrderOldProductAdd> orderOldProductAdds = new ArrayList<>();
        orderOldProductAdds.add(orderOldProductAdd);
        oldProductManagerAdd.setOrderOldProductAdds(orderOldProductAdds);
        oldProdctManagerLogic.addItem(oldProductManagerAdd);
    }

    public void insertNotice(String orderBaseId) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        List<PgOrderProduct> pgOrderProductList = pgOrderProductService.lambdaQuery().eq(PgOrderProduct::getOrderBaseId, orderBaseId).list();
        List<PgOrderWorker> list = pgOrderWorkerService.lambdaQuery().eq(PgOrderWorker::getOrderBaseId, orderBaseId).list();
        List<NoticeRecord> noticeRecords = new ArrayList<>();

        String text = "";

        for (PgOrderProduct pgOrderProduct : pgOrderProductList) {
            text = pgOrderProduct.getMainName()+pgOrderBase.getOrderSmallTypeText()+"*"+pgOrderProduct.getNum()+",";
        }

        text = text.substring(0,text.length() -1);

        for (PgOrderWorker pgOrderWorker : list) {
            NoticeRecord noticeRecord = new NoticeRecord();
            noticeRecord.setNoticeId(pgOrderWorker.getOrderBaseId());
            noticeRecord.setTitle("服务单派工");
            noticeRecord.setContent("服务单号："+pgOrderWorker.getOrderBaseId()+",网点名称："+pgOrderBase.getWebsitName()
            +"，预约时间："+(pgOrderBase.getAppointmentTime() != null?DateUtil.format(pgOrderBase.getAppointmentTime(),"yyyy-MM-dd"):"")+",服务项目："+text+",客户信息："+pgOrderBase.getUserName()+
                    ",客户电话："+pgOrderBase.getUserMobile()+",服务地址："+pgOrderBase.getAddress());
            noticeRecord.setType(NoticeEnum.B.getKey());
            noticeRecord.setIsNotice(IsYesNoEnum.YES.getKey());
            noticeRecord.setReadFlag(IsYesNoEnum.NO.getKey());
            noticeRecord.setAdminUserId(pgOrderWorker.getWorkerId());
            noticeRecord.setAdminNickName(pgOrderWorker.getWorkerName());
            noticeRecord.setIsWorker("YES");
            noticeRecord.setIssueTime(new Date());
            noticeRecord.setAdminCompanyId(pgOrderBase.getCompanyWechatId());
            noticeRecord.setAdminCompanyName(pgOrderBase.getCompanyWechatName());
            noticeRecord.setNoticeType("SYSTEM");
            noticeRecords.add(noticeRecord);

            //公众号通知
            wxPubNoticeLogic.addDispatch(pgOrderWorker.getWorkerMobile(),pgOrderBase.getCompanyWechatId(),pgOrderBase.getOrderTypeText(),
                    pgOrderBase.getId(),pgOrderBase.getAppointmentTime() == null ? pgOrderBase.getDispatchTime():pgOrderBase.getAppointmentTime(), text,
                    StringUtils.isBlank(pgOrderBase.getAddress())?pgOrderBase.getGpsAddress():pgOrderBase.getAddress());
        }

        noticeRecordService.saveBatch(noticeRecords);


    }



    /**
     * 创建工单内部-添加操作明细
     */
    @Transactional
    public void addLog(String orderBaseId,String type,String content,String websitName){
        this.addLog(orderBaseId, type, content, websitName,"");
    }

    /**
     * 创建工单内部-添加操作明细
     */
    @Transactional
    public void addLog(String orderBaseId,String type,String content,String websitName,String imgSrc){
        AdminUserCom adminUser = null;
        try {
            adminUser = commonLogic.getAdminUser();
        }catch(Exception e){

        }
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(orderBaseId);
        PgOrderOperatorLog pgOrderOperatorLog = new PgOrderOperatorLog();
        pgOrderOperatorLog.setContent(content);
        pgOrderOperatorLog.setType(type);
        pgOrderOperatorLog.setOrderBaseId(orderBaseId);
        if(adminUser != null && adminUser.getAdminWebsit() != null) {
            websitName = websitName;
        }
        pgOrderOperatorLog.setCreateWebsit(websitName);
        pgOrderOperatorLog.setImgSrc(imgSrc);
        pgOrderOperatorLog.setCompanyWechatId(pgOrderBase.getCompanyWechatId());
        pgOrderOperatorLog.setCompanyWechatName(pgOrderBase.getCompanyWechatName());
        pgOrderOperatorLog.insert();

        pgOrderBase.setLastOperator(content);
        pgOrderBase.setLastOperatorWebsit(websitName);
        pgOrderBase.setLastOperatorTime(new Date());
        pgOrderBase.updateById();
        //派单
        if(pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.WORKER.getRemark()) || pgOrderOperatorLog.getType().equals(OrderOperatorLogTypeEnum.GP.getRemark())){
            this.insertNotice(pgOrderOperatorLog.getOrderBaseId());
        }

    }

    public OrderSettleDetailBean settleNormDetail(String id) {
        OrderSettleDetailBean bean = new OrderSettleDetailBean();
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        String keys = OrderBaseStatusEnum.YWG.getKey() + "-" + OrderBaseStatusEnum.YJS.getKey();
        if (Objects.isNull(pgOrderBase) || !keys.contains(pgOrderBase.getOrderStatus())) {
            return bean;
        }

        bean.setId(pgOrderBase.getId());
        bean.setWebsitName(pgOrderBase.getWebsitName());
        bean.setWorkerName(pgOrderBase.getWorkerName());
        bean.setMobile(pgOrderBase.getWorkerMobile());
        bean.setIdcard(pgOrderBase.getWorkerIdcard());
        bean.setOrderType(pgOrderBase.getOrderType());
        bean.setOrderSmallType(pgOrderBase.getOrderSmallType());
        bean.setSettleStatus(pgOrderBase.getOrderStatus());

        List<PgOrderSettleNorm> norms = pgOrderSettleNormService.lambdaQuery()
                .eq(PgOrderSettleNorm::getOrderBaseId, id)
                .list();

        List<PgOrderSettleWorker> settleWorkers = pgOrderSettleWorkerService.lambdaQuery()
                .eq(PgOrderSettleWorker::getOrderBaseId, id)
                .list();
        Map<String, List<PgOrderSettleWorker>> workerGroup = settleWorkers.stream()
                .collect(Collectors.groupingBy(PgOrderSettleWorker::getOrderSettleNormId));

        List<OrderSettleNormBean> normList = new ArrayList<>();
        List<OrderSettleNormBean> otherNormList = new ArrayList<>();

        for (PgOrderSettleNorm norm : norms) {
            OrderSettleNormBean normBean = new OrderSettleNormBean();
            BeanUtils.copyProperties(norm, normBean);
            normBean.setWorkerList(workerGroup.get(normBean.getId()));
            if (norm.getSettleNormType().equals(SettleNormTypeEnum.INSTALL.getKey())
                    || norm.getSettleNormType().equals(SettleNormTypeEnum.REPAIR.getKey())) {
                normList.add(normBean);
            } else {
                otherNormList.add(normBean);
            }
        }

        bean.setNormList(normList);
        bean.setOtherNormList(otherNormList);

        return bean;
    }

    @Transactional
    public void settleNormConfirm(OrderSettleDetailBean bean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(bean.getId());
        if (Objects.isNull(pgOrderBase)) {
            throw new RemoteServiceException("工单不存在");
        }

        // 根据单号查出全部工单结算标准记录
        List<PgOrderSettleNorm> allNorms = pgOrderSettleNormService.lambdaQuery()
                .eq(PgOrderSettleNorm::getOrderBaseId, bean.getId())
                .list();

        // 筛选安装维修结算标准记录
        List<PgOrderSettleNorm> norms = allNorms.stream()
                .filter(v -> v.getSettleNormType().equals(SettleNormTypeEnum.INSTALL.getKey()) || v.getSettleNormType().equals(SettleNormTypeEnum.REPAIR.getKey()))
                .collect(Collectors.toList());

        // 筛选其它结算标准记录
        List<PgOrderSettleNorm> otherNorms = allNorms.stream()
                .filter(v -> v.getSettleNormType().equals(SettleNormTypeEnum.OTHER.getKey()))
                .collect(Collectors.toList());

        // 根据单号查出全部结算师傅记录
        List<PgOrderSettleWorker> settleWorkers = pgOrderSettleWorkerService.lambdaQuery()
                .eq(PgOrderSettleWorker::getOrderBaseId, bean.getId())
                .list();

        // 分组安装维修结算标准记录
        Map<String, PgOrderSettleNorm> normMap = norms.stream()
                .collect(Collectors.toMap(PgOrderSettleNorm::getId, Function.identity()));

        // 分组其它结算标准记录
        Map<String, PgOrderSettleNorm> otherNormMap = otherNorms.stream()
                .collect(Collectors.toMap(PgOrderSettleNorm::getId, Function.identity()));

        // 分组结算师傅记录
        Map<String, List<PgOrderSettleWorker>> settleWorkerMap = settleWorkers.stream()
                .collect(Collectors.groupingBy(PgOrderSettleWorker::getOrderSettleNormId));

        List<PgOrderSettleNorm> updateNorms = new ArrayList<>();
        List<PgOrderSettleNorm> updateOtherNorms = new ArrayList<>();
        List<PgOrderSettleWorker> updateWorkerFeeList = new ArrayList<>();

        for (int i = 0; i < bean.getNormList().size(); i++) {
            OrderSettleNormBean norm = bean.getNormList().get(i);
            PgOrderSettleNorm recordNorm = normMap.get(norm.getId());

            // 检查结算参数
            this.checkSettleParams(i, norm, recordNorm);

            // 计算结算金额
            this.computeSettleParams(norm, recordNorm, settleWorkerMap, updateWorkerFeeList);

            // 添加到待更新结算记录list
            updateNorms.add(recordNorm);
        }

        for (int i = 0; i < bean.getOtherNormList().size(); i++) {
            OrderSettleNormBean norm = bean.getOtherNormList().get(i);
            PgOrderSettleNorm recordNorm = otherNormMap.get(norm.getId());
            if (Objects.isNull(recordNorm)
                    || !recordNorm.getSettleNormType().equals(norm.getSettleNormType())
            ) {
                throw new RemoteServiceException(norm.getId() + "匹配错误");
            }

            if (Objects.nonNull(norm.getSettleNum())
                    && StringUtils.isNotBlank(norm.getChannelId())
                    && StringUtils.isNotBlank(norm.getType())
                    && StringUtils.isNotBlank(norm.getLabel())
                    && norm.getSettleNum() > 0) {
                // 其他费用有内容时处理
                if (Objects.isNull(norm.getNormAmount())) {
                    throw new RemoteServiceException("第" + (i + 1) + "行, 单价不能为空");
                }
                // 计算结算金额
                norm.setSettleAmount(norm.getNormAmount().multiply(BigDecimal.valueOf(norm.getSettleNum()))
                        .setScale(2, BigDecimal.ROUND_DOWN));

                if (recordNorm.getIsConfirm().equals(IsYesNoEnum.NO.getKey())) {
                    recordNorm.setChannelId(norm.getChannelId())
                            .setChannelText(norm.getChannelText())
                            .setType(norm.getType())
                            .setTypeName(norm.getTypeName())
                            .setLabel(norm.getLabel())
                            .setSettleNum(norm.getSettleNum())
                            .setNormAmount(norm.getNormAmount())
                            .setSettleAmount(norm.getSettleAmount())
                            .setIsConfirm(IsYesNoEnum.YES.getKey());
                }
                BeanUtils.copyProperties(recordNorm, norm);

                this.handleWorkerSettleFee(norm, settleWorkerMap, updateWorkerFeeList);
            } else {
                BeanUtils.copyProperties(recordNorm, norm);
            }

            updateOtherNorms.add(norm);
        }

        if (CollectionUtil.isNotEmpty(updateNorms)) {
            pgOrderSettleNormService.saveOrUpdateBatch(updateNorms);
        }
        if (CollectionUtil.isNotEmpty(updateOtherNorms)) {
            pgOrderSettleNormService.saveOrUpdateBatch(updateOtherNorms);
        }

        // 订单结算师傅分组
        Map<String, List<PgOrderSettleWorker>> orderNormWorkerMap = updateWorkerFeeList.stream()
                .collect(Collectors.groupingBy(PgOrderSettleWorker::getOrderSettleNormId));
        // 插入结算单
        this.insertSettleOrder(pgOrderBase, updateNorms, updateOtherNorms, orderNormWorkerMap, adminUser);


        Integer count = pgOrderSettleWorkerService.lambdaQuery()
                .eq(PgOrderSettleWorker::getOrderBaseId, pgOrderBase.getId())
                .ne(PgOrderSettleWorker::getSettleNormType, SettleNormTypeEnum.OTHER.getKey())
                .isNull(PgOrderSettleWorker::getSettleOrderId)
                .count();

        if (count == 0) {
            // 更新工单状态
            pgOrderBaseService.lambdaUpdate()
                    .set(PgOrderBase::getOrderStatus, OrderBaseStatusEnum.YJS.getKey())
                    .set(PgOrderBase::getOrderStatusText, OrderBaseStatusEnum.YJS.getRemark())
                    .eq(PgOrderBase::getId, bean.getId())
                    .update();

            // 删除工单标签
            orderFlagLogic.deleteOrderFlag(pgOrderBase.getId(), OrderFlagEnum.YWG);
            orderFlagLogic.saveOrderFlag(new ArrayList<String>() {{
                this.add(pgOrderBase.getId());
            }}, OrderFlagEnum.YJS);
        }
    }

    private void insertSettleOrder(PgOrderBase pgOrderBase, List<PgOrderSettleNorm> updateNorms,
                                   List<PgOrderSettleNorm> updateOtherNorms,
                                   Map<String, List<PgOrderSettleWorker>> orderNormWorkerMap,
                                   AdminUserCom adminUser) {
        List<PgSettleOrder> orderList = new ArrayList<>();
        List<PgOrderSettleWorker> updWorkerList = new ArrayList<>();
        Date curDate = DateUtil.date();
        for (PgOrderSettleNorm updateNorm : updateNorms) {
            List<PgOrderSettleWorker> workerList = orderNormWorkerMap.get(updateNorm.getId());
            for (PgOrderSettleWorker worker : workerList) {
                PgSettleOrder order = new PgSettleOrder();
                order.setId(StringUtils.isBlank(worker.getSettleOrderId()) ? IdWorker.getIdStr() : worker.getSettleOrderId());
                order.setCompanyWechatId(pgOrderBase.getCompanyWechatId());
                order.setCompanyWechatName(pgOrderBase.getCompanyWechatName());
                order.setWebsitId(pgOrderBase.getWebsitId());
                order.setWebsitName(pgOrderBase.getWebsitName());
                order.setOrderBaseId(pgOrderBase.getId());
                order.setCustomerName(pgOrderBase.getUserName());
                order.setCustomerMobile(pgOrderBase.getUserMobile());
                order.setCustomerAddress(pgOrderBase.getAddress());
                order.setOrderStatus(pgOrderBase.getOrderStatus());
                order.setWorkerId(worker.getWorkerId());
                order.setWorkerName(worker.getWorkerName());
                order.setWorkerMobile(worker.getWorkerMobile());
                order.setWorkerIdcard(worker.getWorkerIdcard());
                order.setOrderCreateTime(pgOrderBase.getCreateTime());
                order.setWorkerEndTime(pgOrderBase.getOverTime());
                order.setOrderType(pgOrderBase.getOrderType());
                order.setOrderTypeText(pgOrderBase.getOrderTypeText());
                order.setOrderSmallType(pgOrderBase.getOrderSmallType());
                order.setOrderSmallTypeText(pgOrderBase.getOrderSmallTypeText());
                order.setBrandId(updateNorm.getBrandId());
                order.setBrand(updateNorm.getBrand());
                order.setOrderSource(pgOrderBase.getSource());
                order.setOrderChannelId(updateNorm.getChannelId());
                order.setOrderChannel(updateNorm.getChannelText());
                order.setParentCategoryId(updateNorm.getParentCategoryId());
                order.setParentCategoryName(updateNorm.getParentCategoryName());
                order.setCategoryId(updateNorm.getCategoryId());
                order.setCategoryName(updateNorm.getCategoryName());
                order.setGoodsId(updateNorm.getGoodsId());
                order.setGoodsName(updateNorm.getGoodsName());
                order.setOrderNum(updateNorm.getOrderNum());
                order.setSettleOrderType(updateNorm.getSettleNormType());
                if (updateNorm.getSettleNormType().equals(SettleNormTypeEnum.INSTALL.getKey())) {
                    order.setInstallId(updateNorm.getSettleNormId());
                    order.setInstallLabel(updateNorm.getLabel());
                    order.setInstallNormAmount(updateNorm.getNormAmount());
                } else if (updateNorm.getSettleNormType().equals(SettleNormTypeEnum.REPAIR.getKey())) {
                    order.setRepairId(updateNorm.getSettleNormId());
                    order.setRepairLabel(updateNorm.getLabel());
                    order.setRepairAmount(updateNorm.getRepairAmount());
                    order.setRepairRate(updateNorm.getNormAmount());
                    order.setRepairSettleAmount(updateNorm.getRepairNormAmount());
                }

                order.setSettleNum(updateNorm.getSettleNum());

                if (worker.getPoolStatus().equals(PoolStatusEnum.NO.getKey())) {
                    // 未汇总填充结算单师傅结算费用
                    order.setSettleAmount(worker.getSettleAmount());
                } else {
                    // 否则结算师傅记录费用填充null
                    worker.setSettleAmount(null);
                }
                order.setRemark(updateNorm.getRemark());

                orderList.add(order);

                worker.setSettleOrderId(order.getId());
                if (StringUtils.isBlank(worker.getConfirmBy())) {
                    worker.setConfirmBy(adminUser.getNickName())
                            .setConfirmTime(curDate);
                }

                updWorkerList.add(worker);
            }
        }

        // 其它费用不为空时处理
        if (CollectionUtil.isNotEmpty(updateOtherNorms)) {
            for (PgOrderSettleNorm otherNorm : updateOtherNorms) {
                if (otherNorm.getSettleAmount().compareTo(BigDecimal.ZERO) > 0) {
                    List<PgOrderSettleWorker> workerList = orderNormWorkerMap.get(otherNorm.getId());
                    for (PgOrderSettleWorker worker : workerList) {
                        PgSettleOrder order = new PgSettleOrder();
                        order.setId(StringUtils.isBlank(worker.getSettleOrderId()) ? IdWorker.getIdStr() : worker.getSettleOrderId());
                        order.setCompanyWechatId(pgOrderBase.getCompanyWechatId());
                        order.setCompanyWechatName(pgOrderBase.getCompanyWechatName());
                        order.setWebsitId(pgOrderBase.getWebsitId());
                        order.setWebsitName(pgOrderBase.getWebsitName());
                        order.setOrderBaseId(pgOrderBase.getId());
                        order.setCustomerName(pgOrderBase.getUserName());
                        order.setCustomerMobile(pgOrderBase.getUserMobile());
                        order.setCustomerAddress(pgOrderBase.getAddress());
                        order.setOrderStatus(pgOrderBase.getOrderStatus());
                        order.setWorkerId(worker.getWorkerId());
                        order.setWorkerName(worker.getWorkerName());
                        order.setWorkerMobile(worker.getWorkerMobile());
                        order.setWorkerIdcard(worker.getWorkerIdcard());
                        order.setOrderCreateTime(pgOrderBase.getCreateTime());
                        order.setWorkerEndTime(pgOrderBase.getOverTime());
                        order.setOrderType(pgOrderBase.getOrderType());
                        order.setOrderTypeText(pgOrderBase.getOrderTypeText());
                        order.setOrderSmallType(pgOrderBase.getOrderSmallType());
                        order.setOrderSmallTypeText(pgOrderBase.getOrderSmallTypeText());
                        order.setBrandId(otherNorm.getBrandId());
                        order.setBrand(otherNorm.getBrand());
                        order.setOrderSource(pgOrderBase.getSource());
                        order.setGoodsId(otherNorm.getGoodsId());
                        order.setGoodsName(otherNorm.getGoodsName());
                        order.setOrderNum(otherNorm.getOrderNum());
                        order.setSettleOrderType(otherNorm.getSettleNormType());

                        order.setOtherId(otherNorm.getSettleNormId());
                        order.setOtherType(otherNorm.getType());
                        order.setOtherLabel(otherNorm.getLabel());
                        order.setOtherPrice(otherNorm.getNormAmount());

                        order.setSettleNum(otherNorm.getSettleNum());

                        if (worker.getPoolStatus().equals(PoolStatusEnum.NO.getKey())) {
                            // 未汇总填充结算单师傅结算费用
                            order.setSettleAmount(worker.getSettleAmount());
                        } else {
                            // 否则结算师傅记录费用填充null
                            worker.setSettleAmount(null);
                        }

                        order.setRemark(otherNorm.getRemark());

                        orderList.add(order);

                        if (StringUtils.isBlank(worker.getConfirmBy())) {
                            worker.setConfirmBy(adminUser.getNickName())
                                    .setConfirmTime(curDate);
                        }
                        worker.setSettleOrderId(order.getId());
                        updWorkerList.add(worker);
                    }
                }
            }
        }

        // 插入或更新结算单
        pgSettleOrderService.saveOrUpdateBatch(orderList);

        // 更新订单结算师傅内容
        pgOrderSettleWorkerService.saveOrUpdateBatch(updWorkerList);

        this.insertSettleOrderBak(orderList);

        //将总结算金额记录到工单
        List<PgSettleOrder> existOrders = pgSettleOrderService.lambdaQuery()
                .eq(PgSettleOrder::getOrderBaseId, pgOrderBase.getId())
                .list();
        BigDecimal totalSettleAmount = existOrders.stream().map(PgSettleOrder::getSettleAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        pgOrderBaseService.lambdaUpdate()
                .set(PgOrderBase::getSettleServiceAmount,totalSettleAmount)
                .eq(PgOrderBase::getId, pgOrderBase.getId())
                .update();
    }

    private void handleWorkerSettleFee(OrderSettleNormBean norm, Map<String, List<PgOrderSettleWorker>> settleWorkerMap,
                                       List<PgOrderSettleWorker> updateWorkerFeeList) {
        List<PgOrderSettleWorker> workerList = norm.getWorkerList();
        BigDecimal workerFeeAmount = BigDecimal.ZERO;

        // 旧师傅结算记录
        List<PgOrderSettleWorker> oldSettleWorkers = settleWorkerMap.get(norm.getId());
        Map<String, PgOrderSettleWorker> oldWorkerMap = oldSettleWorkers.stream()
                .collect(Collectors.toMap(PgOrderSettleWorker::getId, Function.identity()));

        for (PgOrderSettleWorker worker : workerList) {
            if (!oldWorkerMap.containsKey(worker.getId())) {
                throw new RemoteServiceException(norm.getGoodsName() + ": 师傅\"" + worker.getWorkerName() + "\"信息异常");
            }

            PgOrderSettleWorker oldSettleWorker = oldWorkerMap.get(worker.getId());
            oldSettleWorker.setSettleAmount(worker.getSettleAmount());

            workerFeeAmount = workerFeeAmount.add(worker.getSettleAmount());
            updateWorkerFeeList.add(oldSettleWorker);
        }
        if (norm.getSettleAmount().compareTo(workerFeeAmount) != 0) {
            throw new RemoteServiceException(norm.getGoodsName() + "师傅合计结算费用与结算金额不一致, 请检查!");
        }
    }

    private void checkSettleParams(int i, PgOrderSettleNorm norm, PgOrderSettleNorm recordNorm) {
        String preStr = "第" + (i+1) + "行, ";
        if (i < 0) {
            preStr = "";
        }
        if (Objects.isNull(recordNorm)
                || !recordNorm.getSettleNormType().equals(norm.getSettleNormType())
                || !recordNorm.getType().equals(norm.getType())) {
            throw new RemoteServiceException(norm.getId() + "匹配错误");
        }

        if (StringUtils.isBlank(norm.getSettleNormId())) {
            throw new RemoteServiceException(preStr + "结算费用编号不能为空");
        }

        if (StringUtils.isBlank(norm.getChannelId())) {
            throw new RemoteServiceException(preStr + "结算工单来源不能为空");
        }

        if (StringUtils.isBlank(norm.getParentCategoryId()) || StringUtils.isBlank(norm.getParentCategoryName())) {
            throw new RemoteServiceException(preStr + "产品大类不能为空");
        }

        if (StringUtils.isBlank(norm.getCategoryId()) || StringUtils.isBlank(norm.getCategoryName())) {
            throw new RemoteServiceException(preStr + "产品小类不能为空");
        }

        if (StringUtils.isBlank(norm.getLabel())) {
            if (recordNorm.getOrderType().equals(OrderTypeEnum.INSTALL.getKey())) {
                throw new RemoteServiceException(preStr + "功率不能为空");
            } else {
                throw new RemoteServiceException(preStr + "质保类型不能为空");
            }
        }

        if (Objects.isNull(norm.getNormAmount())) {
            if (recordNorm.getOrderType().equals(OrderTypeEnum.INSTALL.getKey())) {
                throw new RemoteServiceException(preStr + "结算标准不能为空");
            } else {
                throw new RemoteServiceException(preStr + "维修费结算比例不能为空");
            }
        }

        if (recordNorm.getOrderType().equals(OrderTypeEnum.REPAIR.getKey())) {
            if (Objects.isNull(norm.getRepairAmount())) {
                throw new RemoteServiceException(preStr + "上门费不能为空");
            }
            if (Objects.isNull(norm.getRepairNormAmount())) {
                throw new RemoteServiceException(preStr + "维修费用结算不能为空");
            }
        }

        if (Objects.isNull(norm.getSettleNum())) {
            throw new RemoteServiceException(preStr + "数量不能为空");
        }
    }

    private void computeSettleParams(OrderSettleNormBean norm, PgOrderSettleNorm recordNorm, Map<String,
            List<PgOrderSettleWorker>> settleWorkerMap, List<PgOrderSettleWorker> updateWorkerFeeList
    ) {
        if (recordNorm.getOrderType().equals(OrderTypeEnum.INSTALL.getKey())) {
            norm.setSettleAmount(norm.getNormAmount().multiply(BigDecimal.valueOf(norm.getSettleNum()))
                    .setScale(2, BigDecimal.ROUND_DOWN));
        } else {
            BigDecimal rate = norm.getNormAmount().divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
            norm.setSettleAmount(norm.getRepairNormAmount().multiply(rate).multiply(BigDecimal.valueOf(norm.getSettleNum())).add(norm.getRepairAmount())
                    .setScale(2, BigDecimal.ROUND_DOWN));
        }

        if (recordNorm.getIsConfirm().equals(IsYesNoEnum.NO.getKey())) {
            recordNorm.setChannelId(norm.getChannelId())
                    .setChannelText(norm.getChannelText())
                    .setParentCategoryId(norm.getParentCategoryId())
                    .setParentCategoryName(norm.getParentCategoryName())
                    .setCategoryId(norm.getCategoryId())
                    .setCategoryName(norm.getCategoryName())
                    .setLabel(norm.getLabel())
                    .setSettleNum(norm.getSettleNum())
                    .setRepairAmount(norm.getRepairAmount())
                    .setNormAmount(norm.getNormAmount())
                    .setRepairNormAmount(norm.getRepairNormAmount())
                    .setRemark(norm.getRemark())
                    .setSettleAmount(norm.getSettleAmount())
                    .setIsConfirm(IsYesNoEnum.YES.getKey());
        }

        BeanUtils.copyProperties(recordNorm, norm);

        this.handleWorkerSettleFee(norm, settleWorkerMap, updateWorkerFeeList);
    }

    @Transactional
    public void settleNormReset(OrderSettleDetailBean bean) {
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(bean.getId());
        if (Objects.isNull(pgOrderBase)) {
            throw new RemoteServiceException("单据状态异常");
        }

        List<PgSettleOrder> settleOrders = new ArrayList<>();
        List<PgOrderSettleWorker> settleWorkers = new ArrayList<>();

        for (OrderSettleNormBean normBean : bean.getNormList()) {
            Map<String, Object> result = this.settleNormReset(normBean, true);
            if (Objects.nonNull(result)) {
                List<PgSettleOrder> orders = (List<PgSettleOrder>) result.get("orders");
                List<PgOrderSettleWorker> workers = (List<PgOrderSettleWorker>) result.get("workers");
                settleOrders.addAll(orders);
                settleWorkers.addAll(workers);
            }
        }

        for (OrderSettleNormBean normBean : bean.getOtherNormList()) {
            Map<String, Object> result = this.settleNormReset(normBean, true);
            if (Objects.nonNull(result)) {
                List<PgSettleOrder> orders = (List<PgSettleOrder>) result.get("orders");
                List<PgOrderSettleWorker> workers = (List<PgOrderSettleWorker>) result.get("workers");
                settleOrders.addAll(orders);
                settleWorkers.addAll(workers);
            }
        }

        // 更新结算单师傅结算费用
        if (CollectionUtil.isNotEmpty(settleOrders)) {
            pgSettleOrderService.saveOrUpdateBatch(settleOrders);
            this.insertSettleOrderBak(settleOrders);
        }
        // 更新工单产品师傅结算费用
        if (CollectionUtil.isNotEmpty(settleWorkers)) {
            pgOrderSettleWorkerService.saveOrUpdateBatch(settleWorkers);
        }

    }

    @Transactional
    public Map<String, Object> settleNormReset(OrderSettleNormBean bean, boolean isReturn) {
        PgOrderSettleNorm recordNorm = pgOrderSettleNormService.getById(bean.getId());

        if (Objects.isNull(recordNorm)) {
            throw new RemoteServiceException("单据记录异常");
        }

        if (recordNorm.getSettleAmount().compareTo(BigDecimal.ZERO) <= 0
                && !recordNorm.getSettleNormType().equals(SettleNormTypeEnum.OTHER.getKey())) {
            return null;
        }

        // 查出工单结算标准记录的所有师傅
        List<PgOrderSettleWorker> settleWorkers = pgOrderSettleWorkerService.lambdaQuery()
                .eq(PgOrderSettleWorker::getOrderSettleNormId, recordNorm.getId())
                .list();

        // 按师傅id分组
        Map<String, PgOrderSettleWorker> workerMap = bean.getWorkerList().stream()
                .collect(Collectors.toMap(PgOrderSettleWorker::getWorkerId, Function.identity()));

        DateTime curDate = DateUtil.date();
        // 对比师傅注入新费用
        for (PgOrderSettleWorker oldSettleWorker : settleWorkers) {
            PgOrderSettleWorker settleWorker = workerMap.get(oldSettleWorker.getWorkerId());
            if (Objects.isNull(settleWorker)) {
                throw new RemoteServiceException(oldSettleWorker.getWorkerName() + "师傅的记录异常");
            }
            if (oldSettleWorker.getPoolStatus().equals(PoolStatusEnum.NO.getKey())) {
                oldSettleWorker.setSettleAmount(settleWorker.getSettleAmount())
                        .setConfirmTime(curDate)
                        .setConfirmBy(CommonUtils.getNickName());
            }
        }

        bean.getWorkerList().clear();
        bean.setWorkerList(settleWorkers);
        List<PgOrderSettleWorker> updateWorkerFeeList = new ArrayList<>();

        // 按工单结算标准记录id分组师傅
        Map<String, List<PgOrderSettleWorker>> settleWorkerMap = settleWorkers.stream()
                .collect(Collectors.groupingBy(PgOrderSettleWorker::getOrderSettleNormId));
        // 检查处理师傅费用是否超结算金额
        this.handleWorkerSettleFee(bean, settleWorkerMap, updateWorkerFeeList);

        // 筛选未汇总并且结算单号不为空的结算单号
        List<String> queryList = updateWorkerFeeList.stream()
                .filter(v -> v.getPoolStatus().equals(PoolStatusEnum.NO.getKey()) && StringUtils.isNotBlank(v.getSettleOrderId()))
                .map(PgOrderSettleWorker::getSettleOrderId)
                .collect(Collectors.toList());

        if (CollectionUtil.isEmpty(queryList)) {
            return null;
        }

        List<PgSettleOrder> settleOrders = pgSettleOrderService.lambdaQuery()
                .in(PgSettleOrder::getId, queryList)
                .eq(PgSettleOrder::getPoolStatus, PoolStatusEnum.NO.getKey())
                .list();

        // 待更新师傅List筛选未汇总并且结算单号不为空的key结算单号 value结算费用
        Map<String, BigDecimal> updAmountMap = updateWorkerFeeList.stream()
                .filter(v -> v.getPoolStatus().equals(PoolStatusEnum.NO.getKey()) && StringUtils.isNotBlank(v.getSettleOrderId()))
                .collect(Collectors.toMap(PgOrderSettleWorker::getSettleOrderId, PgOrderSettleWorker::getSettleAmount));

        for (PgSettleOrder settleOrder : settleOrders) {
            BigDecimal settleAmount = updAmountMap.get(settleOrder.getId());
            if (Objects.nonNull(settleAmount)) {
                settleOrder.setSettleAmount(settleAmount);
            }
        }

        if (!isReturn) {
            // 更新结算单师傅结算费用
            pgSettleOrderService.saveOrUpdateBatch(settleOrders);
            // 更新工单产品师傅结算费用
            pgOrderSettleWorkerService.saveOrUpdateBatch(settleWorkers);
        }

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("orders", settleOrders);
        returnMap.put("workers", settleWorkers);

        return returnMap;


//        Integer poolCount = pgOrderSettleWorkerService.lambdaQuery()
//                .eq(PgOrderSettleWorker::getOrderSettleNormId, recordNorm.getId())
//                .eq(PgOrderSettleWorker::getPoolStatus, PoolStatusEnum.NO.getKey())
//                .count();
//
//        if (CollectionUtil.isEmpty(settleWorkers) || poolCount > 0) {
//            throw new RemoteServiceException("师傅结算记录已汇总");
//        }
//        List<PgOrderSettleWorker> updateWorkerFeeList = new ArrayList<>();
//        if (!recordNorm.getSettleNormType().equals("OTHER")) {
//            Map<String, List<PgOrderSettleWorker>> settleWorkerMap = settleWorkers.stream()
//                    .collect(Collectors.groupingBy(PgOrderSettleWorker::getOrderSettleNormId));
//            // 检查结算参数
//            this.checkSettleParams(-1, bean, recordNorm);
//
//            // 计算结算金额
//            this.computeSettleParams(bean, recordNorm, settleWorkerMap, updateWorkerFeeList);
//
//        } else {
//
//        }
    }

    public OrderSettleDetailBean settleNormDetail2(String orderProductId, String id) {
        OrderSettleDetailBean bean = new OrderSettleDetailBean();
        PgOrderBase pgOrderBase = pgOrderBaseService.getById(id);

        String keys = OrderBaseStatusEnum.YWG.getKey() + "-" + OrderBaseStatusEnum.YJS.getKey();
        if (Objects.isNull(pgOrderBase) || !keys.contains(pgOrderBase.getOrderStatus())) {
            return bean;
        }

        bean.setId(pgOrderBase.getId());
        bean.setWebsitName(pgOrderBase.getWebsitName());
        bean.setWorkerName(pgOrderBase.getWorkerName());
        bean.setMobile(pgOrderBase.getWorkerMobile());
        bean.setIdcard(pgOrderBase.getWorkerIdcard());
        bean.setOrderType(pgOrderBase.getOrderType());
        bean.setOrderSmallType(pgOrderBase.getOrderSmallType());
        bean.setSettleStatus(pgOrderBase.getOrderStatus());

        List<PgOrderSettleNorm> norms = pgOrderSettleNormService.lambdaQuery()
                .eq(PgOrderSettleNorm::getPgOrderProductId, orderProductId)
                .list();

        List<PgOrderSettleWorker> settleWorkers = pgOrderSettleWorkerService.lambdaQuery()
                .eq(PgOrderSettleWorker::getOrderBaseId, id)
                .list();
        Map<String, List<PgOrderSettleWorker>> workerGroup = settleWorkers.stream()
                .collect(Collectors.groupingBy(PgOrderSettleWorker::getOrderSettleNormId));

        List<OrderSettleNormBean> normList = new ArrayList<>();
        List<OrderSettleNormBean> otherNormList = new ArrayList<>();

        for (PgOrderSettleNorm norm : norms) {
            OrderSettleNormBean normBean = new OrderSettleNormBean();
            BeanUtils.copyProperties(norm, normBean);
            normBean.setWorkerList(workerGroup.get(normBean.getId()));
            if (norm.getSettleNormType().equals(SettleNormTypeEnum.INSTALL.getKey())
                    || norm.getSettleNormType().equals(SettleNormTypeEnum.REPAIR.getKey())) {
                normList.add(normBean);
            } else {
                otherNormList.add(normBean);
            }
        }

        bean.setNormList(normList);
        bean.setOtherNormList(otherNormList);

        return bean;
    }

    private void insertSettleOrderBak(List<PgSettleOrder> orderList) {
        List<PgSettleOrderBak> bakList = BeanUtil.copyToList(orderList, PgSettleOrderBak.class);
        pgSettleOrderBakService.saveBatch(bakList);
    }
}
