package com.malk.diwei.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.diwei.entity.*;
import com.malk.diwei.entity.Process;
import com.malk.diwei.mapper.*;
import com.malk.diwei.service.ProcessService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WZY
 * @since 2025-03-27
 */
@Service
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Process> implements ProcessService {
    @Autowired
    private ProcessMapper processMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ProcessMaterialMapper processMaterialMapper;

    @Autowired
    private YDClient ydClient;

    @Autowired
    private BomMapper bomMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ColorMapper colorMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Autowired
    private GoodsPartsMapper goodsPartsMapper;

    @Autowired
    private WorkProcStepMapper workProcStepMapper;

    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private ProcessItemMapper processItemMapper;

    @Autowired
    private ProcessONDetailMapper processONDetailMapper;

    private static final Map PROC_STEP_TYPE = new HashMap<>();

    static {
        PROC_STEP_TYPE.put(1, "厂内工序");
        PROC_STEP_TYPE.put(3, "裁剪工序");
        PROC_STEP_TYPE.put(4, "工艺委外工序");
    }

    @Override
    public McR syncProcess() {
        LambdaQueryWrapper<Process> processLambdaQueryWrapper = new LambdaQueryWrapper<>();
        processLambdaQueryWrapper.and(wrapper -> wrapper.ge(Process::getProcessUpdateDatetime, DateUtil.beginOfDay(DateUtil.yesterday()))
                .or()
                .ge(Process::getProcessCreateDatetime,DateUtil.beginOfDay(DateUtil.yesterday())))
                .eq(Process::getEntityObjKey,"ProductionSW")
                .eq(Process::getProcessStatus,2);

        /*processLambdaQueryWrapper.and(wrapper -> wrapper.ge(Process::getProcessUpdateDatetime, "2025-04-10 00:00:00")
                        .or()
                        .ge(Process::getProcessCreateDatetime,"2025-04-10 00:00:00"))
                .eq(Process::getEntityObjKey,"ProductionSW")
                .eq(Process::getProcessStatus,2);*/
        List<Process> processeList= processMapper.selectList(processLambdaQueryWrapper);

        for (Process process : processeList) {
            Map formData = new HashMap();

            formData.put("dateField_m8pi90ec", process.getProcessDate().getTime());//单据日期
            formData.put("textField_m8pi90ei",process.getProcessCode());//单据编号

            LambdaQueryWrapper<Bom> bomLambdaQueryWrapper = new LambdaQueryWrapper<>();
            bomLambdaQueryWrapper.eq(Bom::getBomID, process.getProcessBomID());
            Bom bom = bomMapper.selectOne(bomLambdaQueryWrapper);

            formData.put("textField_m8pi90ej",bom.getBomCode());//BOM
            formData.put("dateField_m8pi90eo",process.getProcessDeliveryDate().getTime());//交货日期

            if (process.getProcessDeptID() != null && process.getProcessDeptID() != 0){
                LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
                departmentLambdaQueryWrapper.eq(Department::getDeptID, process.getProcessDeptID());
                Department department = departmentMapper.selectOne(departmentLambdaQueryWrapper);
                formData.put("textField_m8pi90eq",department.getDeptName());//部门
            }

            formData.put("textField_m8pi90es","总部");//组织机构
            formData.put("textField_m8pi90ex",process.getProcessSOClientName());//订单客户
            formData.put("textField_m8pi90ey",process.getProcessSOClientOrderCode());//客户订单号
            formData.put("textField_m8pi90ez",process.getProcessSOGoodsCode());//订单款号

            if (process.getProcessQCMerchandiserID() != null && process.getProcessQCMerchandiserID() != 0){
                LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                employeeLambdaQueryWrapper.eq(Employee::getEmpID, process.getProcessQCMerchandiserID());
                Employee employee = employeeMapper.selectOne(employeeLambdaQueryWrapper);

                formData.put("textField_m8pi90f4",employee.getEmpName());//QC跟单
            }

            formData.put("textareaField_m8pi90f6",process.getProcessDescription());//备注

            //加工产品
            List<Map> list = processMapper.selectProductById(process.getProcessID());
            List<Map> collect = list.stream().map(map -> {
                Map map1 = new HashMap();
                map1.put("textField_m8pi90fa",map.get("GoodsCode"));//款号
                map1.put("textField_m8pi90fe",map.get("GoodsName"));//款名
                map1.put("textField_m8pi90fi",map.get("UnitName"));//单位
                map1.put("numberField_m8pi90fk",map.get("qty"));//加工数
                map1.put("textField_m8pi90fm",map.get("ProcessItemReferBillCode"));//引用单据编号

                return map1;
            }).collect(Collectors.toList());

            formData.put("tableField_m8pi90f9",collect);

            //加工件数
            int num1 = 0;
            for (Map map : list) {
                num1 += ((BigDecimal) map.get("qty")).intValue();
            }
            formData.put("numberField_m8pi90hw",num1);



            //横机/附件外发明细
            List<Map> processDetailList = processMapper.selectProcessONDetailByCode(process.getProcessCode());
            List<Map> processDetails = new ArrayList<>();
            for (Map processDetail : processDetailList) {
                Map map = new HashMap();
                map.put("textField_m8pi90fo",processDetail.get("ProcessCode"));//外发单号
                map.put("dateField_m8pi90fc",((Date)processDetail.get("ProcessDate")).getTime());//外发日期
                //状态
                int status = ((Short) processDetail.get("ProcessStatus")).intValue();
                switch (status){
                    case 1:map.put("textField_m8pi90fp","草稿");break;
                    case 2:map.put("textField_m8pi90fp","已提交");break;
                    case 3:map.put("textField_m8pi90fp","已审核");break;
                    default:break;
                }
                map.put("textField_m8pi90fq",processDetail.get("ClientName"));//加工厂
                map.put("textField_m8pi90fr",processDetail.get("GoodsPartsName"));//部件
                map.put("textField_m8pi90ft",processDetail.get("WPSProcStepName"));//工序
                map.put("textField_m8pi90fv",processDetail.get("GoodsNeedleType"));//针型
                map.put("textField_m8pi90fx",processDetail.get("GoodsMachineType"));//机型
                map.put("numberField_m8pi90fz",processDetail.get("WPSHadRecordQty"));//外发数


                processDetails.add(map);
            }

            formData.put("tableField_m8pi90fn",processDetails);


            //原料需求
            double num2 = 0.0;
            List<Map> processMaterialList = processMaterialMapper.selectProcessMaterialByGoodsProperty(process.getProcessID(),3);
            List<Map> processMaterials = new ArrayList<>();
            for (Map processMaterial : processMaterialList) {
                Map map = new HashMap();

                map.put("textField_m8pi90g3",processMaterial.get("GoodsPartsName"));//部件
                map.put("textField_m8pi90g5",processMaterial.get("GoodsCode"));//原料编码
                map.put("textField_m8pi90g7",processMaterial.get("GoodsName"));//原料名称
                map.put("textField_m8pi90g9",processMaterial.get("ColorName"));//颜色
                map.put("textField_m8pi90gb",processMaterial.get("ProcessMaterialColorVCode"));//色号
                map.put("textField_m8pi90gd",processMaterial.get("ProcessMaterialDes"));//批号
                map.put("textField_m8pi90gf",processMaterial.get("UnitName"));//单位
                map.put("numberField_m8pi90gh",processMaterial.get("ProcessMaterialQty"));//需求数

                num2 += Double.parseDouble(processMaterial.get("ProcessMaterialQty").toString());

                processMaterials.add(map);
            }

            formData.put("tableField_m8pi90g2",processMaterials);
            formData.put("numberField_m8pi90hy",num2);

            //辅料需求
            double num3 = 0.0;
            List<Map> processMaterialList2 = processMaterialMapper.selectProcessMaterialByGoodsProperty(process.getProcessID(),4);
            List<Map> processMaterials2 = new ArrayList<>();
            for (Map processMaterial : processMaterialList2) {
                Map map = new HashMap();

                map.put("textField_m8pi90h5",processMaterial.get("GoodsCode"));//辅料编码
                map.put("textField_m8pi90h6",processMaterial.get("GoodsName"));//辅料名称
                map.put("textField_m8pi90h7",processMaterial.get("ColorName"));//颜色
                map.put("textField_m8pi90h9",processMaterial.get("GoodsSpecs"));//规格
                map.put("textField_m8pi90ha",processMaterial.get("UnitName"));//单位
                map.put("numberField_m8pi90hb",processMaterial.get("ProcessMaterialQty"));//需求数
                map.put("numberField_m8pi90he",processMaterial.get("ProcessMaterialPickQty"));//已领数

                num3 += Double.parseDouble(processMaterial.get("ProcessMaterialQty").toString());

                processMaterials2.add(map);
            }

            formData.put("tableField_m8pi90hc",processMaterials2);
            formData.put("numberField_m8pi90hz",num3);

            //加工工艺
            LambdaQueryWrapper<WorkProcStep> workProcStepLambdaQueryWrapper = new LambdaQueryWrapper<>();
            workProcStepLambdaQueryWrapper.eq(WorkProcStep::getProcessID,process.getProcessID());
            List<WorkProcStep> workProcStepList = workProcStepMapper.selectList(workProcStepLambdaQueryWrapper);
            List<Map> workProcSteps = new ArrayList<>();
            for (WorkProcStep workProcStep : workProcStepList) {
                Map map = new HashMap();
                map.put("textField_m8pi90hh",workProcStep.getWPSProcStepName());//工序

                int wpsProcStepType = workProcStep.getWPSProcStepType();
                map.put("textField_m8pi90hj",PROC_STEP_TYPE.get(wpsProcStepType));//类型
                map.put("radioField_m8zkxbjm",workProcStep.getWPSProcStepIsFKM() == 1 ? "是" : "否");//横机

                int WPSConfirmQty = 0;
                if (wpsProcStepType == 4){
                    WPSConfirmQty = workProcStep.getWPSConfirmQty();
                }else {
                    WPSConfirmQty =  ((BigDecimal)list.get(0).get("qty")).intValue();
                }
                int WPSHadRecordQty = workProcStep.getWPSHadRecordQty();
                int WPSUnRecordQty = WPSConfirmQty - WPSHadRecordQty;

                map.put("numberField_m8pi90hp",WPSConfirmQty);//应排
                map.put("numberField_m8pi90hq",WPSHadRecordQty);//已排
                map.put("numberField_m8pi90hr",WPSUnRecordQty);//未排

                Long wpsFactoryID = workProcStep.getWPSFactoryID();
                if (wpsFactoryID != null && wpsFactoryID != 0){
                    LambdaQueryWrapper<Client> clientLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    clientLambdaQueryWrapper.eq(Client::getClientID,workProcStep.getWPSFactoryID());
                    Client client = clientMapper.selectOne(clientLambdaQueryWrapper);
                    if (client != null){
                        map.put("textField_m8pi90hn",client.getClientName());//委外加工厂
                    }
                }

                workProcSteps.add(map);
            }

            formData.put("tableField_m8pi90hg",workProcSteps);

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-233DD96AE9A342C69DFF33016370504ETO2Z")
                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_m8pi90ei",process.getProcessCode(),"eq"))))
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.upsert);
        }

        return McR.success();
    }

    @Override
    public McR syncProcessOut() {
        LambdaQueryWrapper<Process> processLambdaQueryWrapper = new LambdaQueryWrapper<>();
        processLambdaQueryWrapper.and(wrapper -> wrapper.ge(Process::getProcessUpdateDatetime, DateUtil.beginOfDay(DateUtil.yesterday()))
                        .or()
                .ge(Process::getProcessCreateDatetime,DateUtil.beginOfDay(DateUtil.yesterday())))
                .eq(Process::getEntityObjKey,"ProductionProcOutSideN")
                .eq(Process::getProcessOutSideType,3)
                .eq(Process::getProcessStatus,2);

        /*processLambdaQueryWrapper.and(wrapper -> wrapper.ge(Process::getProcessUpdateDatetime, "2025-04-10 00:00:00")
                        .or()
                        .ge(Process::getProcessCreateDatetime,"2025-04-10 00:00:00"))
                .eq(Process::getEntityObjKey,"ProductionProcOutSideN")
                .eq(Process::getProcessOutSideType,3)
                .eq(Process::getProcessStatus,2);*/


        List<Process> processeList= processMapper.selectList(processLambdaQueryWrapper);

        for (Process process : processeList) {
            Map formData = new HashMap();

            formData.put("dateField_m8pi90ec", process.getProcessDate().getTime());//单据日期
            formData.put("textField_m8pi90ei",process.getProcessCode());//单据编号
            formData.put("textField_m8pi90es","总部");//组织机构
            formData.put("dateField_m8pi90eo",process.getProcessDeliveryDate().getTime());//交货日期

            LambdaQueryWrapper<Client> clientLambdaQueryWrapper = new LambdaQueryWrapper<>();
            clientLambdaQueryWrapper.eq(Client::getClientID,process.getFactoryID());
            Client client = clientMapper.selectOne(clientLambdaQueryWrapper);
            if (Objects.nonNull(client)){
                formData.put("textField_m8pi90ex",client.getClientName());//加工厂
            }

            if (process.getProcessSalesmanID() != null && process.getProcessSalesmanID() != 0){
                LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                employeeLambdaQueryWrapper.eq(Employee::getEmpID, process.getProcessSalesmanID());
                Employee employee = employeeMapper.selectOne(employeeLambdaQueryWrapper);

                formData.put("textField_m8pjta80",employee.getEmpName());//业务跟单
            }

            if (process.getProcessQCMerchandiserID() != null && process.getProcessQCMerchandiserID() != 0){
                LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                employeeLambdaQueryWrapper.eq(Employee::getEmpID, process.getProcessQCMerchandiserID());
                Employee employee = employeeMapper.selectOne(employeeLambdaQueryWrapper);

                formData.put("textField_m8pi90f4",employee.getEmpName());//QC跟单
            }

            formData.put("textareaField_m8pi90f6",process.getProcessDescription());//备注

            //外发明细
            List<Map> outSideDetails = new ArrayList<>();
            List<Map> outSideDetailList = processMapper.selectOutSideDetails(process.getProcessID());
            int num = 0;
            for (Map outSideDetail : outSideDetailList) {
                Map map = new HashMap();

                map.put("textField_m8pjta82",outSideDetail.get("GoodsPartsName"));//部件
                map.put("textField_m8pi90fa",outSideDetail.get("GoodsCode"));//款号
                map.put("textField_m8pi90fe",outSideDetail.get("GoodsName"));//款名
                map.put("textField_m8pjta83",outSideDetail.get("GoodsNeedleType"));//针型
                map.put("textField_m8pjta84",outSideDetail.get("GoodsMachineType"));//机型
                map.put("textField_m8pjta85",outSideDetail.get("ColorName"));//颜色
                map.put("textField_m8pi90fi",outSideDetail.get("SizeName"));//尺码
                map.put("textField_m8pjta86",outSideDetail.get("WPSProcStepName"));//工序
                map.put("numberField_m8pi90fk",outSideDetail.get("ProcessONDetailQty"));//外发数
                map.put("numberField_m8pjta87",outSideDetail.get("WPSProcStepPrice"));//工序单价
                map.put("textareaField_m8pjta88",outSideDetail.get("ProcessItemDesc"));//备注
                map.put("textField_m8pi90fm",outSideDetail.get("ProcessItemReferBillCode"));//加工单号

                num += ((BigDecimal) outSideDetail.get("ProcessONDetailQty")).intValue();

                outSideDetails.add(map);
            }

            formData.put("tableField_m8pi90f9",outSideDetails);
            formData.put("numberField_m8pi90hw",num);//外发数合计

            List<Map> processMaterialList = processMaterialMapper.selectProcessMaterialByGoodsProperty(process.getProcessID(),3);
            List<Map> processMaterials = new ArrayList<>();
            for (Map processMaterial : processMaterialList) {
                Map map = new HashMap();

                map.put("textField_m8pi90g3",processMaterial.get("GoodsPartsName"));//部件
                map.put("textField_m8pi90g5",processMaterial.get("GoodsCode"));//原料编码
                map.put("textField_m8pi90g7",processMaterial.get("GoodsName"));//原料名称
                map.put("textField_m8pi90g9",processMaterial.get("ColorName"));//颜色
                map.put("textField_m8pi90gb",processMaterial.get("ProcessMaterialColorVCode"));//色号
                map.put("textField_m8pi90gd",processMaterial.get("ProcessMaterialDes"));//批号
                map.put("textField_m8pi90gf",processMaterial.get("UnitName"));//单位
                map.put("numberField_m8pi90gh",processMaterial.get("ProcessMaterialQty"));//需求数
                map.put("numberField_m8pjta81",processMaterial.get("ProcessMaterialPickQty"));//已领数

                processMaterials.add(map);
            }

            formData.put("tableField_m8pi90g2",processMaterials);

            //辅料需求
            List<Map> processMaterialList2 = processMaterialMapper.selectProcessMaterialByGoodsProperty(process.getProcessID(),4);
            List<Map> processMaterials2 = new ArrayList<>();
            for (Map processMaterial : processMaterialList2) {
                Map map = new HashMap();

                map.put("textField_m8pi90h5",processMaterial.get("GoodsCode"));//辅料编码
                map.put("textField_m8pi90h6",processMaterial.get("GoodsName"));//辅料名称
                map.put("textField_m8pi90h7",processMaterial.get("ColorName"));//颜色
                map.put("textField_m8pi90h9",processMaterial.get("GoodsSpecs"));//规格
                map.put("textField_m8pi90ha",processMaterial.get("UnitName"));//单位
                map.put("numberField_m8pi90hb",processMaterial.get("ProcessMaterialQty"));//需求数

                processMaterials2.add(map);
            }

            formData.put("tableField_m8pi90hc",processMaterials2);

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-BEEFBB3E63CB427DA0FFD4391780ED2AAIQ4")
                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_m8pi90ei",process.getProcessCode(),"eq"))))
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.upsert);
        }

        return McR.success();
    }

    @Override
    public McR syncProcessOut2() {
        LambdaQueryWrapper<Process> processLambdaQueryWrapper = new LambdaQueryWrapper<>();
        processLambdaQueryWrapper.and(wrapper -> wrapper.ge(Process::getProcessUpdateDatetime, DateUtil.beginOfDay(DateUtil.yesterday()))
                        .or()
                        .ge(Process::getProcessCreateDatetime,DateUtil.beginOfDay(DateUtil.yesterday())))
                .eq(Process::getEntityObjKey,"ProductionProcOutSideN")
                .eq(Process::getProcessOutSideType,0)
                .eq(Process::getProcessStatus,2);

        /*processLambdaQueryWrapper.and(wrapper -> wrapper.ge(Process::getProcessUpdateDatetime, "2025-04-10 00:00:00")
                        .or()
                        .ge(Process::getProcessCreateDatetime,"2025-04-10 00:00:00"))
                .eq(Process::getEntityObjKey,"ProductionProcOutSideN")
                .eq(Process::getProcessOutSideType,0)
                .eq(Process::getProcessStatus,2);*/
        List<Process> processeList= processMapper.selectList(processLambdaQueryWrapper);

        for (Process process : processeList) {
            Map formData = new HashMap();

            formData.put("dateField_m8pi90ec", process.getProcessDate().getTime());//单据日期
            formData.put("textField_m8pi90ei",process.getProcessCode());//单据编号
            formData.put("textField_m8pi90es","总部");//组织机构
            formData.put("dateField_m8pi90eo",process.getProcessDeliveryDate().getTime());//交货日期

            LambdaQueryWrapper<Client> clientLambdaQueryWrapper = new LambdaQueryWrapper<>();
            clientLambdaQueryWrapper.eq(Client::getClientID,process.getFactoryID());
            Client client = clientMapper.selectOne(clientLambdaQueryWrapper);
            if (Objects.nonNull(client)){
                formData.put("textField_m8pi90ex",client.getClientName());//加工厂
            }

            formData.put("textareaField_m8pi90f6",process.getProcessDescription());//备注

            //外发明细
            double num = 0;
            double price = 0;
            List<Map> outSideDetails = new ArrayList<>();
            List<Map> outSideDetailList = processMapper.selectOutSideDetails(process.getProcessID());

            for (Map outSideDetail : outSideDetailList) {
                Map map = new HashMap();

                map.put("textField_m8pi90fa",outSideDetail.get("GoodsCode"));//款号
                map.put("textField_m8pjta85",outSideDetail.get("ColorName"));//颜色
                map.put("textField_m8pi90fi",outSideDetail.get("SizeName"));//尺码
                if (Objects.isNull(outSideDetail.get("ColorName")) && Objects.isNull(outSideDetail.get("SizeName"))){
                    map.put("textField_m8pld6zz","不分色码");
                }else {
                    map.put("textField_m8pld6zz","分色分码");
                }
                map.put("textField_m8pjta86",outSideDetail.get("WPSProcStepName"));//工序
                map.put("numberField_m8pi90fk",outSideDetail.get("ProcessItemQty"));//委外件数
                map.put("numberField_m8pjta87",outSideDetail.get("WPSProcStepPrice"));//工序单价
                map.put("textareaField_m8pjta88",outSideDetail.get("ProcessItemDesc"));//备注
                map.put("textField_m8pi90fm",outSideDetail.get("ProcessItemReferBillCode"));//加工单号

                num += ((BigDecimal) outSideDetail.get("ProcessONDetailQty")).doubleValue();
                price += ((BigDecimal) outSideDetail.get("WPSProcStepPrice")).doubleValue();

                outSideDetails.add(map);
            }

            formData.put("tableField_m8pi90f9",outSideDetails);
            formData.put("numberField_m8pi90hw",num);//数量合计
            formData.put("numberField_m8pld6zw",price);//金额合计

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-CBB8EADCBBD84982BAD3C6F38CB56171V6PS")
                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_m8pi90ei",process.getProcessCode(),"eq"))))
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.upsert);
        }

        return McR.success();
    }

    @Override
    public McR syncProcessOn() {
        LambdaQueryWrapper<ProcessONDetail> processONDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        processONDetailLambdaQueryWrapper.and(wrapper -> wrapper.ge(ProcessONDetail::getProcessONDetailUpdateDate, DateUtil.beginOfDay(DateUtil.yesterday()))
                .or()
                .ge(ProcessONDetail::getProcessONDetailCreatDate,DateUtil.beginOfDay(DateUtil.yesterday())))
                .eq(ProcessONDetail::getProcessONDetailType,2)//回收
                .eq(ProcessONDetail::getProcessONDetailReceiptWay,2)//扫码录入
                .like(ProcessONDetail::getProcessONDetailCode,"PCWR");


        /*processONDetailLambdaQueryWrapper.and(wrapper -> wrapper.ge(ProcessONDetail::getProcessONDetailUpdateDate, "2025-04-10 00:00:00")
                        .or()
                        .ge(ProcessONDetail::getProcessONDetailCreatDate,"2025-04-10 00:00:00"))
                .eq(ProcessONDetail::getProcessONDetailType,2)//回收
                .eq(ProcessONDetail::getProcessONDetailReceiptWay,2)//扫码录入
                .like(ProcessONDetail::getProcessONDetailCode,"PCWR");*/
        List<ProcessONDetail> processONDetails = processONDetailMapper.selectList(processONDetailLambdaQueryWrapper);

        Set<String> processONDetailCodeSet = new HashSet<>();
        for (ProcessONDetail processONDetail : processONDetails) {
            String processONDetailCode = processONDetail.getProcessONDetailCode();
            processONDetailCodeSet.add(processONDetailCode);
        }

        for (String processONDetailCode : processONDetailCodeSet) {
            Map formData = new HashMap();

            //基础信息
            Map base = processMapper.selectOnBaseInfo(processONDetailCode);
            formData.put("dateField_m8pi90ec",((Date)base.get("ProcessONDetailDate")).getTime());//单据日期
            formData.put("textField_m99n1t8f",base.get("ProcessONDetailCode"));//回收单号
            formData.put("textField_m8pkxdg5",base.get("WPSProcStepName"));//工序
            formData.put("textField_m8pi90ex",base.get("ClientName"));//加工厂

            //关联明细
            List<Map> details = new ArrayList<>();
            List<Map> detailList = processMapper.selectOnDetails(processONDetailCode);
            int sumQty = 0;
            double sumWeight = 0;
            for (Map detail : detailList) {
                Map map= new HashMap();

                map.put("textField_m8pkxdf6",detail.get("GoodsCode"));//款号
                map.put("textField_m99n1t8d",detail.get("GoodsName"));//款名
                map.put("textField_m99n1t8e",detail.get("GoodsPartsName"));//部件
                map.put("textField_m8pkxdfa",detail.get("ColorName"));//颜色
                map.put("textField_m8pkxdfb",detail.get("SizeName"));//尺码
                map.put("numberField_m99n1t88",detail.get("ProcessONDetailQty"));//件数
                map.put("numberField_m99n1t89",detail.get("ProcessONDetailWeight"));//重量
                map.put("textField_m99n1t8a",detail.get("ProcessCode"));//外发单号
                map.put("textField_m99n1t8b",detail.get("ProcessItemReferBillCode"));//毛衫加工单

                sumQty += ((BigDecimal) detail.get("ProcessONDetailQty")).intValue();
                sumWeight += ((BigDecimal) detail.get("ProcessONDetailWeight")).doubleValue();

                details.add(map);
            }

            formData.put("tableField_m8pkxdfh",details);
            formData.put("numberField_m8pkxdgc",sumQty);//件数合计
            formData.put("numberField_m8pkxdgd",sumWeight);//重量合计

            //款号汇总
            //将details根据款号、款名、颜色、尺码进行分组，计算总件数、总数量
            List<Map<String, Object>> summaryList = details.stream()
                    .collect(Collectors.groupingBy(
                            detail -> {
                                // 使用款号、款名、颜色、尺码作为分组键
                                return detail.get("textField_m8pkxdf6") + "-" +
                                        detail.get("textField_m99n1t8d") + "-" +
                                        detail.get("textField_m8pkxdfa") + "-" +
                                        detail.get("textField_m8pkxdfb");
                            }
                    ))
                    .entrySet().stream()
                    .map(entry -> {
                        Map<String, Object> groupSummary = new HashMap<>();
                        List<Map> groupDetails = entry.getValue();
                        int totalQty = groupDetails.stream()
                                .mapToInt(detail -> ((BigDecimal) detail.get("numberField_m99n1t88")).intValue())
                                .sum();
                        double totalWeight = groupDetails.stream()
                                .mapToDouble(detail -> ((BigDecimal) detail.get("numberField_m99n1t89")).doubleValue())
                                .sum();

                        // 设置汇总信息
                        groupSummary.put("textField_m99n1t87", entry.getKey().split("-")[0]); //款号
                        groupSummary.put("textField_m99n1t8c", entry.getKey().split("-")[1]); //款名
                        groupSummary.put("textField_m8pkxdfl", entry.getKey().split("-")[2]); //颜色
                        groupSummary.put("textField_m8pkxdfm", entry.getKey().split("-")[3]); //尺码
                        groupSummary.put("numberField_m8pkxdfn", totalQty); //总件数
                        groupSummary.put("numberField_m8pkxdfw", totalWeight); //总重量

                        return groupSummary;
                    })
                    .collect(Collectors.toList());

            formData.put("tableField_m8pkxdfj",summaryList);

            //条码明细
            List<Map> cardBarDetails = new ArrayList<>();
            List<Map> cardBarDetailList = processMapper.selectOnCardBarDetails(processONDetailCode);
            for (Map cardBarDetail : cardBarDetailList) {
                Map map= new HashMap();
                map.put("textField_m99n1t8p",cardBarDetail.get("ProceCardBarCode"));//条码

                cardBarDetails.add(map);
            }
            formData.put("tableField_m99n1t8k",cardBarDetails);

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-C003D6F6769F400FA324851889EE458EOH9H")
                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_m99n1t8f",processONDetailCode,"eq"))))
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.upsert);

        }

        return McR.success();
    }

    @Override
    public McR syncProcessOn2() {
        LambdaQueryWrapper<ProcessONDetail> processONDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        processONDetailLambdaQueryWrapper.and(wrapper -> wrapper.ge(ProcessONDetail::getProcessONDetailUpdateDate, DateUtil.beginOfDay(DateUtil.yesterday()))
                        .or()
                        .ge(ProcessONDetail::getProcessONDetailCreatDate,DateUtil.beginOfDay(DateUtil.yesterday())))//
                .eq(ProcessONDetail::getProcessONDetailType,2)//回收
                .eq(ProcessONDetail::getProcessONDetailReceiptWay,2)//扫码录入
                .like(ProcessONDetail::getProcessONDetailCode,"PCNR");

        /*processONDetailLambdaQueryWrapper.and(wrapper -> wrapper.ge(ProcessONDetail::getProcessONDetailUpdateDate, "2025-04-10 00:00:00")
                        .or()
                        .ge(ProcessONDetail::getProcessONDetailCreatDate,"2025-04-10 00:00:00"))//
                .eq(ProcessONDetail::getProcessONDetailType,2)//回收
                .eq(ProcessONDetail::getProcessONDetailReceiptWay,2)//扫码录入
                .like(ProcessONDetail::getProcessONDetailCode,"PCNR");*/
        List<ProcessONDetail> processONDetails = processONDetailMapper.selectList(processONDetailLambdaQueryWrapper);

        Set<String> processONDetailCodeSet = new HashSet<>();
        for (ProcessONDetail processONDetail : processONDetails) {
            String processONDetailCode = processONDetail.getProcessONDetailCode();
            processONDetailCodeSet.add(processONDetailCode);
        }

        for (String processONDetailCode : processONDetailCodeSet) {
            Map formData = new HashMap();

            //基础信息
            Map base = processMapper.selectOnBaseInfo(processONDetailCode);
            formData.put("dateField_m8pi90ec",((Date)base.get("ProcessONDetailDate")).getTime());//单据日期
            formData.put("textField_m99n1t8f",base.get("ProcessONDetailCode"));//回收单号
            formData.put("textField_m8pkxdg5",base.get("WPSProcStepName"));//工序
            formData.put("textField_m8pi90ex",base.get("ClientName"));//加工厂

            //关联明细
            List<Map> details = new ArrayList<>();
            List<Map> detailList = processMapper.selectOnDetails(processONDetailCode);
            int sumQty = 0;
            double sumWeight = 0;
            for (Map detail : detailList) {
                Map map= new HashMap();

                map.put("textField_m8pkxdf6",detail.get("GoodsCode"));//款号
                map.put("textField_m99n1t8d",detail.get("GoodsName"));//款名
                map.put("textField_m99n1t8e",detail.get("GoodsPartsName"));//部件
                map.put("textField_m8pkxdfa",detail.get("ColorName"));//颜色
                map.put("textField_m8pkxdfb",detail.get("SizeName"));//尺码
                map.put("numberField_m99n1t88",detail.get("ProcessONDetailQty"));//件数
                map.put("numberField_m99n1t89",detail.get("ProcessONDetailWeight"));//重量
                map.put("textField_m99n1t8a",detail.get("ProcessCode"));//外发单号
                map.put("textField_m99n1t8b",detail.get("ProcessItemReferBillCode"));//毛衫加工单

                sumQty += ((BigDecimal) detail.get("ProcessONDetailQty")).intValue();
                sumWeight += ((BigDecimal) detail.get("ProcessONDetailWeight")).doubleValue();

                details.add(map);
            }

            formData.put("tableField_m8pkxdfh",details);
            formData.put("numberField_m8pkxdgc",sumQty);//件数合计
            formData.put("numberField_m8pkxdgd",sumWeight);//重量合计

            //款号汇总
            //将details根据款号、款名、颜色、尺码进行分组，计算总件数、总数量
            List<Map<String, Object>> summaryList = details.stream()
                    .collect(Collectors.groupingBy(
                            detail -> {
                                // 使用款号、款名、颜色、尺码作为分组键
                                return detail.get("textField_m8pkxdf6") + "-" +
                                        detail.get("textField_m99n1t8d") + "-" +
                                        detail.get("textField_m8pkxdfa") + "-" +
                                        detail.get("textField_m8pkxdfb");
                            }
                    ))
                    .entrySet().stream()
                    .map(entry -> {
                        Map<String, Object> groupSummary = new HashMap<>();
                        List<Map> groupDetails = entry.getValue();
                        int totalQty = groupDetails.stream()
                                .mapToInt(detail -> ((BigDecimal) detail.get("numberField_m99n1t88")).intValue())
                                .sum();
                        double totalWeight = groupDetails.stream()
                                .mapToDouble(detail -> ((BigDecimal) detail.get("numberField_m99n1t89")).doubleValue())
                                .sum();

                        // 设置汇总信息
                        groupSummary.put("textField_m99n1t87", entry.getKey().split("-")[0]); //款号
                        groupSummary.put("textField_m99n1t8c", entry.getKey().split("-")[1]); //款名
                        groupSummary.put("textField_m8pkxdfl", entry.getKey().split("-")[2]); //颜色
                        groupSummary.put("textField_m8pkxdfm", entry.getKey().split("-")[3]); //尺码
                        groupSummary.put("numberField_m8pkxdfn", totalQty); //总件数
                        groupSummary.put("numberField_m8pkxdfw", totalWeight); //总重量

                        return groupSummary;
                    })
                    .collect(Collectors.toList());

            formData.put("tableField_m8pkxdfj",summaryList);

            //条码明细
            List<Map> cardBarDetails = new ArrayList<>();
            List<Map> cardBarDetailList = processMapper.selectOnCardBarDetails2(processONDetailCode);
            for (Map cardBarDetail : cardBarDetailList) {
                Map map= new HashMap();
                map.put("textField_m99n1t8p",cardBarDetail.get("ProceCardBarCode"));//条码

                cardBarDetails.add(map);
            }
            formData.put("tableField_m99n1t8k",cardBarDetails);

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-B6D30D0FD0064383BBD45DD64078B31E3KQK")
                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_m99n1t8f",processONDetailCode,"eq"))))
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.upsert);

        }

        return McR.success();
    }
}
