package com.zfire.jiasm.syncdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zfire.jiasm.syncdata.base.BaseService;
import com.zfire.jiasm.syncdata.constant.GDAppointStatusEnum;
import com.zfire.jiasm.syncdata.constant.GDOrderStatusEnum;
import com.zfire.jiasm.syncdata.constant.OrderTypeEnum;
import com.zfire.jiasm.syncdata.dao.mapper.*;
import com.zfire.jiasm.syncdata.data.Token;
import com.zfire.jiasm.syncdata.gree.GreeLogic;
import com.zfire.jiasm.syncdata.helper.GreeFileResponseHelper;
import com.zfire.jiasm.syncdata.helper.GreeFileSaveHelper;
import com.zfire.jiasm.syncdata.http.PostObjectSample;
import com.zfire.jiasm.syncdata.parameter.InstallCJDetailFile;
import com.zfire.jiasm.syncdata.parameter.OrderPar;
import com.zfire.jiasm.syncdata.parameter.ReAppointment;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.response.ResultData;
import com.zfire.jiasm.syncdata.response.WebsitSH;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.service.RepairProduceDataUploadService;
import com.zfire.jiasm.syncdata.utils.*;
import com.zfire.jiasm.syncdata.utils.oss.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class RepairProduceDataUploadServiceImpl implements RepairProduceDataUploadService {
    @Value("${baseurl4pgid}")
    private String baseurl4pgid;
    @Value("${baseurl}")
    private String baseurl;



    @Autowired
    private TokenCenter tokenCenter;
    @Resource
    BaseService baseService;
    @Resource
    OutJiasmToGreeUploadTaskTypeService outJiasmToGreeUploadTaskTypeService;
    @Resource
    OutJiasmToGreeUploadTaskListService outJiasmToGreeUploadTaskListService;
    @Resource
    OrderBaseService orderBaseService;
    @Resource
    OrderProductService orderProductService;
    @Resource
    OrderRepairOperatingLogService orderRepairOperatingLogService;
    @Resource
    FaGreeSmsService faGreeSmsService;
    @Resource
    GDOrderBaseMapper gdOrderBaseMapper;
    @Resource
    OrderRepairService orderRepairService;
    @Resource
    PublicService publicService;
    @Resource
    BrandLbsRelateService brandLbsRelateService;
    @Resource
    StreetService streetService;
    @Resource
    AreaService areaService;
    @Resource
    ItfTblAssignUploadService itfTblAssignUploadService;
    @Resource
    ItfMessagehuifangentityService itfMessagehuifangentityService;
    @Resource
    FileOrderDetailMapper fileOrderDetailMapper;
    @Resource
    OrderRepairDetailService orderRepairDetailService;
    @Resource
    DetailOrderRepairMapper detailOrderRepairMapper;
    @Resource
    ItfTblWxjsJyktUploadService itfTblWxjsJyktUploadService;
    @Resource
    OrderRepairDetailReasonService orderRepairDetailReasonService;
    @Resource
    ItfTblWxjsXxyyJyktUploadService itfTblWxjsXxyyJyktUploadService;
    @Resource
    OrderDetailFileService orderDetailFileService;
    @Resource
    ItfTblWxjsFjJyktUploadService itfTblWxjsFjJyktUploadService;
    @Resource
    OrderRepairDetailItemService orderRepairDetailItemService;
    @Resource
    ReasonOrderRepairDetailMapper reasonOrderRepairDetailMapper;
    @Resource
    ItfTblWxjsWxxmJyktUploadService itfTblWxjsWxxmJyktUploadService;
    @Resource
    ItfTblAssignFeeUploadService itfTblAssignFeeUploadService;
    @Resource
    ItfTblWxjsPjmxJyktUploadService itfTblWxjsPjmxJyktUploadService;
    @Resource
    WxjsJyktUploadMapper wxjsJyktUploadMapper;
    @Resource
    ItfTblwxjsjyktService itfTblwxjsjyktService;
    @Resource
    ItfTblwxjsxxyyjyktService itfTblwxjsxxyyjyktService;
    @Resource
    ItfTblwxjswxxmjyktService itfTblwxjswxxmjyktService;
    @Resource
    ItfTblwxjspjmxjyktService itfTblwxjspjmxjyktService;
    @Resource
    ItfTblwxjsfjjyktService itfTblwxjsfjjyktService;
    @Resource
    GetOrderProductMapper getOrderProductMapper;
    @Resource
    ItfTblAssignMxUploadService itfTblAssignMxUploadService;
    @Resource
    RepairLogMapper repairLogMapper;
    @Resource
    ItfTblAssignFkmxUploadService itfTblAssignFkmxUploadService;
    @Resource
    ItfTblAssignAppointmentUploadService itfTblAssignAppointmentUploadService;
    @Resource
    FaGreeSmsWorkerService faGreeSmsWorkerService;
    @Resource
    OrderReAppointmentService orderReAppointmentService;
    @Resource
    BrandWebsitService brandWebsitService;
    @Resource
    ReAppointmentOrderMapper reAppointmentOrderMapper;
    @Resource
    OSSUtil ossUtil;
    @Resource
    GreeLogic greeLogic;
    @Resource
    RepairBugService repairBugService;



    @Override
    public void processRepairProduceDataUpload() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 提取品牌信息
        Brand brand = baseService.getBrand();
        if (brand == null) {
            return;
        }

        // 提取品牌商对应的需求小类信息
        Map<String, List<SysDictRef>> sysDictRefXLMapXq = publicService.getListMapXqtoPP(brand);

        log.info("开始生成需要上传的维修工单数据: \uF0B7{}",sdf.format(new Date()));

        Token token = tokenCenter.getCurrentToken();

        // 1:类型定义表中提取数据
        List<OutJiasmToGreeUploadTaskType> taskTypes = outJiasmToGreeUploadTaskTypeService.lambdaQuery()
                .orderByAsc(OutJiasmToGreeUploadTaskType::getId).list();
        try{
            for (OutJiasmToGreeUploadTaskType taskType:taskTypes){
                // 任务类型
                int uploadTaskType = taskType.getUploadTaskType();
                // 需从格力系统获取的列名 taskType.getGreekeyName();
                // 获取列名对应的表名 taskType.getSrcTabNameForGreekey();
                // 列名(greekeyName)的获取方式 taskType.getGreekeyGetMode();

                // 2：数据上传任务清单表中提取对应任务类型的需要上传的数据
                List<OutJiasmToGreeUploadTaskList> result = outJiasmToGreeUploadTaskListService.lambdaQuery()
                        .eq(OutJiasmToGreeUploadTaskList::getSynStatus,0)
                        .eq(OutJiasmToGreeUploadTaskList::getUploadTaskType,uploadTaskType)
                        // .eq(OutJiasmToGreeUploadTaskList::getSynReqId,2812L)// 测试用
                        .orderByAsc(OutJiasmToGreeUploadTaskList::getSynReqId).list();
                // 相同任务类型的数据逐个处理
                for (OutJiasmToGreeUploadTaskList row: result){
                    Long taskId = row.getSynReqId();
                    try {
                        OutJiasmToGreeUploadTaskList sourceData = outJiasmToGreeUploadTaskListService.lambdaQuery()
                                .eq(OutJiasmToGreeUploadTaskList::getSynReqId,taskId)
                                .last("limit 1")
                                .one();
                        if (!sourceData.getSynStatus().equals(0)){
                            continue;
                        }

                        String newDykh = "";
                        // 需从格力总部获取相对列值  维修工单的pgid从格力总部获取
                        if (taskType.getGreekeyName() != null && taskType.getGreekeyName().trim().length() > 0 &&
                                taskType.getSrcTabNameForGreekey() != null && taskType.getSrcTabNameForGreekey().trim().length() > 0) {
                            newDykh = getpgid(token, uploadTaskType, taskType.getSrcTabNameForGreekey(), taskType.getGreekeyGetMode(), row, newDykh);
                        }

                        // 过程名称，同步任务表中的id,同步任务表中的工单号，同步任务表中的需同步的表的主键，newDykh(pgid-主键)，true
                        // 66 - TL_PrePareSynDataby_fa_order_repair_test
                        // 维修工单 基础表数据同步
                        if (row.getTableName().equals("order_base") &&
                                row.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_REPAIR.getCode())){

                            // 提取工单数据
                            OrderBase orderBase = orderBaseService.lambdaQuery()
                                    .eq(OrderBase::getId, sourceData.getOrderNo()).one();
                            if (orderBase !=null && orderBase.getUploadFlag()){
                                // 增加初始化处理，不需要事务
                                if (!dataInit(sourceData, newDykh, orderBase)){
                                    continue;
                                }
                            }
                            if (uploadTaskType==66){
                                generateItfTblAssignUpload(brand, sysDictRefXLMapXq, taskId,
                                        sourceData, newDykh, row);
                            } else if (uploadTaskType==661){
                                // 661 - TL_PrePareSynDataby_assign_cj
                                generateItfTblAssignUploadTow(brand, row, sourceData, newDykh);
                            }
                        } else if (row.getTableName().equals("order_product") &&
                                row.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_REPAIR.getCode())){
                            // 生成维修单明细数据 TL_PrePareSynDataby_fa_order_repair_product    68
                            generateOrderProduct(brand, uploadTaskType, row, sourceData, newDykh);
                        } else if (row.getTableName().equals("order_repair_operating_log")){
                            // 生成维修单过程反馈数据 TL_PrePareSynDataby_fa_order_repair_operating_log   67
                            // 原预约改约在这里处理 现移到下面 order_re_appointment
                            generateItfTblAssignFkmxUpload(brand, uploadTaskType,row, taskId, sourceData, newDykh);
                        } else if (row.getTableName().equals("order_re_appointment") &&
                                row.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_REPAIR.getCode())){
                            // 安装工单用户改约明细 与操作明细最好放在一起，因表设计分开，所以独立开来处理
                            getAppointment(row);
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        String msg ="开始预处理生成需要上传的维修工单数据出错: "+taskId;
                        log.info(msg);
                        if (ex.getMessage() !=null){
                            msg = ex.getMessage();
                        }
                        publicService.updateUploadTaskLisError(row,msg);
                    }
                    // 修改 itf_fa_to_gree_upload_task_list
                }
            }
            log.info("生成需要上传的维修工单数据结束: \uF0B7{}",sdf.format(new Date()));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("开始预处理生成需要上传的维修工单数据出错");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void generateItfTblAssignFkmxUpload(Brand brand, int uploadTaskType, OutJiasmToGreeUploadTaskList row, Long taskId,
                                               OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        // 提取工单数据
        OrderBase orderBase = orderBaseService.lambdaQuery()
                .eq(OrderBase::getId, sourceData.getOrderNo())
                .last("limit 1")
                .one();

        if (orderBase !=null && orderBase.getUploadFlag()){
            if (StringUtils.isEmpty(orderBase.getPgid())){
                publicService.updateUploadTaskLisError(sourceData,"order_base表pgid为空暂不同步");
                return;
            }

            // 修改日志表pgid   getpgid方法已处理
            // 修改当前ID的 fkid该值通过接口获取的
            upfkid(sourceData,newDykh);
            // 修改日志表内部序列outid + 自生成 fkmxguid
            upOrderRepairOperatingLogOutId(orderBase);
            // 生成维修单过程反馈数据
            getItfTblAssignFkmxUpload(brand, taskId, sourceData,orderBase);
            // 改约或者预约时增加写 itf_tbl_assign_appointment_upload 这里不再处理移动外面单独处理
            // getItfTblAssignAppointmentUpload(sourceData);
        }

        // 修改数据上传任务表中的状态   这里固定值 68
        publicService.updateUploadTaskListStatus(row.getOrderNo(), row.getSynReqId(),1, uploadTaskType);
    }

    @Transactional(rollbackFor = Exception.class)
    public  void getAppointment(OutJiasmToGreeUploadTaskList ojtutl) {
        OrderBase orderBase = orderBaseService.lambdaQuery()
                .eq(OrderBase::getId, ojtutl.getOrderNo())
                .last("limit 1")
                .one();

        // 待审批改约时不同步处理
        OrderReAppointment itau = orderReAppointmentService.lambdaQuery()
                .eq(OrderReAppointment::getId,ojtutl.getId())
                .last("limit 1").one();

        if (orderBase !=null  && orderBase.getUploadFlag() && itau.getExamineStatus().equals("OK")){
            // 修改内部序列outid
            upOutId(orderBase);
            // 无pgid时先不同步待工单主表同步后再同步
            if (StringUtils.isEmpty(orderBase.getPgid())){
                return;
            }
            ReAppointment request = new ReAppointment();
            request.setOrderNo(ojtutl.getOrderNo());
            request.setId(ojtutl.getId());
            ItfTblAssignAppointmentUpload add = reAppointmentOrderMapper.getAppointment(request);
            itfTblAssignAppointmentUploadService.save(add);
        }

        // 修改数据上传任务表中的状态 单号,id,同步状态,类型
        publicService.updateUploadTaskListStatus(ojtutl.getOrderNo(), ojtutl.getSynReqId(),1, ojtutl.getUploadTaskType());
    }

    public void upOutId(OrderBase orderBase) {
        List<OrderReAppointment> upList = new ArrayList<>();

        List<OrderReAppointment> detaillisto = orderReAppointmentService.lambdaQuery()
                .eq(OrderReAppointment::getOrderBaseId, orderBase.getId())
                .eq(OrderReAppointment::getOutId, 0).list();
        if (CollectionUtils.isEmpty(detaillisto)){
            return;
        }

        List<OrderReAppointment> detaillist = orderReAppointmentService.lambdaQuery()
                .eq(OrderReAppointment::getOrderBaseId, orderBase.getId())
                .ne(OrderReAppointment::getOutId, 0)
                .orderByAsc(OrderReAppointment::getCreateTime).list();

        int outId=0;
        if (CollectionUtils.isNotEmpty(detaillist)){
            // 找出最大的序 默认值为0
            for (OrderReAppointment item:detaillist){
                if (outId<item.getOutId()){
                    outId = item.getOutId();
                }
            }
        }

        for (OrderReAppointment ite:detaillist){
            if (ite.getOutId() == 0){
                outId++;
                OrderReAppointment n = new OrderReAppointment();
                n.setId(ite.getId());
                n.setOutId(outId);
                n.setUpdateTime(new Date());
                if (StringUtils.isNotEmpty(orderBase.getPgid())){
                    n.setPgid(orderBase.getPgid());
                }
                upList.add(n);
            }
        }
        // 修改序
        if (upList.size()>0){
            orderReAppointmentService.updateBatchById(upList);
            upList.clear();
        }
    }

    public void upOrderRepairOperatingLogOutId(OrderBase orderBase) {
        List<OrderRepairOperatingLog> upList = new ArrayList<>();
        List<OrderRepairOperatingLog> upfkmxList = new ArrayList<>();

        List<OrderRepairOperatingLog> detaillist = orderRepairOperatingLogService.lambdaQuery()
                .eq(OrderRepairOperatingLog::getOrderBaseId, orderBase.getId())
                .orderByAsc(OrderRepairOperatingLog::getCreateTime).list();
        // 找出最大的序 默认值为0
        int outId=0;
        if (detaillist!=null && detaillist.size()>0){
            for (OrderRepairOperatingLog item:detaillist){
                if (outId<item.getOutId()){
                    outId = item.getOutId();
                }
                if (StringUtils.isEmpty(item.getFkmxguid())){
                    OrderRepairOperatingLog n = new OrderRepairOperatingLog();
                    n.setId(item.getId());
                    n.setFkmxguid(IdWorker.getIdStr());
                    n.setUpdateTime(new Date());
                    upfkmxList.add(n);
                }
            }
            for (OrderRepairOperatingLog ite:detaillist){
                if (ite.getOutId() == 0){
                    outId++;
                    OrderRepairOperatingLog n = new OrderRepairOperatingLog();
                    n.setId(ite.getId());
                    n.setOutId(outId);
                    n.setUpdateTime(new Date());
                    upList.add(n);
                }
            }
            // 修改序
            if (upList.size()>0){
                orderRepairOperatingLogService.updateBatchById(upList);
                upList.clear();
            }
            detaillist.clear();
            if (upfkmxList.size()>0){
                orderRepairOperatingLogService.updateBatchById(upfkmxList);
                upfkmxList.clear();
            }
        }
    }

    public void upfkid(OutJiasmToGreeUploadTaskList sourceData,String newDykh) {
        OrderPar request = new OrderPar();
        request.setId(sourceData.getId());
        request.setOrderNo(sourceData.getOrderNo());
        request.setFkid(newDykh);
        repairLogMapper.upRepairLogFkid(request);
    }

    public void getItfTblAssignAppointmentUpload(OutJiasmToGreeUploadTaskList sourceData) {
        OrderPar req = new OrderPar();
        req.setId(sourceData.getId());
        req.setOrderNo(sourceData.getOrderNo());
        ItfTblAssignAppointmentUpload app = repairLogMapper.getItfTblAssignAppointmentUpload(req);
        if (app != null){
            itfTblAssignAppointmentUploadService.save(app);
        }
    }

    @NotNull
    public void getItfTblAssignFkmxUpload(Brand brand, Long taskId, OutJiasmToGreeUploadTaskList sourceData, OrderBase orderBase) {
        OrderPar req = new OrderPar();
        WebsitSH websitSH = new WebsitSH();
        req.setId(sourceData.getId());
        req.setOrderNo(sourceData.getOrderNo());
        req.setBrandId(brand.getBrandId());
        ItfTblAssignFkmxUpload fkmx = repairLogMapper.getItfTblAssignFkmxUpload(req);
        // 售后网点处理
        websitSH = publicService.ptshwdToshshwd(fkmx.getFkwdno(), orderBase.getMainId());
        fkmx.setFkwdno(websitSH.getWdId());
        fkmx.setFkwdmc(websitSH.getWdmc());


        fkmx.setUploadTaskSynReqId(taskId);
        fkmx.setWorkerOrderNo(sourceData.getOrderNo());
        itfTblAssignFkmxUploadService.save(fkmx);
    }

    /**
     * 过程名称，out_jiasm_to_gree_upload_task_list同步任务表中的id,
     * 同步任务表中的工单号，需同步的表的主键，newDykh(OrderProduct.pgmxid品牌方主键)，true
     * TL_PrePareSynDataby_fa_order_repair_product
     * @param brand
     * @param uploadTaskType
     * @param row
     * @param sourceData
     */
    @Transactional(rollbackFor = Exception.class)
    public void generateOrderProduct(Brand brand, int uploadTaskType, OutJiasmToGreeUploadTaskList row,
                                     OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        // 提取工单数据
        OrderProduct op = orderProductService.lambdaQuery()
                .eq(OrderProduct::getId,row.getId())
                .last("limit 1")
                .one();
        if (op == null){
            publicService.updateUploadTaskLisError(sourceData,"找不到对应记录:"+row.getId());
            return;
        }
        if (StringUtils.isEmpty(op.getPgid())){
            publicService.updateUploadTaskLisError(sourceData,"order_product表pgid为空不同步");
            return;
        }

        // order_product.pgmxid是直接在表内取出来的 无值的话调接口获取
        // 修改对应ID的pgmxid
        upPgmxid(row, sourceData, newDykh);

        // 修改内部序
        upOrderProductOutId(sourceData);

        // 生成数据
        getItfTblAssignMxUpload(brand, sourceData);

        // 修改数据上传任务表中的状态   这里固定值 68
        publicService.updateUploadTaskListStatus(row.getOrderNo(), row.getSynReqId(),1, uploadTaskType);
    }

    public void upOrderProductOutId(OutJiasmToGreeUploadTaskList sourceData) {
        List<OrderProduct> upList = new ArrayList<>();
        // 查看是否有需要修改的数据
        List<OrderProduct> ops = orderProductService.lambdaQuery()
                .eq(OrderProduct::getOrderBaseId, sourceData.getOrderNo())
                .eq(OrderProduct::getOutId, 0)
                .list();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(ops)){
            return;
        }

        List<OrderProduct> oplist = orderProductService.lambdaQuery()
                .eq(OrderProduct::getOrderBaseId, sourceData.getOrderNo())
                .ne(OrderProduct::getOutId, 0)
                .orderByAsc(OrderProduct::getCreateTime).list();
        // 找出最大的序 默认值为0
        int outId=0;
        if (oplist!=null && oplist.size()>0){
            for (OrderProduct item:oplist){
                if (outId<item.getOutId()){
                    outId = item.getOutId();
                }
            }
        }

        for (OrderProduct ite:ops){
            outId++;
            OrderProduct n = new OrderProduct();
            MyBeanUtils.copyProperties(ite,n);
            n.setOutId(outId);
            n.setUpdateTime(new Date());
            upList.add(n);
        }
        // 修改序
        if (upList.size()>0){
            orderProductService.updateBatchById(upList);
            upList.clear();
        }
        oplist.clear();
    }

    public void getItfTblAssignMxUpload(Brand brand, OutJiasmToGreeUploadTaskList sourceData) {
        OrderPar request = new OrderPar();
        WebsitSH websitSH = new WebsitSH();
        OrderBase orderBase = orderBaseService.lambdaQuery()
                .eq(OrderBase::getId,sourceData.getOrderNo())
                .last("limit 1")
                .one();

        request.setBrandId(brand.getBrandId());
        request.setId(sourceData.getId());
        request.setOrderNo(sourceData.getOrderNo());
        ItfTblAssignMxUpload mx = getOrderProductMapper.getItfTblAssignMxUpload(request);
        // 维修工单的jxid可以直接给0值 上面查询语句中直接赋值即可
        // 这里故障代码单独处理
        setMxGzxxid(sourceData, mx);

        mx.setWorkerOrderNo(sourceData.getOrderNo());
        // 销售单位处理
        websitSH = publicService.ptxswdToshxswd(mx.getXsdw(),orderBase.getMainId());
        mx.setXsdw(websitSH.getWdId());
        // 服务单位处理 售后网点处理
        websitSH = publicService.ptshwdToshshwd(orderBase.getReceWebsitId(),orderBase.getMainId());
        mx.setFwdw(websitSH.getWdId());
        mx.setCzwd(websitSH.getWdId());


        itfTblAssignMxUploadService.save(mx);
    }

    private void setMxGzxxid(OutJiasmToGreeUploadTaskList sourceData, ItfTblAssignMxUpload mx) {
        RepairBug repairBug =null;
        OrderProduct orderProduct = orderProductService.lambdaQuery()
        .eq(OrderProduct::getId, sourceData.getId()).one();
        // 大小类一起查询
        if (StringUtils.isNotEmpty(orderProduct.getSmallId())){
            repairBug = repairBugService.lambdaQuery()
                    .eq(RepairBug::getMainId,orderProduct.getMainId())
                    .eq(RepairBug::getSmallId,orderProduct.getSmallId())
                    .eq(RepairBug::getBugObj,orderProduct.getFaultReason())
                    .eq(RepairBug::getStatus,"ON")
                    .last("limit 1").one();
            if (repairBug!=null){
                mx.setGzxxid(repairBug.getGzid());
            }
        }
        // 大类查询 大类一定有
        if (repairBug == null){
            repairBug = repairBugService.lambdaQuery()
                    .eq(RepairBug::getMainId,orderProduct.getMainId())
                    .eq(RepairBug::getBugObj,orderProduct.getFaultReason())
                    .eq(RepairBug::getStatus,"ON")
                    .last("limit 1").one();
            if (repairBug!=null){
                mx.setGzxxid(repairBug.getGzid());
            }
        }
    }

    public void upPgmxid(OutJiasmToGreeUploadTaskList row, OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        OrderPar orderPar = new OrderPar();
        orderPar.setOrderNo(sourceData.getOrderNo());
        orderPar.setPgid(newDykh);
        orderPar.setId(row.getId());
        getOrderProductMapper.upPgmxid(orderPar);

        /*List<OrderProduct> opuplist = new ArrayList<>();
        List<OrderProduct> oldoplist = new ArrayList<>();
        oldoplist = orderProductService.lambdaQuery()
                .eq(OrderProduct::getOrderBaseId,sourceData.getOrderNo()).list();
        for (OrderProduct item:oldoplist){
            if (StringUtils.isEmpty(item.getPgmxid())){
                item.setPgmxid(publicService.getUUID());
                opuplist.add(item);
            }
        }
        if (opuplist.size()>0){
            orderProductService.updateBatchById(opuplist);
            opuplist.clear();
        }*/
    }

    @Transactional(rollbackFor = Exception.class)
    public void generateItfTblAssignUploadTow(Brand brand, OutJiasmToGreeUploadTaskList row, OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        // 过程名称，同步任务表中的id,同步任务表中的工单号，同步任务表中的需同步的表的主键，newDykh(pgid-主键)，true
        // 同步任务表中的id,同步任务表中的工单号,同步任务表中的需同步的表的主键,newDykh(pgid-主键)
        // 661 - TL_PrePareSynDataby_assign_cj

        // 提取工单数据
        OrderBase orderBase = orderBaseService.lambdaQuery()
                .eq(OrderBase::getId, sourceData.getOrderNo()).one();
        if (orderBase !=null && orderBase.getUploadFlag()){
            // 删除工单更新被忽略
            // 修改工单的pgid,pgguid
            uppare(newDykh, orderBase);

            // 如果无附件则忽略结算数据上传处理
            if (checkFile(row, orderBase)) {
                return ;
            }
            // 生成数据
            if (generateData(brand, orderBase)) {
                return ;
            }
        }

        // 修改数据上传任务表中的状态   这里固定值 661
        publicService.updateUploadTaskListStatus(row.getOrderNo(), row.getSynReqId(),1,661);
        return ;
    }

    public boolean generateData(Brand brand, OrderBase orderBase) {
        // 工单，采集表id,uuid, TL_fa_order_repair_detail_js
        // j_syn_task_no 统一uuid
        String j_syn_task_no = publicService.getUUID();
        // 提取所有采集数据
        List<OrderRepairDetail> ords = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, orderBase.getId()).list();
        for (OrderRepairDetail item :ords){
            // 状态 0=未采集,1=已采集,2=作废,3=临时保存
            if (item.getStatus().equals(0)){
                // 有一个待采全部不再处理
                return true;
            }
            // 生成维修结算数据 itf_tbl_wxjs_jykt_upload
            Long synReqId = generateJyktData(brand, orderBase, item);
            // 生成维修结算2表数据
            generateJyktDataTow(orderBase, item, synReqId,j_syn_task_no);
            // 生成维修现象+维修现象2表数据 TL_fa_order_repair_fault_info_js
            generateItfTblwxjsxxyyjyktAndTow(j_syn_task_no, item);
            //  生成附件数据+附件数据2表数据 TL_fa_order_repair_annex_js
            if (generateInstallCJDetailFileAndTow(orderBase, j_syn_task_no, item)) {
                return true;
            }
            // 生成维修项目现象、维修项目现象2数据 TL_fa_order_repair_data_info_js
            if (generateItfTblWxjsWxxmJyktUploadAndTow(orderBase, j_syn_task_no, item)){
                return true;
            }
            // 生成配件、配件2表数据 TL_fa_order_repair_part_info_js
            generateItfTblWxjsPjmxJyktUploadAndTow(orderBase, j_syn_task_no, item);
        }
        return false;
    }

    public boolean checkFile(OutJiasmToGreeUploadTaskList row, OrderBase orderBase) {
        // 提取附件数据
        List<OrderDetailFile> files = orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId, orderBase.getId()).list();
        if (files !=null && files.size()>0){
            // 检查附件的完整性 不完整取消上传
            if (checkFiles(orderBase)) {
                // 结束
                return true;
            }
        } else {
            // 修改数据上传任务表中的状态   这里固定值 661
            publicService.updateUploadTaskListStatus(row.getOrderNo(), row.getSynReqId(),1,661);
            return true;
        }
        return false;
    }

    public void uppare(String newDykh, OrderBase orderBase) {
        if (StringUtils.isEmpty(orderBase.getPgid()) || StringUtils.isEmpty(orderBase.getPgguid())){
            OrderBase up = new OrderBase();
            up.setId(orderBase.getId());
            if (StringUtils.isEmpty(orderBase.getPgid())){
                up.setPgid(newDykh);
                orderBase.setPgguid(newDykh);
            }
            if (StringUtils.isEmpty(orderBase.getPgguid())){
                up.setPgguid(publicService.getUUID());
                orderBase.setPgguid(up.getPgguid());
            }
            orderBaseService.updateById(up);
        }
    }

    public void generateItfTblWxjsPjmxJyktUploadAndTow(OrderBase orderBase, String j_syn_task_no, OrderRepairDetail item) {
        // 提取配置件数据
        List<OrderRepairDetailReason> reasons =  orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderRepairDetailId, item.getId()).list();
        for (OrderRepairDetailReason rs:reasons){
            /*if (StringUtils.isEmpty(rs.getNewPartNo())){
                continue;
            }*/
            // 生成配件数据
            ItfTblWxjsPjmxJyktUpload pj = generateItfTblWxjsPjmxJyktUpload(orderBase, rs);
            // 配件2表数据
            generateItfTblwxjspjmxjykt(j_syn_task_no, pj);
        }
    }

    @NotNull
    public ItfTblWxjsPjmxJyktUpload generateItfTblWxjsPjmxJyktUpload(OrderBase orderBase, OrderRepairDetailReason rs) {
        OrderPar request = new OrderPar();
        request.setId(rs.getId());
        ItfTblWxjsPjmxJyktUpload pj = reasonOrderRepairDetailMapper.getItfTblWxjsPjmxJyktUpload(request);
        pj.setWorkerOrderNo(orderBase.getId());
        pj.setSynStatus(44);
        itfTblWxjsPjmxJyktUploadService.save(pj);
        return pj;
    }

    public void generateItfTblwxjspjmxjykt(String j_syn_task_no, ItfTblWxjsPjmxJyktUpload pj) {
        ItfTblwxjspjmxjykt pjt = new ItfTblwxjspjmxjykt();
        MyBeanUtils.copyProperties(pj,pjt);
        pjt.setSynTaskNo(j_syn_task_no);
        pjt.setId(pj.getWxjsmxguid());
        itfTblwxjspjmxjyktService.save(pjt);
    }

    public boolean generateItfTblWxjsWxxmJyktUploadAndTowBak(OrderBase orderBase, String j_syn_task_no, OrderRepairDetail item) {
        // 提取维修项目数据
        List<OrderRepairDetailItem> ordList =  orderRepairDetailItemService.lambdaQuery()
                .eq(OrderRepairDetailItem::getOrderRepairDetailId, item.getId()).list();
        for (OrderRepairDetailItem ord: ordList){
            // 确保采集现象表数据存在数据
            OrderRepairDetailReason ordr =  orderRepairDetailReasonService.lambdaQuery()
                    .eq(OrderRepairDetailReason::getOrderRepairDetailId, ord.getOrderRepairDetailId())
                    .one();
            if (ordr == null){
                // 有一个有问题全部不处理
                return true;
            }
            // 修改wxjsguid与明细表数据相同
            if (StringUtils.isEmpty(ord.getWxjsguid())){
                OrderRepairDetailItem up = new OrderRepairDetailItem();
                up.setId(ord.getId());
                up.setWxjsguid(ordr.getWxjsguid());
                ord.setWxjsguid(ordr.getWxjsguid());
            }
            // 生成维修项目现象数据
            ItfTblWxjsWxxmJyktUpload wxxm = generateItfTblWxjsWxxmJyktUpload(orderBase, ord.getId());
            // 生成维修项目现象2表数据
            generateItfTblwxjswxxmjykt(j_syn_task_no, wxxm);
        }
        return false;
    }

    public boolean generateItfTblWxjsWxxmJyktUploadAndTow(OrderBase orderBase, String j_syn_task_no, OrderRepairDetail item) {
        // 提取维修项目数据
        List<OrderRepairDetailReason> ordrs =  orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderBaseId, orderBase.getId()).list();

        for (OrderRepairDetailReason i: ordrs){
            // 生成维修项目现象数据
            ItfTblWxjsWxxmJyktUpload wxxm = generateItfTblWxjsWxxmJyktUpload(orderBase, i.getId());
            // 生成维修项目现象2表数据
            generateItfTblwxjswxxmjykt(j_syn_task_no, wxxm);
        }
        return false;
    }

    @NotNull
    public ItfTblWxjsWxxmJyktUpload generateItfTblWxjsWxxmJyktUpload(OrderBase orderBase, String id) {
        OrderPar request = new OrderPar();
        request.setId(id);
        ItfTblWxjsWxxmJyktUpload wxxm = reasonOrderRepairDetailMapper.getItfTblWxjsWxxmJyktUpload(request);
        wxxm.setWorkerOrderNo(orderBase.getId());
        wxxm.setSynStatus(44);
        itfTblWxjsWxxmJyktUploadService.save(wxxm);
        return wxxm;
    }

    public void generateItfTblwxjswxxmjykt(String j_syn_task_no, ItfTblWxjsWxxmJyktUpload wxxm) {
        // 查看维修结算2表数据有无插入成功
        ItfTblwxjsjykt jskt = itfTblwxjsjyktService.lambdaQuery()
                .eq(ItfTblwxjsjykt::getSynTaskNo, j_syn_task_no).one();
        if (jskt !=null){
            ItfTblwxjswxxmjykt xmt = new ItfTblwxjswxxmjykt();
            MyBeanUtils.copyProperties(wxxm,xmt);
            xmt.setSynTaskNo(j_syn_task_no);
            xmt.setId(wxxm.getWxjsguid());
            itfTblwxjswxxmjyktService.save(xmt);
        }
    }

    public boolean generateInstallCJDetailFileAndTow(OrderBase orderBase, String j_syn_task_no, OrderRepairDetail item) {
        // 提取数据采集附件数据
        List<OrderDetailFile> odfs =  orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId, orderBase.getId())
                .eq(OrderDetailFile::getOrderDetailId, item.getId()).list();
        for (OrderDetailFile file:odfs){
            // path未准备上传被忽略 有一个有问题全部不处理
            if (StringUtils.isEmpty(file.getFilePath())){
                return true;
            }
            // 品牌方fileindex未获取上传被忽略
            if (StringUtils.isEmpty(file.getBrandFilePath())){
                return true;
            }
           /* // 修改附件的fjguid
            if (StringUtils.isEmpty(file.getFjguid())){
                OrderDetailFile upf = new OrderDetailFile();
                upf.setId(file.getId());
                upf.setFjguid(UUID.randomUUID().toString());
                orderDetailFileService.updateById(upf);
                file.setFjguid(upf.getFjguid());
            }
            // 修改采集明细序号 wxmxguid
            if (StringUtils.isEmpty(file.getPgwcmxid())){
                OrderDetailFile upf = new OrderDetailFile();
                upf.setId(file.getId());
                upf.setPgwcmxid(UUID.randomUUID().toString());
                orderDetailFileService.updateById(upf);
                file.setPgwcmxid(upf.getPgwcmxid());
            }*/
            // 生成附件数据
            ItfTblWxjsFjJyktUpload fj = generateInstallCJDetailFile(orderBase, file);
            // 生成附件2表数据
            generateInstallCJDetailFileTow(j_syn_task_no, fj);
        }
        return false;
    }

    public void generateInstallCJDetailFileTow(String j_syn_task_no, ItfTblWxjsFjJyktUpload fj) {
        ItfTblwxjsfjjykt fjt = new ItfTblwxjsfjjykt();
        MyBeanUtils.copyProperties(fj,fjt);
        fjt.setSynTaskNo(j_syn_task_no);
        fjt.setCreatedBy(fj.getCreatedBy());
        fjt.setCreatedDate(fj.getCreatedDate());
        fjt.setFjIndex(fj.getFjIndex());
        fjt.setId(fj.getFjguid());
        fjt.setLastModifiedBy(fj.getLastModifiedBy());
        fjt.setLastModifiedDate(fj.getLastModifiedDate());
        itfTblwxjsfjjyktService.save(fjt);
    }

    @NotNull
    public ItfTblWxjsFjJyktUpload generateInstallCJDetailFile(OrderBase orderBase, OrderDetailFile file) {
        InstallCJDetailFile request = new InstallCJDetailFile();
        request.setOrderNo(orderBase.getId());
        request.setId(file.getId());
        ItfTblWxjsFjJyktUpload fj = fileOrderDetailMapper.getItfTblWxjsFjJyktUpload(request);
        fj.setFjIndex(fj.getFaOrderRepairAnnexId());
        fj.setSynStatus(44);
        itfTblWxjsFjJyktUploadService.save(fj);
        return fj;
    }

    public void generateItfTblwxjsxxyyjyktAndTow(String j_syn_task_no, OrderRepairDetail item) {
        // 维修数据采集故障现象表
        // 提取维修数据采集故障现象数据  数据采集明细表的所有id
        List<OrderRepairDetailReason> reasons =  orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderRepairDetailId, item.getId()).list();
        for (OrderRepairDetailReason r : reasons){
            // 父级故障现象数据忽略上传
            if (StringUtils.isEmpty(r.getRepairBugParentId()) || StringUtils.isEmpty(r.getNumber())){
                continue;
            }
            // 修改 维修现象主键、维修明细主键
            // upxxyyguid(r);
            // 生成维修现象数据
            ItfTblWxjsXxyyJyktUpload add = generateJyktUT(item, r);
            // 生成维修现象2表数据
            generateItfTblwxjsxxyyjykt(j_syn_task_no, add);
        }
    }

    public void generateItfTblwxjsxxyyjykt(String j_syn_task_no, ItfTblWxjsXxyyJyktUpload add) {
        // 查看维修结算2表数据有无插入成功
        ItfTblwxjsjykt jskt = itfTblwxjsjyktService.lambdaQuery()
                .eq(ItfTblwxjsjykt::getSynTaskNo, j_syn_task_no).one();
        if (jskt !=null){
            ItfTblwxjsxxyyjykt ad = new ItfTblwxjsxxyyjykt();
            ad.setSynTaskNo(j_syn_task_no);
            ad.setWorkerOrderNo(add.getWorkerOrderNo());
            ad.setCjsj(add.getCjsj());
            ad.setCreatedBy(add.getCreatedBy());
            ad.setCreatedDate(add.getCreatedDate());
            ad.setGzpx(add.getGzpx());
            ad.setId(add.getWxjsguid());
            ad.setLastModifiedBy(add.getLastModifiedBy());
            ad.setLastModifiedDate(ad.getLastModifiedDate());
            ad.setMshu(add.getMshu());
            ad.setWxjsguid(add.getWxjsguid());
            ad.setWxjsmxguid(add.getWxjsmxguid());
            ad.setXxyyh(add.getXxyyh());
            ad.setXxyyhmc(add.getXxyyhmc());
            itfTblwxjsxxyyjyktService.save(ad);
        }
    }

    public void generateJyktDataTow(OrderBase orderBase, OrderRepairDetail item, Long synReqId, String j_syn_task_no) {
        OrderPar request = new OrderPar();
        request.setOrderNo(orderBase.getId());
        request.setId(String.valueOf(item.getOutId()));
        request.setSynReqId(synReqId);
        ItfTblwxjsjykt jsjy = wxjsJyktUploadMapper.getItfTblWxjsJykt(request);
        jsjy.setSynTaskNo(j_syn_task_no);
        // 省市等信息单独处理
        setssxcInfo(jsjy);
        itfTblwxjsjyktService.save(jsjy);
    }

    public void setssxcInfo(ItfTblwxjsjykt jsjy) {
        List<BrandLbsRelate> br;
        // 街道处理
        if (StringUtils.isNotEmpty(jsjy.getXzhen())){
            br = brandLbsRelateService.lambdaQuery()
                    .eq(BrandLbsRelate::getLbsStreetId, jsjy.getXzhen())
                    .eq(BrandLbsRelate::getDel,0)
                    .isNotNull(BrandLbsRelate::getStreetId).list();
            if (br !=null && br.size()>0){
                jsjy.setXzhen(br.get(0).getStreetId());
                jsjy.setXian(br.get(0).getAreaId());
                jsjy.setCshi(br.get(0).getCityId());
                jsjy.setSfen(br.get(0).getProvinceId());

                Street street = streetService.lambdaQuery()
                        .eq(Street::getStatus, 1)
                        .eq(Street::getProvinceId, jsjy.getSfen())
                        .eq(Street::getCityId, jsjy.getCshi())
                        .eq(Street::getAreaId, jsjy.getXian())
                        .eq(Street::getStreetId, jsjy.getXzhen()).one();
                if (street !=null){
                    jsjy.setXzhen(street.getStreet());
                    jsjy.setSfen(street.getProvince());
                    jsjy.setCshi(street.getCity());
                    jsjy.setXian(street.getArea());
                    return;
                }
            }
        }

        // 总部区必选
        br = brandLbsRelateService.lambdaQuery()
                .eq(BrandLbsRelate::getLbsDistrictId, jsjy.getXian())
                .eq(BrandLbsRelate::getDel,0)
                .isNotNull(BrandLbsRelate::getAreaId).list();
        if (br !=null && br.size()>0){
            jsjy.setXian(br.get(0).getAreaId());
        }

        Area area = areaService.lambdaQuery()
                .eq(Area::getAreaId, jsjy.getXian()).one();
        if (area !=null){
            jsjy.setSfen(area.getProvince());
            jsjy.setCshi(area.getCity());
            jsjy.setXian(area.getArea());
        }
    }

    public Long generateJyktData(Brand brand, OrderBase orderBase, OrderRepairDetail item) {
        ItfTblWxjsJyktUpload jykt = generateJykt(brand, orderBase, item);
        jykt.setSynStatus(44);
        itfTblWxjsJyktUploadService.save(jykt);
        return jykt.getSynReqId();
    }

    public boolean checkFiles(OrderBase orderBase) {
        // 检查内机条码附件完整性
        InstallCJDetailFile installCJDetailFile = new InstallCJDetailFile();
        installCJDetailFile.setOrderNo(orderBase.getId());
        installCJDetailFile.setType(1);
        OrderDetailFile detailFiles = fileOrderDetailMapper.getIdReT(installCJDetailFile);
        if (detailFiles !=null){
            // 采集表中提取数据
            OrderRepairDetail ord = orderRepairDetailService.lambdaQuery()
                    .eq(OrderRepairDetail::getId,detailFiles.getOrderDetailId()).one();
            if (!ord.getType().equals("INSIDE")){
                // 清理附件表
                OrderDetailFile del = new OrderDetailFile();
                del.setId(detailFiles.getId());
                orderDetailFileService.removeById(del);
            } else {
                // 内机不完整上传被忽略
                return true;
            }
        }
        // 检查外机条码附件完整性
        installCJDetailFile.setType(2);
        detailFiles = fileOrderDetailMapper.getIdReT(installCJDetailFile);
        if (detailFiles !=null){
            // 采集表中提取数据
            OrderRepairDetail ord = orderRepairDetailService.lambdaQuery()
                    .eq(OrderRepairDetail::getId,detailFiles.getOrderDetailId()).one();

            if (!ord.getType().equals("OUT")){
                // 清理附件表
                OrderDetailFile del = new OrderDetailFile();
                del.setId(detailFiles.getId());
                orderDetailFileService.removeById(del);
            } else {
                // 外机不完整上传被忽略
                return true;
            }
        }
        // 再次判断完整性
        List<OrderDetailFile> odfs = fileOrderDetailMapper.getIdRe(installCJDetailFile);
        if (odfs !=null && odfs.size()>0){
            // 不完整上传被忽略
            return true;
        }
        return false;
    }

    /**
     * 1： 生成维修工单主表数据
     * 2：发短信评价
     * 3：生成采集明细数据
     *    维修数据采集故障现象表
     *
     *
     *
     */
    public void generateItfTblAssignUpload(Brand brand, Map<String, List<SysDictRef>> sysDictRefXLMapXq,
                                           Long taskId, OutJiasmToGreeUploadTaskList sourceData, String newDykh,
                                           OutJiasmToGreeUploadTaskList row) {
        // 提取工单数据
        OrderBase orderBase = orderBaseService.lambdaQuery()
                .eq(OrderBase::getId, sourceData.getOrderNo()).one();
        if (orderBase !=null && orderBase.getUploadFlag()){
            // 增加初始化处理，不需要事务
            // dataInit(sourceData, newDykh, orderBase);

            if (itfTblAssignUpload(brand, sysDictRefXLMapXq,taskId, sourceData, newDykh,row, orderBase)){
                return ;
            }
        }
        // 修改数据上传任务表中的状态   这里固定值 66
        publicService.updateUploadTaskListStatus(row.getOrderNo(),row.getSynReqId(),1,66);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean itfTblAssignUpload(Brand brand, Map<String, List<SysDictRef>> sysDictRefXLMapXq,
                                           Long taskId, OutJiasmToGreeUploadTaskList sourceData, String newDykh,
                                           OutJiasmToGreeUploadTaskList row, OrderBase orderBase) {
        // 删除工单更新被忽略
        // 接收派工网点为空上传被忽略
        if (StringUtils.isEmpty(orderBase.getReceWebsitId()) || orderBase.getReceWebsitId().equals("0")){
            publicService.updateUploadTaskListStatus(row.getOrderNo(),row.getSynReqId(),1,66);
            return Boolean.TRUE;
        }
        // 生成待同步的工单主表数据
        getItfTblAssignUpload(brand, sysDictRefXLMapXq, taskId, sourceData, newDykh, orderBase);
        // 生成短信评价发送数据
        generateMessage(brand, sourceData, newDykh, orderBase);
        // 检查附件完整性 未同步图片不处理本记录数据同步
        if (checkFile(sourceData.getOrderNo(),row.getSynReqId())){
            return Boolean.TRUE;
        }
        // 处理采集明细数据(生成维修结算+生成维修现象数据)    TL_PrePareSynDataby_fa_order_repair_detail
        generateRepairDetailOrReason(brand, orderBase);
        return Boolean.FALSE;
    }

    public Boolean dataInit(OutJiasmToGreeUploadTaskList sourceData, String newDykh, OrderBase orderBase) throws IOException {
        // 同步工单的pgid,pguuid
        upOrderBasePgid(orderBase, newDykh);
        // 同步维修工单产品信息 pgid
        upOrderProduct(sourceData, newDykh);
        // 同步维修工单操作日志pgid
        uporderRepairOperatingLogpgid(sourceData, newDykh);
        // 同步预约改约-总部短信发送请求fjid 这里字段必须有值，这里无需处理
        // upFaGreeSmsFjid(sourceData, newDykh);
        // 同步派服务人员-短信发送请求fjid 这里字段必须有值，这里无需处理
        // upFaGreeSmsWorker(sourceData, newDykh);
        // 修改序采集单内的序
        upOrderRepairDetail(orderBase.getId());

        // 格力总部数据采集主键为空时代表为公司采集的数据，brandwxjsguid填写UUID
        updateOrderRepairDetailWxjsguid(orderBase.getId());

        // 修改 wxjsmxguid
        updateOrderRepairDetailWxjsmxguid(orderBase);

        // 采集明细表全表更新pgid = brand_pgid
        upBrandPgid(orderBase);

        // 故障现象原因序
        upOrderRepairDetailReasonOutId(orderBase.getId());

        // wxxmguid自生成
        upOrderRepairDetailReasonwxxmguid(orderBase.getId());

        // 修改 维修现象主键、维修明细主键
        upOrderRepairDetailReason(orderBase.getId());

        // 修改附件序 outid
        upOrderDetailFileOutId(orderBase.getId());

        // 上传图片
        generateFileInit(orderBase);

        return checkOrderDetailFile(orderBase.getId());
    }

    private void updateOrderRepairDetailWxjsmxguid(OrderBase orderBase) {
        List<OrderRepairDetail> upList = new ArrayList<>();
        // 看有无需要修改的数据
        List<OrderRepairDetail> detaillistz = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, orderBase.getId())
                .eq(OrderRepairDetail::getWxjsmxguid, "").list();
        if (CollectionUtils.isEmpty(detaillistz)){
            return;
        }
        for (OrderRepairDetail i:detaillistz){
            i.setWxjsmxguid(publicService.getUUID());
            upList.add(i);
        }
        // 修改序
        if (upList.size()>0){
            orderRepairDetailService.updateBatchById(upList);
            upList.clear();
        }
        detaillistz.clear();
    }

    public void upOrderDetailFileOutId(String orderBaseId) {
        List<OrderDetailFile> upList = new ArrayList<>();
        // 查看是否有需要修改的数据
        List<OrderDetailFile> oids = orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId, orderBaseId)
                .eq(OrderDetailFile::getOutId, 0)
                .list();
        if (CollectionUtils.isEmpty(oids)){
            return;
        }

        List<OrderDetailFile> detaillist = orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId, orderBaseId)
                .list();
        // 找出最大的序 默认值为0
        int outId=0;
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(detaillist)){
            for (OrderDetailFile item:detaillist){
                if (outId<item.getOutId()){
                    outId = item.getOutId();
                }
            }
        }

        for (OrderDetailFile ite:detaillist){
            if (ite.getOutId() == 0){
                outId++;
                ite.setOutId(outId);
                upList.add(ite);
            }
        }
        // 修改序
        if (upList.size()>0){
            orderDetailFileService.updateBatchById(upList);
            upList.clear();
        }
        detaillist.clear();
    }

    public void upOrderRepairDetailReasonOutId(String orderBaseId) {
        List<OrderRepairDetailReason> upList = new ArrayList<>();
        // 查看是否有需要修改的数据
        List<OrderRepairDetailReason> oids = orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderBaseId, orderBaseId)
                .eq(OrderRepairDetailReason::getOutId, 0)
                .list();
        if (CollectionUtils.isEmpty(oids)){
            return;
        }

        List<OrderRepairDetailReason> detaillist = orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderBaseId, orderBaseId)
                .list();
        // 找出最大的序 默认值为0
        int outId=0;
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(detaillist)){
            for (OrderRepairDetailReason item:detaillist){
                if (outId<item.getOutId()){
                    outId = item.getOutId();
                }
            }
        }

        for (OrderRepairDetailReason ite:detaillist){
            if (ite.getOutId() == 0){
                outId++;
                ite.setOutId(outId);
                ite.setXxyyguid(publicService.getUUID());
                if (StringUtils.isEmpty(ite.getWxjsguid())){
                    ite.setWxjsguid(publicService.getUUID());
                }

                upList.add(ite);
            }
        }
        // 修改序
        if (upList.size()>0){
            orderRepairDetailReasonService.updateBatchById(upList);
            upList.clear();
        }
        detaillist.clear();
    }

    public void upOrderRepairDetailReasonwxxmguid(String orderBaseId) {
        List<OrderRepairDetailReason> upList = new ArrayList<>();
        // 查看是否有需要修改的数据
        List<OrderRepairDetailReason> oids = orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderBaseId, orderBaseId)
                .eq(OrderRepairDetailReason::getWxxmguid, "")
                .list();
        if (CollectionUtils.isEmpty(oids)){
            return;
        }
        for (OrderRepairDetailReason item:oids){
            item.setWxxmguid(publicService.getUUID());
            upList.add(item);
        }

        // 修改序
        if (upList.size()>0){
            orderRepairDetailReasonService.updateBatchById(upList);
            upList.clear();
        }
        oids.clear();
    }


    public Boolean checkOrderDetailFile(String id) {
        List<OrderDetailFile> detailFiles = new ArrayList<>();
        Boolean flag = Boolean.TRUE;
        detailFiles = orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId, id).list();
        for (OrderDetailFile file:detailFiles){
            // 工单号， file的id即附件表的id,uuid统一值
            // path未准备上传被忽略
            if (StringUtils.isEmpty(file.getFilePath())){
                flag = Boolean.FALSE;
                break;
            }
            // 品牌方fileindex未获取上传被忽略
            if (StringUtils.isEmpty(file.getBrandFilePath())){
                flag = Boolean.FALSE;
                break;
            }
        }
        detailFiles.clear();
        return flag;
    }

    public void updateOrderRepairDetailWxjsguid(String id) {
        List<OrderRepairDetail> upList = new ArrayList<>();
        // 看有无需要修改的数据
        List<OrderRepairDetail> detaillistz = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, id)
                .eq(OrderRepairDetail::getBrandWxjsguid, "").list();
        if (CollectionUtils.isEmpty(detaillistz)){
            return;
        }
        for (OrderRepairDetail i:detaillistz){
            OrderRepairDetail u = new OrderRepairDetail();
            MyBeanUtils.copyProperties(i,u);
            u.setBrandWxjsguid(publicService.getUUID());
            upList.add(u);
        }
        // 修改序
        if (upList.size()>0){
            orderRepairDetailService.updateBatchById(upList);
            upList.clear();
        }
        detaillistz.clear();
    }

    public Boolean checkFile(String orderNo, Long synReqId){
        InstallCJDetailFile installCJDetailFile = new InstallCJDetailFile();
        installCJDetailFile.setOrderNo(orderNo);
        List<OrderDetailFile> detailFiles = fileOrderDetailMapper.getIdRe(installCJDetailFile);
        if (detailFiles !=null && detailFiles.size()>0){
            // 修改数据上传任务表中的状态
            updateUploadTaskList(synReqId,9,"总部采集忽略上传或者广佛采集未得到格力图片ID");
            return Boolean.TRUE;
        }

        return Boolean.FALSE;
    }

    // 修改 维修现象主键、维修明细主键
    public void upOrderRepairDetailReason(String id) {
        List<OrderRepairDetailReason> ulist = new ArrayList<>();
        // 提取采集的数据
        List<OrderRepairDetail> orderRepairDetails = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, id)
                .orderByAsc(OrderRepairDetail::getId)
                .list();
        if (orderRepairDetails != null && orderRepairDetails.size() > 0) {
            for (OrderRepairDetail detail : orderRepairDetails) {
                // status 状态:0=待采集,1=采集中,2=已采集,3=已完成
                if (detail.getStatus().equals(0)) {
                    continue;
                }
                List<OrderRepairDetailReason> reasons = orderRepairDetailReasonService.lambdaQuery()
                        .eq(OrderRepairDetailReason::getOrderRepairDetailId, detail.getId()).list();
                for (OrderRepairDetailReason r : reasons) {
                    if (StringUtils.isEmpty(r.getXxyyguid()) || StringUtils.isEmpty(r.getWxjsguid())) {
                        OrderRepairDetailReason up = new OrderRepairDetailReason();
                        if (StringUtils.isEmpty(r.getXxyyguid())) {
                            r.setXxyyguid(publicService.getUUID());
                        }
                        if (StringUtils.isEmpty(r.getWxjsguid())) {
                            r.setWxjsguid(publicService.getUUID());
                        }
                        ulist.add(up);
                    }
                }
            }
            if (ulist.size() > 0) {
                orderRepairDetailReasonService.updateBatchById(ulist);
            }
        }
    }


    public void generateRepairDetailOrReason(Brand brand, OrderBase orderBase) {
        List<ItfTblWxjsJyktUpload> jykts = new ArrayList<>();
        List<ItfTblWxjsXxyyJyktUpload>  jyktus = new ArrayList<>();
        List<ItfTblWxjsFjJyktUpload> fjs = new ArrayList<>();
        List<ItfTblWxjsWxxmJyktUpload> wxxms = new ArrayList<>();
        List <ItfTblWxjsPjmxJyktUpload> pjs = new ArrayList<>();
        List<ItfTblAssignFeeUpload> fees = new ArrayList<>();

        // 提取采集的数据
        List<OrderRepairDetail> orderRepairDetails = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, orderBase.getId())
                .orderByAsc(OrderRepairDetail::getId)
                .list();
        if (orderRepairDetails !=null && orderRepairDetails.size()>0){
            for (OrderRepairDetail detail :orderRepairDetails){
                // status 状态:0=待采集,1=采集中,2=已采集,3=已完成
                if (detail.getStatus().equals(0)){
                    continue;
                }
                // 生成维修结算数据
                jykts.add(generateJykt(brand, orderBase, detail));
                // 生成维修故障现象数据   TL_PrePareSynDataby_fa_order_repair_fault_info
                generateReason(jyktus, detail);
                // 生成维修数据采集附件数据  TL_PrePareSynDataby_fa_order_repair_annex
                generateFile(orderBase, detail, fjs);
                // 生成维修项目现象、维修费用数据 TL_PrePareSynDataby_fa_order_repair_data_info
                generateFee(orderBase, detail,brand, wxxms, fees);
                // 生成配件数据  TL_PrePareSynDataby_fa_order_repair_part_info
                generatePj(orderBase, pjs, detail);
            }

            if (jykts.size()>0){
                itfTblWxjsJyktUploadService.saveBatch(jykts);
                jykts.clear();
            }
            if (jyktus.size()>0){
                itfTblWxjsXxyyJyktUploadService.saveBatch(jyktus);
                jyktus.clear();
            }
            if (fjs.size()>0){
                itfTblWxjsFjJyktUploadService.saveBatch(fjs);
                fjs.clear();
            }
            if (wxxms.size()>0){
                itfTblWxjsWxxmJyktUploadService.saveBatch(wxxms);
                wxxms.clear();
            }
            if (fees.size()>0){
                itfTblAssignFeeUploadService.saveBatch(fees);
                fees.clear();
            }
            if (pjs.size()>0){
                itfTblWxjsPjmxJyktUploadService.saveBatch(pjs);
                pjs.clear();
            }
        }
    }

    public void generatePj(OrderBase orderBase, List<ItfTblWxjsPjmxJyktUpload> pjs, OrderRepairDetail detail) {
        // 提取配置件数据
        List<OrderRepairDetailReason> reasons =  orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderRepairDetailId, detail.getId()).list();
        for (OrderRepairDetailReason rs:reasons){
            // 好像是有没有都要生成，
            /*if (StringUtils.isEmpty(rs.getNewPartNo())){
                continue;
            }*/
            OrderPar request = new OrderPar();
            request.setId(rs.getId());
            ItfTblWxjsPjmxJyktUpload pj = reasonOrderRepairDetailMapper.getItfTblWxjsPjmxJyktUpload(request);
            pj.setWorkerOrderNo(orderBase.getId());
            pjs.add(pj);
        }
    }

    public void generateFeeBak(OrderBase orderBase, OrderRepairDetail detail,Brand brand,
                            List<ItfTblWxjsWxxmJyktUpload> wxxms,
                            List<ItfTblAssignFeeUpload> fees){
        // 提取维修项目数据
        List<OrderRepairDetailItem> ords =  orderRepairDetailItemService.lambdaQuery()
                .eq(OrderRepairDetailItem::getOrderRepairDetailId, detail.getId()).list();
        for (OrderRepairDetailItem ord: ords){
            // 确保采集现象表数据存在数据
            OrderRepairDetailReason ordr =  orderRepairDetailReasonService.lambdaQuery()
                    .eq(OrderRepairDetailReason::getOrderRepairDetailId, ord.getOrderRepairDetailId())
                    .one();
            if (ordr == null){
                return ;
            }
            // 修改wxjsguid与明细表数据相同
            if (StringUtils.isEmpty(ord.getWxjsguid())){
                OrderRepairDetailItem up = new OrderRepairDetailItem();
                up.setId(ord.getId());
                up.setWxjsguid(ordr.getWxjsguid());
                ord.setWxjsguid(ordr.getWxjsguid());
            }
            // 生成维修项目现象数据
            OrderPar request = new OrderPar();
            request.setId(ord.getId());
            ItfTblWxjsWxxmJyktUpload wxxm = reasonOrderRepairDetailMapper.getItfTblWxjsWxxmJyktUpload(request);
            wxxm.setWorkerOrderNo(orderBase.getId());
            wxxms.add(wxxm);

            // 生成维修费用数据
            request.setBrandId(brand.getBrandId());
            request.setMainId(orderBase.getMainId());
            ItfTblAssignFeeUpload fee = reasonOrderRepairDetailMapper.getItfTblAssignFeeUpload(request);
            fee.setWorkerOrderNo(orderBase.getId());
            fee.setPgid(Long.valueOf(orderBase.getPgid()));
            fees.add(fee);
        }
    }

    public void generateFee(OrderBase orderBase, OrderRepairDetail detail,Brand brand,
                            List<ItfTblWxjsWxxmJyktUpload> wxxms,
                            List<ItfTblAssignFeeUpload> fees){
        // 提取维修项目数据
        List<OrderRepairDetailReason> ordrs =  orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderBaseId, orderBase.getId()).list();
        for (OrderRepairDetailReason item : ordrs){
            // 生成维修项目现象数据
            OrderPar request = new OrderPar();
            request.setId(item.getId());
            ItfTblWxjsWxxmJyktUpload wxxm = reasonOrderRepairDetailMapper.getItfTblWxjsWxxmJyktUpload(request);
            wxxm.setWorkerOrderNo(orderBase.getId());
            wxxms.add(wxxm);

            // 生成维修费用数据
            request.setBrandId(brand.getBrandId());
            request.setMainId(orderBase.getMainId());
            ItfTblAssignFeeUpload fee = reasonOrderRepairDetailMapper.getItfTblAssignFeeUpload(request);
            fee.setWorkerOrderNo(orderBase.getId());
            fee.setPgid(Long.valueOf(orderBase.getPgid()));
            fees.add(fee);
        }
    }

    public void generateFile(OrderBase orderBase, OrderRepairDetail detail, List<ItfTblWxjsFjJyktUpload> fjs){
        // 提取数据采集附件数据
        List<OrderDetailFile> odfs =  orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId,orderBase.getId())
                .eq(OrderDetailFile::getOrderDetailId, detail.getId()).list();
        for (OrderDetailFile file:odfs){
            // 工单号， file的id即附件表的id,uuid统一值
            // path未准备上传被忽略
            if (StringUtils.isEmpty(file.getFilePath())){
                continue;
            }
            // 品牌方fileindex未获取上传被忽略
            /*if (StringUtils.isEmpty(file.getBrandFileIndex())){
                continue;
            }*/

            if (StringUtils.isEmpty(file.getBrandFilePath())){
                continue;
            }
           /* // 修改附件的fjguid
            if (StringUtils.isEmpty(file.getFjguid())){
                OrderDetailFile upf = new OrderDetailFile();
                upf.setId(file.getId());
                upf.setFjguid(UUID.randomUUID().toString());
                orderDetailFileService.updateById(upf);
                file.setFjguid(upf.getFjguid());
            }
            // 修改采集明细序号 wxmxguid
            if (StringUtils.isEmpty(file.getPgwcmxid())){
                OrderDetailFile upf = new OrderDetailFile();
                upf.setId(file.getId());
                upf.setPgwcmxid(UUID.randomUUID().toString());
                orderDetailFileService.updateById(upf);
                file.setPgwcmxid(upf.getPgwcmxid());
            }*/

            // 生成附件数据
            InstallCJDetailFile request = new InstallCJDetailFile();
            request.setOrderNo(orderBase.getId());
            request.setId(file.getId());
            ItfTblWxjsFjJyktUpload fj = fileOrderDetailMapper.getItfTblWxjsFjJyktUpload(request);
            fjs.add(fj);
        }
    }

    public void generateFileInit(OrderBase orderBase) throws IOException {
        // 提取采集的数据
        List<OrderRepairDetail> orderRepairDetails = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, orderBase.getId())
                .orderByAsc(OrderRepairDetail::getId)
                .list();
        if (orderRepairDetails !=null && orderRepairDetails.size()>0){
            for (OrderRepairDetail detail :orderRepairDetails){
                // status 状态:0=待采集,1=采集中,2=已采集,3=已完成
                if (detail.getStatus().equals(0)){
                    continue;
                }
                OrderDetailFileInit(orderBase, detail);

                // 同步图片
                OrderDetailFileUpload(orderBase, detail);
            }
        }
    }


    public void OrderDetailFileInit(OrderBase orderBase, OrderRepairDetail detail){
        List<OrderDetailFile> upodfs = new ArrayList<>();
        List<OrderDetailFile> odfs = new ArrayList<>();
        // 提取数据采集附件数据
        odfs =  orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId,orderBase.getId())
                .eq(OrderDetailFile::getOrderDetailId, detail.getId()).list();
        for (OrderDetailFile file:odfs){
            if (StringUtils.isEmpty(file.getFjguid()) || StringUtils.isEmpty(file.getPgwcmxid())){
                OrderDetailFile upf = new OrderDetailFile();
                MyBeanUtils.copyProperties(file,upf);
                // 修改附件的fjguid
                if (StringUtils.isEmpty(file.getFjguid())){
                    upf.setFjguid(publicService.getUUID());
                    file.setFjguid(upf.getFjguid());
                }
                // 修改采集明细序号 wxmxguid
                if (StringUtils.isEmpty(file.getPgwcmxid())){
                    upf.setPgwcmxid(publicService.getUUID());
                }
                upodfs.add(upf);
            }
        }
        if (upodfs.size()>0){
            orderDetailFileService.updateBatchById(upodfs);
            upodfs.clear();
        }
        odfs.clear();
    }

    public void OrderDetailFileUpload(OrderBase orderBase, OrderRepairDetail detail) throws IOException {
        String oldFile ="";
        String newFile ="";
        // 提取数据采集附件数据
        List<OrderDetailFile> odfs =  orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOrderBaseId,orderBase.getId())
                .eq(OrderDetailFile::getOrderDetailId, detail.getId()).list();
        for (OrderDetailFile file:odfs){
            // path未准备上传被忽略
            if (StringUtils.isEmpty(file.getFilePath())){
                continue;
            }
            if (StringUtils.isEmpty(file.getBrandFilePath())){
                // 上传图片
                oldFile = publicService.path(file.getFilePath());
                File nFile = publicService.createf(oldFile);

                baseService.saveToFile(ossUtil.getUrlWw(file.getFilePath()),nFile);
                // 获取文件
                newFile = oldFile;
                WebsitSH websitSH = publicService.ptshwdToshshwd(orderBase.getWebsitId(), orderBase.getMainId());
                log.info("图片上传网点编号:{}",websitSH.getWdId());
                Boolean flag = uploadFileexc(newFile, oldFile,websitSH.getWdId(), file);
                new File(newFile).delete();
                if (!flag) {
                    continue;
                }
            }
        }
    }

    public Boolean uploadFileexc(String newFile, String oldFile,String wdno,OrderDetailFile file) {
        try{
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+oldFile);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(newFile, resultData.getExtData());
                // 3: 保存文件
                if (org.apache.commons.lang3.StringUtils.isEmpty(result.trim())){
                    Map<String,String>req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(oldFile, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);

                    if (responses.getStatusCode() == 200){
                        file.setBrandFilePath(responses.getData().getId());
                        file.setSynErrMsg("");
                        orderDetailFileService.updateById(file);
                    } else {
                        // 失败
                        file.setSynErrMsg("保存图片信息失败");
                        orderDetailFileService.updateById(file);
                        return Boolean.FALSE;
                    }
                } else {
                    // 上传图片到OSS失败
                    file.setSynErrMsg("上传图片到OSS失败");
                    orderDetailFileService.updateById(file);
                    return Boolean.FALSE;
                }
            } else {
                //  获取签名信息失败
                file.setSynErrMsg("获取签名信息失败");
                orderDetailFileService.updateById(file);
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        } catch (Exception ex) {
            file.setSynErrMsg("操作图片信息失败");
            orderDetailFileService.updateById(file);
            return Boolean.FALSE;
        }
    }

    public void getSaveFileInfo(String id1, ResultData resultData, Map<String, String> req) {
        req.put("bizAppId","flydiy-auto-sit-default-front-greeshmerge");
        req.put("bizTable","default");
        req.put("bizType","default");
        req.put("accessType","auth");
        req.put("url", resultData.getExtData().getDir());
        // req.put("name", id1 +".jpeg");
        req.put("name", id1);
    }

    public void generateReason(List<ItfTblWxjsXxyyJyktUpload> jyktus, OrderRepairDetail detail) {
        // 提取维修数据采集故障现象数据  数据采集明细表的所有id
        List<OrderRepairDetailReason> reasons =  orderRepairDetailReasonService.lambdaQuery()
                .eq(OrderRepairDetailReason::getOrderRepairDetailId, detail.getId()).list();
        for (OrderRepairDetailReason r : reasons){
            // 只传最低级别(父级不等于子级)
            if (StringUtils.isNotEmpty(r.getRepairBugParentId()) && StringUtils.isNotEmpty(r.getRepairBugId()) &&
                    r.getRepairBugParentId().equals(r.getRepairBugId())){
                continue;
            }
            // 现象原因号不传
            if (StringUtils.isEmpty(r.getNumber())){
                continue;
            }
            // 修改 维修现象主键、维修明细主键
            // upxxyyguid(r);
            // 生成维修现象数据
            generateJyktU(jyktus, detail, r);
        }
    }



    public void generateJyktU(List<ItfTblWxjsXxyyJyktUpload> jyktus, OrderRepairDetail detail, OrderRepairDetailReason r) {
        ItfTblWxjsXxyyJyktUpload add = new ItfTblWxjsXxyyJyktUpload();
        add.setWorkerOrderNo(detail.getOrderBaseId());
        add.setFaOrderRepairFaultInfoId(r.getOutId());
        add.setXxyyguid(r.getXxyyguid());
        add.setCreatedBy("guangfo");
        add.setCreatedDate(r.getCreateTime());
        add.setLastModifiedBy("guangfo");
        add.setLastModifiedDate(r.getUpdateTime());
        add.setWxjsguid(detail.getBrandWxjsguid());
        add.setXxyyh(r.getNumber());
        if (StringUtils.isNotEmpty(r.getRemark())){
            add.setMshu(r.getRemark());
        } else if (StringUtils.isNotEmpty(r.getName())){
            add.setMshu(r.getName());
        }
        add.setWxjsmxguid(detail.getWxjsmxguid());
        add.setCjsj(r.getCreateTime());
        add.setXxyyhmc(r.getName());
        jyktus.add(add);
    }

    public ItfTblWxjsXxyyJyktUpload generateJyktUT(OrderRepairDetail detail, OrderRepairDetailReason r) {
        ItfTblWxjsXxyyJyktUpload add = new ItfTblWxjsXxyyJyktUpload();
        add.setWorkerOrderNo(detail.getOrderBaseId());
        add.setFaOrderRepairFaultInfoId(r.getOutId());
        add.setXxyyguid(r.getXxyyguid());
        add.setCreatedBy("guangfo");
        add.setCreatedDate(r.getCreateTime());
        add.setLastModifiedBy("guangfo");
        add.setLastModifiedDate(r.getUpdateTime());
        add.setWxjsguid(detail.getBrandWxjsguid());
        add.setXxyyh(r.getNumber());
        if (StringUtils.isNotEmpty(r.getRemark())){
            add.setMshu(r.getRemark());
        } else if (StringUtils.isNotEmpty(r.getName())){
            add.setMshu(r.getName());
        }
        add.setWxjsmxguid(detail.getWxjsmxguid());
        add.setCjsj(r.getCreateTime());
        add.setXxyyhmc(r.getName());
        add.setSynStatus(44);
        itfTblWxjsXxyyJyktUploadService.save(add);
        return add;
    }

    public void upxxyyguid(OrderRepairDetailReason r) {
        OrderRepairDetailReason up = new OrderRepairDetailReason();
        up.setId(r.getId());
        if (StringUtils.isEmpty(r.getXxyyguid())){
            up.setXxyyguid(publicService.getUUID());
            r.setXxyyguid(up.getXxyyguid());
        }
        if (StringUtils.isEmpty(r.getWxjsguid())){
            up.setWxjsguid(publicService.getUUID());
            r.setWxjsguid(up.getWxjsguid());
        }
        orderRepairDetailReasonService.updateById(up);
    }

    public ItfTblWxjsJyktUpload generateJykt(Brand brand, OrderBase orderBase, OrderRepairDetail detail) {
        WebsitSH websitSH = new WebsitSH();

        /*// 修改序采集单内的序
        upOrderRepairDetail(orderBase.getId());
        // 格力总部数据采集主键为空时代表为公司采集的数据，填写UUID
        upBrandWxjsguid(detail);
        // 采集明细表全表更新pgid = brand_pgid
        upBrandPgid(orderBase);*/

        // 生成维修结算数据
        OrderPar request = new OrderPar();
        request.setOrderNo(orderBase.getId());
        request.setId(detail.getId());
        request.setBrandId(brand.getBrandId());
        ItfTblWxjsJyktUpload jykt = detailOrderRepairMapper.getItfTblWxjsJyktUpload(request);

        if (jykt.getBwgsj()==null && orderBase.getOverTime() !=null){
            jykt.setBwgsj(orderBase.getOverTime());
        }
        if (jykt.getBwgsj()==null){
            jykt.setBwgsj(new Date());
        }

        // 1=已结算,2=待结算
        jykt.setJszt("2");
        // 这里可以填写一个自生成的值
        if (StringUtils.isEmpty(jykt.getPgmxid())){
            jykt.setPgmxid(IdWorker.getIdStr());
        }
        // 售后网点处理
        websitSH = publicService.ptshwdToshshwd(orderBase.getWebsitId(),orderBase.getMainId());
        jykt.setAzwdbh(websitSH.getWdId());
        jykt.setAzwdmc(websitSH.getWdmc());
        // 维修网点即售后网点处理
        jykt.setWxwdno(websitSH.getWdId());
        jykt.setWxwdmc(websitSH.getWdmc());

        // 提取安装师傅的账号ID信息
        jykt.setWxgid(publicService.getBrandWorkerId(orderBase.getWorkerId(),websitSH.getWdId(),brand.getBrandId(),orderBase.getWebsitId()));
        // 这里的czrid放师傅所以网点编号
        jykt.setCzrid(publicService.getBrandWorkerNo(orderBase.getWorkerId(),websitSH.getWdId(),brand.getBrandId(),orderBase.getWebsitId()));
        jykt.setWxgdh(orderBase.getWorkerMobile());

        // 结算网点编号即售后网点处理
        websitSH = publicService.ptshwdToshshwd(jykt.getJswdno(),orderBase.getMainId());
        jykt.setJswdno(websitSH.getWdId());
        jykt.setJswdmc(websitSH.getWdmc());

        jykt.setBxrq(orderBase.getCreateTime());
        if (orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G8.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G9.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G10.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G11.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G12.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G13.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G14.getCode())){
            jykt.setStat(1120L);
        } else {
            jykt.setStat(1100L);
        }
        return jykt;
    }

    public void upOrderRepairDetail(String id) {
        List<OrderRepairDetail> upList = new ArrayList<>();
        // 看有无需要修改的数据
        List<OrderRepairDetail> detaillistz = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, id)
                .eq(OrderRepairDetail::getOutId, 0)
                .orderByAsc(OrderRepairDetail::getCreateTime).list();
        if (CollectionUtils.isEmpty(detaillistz)){
            return;
        }

        List<OrderRepairDetail> detaillist = orderRepairDetailService.lambdaQuery()
                .eq(OrderRepairDetail::getOrderBaseId, id)
                .ne(OrderRepairDetail::getOutId, 0)
                .orderByAsc(OrderRepairDetail::getCreateTime).list();
        // 找出最大的序 默认值为0
        int outId=0;
        if (detaillist!=null && detaillist.size()>0){
            for (OrderRepairDetail item:detaillist){
                if (outId<item.getOutId()){
                    outId = item.getOutId();
                }
            }
        }

        for (OrderRepairDetail ite:detaillistz){
            if (ite.getOutId() == 0){
                outId++;
                OrderRepairDetail n = new OrderRepairDetail();
                n.setId(ite.getId());
                n.setOutId(outId);
                // n.setOutId(Integer.valueOf(IdWorker.getIdStr().substring(0,11)));
                upList.add(n);
            }
        }
        // 修改序
        if (upList.size()>0){
            orderRepairDetailService.updateBatchById(upList);
            upList.clear();
        }
        detaillist.clear();
    }

    public void upBrandPgid(OrderBase orderBase) {
        OrderPar request = new OrderPar();
        request.setOrderNo(orderBase.getPgid());
        request.setPgid(orderBase.getPgid());

        detailOrderRepairMapper.updatePgid(request);
    }

    public void upBrandWxjsguid(OrderRepairDetail detail) {
        if (StringUtils.isEmpty(detail.getBrandWxjsguid())){
            // 修改uuid
            OrderRepairDetail up = new OrderRepairDetail();
            up.setId(detail.getId());
            up.setBrandWxjsguid(publicService.getUUID());
            orderRepairDetailService.updateById(up);
            detail.setBrandWxjsguid(up.getBrandWxjsguid());
        }
    }

    public void updateUploadTaskList(Long synReqId,Integer synStatus,String msg) {
        OutJiasmToGreeUploadTaskList upoutgultl = new OutJiasmToGreeUploadTaskList();
        upoutgultl.setSynReqId(synReqId);
        upoutgultl.setSynStatus(synStatus);
        upoutgultl.setSynTime(new Date());
        upoutgultl.setSynErrMsg(msg);
        outJiasmToGreeUploadTaskListService.updateById(upoutgultl);
    }

    public void getItfTblAssignUpload(Brand brand, Map<String, List<SysDictRef>> sysDictRefXLMapXq, Long taskId, OutJiasmToGreeUploadTaskList sourceData, String newDykh, OrderBase orderBase) {
        /*// 同步工单的pgid
        upOrderBasePgid(sourceData, orderBase, newDykh);
        // 同步工单的pguuid
        upOrderBasePgguid(sourceData, orderBase);
        // 同步维修工单产品信息 pgid
        upOrderProduct(sourceData, newDykh);
        // 同步维修工单操作日志pgid
        uporderRepairOperatingLogpgid(sourceData, newDykh);
        // 同步预约改约-总部短信发送请求fjid
        upFaGreeSmsFjid(sourceData, newDykh);
        // 同步派服务人员-短信发送请求fjid
        upFaGreeSmsWorker(sourceData, newDykh);*/

        // 数据写入待同步-维修工单上传记录表
        OrderPar orderPar = new OrderPar();
        orderPar.setBrandId(brand.getBrandId());
        orderPar.setOrderNo(sourceData.getOrderNo());
        ItfTblAssignUpload itass = gdOrderBaseMapper.getItfTblAssignUpload(orderPar);


        // 信息渠道id 取的是info_channel 有问题
        itass.setUploadTaskSynReqId(taskId);
        // 部分参数单独处理
        getpreparOrderPar(sysDictRefXLMapXq, orderBase, itass, sourceData.getOrderNo(),brand);
        // 保存
        itfTblAssignUploadService.save(itass);
    }

    public void upOrderProduct(OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        List<OrderProduct> uops = new ArrayList<>();
        List<OrderProduct> ops = orderProductService.lambdaQuery()
                .eq(OrderProduct::getOrderBaseId,sourceData.getOrderNo())
                .eq(OrderProduct::getPgid,"").list();
        if (CollectionUtils.isEmpty(ops)){
            return;
        }
        for (OrderProduct item:ops){
            OrderProduct u = new OrderProduct();
            MyBeanUtils.copyProperties(item,u);
            u.setPgid(newDykh);
            uops.add(u);
        }

        orderProductService.updateBatchById(uops);
        uops.clear();
    }

    public void upFaGreeSmsWorker(OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        FaGreeSmsWorker up = new FaGreeSmsWorker();
        up.setFjid(newDykh);
        QueryWrapper upWrapper = new QueryWrapper<FaGreeSmsWorker>()
                .eq("worker_order_no", sourceData.getOrderNo())
                .eq("azorwx",2)
                .and(wrapper->wrapper.isNull("fjid")
                        .or().eq("fjid","").or().eq("fjid",0));
        faGreeSmsWorkerService.update(up,upWrapper);
    }

    public void generateMessage(Brand brand, OutJiasmToGreeUploadTaskList sourceData, String newDykh, OrderBase orderBase) {
        WebsitSH websitSH = new WebsitSH();

        if ((orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G8.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G9.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G10.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G11.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G14.getCode())) &&
                (orderBase.getDispatchStatus().equals(GDAppointStatusEnum.REPAIR_STATUS_G6.getCode()) ||
                        orderBase.getDispatchStatus().equals(GDAppointStatusEnum.REPAIR_STATUS_G13.getCode()) ||
                        orderBase.getDispatchStatus().equals(GDAppointStatusEnum.REPAIR_STATUS_G14.getCode()))){
            // 不上传总部的工单报完工后全部发评价
            String pgid="";
            if (StringUtils.isEmpty(orderBase.getPgid()) || orderBase.getPgid().equals("0")){
                pgid= newDykh;
            } else {
                pgid = orderBase.getPgid();
            }

            List<ItfMessagehuifangentity> imhs = itfMessagehuifangentityService.lambdaQuery()
                    .eq(ItfMessagehuifangentity::getOrderBaseId, orderBase.getId()).list();

            // 这里为自建工单，是不会走这里的
            if (pgid.equals("0")){
                if (imhs==null || imhs.size()<1){
                    // 生成短信数据
                    OrderPar orderPar = new OrderPar();
                    orderPar.setBrandId(brand.getBrandId());
                    orderPar.setOrderNo(sourceData.getOrderNo());
                    ItfMessagehuifangentity addms = gdOrderBaseMapper.getItfMessagehuifangentity(orderPar);
                    if (addms==null){
                        return;
                    }
                    // 售后网点处理 fjwd
                    websitSH = publicService.ptshwdToshshwd(addms.getFjwd(), orderBase.getMainId());
                    addms.setFjwd(websitSH.getWdId());

                    String id = publicService.getUUID();
                    if (id.length()>32){
                        addms.setSynTaskNo(id.substring(0,32));
                    } else {
                        addms.setSynTaskNo(id);
                    }

                    addms.setFsma(publicService.getfsma(addms.getSjid()));
                    addms.setFsnr("尊敬的用户：请对本次服务评价：满意回复1；一般回复2；不满意回复3。并注明原因！关注官微“格力售后服务”，为您提供更优质服务！");
                    addms.setDxguid(publicService.getUUID());
                    addms.setSjid(orderBase.getUserMobile().replace(" ",""));
                    publicService.addItfMessagehuifangentity(addms,orderBase.getOrderType(),6);
                }
            } else {
                OrderRepair or = orderRepairService.lambdaQuery()
                        .eq(OrderRepair::getOrderBaseId, orderBase.getId()).one();

                /**
                 * 1：短信发送改为一单只发一次
                 * 2：根据总部规则 特殊用户或投诉工单不发送评价短信
                 * 3：增加发送评价短信时判断报完工日期与当前日期小于7天才发
                 */
                // 2-FIRST,5-特级投诉
                if ((imhs !=null || imhs.size()>0) ||
                        (orderBase.getComplaint().equals("FIRST") || orderBase.getComplaint().equals("SUPER")) ||
                        (orderBase.getUserAttr().equals("特殊用户1") ||
                                orderBase.getUserAttr().equals("特殊用户2") ||
                                orderBase.getUserAttr().equals("特殊用户3")) ||
                        (orderBase.getVip().equals("VIP1") ||
                                orderBase.getVip().equals("VIP2") ||
                                orderBase.getVip().equals("VIP3") ||
                                orderBase.getVip().equals("VIP4")) ||
                        (or.getDemandSmallTypeName().indexOf("巡检")>=0 ||
                                or.getDemandSmallTypeName().indexOf("巡视")>=0 ||
                                or.getDemandSmallTypeName().indexOf("清洗保养")>=0)) {
                    // 什么都不做
                } else {
                    if (imhs==null || imhs.size()<1){
                        // 生成短信数据
                        OrderPar orderPar = new OrderPar();
                        orderPar.setBrandId(brand.getBrandId());
                        orderPar.setOrderNo(sourceData.getOrderNo());
                        ItfMessagehuifangentity addms = gdOrderBaseMapper.getItfMessagehuifangentityT(orderPar);
                        if (addms==null){
                            return;
                        }

                        // 售后网点处理 fjwd
                        websitSH = publicService.ptshwdToshshwd(addms.getFjwd(), orderBase.getMainId());
                        addms.setFjwd(websitSH.getWdId());

                        String id = publicService.getUUID();
                        if (id.length()>32){
                            addms.setSynTaskNo(id.substring(0,32));
                        } else {
                            addms.setSynTaskNo(id);
                        }

                        addms.setFsma(publicService.getfsma(addms.getSjid()));
                        addms.setFsnr("尊敬的用户：请对本次服务评价：满意回复1；一般回复2；不满意回复3。并注明原因！关注官微“格力售后服务”，为您提供更优质服务！");
                        addms.setDxguid(publicService.getUUID());
                        publicService.addItfMessagehuifangentity(addms,orderBase.getOrderType(),6);
                    }
                }
            }
        }
    }



    public void getpreparOrderPar(Map<String, List<SysDictRef>> sysDictRefXLMapXq, OrderBase orderBase,
                                   ItfTblAssignUpload itass, String orderNo, Brand brand) {
        WebsitSH websitSH = new WebsitSH();

        // 创建人及创建人名称改为对应的创建网点
        websitSH = publicService.ptxswdToshxswd(itass.getCjren(), orderBase.getMainId());
        if (StringUtils.isEmpty(websitSH.getWdId())){
            websitSH = publicService.ptshwdToshshwd(itass.getCjren(), orderBase.getMainId());
        }
        itass.setCjren(websitSH.getWdId());
        itass.setCjrmc(websitSH.getWdmc());

        // 售后网点处理 wxwdno
        websitSH = publicService.ptshwdToshshwd(itass.getWxwdno(), orderBase.getMainId());

        itass.setWxwdno(websitSH.getWdId());
        itass.setWxwdmc(websitSH.getWdmc());
        // 操作网点处理 即维修网点
        itass.setZjczwd(websitSH.getWdId());
        if (StringUtils.isNotEmpty(websitSH.getBrandSysWebsitNumber())){
            itass.setZjczwdxtbh(Long.valueOf(websitSH.getBrandSysWebsitNumber()));
        }
        itass.setCjwdno(websitSH.getWdId());
        // 接收派工网点也可认为是售后网点处理 这里是不能为空的，为空时云售后无法显示
        itass.setXjwdno(websitSH.getWdId());
        itass.setXjwdmc(websitSH.getWdmc());
        // 提取安装师傅的账号信息
        itass.setWxrenid(publicService.getBrandWorkerId(orderBase.getWorkerId(),websitSH.getWdId(),brand.getBrandId(),orderBase.getWebsitId()));

        // 销售单位处理 xsdwno
        websitSH = publicService.ptxswdToshxswd(itass.getXswdno(), orderBase.getMainId());
        itass.setXswdno(websitSH.getWdId());
        itass.setXswdmc(websitSH.getWdmc());

        // 所属区域处理
        BrandWebsit bb = brandWebsitService.lambdaQuery()
                .eq(BrandWebsit::getGroupCompanyId,brand.getBrandId())
                .eq(BrandWebsit::getBrandWebsitNumber,itass.getXjwdno()).one();
        itass.setSsqy("");
        if (bb !=null){
            itass.setSsqy(bb.getBelongCompany());
        }

        //维修总数量放在了工单子信息总数量中，感觉有问题
        itass.setWxshul(orderBase.getTotalNum());
        // 省市等信息单独处理
        setssxz(itass);
        // 同步 用户预约网点操作时间  看预约改约表内有无记录
        setYhyyczsj(itass, orderNo);

        if (orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G1.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G2.getCode()) ||
                orderBase.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G4.getCode())){
            itass.setExtjson1("0");
        } else {
            itass.setExtjson1("1");
        }

        OrderRepair or = orderRepairService.lambdaQuery()
                .eq(OrderRepair::getOrderBaseId,orderNo).one();
        if (or == null ){
            return;
        }
        itass.setCxyzm(or.getCxyzm());
        itass.setChaoshiqe(or.getChaoshiqe());
        itass.setZbby(or.getZbby());
        itass.setZptype(or.getZptype());
        itass.setYhif(or.getYhif());
        itass.setAuthState(orderBase.getOrderStatus());
        itass.setTsdengji(or.getTsdengji());
        if (StringUtils.isNotEmpty(or.getDemandSmallTypeId()) &&
                sysDictRefXLMapXq.containsKey(or.getDemandSmallTypeId())){
            itass.setXqxiaolei(sysDictRefXLMapXq.get(or.getDemandSmallTypeId()).get(0).getRefDictCode());
        } else {
            itass.setXqxiaolei(or.getDemandSmallTypeId());
        }

        if (orderBase.getOverTime()!=null){
            itass.setWcsj(orderBase.getOverTime());
            itass.setFwrybwgsj(orderBase.getOverTime());
        } else {
            if (orderBase.getUpdateTime()!=null){
                itass.setWcsj(orderBase.getUpdateTime());
                itass.setFwrybwgsj(orderBase.getUpdateTime());
            }
        }

    }

    public void setYhyyczsj(ItfTblAssignUpload itass, String orderNo) {
        List<OrderReAppointment> yys =  orderReAppointmentService.lambdaQuery()
                .eq(OrderReAppointment::getOrderBaseId, orderNo)
                .eq(OrderReAppointment::getFlag,0)
                .orderByDesc(OrderReAppointment::getCreateTime).list();
        if (!CollectionUtils.isEmpty(yys)){
            itass.setYhyyczsj(yys.get(0).getCreateTime());
        } else {
            List<OrderReAppointment> yyst =  orderReAppointmentService.lambdaQuery()
                    .eq(OrderReAppointment::getOrderBaseId, orderNo)
                    .eq(OrderReAppointment::getFlag,1)
                    .orderByDesc(OrderReAppointment::getCreateTime).list();
            if (!CollectionUtils.isEmpty(yyst)){
                itass.setYhyyczsj(yyst.get(0).getCreateTime());
            }
        }
    }

    public void setssxz(ItfTblAssignUpload itass){
        List<BrandLbsRelate> br;
        // 街道处理
        if (StringUtils.isNotEmpty(itass.getXzhenid())){
            br = brandLbsRelateService.lambdaQuery()
                    .eq(BrandLbsRelate::getLbsStreetId, itass.getXzhenid())
                    .eq(BrandLbsRelate::getDel,0)
                    .isNotNull(BrandLbsRelate::getStreetId).list();
            if (br !=null && br.size()>0){
                itass.setXzhenid(br.get(0).getStreetId());

                Street street = streetService.lambdaQuery()
                        .eq(Street::getStatus, 1)
                        .eq(Street::getProvince, itass.getSfenid())
                        .eq(Street::getCity, itass.getCshiid())
                        .eq(Street::getArea, itass.getXianid())
                        .eq(Street::getStreet, itass.getXzhenid()).one();
                if (street !=null){
                    itass.setXzhen(street.getStreet());
                    itass.setSfenid(Long.valueOf(street.getProvinceId()));
                    itass.setCshiid(Long.valueOf(street.getCityId()));
                    itass.setXianid(Long.valueOf(street.getAreaId()));

                    itass.setSfen(street.getProvince());
                    itass.setCshi(street.getCity());
                    itass.setXian(street.getArea());
                    return;
                }
            }
        }

        //省
        br = brandLbsRelateService.lambdaQuery()
                .eq(BrandLbsRelate::getLbsProvinceId, itass.getSfenid())
                .eq(BrandLbsRelate::getDel,0)
                .isNotNull(BrandLbsRelate::getProvinceId).list();
        if (br !=null && br.size()>0){
            itass.setSfenid(Long.valueOf(br.get(0).getProvinceId()));
        }
        //市
        br = brandLbsRelateService.lambdaQuery()
                .eq(BrandLbsRelate::getLbsCityId, itass.getCshiid())
                .eq(BrandLbsRelate::getDel,0)
                .isNotNull(BrandLbsRelate::getCityId).list();
        if (br !=null && br.size()>0){
            itass.setCshiid(Long.valueOf(br.get(0).getCityId()));
        }
        //区
        br = brandLbsRelateService.lambdaQuery()
                .eq(BrandLbsRelate::getLbsDistrictId, itass.getXianid())
                .eq(BrandLbsRelate::getDel,0)
                .isNotNull(BrandLbsRelate::getAreaId).list();
        if (br !=null && br.size()>0){
            itass.setXianid(Long.valueOf(br.get(0).getAreaId()));
        }

        // 总部区必选
        Area area = areaService.lambdaQuery()
                .eq(Area::getAreaId, itass.getXianid()).one();
        Street st = new Street();
        if (area !=null){
            itass.setSfen(area.getProvince());
            itass.setCshi(area.getCity());
            itass.setXian(area.getArea());
        }
    }

    public String getpgid(Token token, int uploadTaskType, String srcTabNameForGreekey, String greekeyGetMode,
                           OutJiasmToGreeUploadTaskList row, String newDykh) throws Exception {
        // 获取方式 Qry=从控制表获取 Ins=插入表获取自增列
        String greeKey;
        // 这里仅67满足
        if (greekeyGetMode != null && greekeyGetMode.equalsIgnoreCase("Ins")) {
            Long pgid = null;
            if (uploadTaskType == 67) {
                // 提取工单数据 取pgid
                OrderBase orderBase = orderBaseService.lambdaQuery()
                        .eq(OrderBase::getId, row.getOrderNo()).one();
                if (StringUtils.isNotEmpty(orderBase.getPgid())){
                    OrderPar request = new OrderPar();
                    request.setPgid(orderBase.getPgid());
                    request.setOrderNo(row.getOrderNo());
                    repairLogMapper.upRepairLogPgid(request);
                    pgid = Long.valueOf(orderBase.getPgid());
                }
            }
            if (pgid == null || pgid.toString().equals("0")) {
                throw new Exception("[工单号=" + row.getOrderNo() + "]的pgid为0,暂不传输!");
            }

            // TL_get_fa_order_repair_operating_log_fkid
            // 查看日志表对应ID的的fikd 值 荐存在直接返回该值无时通过网点接口做取
            OrderRepairOperatingLog rlog = orderRepairOperatingLogService.lambdaQuery()
                    .eq(OrderRepairOperatingLog::getId,row.getId()).one();
            if (StringUtils.isNotEmpty(rlog.getFkid())){
                newDykh = rlog.getFkid();
            } else {
                while (true) {
                    String serviceName = DataUtil.fromDbName2ServiceName(srcTabNameForGreekey);
                    String addDataUrl = baseurl + serviceName + "/add";
                    JSONResult addResult = HttpUtil.httpRequestWithToken(addDataUrl, "POST",
                            JSON.toJSONStringWithDateFormat(
                                    genDataMapFromSource(pgid, row.getTaskExtraInfo(), uploadTaskType),
                                    "yyyy-MM-dd HH:mm:ss"),
                            token);
                    if (!addResult.isOK()) {
                        throw new Exception(
                                "新增数据获取主键失败[" + serviceName + "],[" + addResult.getMsg() + "]");
                    } else {
                        if (addResult.getData() == null || addResult.getData().equals("")) {
                            throw new Exception("新增数据获取主键返回空[" + serviceName + "]");
                        } else {
                            newDykh = addResult.getData().toString();
                        }
                    }

                    // TL_get_fa_order_repair_operating_log_fkid_flag
                    OrderPar request = new OrderPar();
                    request.setPgid(newDykh);
                    OrderRepairOperatingLog r = repairLogMapper.getFkid(request);
                    if(r != null){
                        log.info("fkid在总部重复[" + newDykh + "]");
                    }else {
                        break;
                    }
                }
            }
        } else if (uploadTaskType == 66 || uploadTaskType == 661) {
            // pgid从主表中获取
            OrderBase ob = orderBaseService.lambdaQuery()
                    .eq(OrderBase::getId, row.getOrderNo()).one();
            greeKey = ob.getPgid();
            if (greeKey == null || greeKey.trim().equals("") || greeKey.trim().equals("0")) {
                Token token4Pgid = tokenCenter.getCurrentToken4Pgid();
                String url = baseurl4pgid + "api/repairEnter/getPgidSerial";
                JSONObject jsonObject = HttpUtil.httpRequestGetPgid(url, "POST", token4Pgid, null,
                        null);
                if (jsonObject.getString("statusCode").equals("200")) {
                    String data = jsonObject.getString("data");
                    newDykh = data;
                } else {
                    String message = jsonObject.getString("message");
                    if (message == null || message.trim().length() == 0) {
                        message = "取pgid失败";
                    }
                    throw new Exception(message);
                }
            } else {
                newDykh = greeKey;
            }
        } else if (uploadTaskType == 68) {
            // 从工单机型表中取对应ID的 pgmxid
            OrderProduct op = orderProductService.lambdaQuery()
                    .eq(OrderProduct::getOrderBaseId, row.getOrderNo())
                    .eq(OrderProduct::getId, row.getId()).one();
            greeKey = op.getPgmxid();
            if (greeKey == null || greeKey.trim().equals("") || greeKey.trim().equals("0")) {
                Token token4Pgid = tokenCenter.getCurrentToken4Pgid();
                String url = baseurl4pgid + "api/repairEnter/getMxIdserial";
                JSONObject jsonObject = HttpUtil.httpRequestGetPgid(url, "POST", token4Pgid, null,
                        null);
                if (jsonObject.getString("statusCode").equals("200")) {
                    String data = jsonObject.getString("data");
                    newDykh = data;
                } else {
                    String message = jsonObject.getString("message");
                    if (message == null || message.trim().length() == 0) {
                        message = "取pgmxid失败";
                    }
                    throw new Exception(message);
                }

            } else {
                newDykh = greeKey;
            }
        } else {
            String url = baseurl + "konghao/getDykh";
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("tabName", srcTabNameForGreekey);
            JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST",
                    JSON.toJSONString(paramMap), token);
            if (!jsonResult.isOK()) {
                throw new Exception("取dykh失败[" + jsonResult.getMsg() + "]");
            }
            JSONObject data = (JSONObject) jsonResult.getData();
            newDykh = data.getString("newDykh");
        }
        return newDykh;
    }

    public Map<String, Object> genDataMapFromSource(Long pgid, String taskExtraInfo, int uploadTaskType) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(DataUtil.fromDbName2ServiceName("pgid"), pgid);
        if (uploadTaskType == 67) {
            paramMap.put(DataUtil.fromDbName2ServiceName("fklb"), taskExtraInfo);
        }
        return paramMap;
    }

    public void upFaGreeSmsFjid(OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        FaGreeSms up = new FaGreeSms();
        up.setFjid(newDykh);
        QueryWrapper upWrapper = new QueryWrapper<FaGreeSms>()
                .eq("worker_order_no", sourceData.getOrderNo())
                .eq("azorwx",2)
                .and(wrapper->wrapper.isNull("fjid")
                        .or().eq("fjid","").or().eq("fjid",0));
        faGreeSmsService.update(up,upWrapper);
    }

    public void uporderRepairOperatingLogpgid(OutJiasmToGreeUploadTaskList sourceData, String newDykh) {
        List<OrderRepairOperatingLog> uops = new ArrayList<>();
        List<OrderRepairOperatingLog> ops = orderRepairOperatingLogService.lambdaQuery()
                .eq(OrderRepairOperatingLog::getOrderBaseId,sourceData.getOrderNo())
                .eq(OrderRepairOperatingLog::getPgid,0L).list();
        if (CollectionUtils.isEmpty(ops)){
            return;
        }
        for (OrderRepairOperatingLog item:ops){
            OrderRepairOperatingLog u = new OrderRepairOperatingLog();
            MyBeanUtils.copyProperties(item,u);
            u.setPgid(Long.valueOf(newDykh));
            uops.add(u);
        }

        orderRepairOperatingLogService.updateBatchById(uops);
        uops.clear();
    }

    public void upOrderBasePgguid(OutJiasmToGreeUploadTaskList sourceData, OrderBase orderBase) {
        if (StringUtils.isEmpty(orderBase.getPgguid()) || orderBase.getPgguid().equals("0")){
            OrderBase up = new OrderBase();
            up.setPgguid(publicService.getUUID());
            QueryWrapper upWrapper = new QueryWrapper<OrderBase>()
                    .eq("id", sourceData.getOrderNo())
                    .and(wrapper->wrapper.isNull("pgguid")
                            .or().eq("pgguid","").or().eq("pgguid",0));
            orderBaseService.update(up,upWrapper);
            orderBase.setPgguid(up.getPgguid());
        }
    }

    public void upOrderBasePgid(OrderBase orderBase, String newDykh) {
        if (StringUtils.isEmpty(orderBase.getPgid()) || orderBase.getPgid().equals("0")){
            orderBase.setPgid(newDykh);
        }
        if (StringUtils.isEmpty(orderBase.getPgguid()) || orderBase.getPgguid().equals("0")){
            orderBase.setPgguid(publicService.getUUID());
        }

        orderBase.updateById();
    }

    public void stopUpload(@NotNull OutJiasmToGreeUploadTaskList ojtutl, String msg) {
        OutJiasmToGreeUploadTaskList up = new OutJiasmToGreeUploadTaskList();
        up.setSynReqId(ojtutl.getSynReqId());
        up.setSynStatus(99);
        up.setSynTime(new Date());
        up.setSynErrMsg(msg);
        outJiasmToGreeUploadTaskListService.updateById(up);
    }

}
