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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zfire.jiasm.syncdata.api.OrderAddBeanDTO;
import com.zfire.jiasm.syncdata.constant.*;
import com.zfire.jiasm.syncdata.dao.mapper.AZGDFYQDDownloadMapper;
import com.zfire.jiasm.syncdata.dao.mapper.AZGDFkMxDownloadMapper;
import com.zfire.jiasm.syncdata.dao.mapper.AZGDLcLsDownloadMapper;
import com.zfire.jiasm.syncdata.parameter.OrderPar;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.response.WebsitFWS;
import com.zfire.jiasm.syncdata.service.AddInstallBusiness;
import com.zfire.jiasm.syncdata.service.JiasmApi;
import com.zfire.jiasm.syncdata.service.OrderService;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.utils.MyBeanUtils;
import com.zfire.jiasm.syncdata.utils.ResponseHelper;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AddInstallBusinessImpl implements AddInstallBusiness {
    @Resource
    ItfTblAzAssignLcLsDownloadService itfTblAzAssignLcLsDownloadService;
    @Resource
    ItfTblAzAssignMxDownloadService itfTblAzAssignMxDownloadService;
    @Resource
    AZGDLcLsDownloadMapper azGDLcLsDownloadMapper;
    @Resource
    OrderBaseService orderBaseService;
    @Resource
    OrderWorkerService orderWorkerService;
    @Resource
    OrderProductService orderProductService;
    @Resource
    ItfTblAzAssignFkmxDownloadService itfTblAzAssignFkmxDownloadService;
    @Resource
    OrderInstallOperatingLogService orderInstallOperatingLogService;
    @Resource
    AZGDFkMxDownloadMapper azGDFkMxDownloadMapper;
    @Resource
    ItfTblAzAssignFeeDownloadService itfTblAzAssignFeeDownloadService;
    @Resource
    AZGDFYQDDownloadMapper azGDFYQDDownloadMapper;
    @Resource
    OrderInstallService orderInstallService;
    @Resource
    ItfTblAzAssignAppointmentDownloadService itfTblAzAssignAppointmentDownloadService;
    @Resource
    OrderReAppointmentService orderReAppointmentService;
    @Resource
    ItfTblAzAssignSatisfactionDownloadService itfTblAzAssignSatisfactionDownloadService;
    @Resource
    OrderAppraiseService orderAppraiseService;
    @Resource
    OrderService orderService;
    @Resource
    PublicService publicService;
    @Resource
    FaGreeSmsService faGreeSmsService;
    @Resource
    OrderAppealService orderAppealService;
    @Resource
    ItfGreeToFaDownloadTaskListService itfGreeToFaDownloadTaskListService;
    @Resource
    OrderInstallDetailService orderInstallDetailService;
    @Resource
    OrderDetailFileService orderDetailFileService;
    @Autowired
    JiasmApi jiasmApi;
    @Autowired
    SysVariableConfigService sysVariableConfigService;
    @Autowired
    ItfMessagehuifangentityService itfMessagehuifangentityService;
    @Resource
    SyncCreateOrderService syncCreateOrderService;





    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrder(Map<String, List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                         Map<String, List<SysDictRef>> sysDictRefXiLieMap, Brand brand, ItfTblAzAssignLcLsDownload item, Map<String,String> productMap) {
        List<OrderReAppointment> oa = new ArrayList<>();
        List<OrderAppraise> oanew = new ArrayList<>();
        List<OrderProduct> orderProducts = new ArrayList<>();
        List<OrderInstallDetail> oids = new ArrayList<>();
        List<OrderDetailFile> odfs = new ArrayList<>();
        List<ItfTblAzAssignFkmxDownload> fkmxs = new ArrayList<>();
        List<Long> synReqIds = new ArrayList<>();
        List<Long> synReqFkMxIds = new ArrayList<>();
        List<Long> synReqYfYyIds = new ArrayList<>();
        List<FaGreeSms> faGreeSms = new ArrayList<>();
        List<OrderAppeal> orderAppeal = new ArrayList<>();
        List<ItfGreeToFaDownloadTaskList> its = new ArrayList<>();

        List<ItfTblAzAssignMxDownload> orderMx = itfTblAzAssignMxDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignMxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignMxDownload::getSynStatus, SynStatusEnum.UN_SYN.getCode())
                .orderByAsc(ItfTblAzAssignMxDownload::getSynReqId)
                .list();
        synReqIds = orderMx.stream().map(ItfTblAzAssignMxDownload::getSynReqId).collect(Collectors.toList());

        fkmxs = itfTblAzAssignFkmxDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignFkmxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignFkmxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignFkmxDownload::getCreatedDate)
                .list();
        synReqFkMxIds = fkmxs.stream().map(ItfTblAzAssignFkmxDownload::getSynReqId).collect(Collectors.toList());

        // 分销商城订单 这里不再判断
        /*if (item.getShopno().equals("88888888")){
            ItfFxInstallReq itfFxInstallReq=itfFxInstallReqService.lambdaQuery()
                    .eq(ItfFxInstallReq::getPgguid,item.getPgguid()).one();
            if (itfFxInstallReq==null){
                synItfTblAzAssignLcLsDownload(item.getSynReqId(), 99, "分销商城订单生成失败(itf_fx_install_req pgguid="+item.getPgguid());
                return;
            }
        }*/

        // 获取安装工单主表 + 采集数据下载
        OrderBase orderBase = getAddOrderBase(item, brand,its);

        // 以旧换新数据下载同步表
        getOldForNewProduct(item, orderBase,its);

        // 获取工单师傅信息
        OrderWorker orderWorker = getOrderWorker(orderBase);
        // 获取工单机型 + 生成采集明细数据+附件数据
        getOrderProduct(orderBase, orderProducts, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap,
                orderMx,oids,odfs, productMap);
        // 获取工单操作明细- 操作日志表
        List<OrderInstallOperatingLog> oiolList = getOrderInstallOperatingLogs(fkmxs, orderBase,item);
        // 获取安装费用清单 - 对应扩展表
        List<ItfTblAzAssignFeeDownload> fyqd = itfTblAzAssignFeeDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignFeeDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignFeeDownload::getSynStatus,0)
                .orderByDesc(ItfTblAzAssignFeeDownload::getSynReqId)
                .list();
        // 获取工单扩展信息  - 费用清单是不能放在扩展表的，这里有误 从订单表取才可以
        OrderInstall orderInstall = getOrderInstall(orderBase, item, fyqd);
        // 获取用户预约改约信息
        List<ItfTblAzAssignAppointmentDownload> appointments = itfTblAzAssignAppointmentDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignAppointmentDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignAppointmentDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignAppointmentDownload::getSynReqId)
                .list();
        synReqYfYyIds = appointments.stream().map(ItfTblAzAssignAppointmentDownload::getSynReqId).collect(Collectors.toList());
        getOrderAppointment(orderBase, oa, appointments);

        // 获取用户客户评价信息
        List<Long> getpjSynReqId = new ArrayList<>();
        getOrderAppraise(orderBase, sysDictRefDLMap, oanew, item.getDownloadTaskNo(), getpjSynReqId,faGreeSms,orderAppeal);

        // 安装工单数据落本地表
        addOrderData(orderBase, orderWorker, orderInstall, orderProducts, oiolList, oa, oanew,
                item.getSynReqId(), synReqIds, synReqFkMxIds, synReqYfYyIds, fyqd, getpjSynReqId,
                faGreeSms,orderAppeal, its, oids,odfs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrderApi(Map<String, List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                         Map<String, List<SysDictRef>> sysDictRefXiLieMap, Brand brand,
                            ItfTblAzAssignLcLsDownload item, Boolean flag, Map<String,String> productMap) throws Exception {
        List<OrderReAppointment> oa = new ArrayList<>();
        List<OrderAppraise> oanew = new ArrayList<>();
        List<OrderProduct> orderProducts = new ArrayList<>();
        List<OrderInstallDetail> oids = new ArrayList<>();
        List<OrderDetailFile> odfs = new ArrayList<>();
        List<ItfTblAzAssignFkmxDownload> fkmxs = new ArrayList<>();
        List<Long> synReqIds = new ArrayList<>();
        List<Long> synReqFkMxIds = new ArrayList<>();
        List<Long> synReqYfYyIds = new ArrayList<>();
        List<FaGreeSms> faGreeSms = new ArrayList<>();
        List<OrderAppeal> orderAppeal = new ArrayList<>();
        List<ItfGreeToFaDownloadTaskList> its = new ArrayList<>();

        // 工单产品
        List<ItfTblAzAssignMxDownload> orderMx = itfTblAzAssignMxDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignMxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignMxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignMxDownload::getSynReqId)
                .list();
        synReqIds = orderMx.stream().map(ItfTblAzAssignMxDownload::getSynReqId).collect(Collectors.toList());

        fkmxs = itfTblAzAssignFkmxDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignFkmxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignFkmxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignFkmxDownload::getCreatedDate)
                .list();
        synReqFkMxIds = fkmxs.stream().map(ItfTblAzAssignFkmxDownload::getSynReqId).collect(Collectors.toList());
        log.info("提取反馈明细数据:{} 条目数{}", item.getDownloadTaskNo(),synReqFkMxIds.size());

        // 获取安装工单主表
        // 同时生成改派申请数据、采集预下载数据 2201 称到最下面处理
        OrderBase orderBase = getAddOrderBaseApi(item, brand,its);

        // 以旧换新数据下载同步表
        getOldForNewProduct(item, orderBase,its);

        // 获取工单师傅信息
        OrderWorker orderWorker = getOrderWorker(orderBase);
        // 获取工单机型 + 生成采集明细数据+附件数据
        getOrderProduct(orderBase, orderProducts, sysDictRefDLMap, sysDictRefXLMap,
                sysDictRefXiLieMap, orderMx,oids,odfs, productMap);

        // 获取工单操作明细- 操作日志表
        List<OrderInstallOperatingLog> oiolList = getOrderInstallOperatingLogs(fkmxs, orderBase, item);

        // 获取安装费用清单 - 对应扩展表
        List<ItfTblAzAssignFeeDownload> fyqd = itfTblAzAssignFeeDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignFeeDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignFeeDownload::getSynStatus,0)
                .orderByDesc(ItfTblAzAssignFeeDownload::getSynReqId)
                .list();
        // 获取工单扩展信息  - 费用清单是不能放在扩展表的，这里有误 从订单表取才可以
        OrderInstall orderInstall = getOrderInstall(orderBase, item, fyqd);
        // 获取用户预约改约信息
        List<ItfTblAzAssignAppointmentDownload> appointments = itfTblAzAssignAppointmentDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignAppointmentDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignAppointmentDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignAppointmentDownload::getSynReqId)
                .list();
        synReqYfYyIds = appointments.stream().map(ItfTblAzAssignAppointmentDownload::getSynReqId).collect(Collectors.toList());
        getOrderAppointment(orderBase, oa, appointments);

        // 获取用户客户评价信息
        List<Long> getpjSynReqId = new ArrayList<>();
        getOrderAppraise(orderBase, sysDictRefDLMap, oanew, item.getDownloadTaskNo(), getpjSynReqId,faGreeSms,orderAppeal);

        //网点转换还原
        publicService.revertFun(orderBase, item);

        createInstallOrder(item, orderProducts, oiolList, odfs, synReqIds, synReqFkMxIds,
                synReqYfYyIds, faGreeSms,  orderAppeal,
                 its, orderBase, orderWorker, fyqd,
                orderInstall, getpjSynReqId, flag, oids, oa);

    }



    private void createInstallOrder(ItfTblAzAssignLcLsDownload item, List<OrderProduct> orderProducts,
                                    List<OrderInstallOperatingLog> oiolList,
                                    List<OrderDetailFile> odfs, List<Long> synReqIds, List<Long> synReqFkMxIds,
                                    List<Long> synReqYfYyIds, List<FaGreeSms> faGreeSms, List<OrderAppeal> orderAppeal,
                                    List<ItfGreeToFaDownloadTaskList> its, OrderBase orderBase, OrderWorker orderWorker,
                                    List<ItfTblAzAssignFeeDownload> fyqd,
                                    OrderInstall orderInstall, List<Long> getpjSynReqId, Boolean flag,
                                    List<OrderInstallDetail> oids,
                                    List<OrderReAppointment> oa) throws Exception {
        // 创建工单
        OrderAddBeanDTO createOrder = new OrderAddBeanDTO();
        // 工单机型
        List<OrderProduct> orderProductList = new ArrayList<>();
        // 工单辅材表
        List<OrderMaterial> orderMaterialList = new ArrayList<>();
        // 工单清洗项目
        List<OrderCleanItem> orderCleanItems = new ArrayList<>();

        // 工单主表、机型、辅材、清洗、预约改约记录、师傅、创建日志、生成采集数据不要
        getOrderApi(orderProducts, orderBase, orderWorker, orderInstall, createOrder,
                orderProductList, orderMaterialList, orderCleanItems, flag);
        log.info("创建安装工单接口 request:{}", JSONObject.toJSONString(createOrder));
        ResponseHelper respone = jiasmApi.orderAdd(createOrder);
        log.info("创建安装工单接口 respone:{}", JSONObject.toJSONString(respone));
        if (respone.getCode()==200){
            if (flag){
                SyncCreateOrder sco = new SyncCreateOrder();
                sco.setId(publicService.getUUID());
                sco.setOrderBaseId(createOrder.getGreeId());
                sco.setPgidOrPgguid(item.getPgguid());
                sco.setOrderJson(JSONObject.toJSONString(createOrder));
                sco.setCreateTime(new Date());
                syncCreateOrderService.save(sco);
            }

            // 安装工单数据落本地表
            addOrderDataApi(item.getSynReqId(), synReqIds, synReqFkMxIds, synReqYfYyIds, fyqd, getpjSynReqId,
                    faGreeSms, orderAppeal, its, odfs, oiolList, oids, oa);
        } else {
            String msg = publicService.getErrormessage(respone);
            log.info(msg);
            // 抛异常目的是把前期的数据修改回滚
            throw new Exception(msg);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void UpdateOrder(Map<String, List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                            Map<String, List<SysDictRef>> sysDictRefXiLieMap, Brand brand, ItfTblAzAssignLcLsDownload item) {
        List<Long> synReqYfYyIds = new ArrayList<>();
        List<OrderReAppointment> addoalists = new ArrayList<>();
        List<ItfTblAzAssignMxDownload> mxsynreqids = new ArrayList<>();
        List<ItfTblAzAssignFkmxDownload> synreqids = new ArrayList<>();
        List<OrderProduct> orderProductsUpdate = new ArrayList<>();
        List<OrderInstallOperatingLog> addoiolList = new ArrayList<>();
        List<Long> getpjSynReqId = new ArrayList<>();
        List<OrderAppraise> addoalist = new ArrayList<>();
        List<FaGreeSms> faGreeSms = new ArrayList<>();
        List<OrderAppeal> orderAppeal = new ArrayList<>();
        List<ItfGreeToFaDownloadTaskList> its = new ArrayList<>();
        List<OrderInstallDetail> oids = new ArrayList<>();
        List<String> delOrderProduct = new ArrayList<>();
        List<String> delOrderInstallDetail = new ArrayList<>();
        List<OrderDetailFile> odfs = new ArrayList<>();

        // 提取本地订单
        OrderBase old = orderBaseService.lambdaQuery()
                .eq(OrderBase::getPgguid, item.getPgguid())
                .last("limit 1").one();

        // 获取安装工单主表
        OrderBase newLCLS = getAddOrderBaseUp(item, brand,its);
        // 这里一定不能少 已生成了工单号，不能再次生成
        newLCLS.setId(old.getId());
        newLCLS.setDispatchStatus(old.getDispatchStatus());

        // 获取工单主表要同步的数据  upInfo 为null
        OrderBase upInfo = getOrderBaseUp(old, item, newLCLS);

        // 以旧换新数据下载同步表
        getOldForNewProductt(item, newLCLS,its,old);

        // 获取工单师傅信息来自于工单主表数据只有修改的情况
        OrderWorker own =getOrderWorkerUpdate(old.getId(), upInfo, newLCLS);

        // 获取产品明细要同步的数据 -只存在修改，减少与增加的情况不存在
        /*getOrderProductsUpdate(sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap, old, newLCLS,
                item.getDownloadTaskNo(),mxsynreqids,orderProductsUpdate,oids,delOrderInstallDetail,odfs,delOrderProduct);*/

        // 获取操作明细同步数据，即反馈明细
        addoiolList = getOrderInstallOperatingLogsadd(item, old, newLCLS, synreqids);

        // 费用清单 放扩展表
        // 提取已同步的数据
        OrderInstall oldOrderInstall = orderInstallService.lambdaQuery()
                .eq(OrderInstall::getOrderBaseId,old.getId())
                .last("limit 1").one();
        // 获取安装费用清单
        List<ItfTblAzAssignFeeDownload> fyqd = itfTblAzAssignFeeDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignFeeDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignFeeDownload::getSynStatus,0)
                .list();
        OrderInstall orderInstall = getOrderInstall(newLCLS, item, fyqd);
        // 已同步的有数据，后期的一定有数据  直接修改
        if (oldOrderInstall != null && orderInstall!=null){
            orderInstall.setId(oldOrderInstall.getId());
            orderInstall.setUpdateBy(newLCLS.getLastOperatorBy());
            orderInstall.setUpdateTime(newLCLS.getLastOperatorTime());
        }

        // 获取用户预约改约信息
        synReqYfYyIds = getYfYyLongs(item, old, newLCLS, addoalists);

        // 获取评价同步数据
        addoalist = getOrderAppraises(sysDictRefDLMap, item, upInfo, getpjSynReqId,faGreeSms, orderAppeal);

        // 安装工单数据修改落本地表
        addOrUpdateOrderData(item, upInfo, own, mxsynreqids, orderProductsUpdate, synreqids,
                addoiolList, fyqd, orderInstall, synReqYfYyIds, addoalists, getpjSynReqId,
                addoalist, faGreeSms,orderAppeal, its,oids, delOrderInstallDetail,odfs,delOrderProduct);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderApi(Map<String, List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                               Map<String, List<SysDictRef>> sysDictRefXiLieMap, Brand brand,
                               ItfTblAzAssignLcLsDownload item, Boolean flag, Map<String,String> productMap) throws Exception {
        List<Long> synReqYfYyIds = new ArrayList<>();
        List<OrderReAppointment> addoalists = new ArrayList<>();
        List<ItfTblAzAssignMxDownload> mxsynreqids = new ArrayList<>();
        List<ItfTblAzAssignFkmxDownload> synreqids = new ArrayList<>();
        List<OrderProduct> orderProductsUpdate = new ArrayList<>();
        List<OrderInstallOperatingLog> addoiolList = new ArrayList<>();
        List<Long> getpjSynReqId = new ArrayList<>();
        List<OrderAppraise> addoalist = new ArrayList<>();
        List<FaGreeSms> faGreeSms = new ArrayList<>();
        List<OrderAppeal> orderAppeal = new ArrayList<>();
        List<ItfGreeToFaDownloadTaskList> its = new ArrayList<>();
        List<OrderInstallDetail> oids = new ArrayList<>();
        List<String> delOrderProduct = new ArrayList<>();
        List<String> delOrderInstallDetail = new ArrayList<>();
        List<OrderDetailFile> odfs = new ArrayList<>();
        OrderBase oldr = new OrderBase();

        // 向工单子表下载任务表插入数据
        downInformation(item);

        // 提取本地订单
        OrderBase old = orderBaseService.lambdaQuery()
                .eq(OrderBase::getPgguid, item.getPgguid())
                .last("limit 1").one();

        // 为网点还原准备
        MyBeanUtils.copyProperties(old,oldr);

        // 获取安装工单主表 并生成采集数据下载数据 2201
        OrderBase newLCLS = getAddOrderBaseUpApi(item, brand, its);
        // 这里一定不能少 已生成了工单号，不能再次生成
        newLCLS.setId(old.getId());
        newLCLS.setDispatchStatus(old.getDispatchStatus());

        // 获取工单主表要同步的数据  upInfo 为null
        OrderBase upInfo = getOrderBaseUp(old, item, newLCLS);

        // 以旧换新数据下载同步表
        getOldForNewProductt(item, newLCLS,its,old);

        // 获取工单师傅信息来自于工单主表数据只有修改的情况
        OrderWorker own =getOrderWorkerUpdate(old.getId(), upInfo, newLCLS);

        // 获取产品明细要同步的数据 -只存在修改，减少与增加的情况不存在
        getOrderProductsUpdate(sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap, old, newLCLS,
                item.getDownloadTaskNo(),mxsynreqids,orderProductsUpdate,oids,delOrderInstallDetail,
                odfs,delOrderProduct, productMap);

        // 获取操作明细同步数据，即反馈明细
        addoiolList = getOrderInstallOperatingLogsadd(item, old, newLCLS, synreqids);

        // 费用清单 放扩展表
        // 提取已同步的数据
        OrderInstall oldOrderInstall = orderInstallService.lambdaQuery()
                .eq(OrderInstall::getOrderBaseId,old.getId())
                .last("limit 1").one();
        // 获取安装费用清单
        List<ItfTblAzAssignFeeDownload> fyqd = itfTblAzAssignFeeDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignFeeDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignFeeDownload::getSynStatus,0)
                .list();
        OrderInstall orderInstall = getOrderInstall(newLCLS, item, fyqd);
        // 已同步的有数据，后期的一定有数据  直接修改
        if (oldOrderInstall != null && orderInstall!=null){
            orderInstall.setId(oldOrderInstall.getId());
            orderInstall.setUpdateBy(newLCLS.getLastOperatorBy());
            orderInstall.setUpdateTime(newLCLS.getLastOperatorTime());
        }

        // 获取用户预约改约信息
        synReqYfYyIds = getYfYyLongs(item, old, newLCLS, addoalists);

        // 获取评价同步数据
        addoalist = getOrderAppraises(sysDictRefDLMap, item, newLCLS, getpjSynReqId,faGreeSms, orderAppeal);


        // 创建工单
        OrderAddBeanDTO order = new OrderAddBeanDTO();
        // 工单机型
        List<OrderProduct> orderProductList = new ArrayList<>();
        // 工单辅材表
        List<OrderMaterial> orderMaterialList = new ArrayList<>();
        // 工单清洗项目
        List<OrderCleanItem> orderCleanItems = new ArrayList<>();

        // 网点转换还原
        revertFun(oldr, item, upInfo);

        // 工单主表、机型、辅材、清洗、预约改约记录、师傅、创建日志、生成采集数据不要
        getOrderApi(orderProductsUpdate, upInfo, own, orderInstall, order, orderProductList, orderMaterialList, orderCleanItems,flag);
        log.info("修改安装工单接口 request:{}", JSONObject.toJSONString(order));
        ResponseHelper respone = jiasmApi.orderAdd(order);
        log.info("修改安装工单接口 respone:{}", JSONObject.toJSONString(respone));
        if (respone.getCode()==200){
            // 安装工单数据修改落本地表
            addOrUpdateOrderDataApi(item, mxsynreqids, synreqids,addoiolList,
                    fyqd, synReqYfYyIds, getpjSynReqId,
                    addoalist, faGreeSms,orderAppeal, its,odfs, addoalists);
        } else {
            String msg = publicService.getErrormessage(respone);
            log.info(msg);
            // 抛异常目的是把前期的数据修改回滚
            throw new Exception(msg);
        }
    }

    public void addOrUpdateOrderDataApi(ItfTblAzAssignLcLsDownload item,
                                     List<ItfTblAzAssignMxDownload> mxsynreqids,
                                     List<ItfTblAzAssignFkmxDownload> synreqids,List<OrderInstallOperatingLog> addoiolList,
                                     List<ItfTblAzAssignFeeDownload> fyqd,List<Long> synReqYfYyIds,
                                     List<Long> getpjSynReqId, List<OrderAppraise> addoalist,
                                     List<FaGreeSms> faGreeSms,List<OrderAppeal> orderAppeal,List<ItfGreeToFaDownloadTaskList> its,
                                     List<OrderDetailFile> odfs,List<OrderReAppointment> addoalists) {
        // 同步修改订单基础表

        // lc_ls同步状态改成1 同步成功
        synItfTblAzAssignLcLsDownload(item.getSynReqId(),1,"成功");
        // 同步新增或修改师傅信息 own 从工单主表过来，无load表修改
        // 同步修改产品明细表
        if (mxsynreqids.size()>0){
            itfTblAzAssignMxDownloadService.updateBatchById(mxsynreqids);
            mxsynreqids.clear();
        }
        // 同步新增操作日志表
        if (addoiolList.size()>0){
            orderInstallOperatingLogService.saveBatch(addoiolList);
            addoiolList.clear();
        }
        // 同步新增操作日志表
        if (synreqids.size()>0){
            itfTblAzAssignFkmxDownloadService.updateBatchById(synreqids);
            synreqids.clear();
        }

        // 同步修改安装工单扩展表
        if (CollectionUtils.isNotEmpty(fyqd)){
            upItfTblAzAssignFeeDownload(fyqd);
        }

        // 同步用户预约表
        if (addoalists.size()>0){
            orderReAppointmentService.updateBatchById(addoalists);
            addoalists.clear();
        }
        if (synReqYfYyIds.size()>0){
            upItfTblAzAssignAppointment(synReqYfYyIds);
            synReqYfYyIds.clear();
        }

        // 预约改约-总部短信发送
        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }

        // 差评申诉
        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }

        // 以旧换新
        if (its.size()>0){
            itfGreeToFaDownloadTaskListService.saveBatch(its);
            its.clear();
        }

        // 改派申请单

        // 删除产品机型
        // 新增采集附件
        if (odfs.size()>0){
            orderDetailFileService.saveOrUpdateBatch(odfs);
            odfs.clear();
        }

        // 客户评价
        if (getpjSynReqId.size()>0){
            upItfTblAzAssignSatisfactionDownload(getpjSynReqId);
            getpjSynReqId.clear();
        }

    }

    public void addOrderDataApi(Long synReqId, List<Long> synReqIds,  List<Long> synReqFkMxIds,
                                List<Long> synReqYfYyIds,
                                List<ItfTblAzAssignFeeDownload> fyqd, List<Long> getpjSynReqId,
                                List<FaGreeSms> faGreeSms,List<OrderAppeal> orderAppeal,
                                List<ItfGreeToFaDownloadTaskList> its,
                                List<OrderDetailFile> odfs, List<OrderInstallOperatingLog> oiolList,
                                List<OrderInstallDetail> oids,
                                List<OrderReAppointment> oa) {
        // 工单基础表
        // 工单扩展信息
        // 工单师傅表
        // 工单机型表
        // 采集明细

        // 采集附件
        if (odfs.size()>0){
            orderDetailFileService.saveBatch(odfs);
            odfs.clear();
        }
        if (synReqIds.size()>0){
            upItfTblAzAssignMxDownload(synReqIds);
            synReqIds.clear();
        }

        // 采集明细
        /*if (oids.size()>0){
            orderInstallDetailService.saveBatch(oids);
            oids.clear();
        }*/

        // 同步新增操作日志表
        if (oiolList.size()>0){
            orderInstallOperatingLogService.saveBatch(oiolList);
            oiolList.clear();
        }
        // 操作明细表
        if (synReqFkMxIds.size()>0){
            upItfTblAzAssignFkmxDownload(synReqFkMxIds);
            synReqFkMxIds.clear();
        }

        // 安装费用清单表
        if (CollectionUtils.isNotEmpty(fyqd)){
            upItfTblAzAssignFeeDownload(fyqd);
        }

        // 用户预约改约信息表
        if (oa.size()>0){
            orderReAppointmentService.saveOrUpdateBatch(oa);
            oa.clear();
        }
        if (synReqYfYyIds.size()>0){
            upItfTblAzAssignAppointment(synReqYfYyIds);
            synReqYfYyIds.clear();
        }


        // 差评给网点发短信
        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }
        // 生成申诉数据
        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }
        // 以旧换新
        if (its.size()>0){
            itfGreeToFaDownloadTaskListService.saveBatch(its);
            its.clear();
        }
        // 客户评价信息
        if (getpjSynReqId.size()>0){
            upItfTblAzAssignSatisfactionDownload(getpjSynReqId);
            getpjSynReqId.clear();
        }
        // 改派申请单
        // 修改同步状态
        upItfTblAzAssignLcLsDownload(synReqId);
    }

    private void getOrderApi(List<OrderProduct> orderProducts, OrderBase orderBase,
                             OrderWorker orderWorker,OrderInstall orderInstall, OrderAddBeanDTO createOrder,
                             List<OrderProduct> orderProductList, List<OrderMaterial> orderMaterialList,
                             List<OrderCleanItem> orderCleanItems,Boolean flag) {
        if (orderProducts!=null){
            orderProductList.addAll(orderProducts);
        }
        if (orderInstall !=null){
            MyBeanUtils.copyProperties(orderInstall, createOrder);
        }
        // 工单
        MyBeanUtils.copyProperties(orderBase, createOrder);
        // 新增
        if (flag){
            createOrder.setGreeId(orderBase.getId());
            createOrder.setId("");
        }
        createOrder.getOrderMaterialList().addAll(orderMaterialList);
        createOrder.getOrderCleanItems().addAll(orderCleanItems);
        createOrder.getOrderProductList().addAll(orderProductList);
        createOrder.setOperatorFlag(2);
        createOrder.setFlag(1);
        if (orderBase.getOutCjDownloadFlag() == null){
            createOrder.setOutCjDownloadFlag(0);
        }

        if (orderWorker !=null){
            List<String> workerIds = new ArrayList<>();
            workerIds.add(orderWorker.getWorkerId());
            createOrder.getWebsitWorkerIds().addAll(workerIds);
        }
        createOrder.setLinkName(orderBase.getUserName());
    }

    private void downInformation(ItfTblAzAssignLcLsDownload item) {
        ItfGreeToFaDownloadTaskList tl = new ItfGreeToFaDownloadTaskList();
        tl.setDownloadTaskNo(IdWorker.getIdStr());
        tl.setDownloadKeyValue(item.getPgguid());
        tl.setDownloadTaskType(2206);
        tl.setDownloadStatus(0);
        tl.insert();
    }

    public void addOrUpdateOrderData(ItfTblAzAssignLcLsDownload item, OrderBase upInfo, OrderWorker own,
                                     List<ItfTblAzAssignMxDownload> mxsynreqids, List<OrderProduct> orderProductsUpdate,
                                     List<ItfTblAzAssignFkmxDownload> synreqids, List<OrderInstallOperatingLog> addoiolList,
                                     List<ItfTblAzAssignFeeDownload> fyqd, OrderInstall orderInstall, List<Long> synReqYfYyIds,
                                     List<OrderReAppointment> addoalists, List<Long> getpjSynReqId, List<OrderAppraise> addoalist,
                                     List<FaGreeSms> faGreeSms,List<OrderAppeal> orderAppeal,List<ItfGreeToFaDownloadTaskList> its,
                                     List<OrderInstallDetail> oids,
                                     List<String> oiddels,List<OrderDetailFile> odfs,List<String> delOrderProduct) {
        // 同步修改订单基础表
        if (upInfo !=null){
            orderBaseService.updateById(upInfo);
            // lc_ls同步状态改成1 同步成功
            synItfTblAzAssignLcLsDownload(item.getSynReqId(),1,"成功");
        }

        // 同步新增或修改师傅信息 own 从工单主表过来，无load表修改
        if (own != null){
            orderWorkerService.saveOrUpdate(own);
        }

        // 同步修改产品明细表
        if (orderProductsUpdate.size()>0){
            orderProductService.saveOrUpdateBatch(orderProductsUpdate);
            orderProductsUpdate.clear();
        }
        if (mxsynreqids.size()>0){
            itfTblAzAssignMxDownloadService.updateBatchById(mxsynreqids);
            mxsynreqids.clear();
        }

        // 同步新增操作日志表
        if (addoiolList.size()>0){
            orderInstallOperatingLogService.saveBatch(addoiolList);
            addoiolList.clear();
        }
        if (synreqids.size()>0){
            itfTblAzAssignFkmxDownloadService.updateBatchById(synreqids);
            synreqids.clear();
        }

        // 同步修改安装工单扩展表
        if (orderInstall !=null){
            orderInstallService.saveOrUpdate(orderInstall);
        }
        if (CollectionUtils.isNotEmpty(fyqd)){
            upItfTblAzAssignFeeDownload(fyqd);
        }

        // 同步用户预约表
        if (addoalists.size()>0){
            orderReAppointmentService.saveBatch(addoalists);
            addoalists.clear();
        }
        if (synReqYfYyIds.size()>0){
            upItfTblAzAssignAppointment(synReqYfYyIds);
            synReqYfYyIds.clear();
        }

        // 预约改约-总部短信发送
        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }

        // 差评申诉
        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }

        // 以旧换新
        if (its.size()>0){
            itfGreeToFaDownloadTaskListService.saveBatch(its);
            its.clear();
        }

        // 改派申请单

        // 更新采集表
        if (oids.size()>0){
            orderInstallDetailService.saveOrUpdateBatch(oids);
            oids.clear();
        }
        // 删除采集数据
        if (oiddels.size()>0){
            orderInstallDetailService.removeByIds(oiddels);
            oiddels.clear();
        }
        // 删除产品机型
        if (delOrderProduct.size()>0){
            orderProductService.removeByIds(delOrderProduct);
            delOrderProduct.clear();
        }
        // 新增采集附件
        if (odfs.size()>0){
            orderDetailFileService.saveOrUpdateBatch(odfs);
            odfs.clear();
        }

        // 客户评价
        if (getpjSynReqId.size()>0){
            upItfTblAzAssignSatisfactionDownload(getpjSynReqId);
            getpjSynReqId.clear();
        }

    }

    @NotNull
    private List<Long> getYfYyLongs(ItfTblAzAssignLcLsDownload item, OrderBase old, OrderBase newLCLS, List<OrderReAppointment> addoalists) {
        List<Long> synReqYfYyIds;
        List<OrderReAppointment> oaps = new ArrayList<>();
        // 提取已同步的
        List<OrderReAppointment> oapps = orderReAppointmentService.lambdaQuery()
                .select(OrderReAppointment::getId)
                .eq(OrderReAppointment::getOrderBaseId, old.getId()).list();
        List<String> oappslist  = oapps.stream().map(OrderReAppointment::getId).collect(Collectors.toList());

        // 获取用户预约改约信息
        List<ItfTblAzAssignAppointmentDownload> appointments = itfTblAzAssignAppointmentDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignAppointmentDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignAppointmentDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignAppointmentDownload::getSynReqId)
                .list();
        synReqYfYyIds = appointments.stream().map(ItfTblAzAssignAppointmentDownload::getSynReqId).collect(Collectors.toList());
        // 提取本次获取的
        getOrderAppointment(newLCLS, oaps, appointments);

        // 移除已同步过的
        for (OrderReAppointment oa:oaps){
            if (!oappslist.contains(oa.getId())){
                addoalists.add(oa);
            }
        }
        return synReqYfYyIds;
    }

    @NotNull
    private List<OrderAppraise> getOrderAppraises(Map<String, List<SysDictRef>> sysDictRefDLMap,
                                                  ItfTblAzAssignLcLsDownload item,
                                                  OrderBase newLCLS, List<Long> getpjSynReqId,
                                                  List<FaGreeSms> faGreeSms,List<OrderAppeal> orderAppeal) {
        List<OrderAppraise> oanew = new ArrayList<>();
        // 提取本次获取的
        getOrderAppraise(newLCLS, sysDictRefDLMap, oanew, item.getDownloadTaskNo(), getpjSynReqId,faGreeSms, orderAppeal);

        return oanew;
    }

    private void upItfTblAzAssignSatisfactionDownload(List<Long> getpjSynReqId) {
        List<ItfTblAzAssignSatisfactionDownload> sas =new ArrayList<>();
        for (int i = 0; i< getpjSynReqId.size(); i++){
            ItfTblAzAssignSatisfactionDownload add = new ItfTblAzAssignSatisfactionDownload();
            add.setSynReqId(getpjSynReqId.get(i));
            add.setSynStatus(1);
            add.setSynTime(new Date());
            add.setSynErrMsg("成功");
            sas.add(add);
        }
        itfTblAzAssignSatisfactionDownloadService.updateBatchById(sas);
    }

    @NotNull
    private List<OrderInstallOperatingLog> getOrderInstallOperatingLogsadd(ItfTblAzAssignLcLsDownload item, OrderBase old,
                                                                           OrderBase newLCLS, List<ItfTblAzAssignFkmxDownload> synreqids) {
        // 提取已同步的
        List<OrderInstallOperatingLog> oiols = orderInstallOperatingLogService.lambdaQuery()
                .select(OrderInstallOperatingLog::getPgguid,
                        OrderInstallOperatingLog::getFkid)
                .eq(OrderInstallOperatingLog::getOrderBaseId, old.getId()).list();

        List<String> oiolslist  = oiols.stream().map(OrderInstallOperatingLog::getFkid).collect(Collectors.toList());

        List<ItfTblAzAssignFkmxDownload> fkmxs = itfTblAzAssignFkmxDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignFkmxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAzAssignFkmxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignFkmxDownload::getCreatedDate)
                .list();

        List<OrderInstallOperatingLog> oiolList = getOrderInstallOperatingLogs(fkmxs, newLCLS,item);
        // 移除已同步过的
        List<OrderInstallOperatingLog> addoiolList = new ArrayList<>();
        for (OrderInstallOperatingLog ol:oiolList){
            if (!oiolslist.contains(ol.getFkid())){
                addoiolList.add(ol);
            }
        }

        for (ItfTblAzAssignFkmxDownload i : fkmxs){
            ItfTblAzAssignFkmxDownload n = new ItfTblAzAssignFkmxDownload();
            n.setSynReqId(i.getSynReqId());
            n.setSynStatus(1);
            n.setSynTime(new Date());
            synreqids.add(n);
        }

        return addoiolList;
    }

    private OrderWorker getOrderWorkerUpdate(String id, OrderBase upInfo, OrderBase newLCLS){
        OrderWorker oow = orderWorkerService.lambdaQuery()
                .eq(OrderWorker::getOrderBaseId,id)
                .eq(OrderWorker::getOutWorkerSource,Boolean.FALSE)
                .eq(OrderWorker::getIsMaster,Boolean.TRUE)
                .last("limit 1").one();
        OrderWorker own = new OrderWorker();
        Boolean uf = Boolean.FALSE;

        if (upInfo !=null){
            OrderWorker newow = getOrderWorker(newLCLS);
            if (oow ==null){
                if (newow !=null){
                    return newow;
                }
                return null;
            }
            // 工单师傅信息为空时用本地的师傅信息
            if (newow==null){
                newLCLS.setWorkerId(own.getWorkerId());
                newLCLS.setWorkerName(own.getWorkerName());
                newLCLS.setWorkerMobile(own.getWorkerMobile());
                newLCLS.setWorkerIdcard(own.getWorkerIdcard());
                return null;
            }

            // 师傅信息变更，或是改派师傅
            if (!oow.getWorkerId().equals(newow.getWorkerId())) {
                own.setWorkerId(newow.getWorkerId());
                uf = Boolean.TRUE;
            }
            if (!oow.getWorkerName().equals(newow.getWorkerName())) {
                own.setWorkerName(newow.getWorkerName());
                uf = Boolean.TRUE;
            }
            if (!oow.getWorkerMobile().equals(newow.getWorkerMobile())) {
                own.setWorkerMobile(newow.getWorkerMobile());
                uf = Boolean.TRUE;
            }
            if (!oow.getWorkerIdcard().equals(newow.getWorkerIdcard())) {
                own.setWorkerIdcard(newow.getWorkerIdcard());
                uf = Boolean.TRUE;
            }
            if (uf){
                own.setId(oow.getId());
                own.setUpdateBy(newLCLS.getLastOperatorBy());
                own.setUpdateTime(newLCLS.getLastOperatorTime());
                return own;
            }
        }
        return null;
    }

    private void getOrderProductsUpdate(Map<String, List<SysDictRef>> sysDictRefDLMap, Map<String,
            List<SysDictRef>> sysDictRefXLMap, Map<String,
            List<SysDictRef>> sysDictRefXiLieMap,
                                        OrderBase old, OrderBase newLCLS, String downloadTaskNo,
                                        List<ItfTblAzAssignMxDownload> synreqids,
                                        List<OrderProduct> orderProductsUpdate,
                                        List<OrderInstallDetail> oids,List<String> oiddels,
                                        List<OrderDetailFile> odfs,
                                        List<String> delOrderProduct, Map<String,String> productMap) {
        List<OrderProduct> orderProductsOld = new ArrayList<>();
        List<String> orderMxList = new ArrayList<>();

        // 提取下载产品明细表
        List<ItfTblAzAssignMxDownload> orderMx = itfTblAzAssignMxDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignMxDownload::getDownloadTaskNo, downloadTaskNo)
                .eq(ItfTblAzAssignMxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignMxDownload::getSynReqId)
                .list();
        orderMx.stream().forEach(mx->{
            orderMxList.add(mx.getPgmxid());
        });

        // 提取本地现有的产品机型
        orderProductsOld = orderProductService.lambdaQuery()
                .eq(OrderProduct::getOrderBaseId, old.getId()).list();

        // 新增或是修改
        if (addOrUp(sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap, old, newLCLS, synreqids,
                orderProductsUpdate, oids, oiddels, odfs, orderProductsOld,orderMx, productMap)){
            return;
        }

        // 处理总部删除的情况
        for (OrderProduct o : orderProductsOld) {
            if (!orderMxList.contains(o.getPgmxid())){
                // 移除产品机型
                delOrderProduct.add(o.getId());
                // 需要移除采集明细
                // 提取 采集记录
                List<OrderInstallDetail> olds = new ArrayList<>();
                olds = orderInstallDetailService.lambdaQuery()
                        .eq(OrderInstallDetail::getOrderBaseId, o.getOrderBaseId())
                        .eq(OrderInstallDetail::getOrderProductId, o.getId()).list();
                for (OrderInstallDetail i:olds){
                    oiddels.add(i.getId());
                }
            }
        }
    }

    private boolean addOrUp(Map<String, List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                            Map<String, List<SysDictRef>> sysDictRefXiLieMap, OrderBase old, OrderBase newLCLS,
                            List<ItfTblAzAssignMxDownload> synreqids, List<OrderProduct> orderProductsUpdate,
                            List<OrderInstallDetail> oids, List<String> oiddels, List<OrderDetailFile> odfs,
                            List<OrderProduct> orderProductsOld,
                            List<ItfTblAzAssignMxDownload> orderMx, Map<String,String> productMap) {
        // 提取现有的采集明细数据
        List<OrderInstallDetail> oldOids = new ArrayList<>();
        Map<String,List<OrderProduct>> oldProductMap = new HashMap<>();
        Map<String,List<OrderInstallDetail>> oldOidsMap = new HashMap<>();
        oldOids= orderInstallDetailService.lambdaQuery()
                .eq(OrderInstallDetail::getOrderBaseId,old.getId()).list();
        oldOidsMap = oldOids.stream().collect(Collectors.groupingBy(OrderInstallDetail::getOrderProductId));

        oldProductMap = orderProductsOld.stream().collect(Collectors.groupingBy(OrderProduct::getPgmxid));

        for (ItfTblAzAssignMxDownload mx: orderMx){
            // 这里做法为重新生成新的产品机型，然后与本地比较是新增还是修改
            // 生成工单产品对象 获取新同步的工单机型
            OrderProduct n = getProductInfo(sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap,
                    newLCLS, mx, productMap);
            // 存在修改 不存在新增
            for (OrderProduct o : orderProductsOld) {
                if (n.getPgmxid().equals(o.getPgmxid())) {
                    // 存在进行修改
                    updateOrderProduct(newLCLS, o, n, oids, oldOids);
                    break;
                }
            }
            int oldnum=0;
            int shul = mx.getShul();
            if (shul>100) {
                shul=1;
            }
            // 看是否已同步过的 如是已同步过来，需调整数量 调整的数据就是生成的产品机型 n
            if (oldProductMap.containsKey(mx.getPgmxid())){
                if (upProductAndDetail(old, oids, oiddels, odfs, oldOidsMap, oldProductMap, mx, n, oldnum, shul)) {
                    return true;
                }
            } else {
                // 这里为新增，需要新增对应的采集及附件
                // 生成采集明细数据+附件数据
                int insertnum=1;
                int outid=1;
                // 生成采集明细数据+附件数据
                // extracted(old, oids, odfs, insertnum, outid, mx, n);
            }
            orderProductsUpdate.add(n);

            ItfTblAzAssignMxDownload mxu = new ItfTblAzAssignMxDownload();
            mxu.setSynReqId(mx.getSynReqId());
            mxu.setSynStatus(1);
            mxu.setSynTime(new Date());
            synreqids.add(mxu);
        }
        return false;
    }

    private boolean upProductAndDetail(OrderBase old, List<OrderInstallDetail> oids, List<String> oiddels, List<OrderDetailFile> odfs, Map<String, List<OrderInstallDetail>> oldOidsMap, Map<String, List<OrderProduct>> oldProductMap, ItfTblAzAssignMxDownload mx, OrderProduct n, int oldnum, int shul) {
        OrderProduct oldOpt = oldProductMap.get(mx.getPgmxid()).get(0);
        if (!oldOpt.getNum().equals(shul)){
            // 看已采集数
            for (OrderInstallDetail oid : oldOidsMap.get(oldOpt.getId())) {
                if (oid.getStatus().equals(1)) {
                    oldnum++;
                }
            }
            if (oldnum > shul){
                synItfTblAzAssignMxDownload(mx.getSynReqId(),9,
                        "总部修改的产品数不能小于已采集数,需人工处理，工单号："+ old.getId());
                return true;
            }
            // 如果产品数量大于已采集数则可以更新产品表的数量  这里的n就是本次处理的，新增的N不可能找到
            n.setUndoneNum(n.getNum()- oldnum);

            // 比较新旧数量,如果新数量少就删除，如果多就新增
            // 原产品数量大于新的产品数量，删除采集记录
            if (oldOpt.getNum()> shul){
                int insertNum = 1;
                // 提取 采集记录
                List<OrderInstallDetail> olds = new ArrayList<>();
                olds= orderInstallDetailService.lambdaQuery()
                        .eq(OrderInstallDetail::getOrderBaseId, old.getId())
                        .eq(OrderInstallDetail::getOrderProductId, n.getId())
                        .eq(OrderInstallDetail::getStatus,0)
                        .orderByAsc(OrderInstallDetail::getOutId).list();

                // 存在未采集的数据删除，其他不删
                if (olds.size()>1){
                    int oldssize = olds.size()-1;
                    while (insertNum <= (oldOpt.getNum() - shul)){
                        oiddels.add(olds.get(oldssize).getId());
                        oldssize-- ;
                        insertNum++;
                    }
                }
            } else if (oldOpt.getNum()< shul) {
                // 提取 采集记录
                List<OrderInstallDetail> olds = new ArrayList<>();
                OrderInstallDetail iod = new OrderInstallDetail();
                olds= orderInstallDetailService.lambdaQuery()
                        .eq(OrderInstallDetail::getOrderBaseId, old.getId())
                        .eq(OrderInstallDetail::getOrderProductId, n.getId())
                        .orderByAsc(OrderInstallDetail::getOutId).list();
                // 原产品数量小于新的产品数量，需要新增记录
                // 生成采集明细数据+附件数据
                // 取最大的序
                int insertnum = 0;
                int outid = 0;
                insertnum =olds.get(olds.size()-1).getOutId()+1;
                outid = insertnum;
                extracted(old, oids, odfs, insertnum, outid, mx, n);
            }
        }
        return false;
    }


    private void synItfTblAzAssignMxDownload(Long synReqId, Integer synStatus, String msg){
        ItfTblAzAssignMxDownload mx = new ItfTblAzAssignMxDownload();
        mx.setSynReqId(synReqId);
        mx.setSynStatus(synStatus);
        mx.setSynTime(new Date());
        mx.setSynErrMsg(msg);
        itfTblAzAssignMxDownloadService.updateById(mx);
    }


    private OrderProduct getProductInfo(Map<String, List<SysDictRef>> sysDictRefDLMap,
                                        Map<String, List<SysDictRef>> sysDictRefXLMap,
                                        Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                                        OrderBase newLCLS, ItfTblAzAssignMxDownload mx,
                                        Map<String,String> productMap) {
        OrderProduct op = new OrderProduct();
        op.setId(publicService.getUUID());
        op.setOrderBaseId(newLCLS.getId());
        // pgmxid主键
        op.setPgmxid(mx.getPgmxid());
        op.setPgguid(mx.getPgguid());
        op.setMainId(String.valueOf(mx.getSpid()));
        op.setMainName(mx.getSpmc());
        if (sysDictRefDLMap.containsKey(String.valueOf(mx.getSpid()))){
            op.setMainId(sysDictRefDLMap.get(String.valueOf(mx.getSpid())).get(0).getDictCode());
            op.setMainName(sysDictRefDLMap.get(String.valueOf(mx.getSpid())).get(0).getDictValue());
        }

        op.setSmallId(String.valueOf(mx.getXlid()));
        op.setSmallName(mx.getXlmc());
        if (!mx.getXlid().equals(0L) && sysDictRefXLMap.containsKey(String.valueOf(mx.getXlid()))) {
            op.setSmallId(sysDictRefXLMap.get(String.valueOf(mx.getXlid())).get(0).getDictCode());
            op.setSmallName(sysDictRefXLMap.get(String.valueOf(mx.getXlid())).get(0).getDictValue());
        }

        op.setSeriesId(mx.getXiid());
        op.setSeriesName(mx.getXimc());
        if (StringUtils.isNotEmpty(mx.getXiid())){
            if (!mx.getXiid().equals("0") && sysDictRefXiLieMap.containsKey(mx.getXiid())) {
                op.setSeriesId(sysDictRefXiLieMap.get(mx.getXiid()).get(0).getDictCode());
                op.setSeriesName(sysDictRefXiLieMap.get(mx.getXiid()).get(0).getDictValue());
            }
        }

        // 改成 product 表中的 product_id
        // op.setProductId(mx.getJxno());
        op.setProductId("");
        if (productMap.containsKey(mx.getJxno())){
            op.setProductId(productMap.get(mx.getJxno()));
        }
        op.setOutJxno(mx.getJxno());

        op.setProductName(mx.getJxmc());
        op.setInsideCode(mx.getNjtm());
        op.setOutCode(mx.getWjtm());
        op.setNum(mx.getShul());
        if (op.getNum()>100){
            op.setNum(1);
        }
        op.setPrice(mx.getJiage());
        op.setUnit(mx.getDanw());
        op.setMaterialNumber(mx.getWldm());
        op.setInsideNum(mx.getNjsl());
        op.setOutNum(mx.getWjsl());
        // op.setUndoneNum(mx.getWwsl());
        op.setUndoneNum(op.getNum());
        op.setCreateTime(mx.getCjdt());
        op.setCreateBy(mx.getCreatedBy());
        // 销售单位
        op.setSaleWebsit(newLCLS.getSaleWebsitId());
        // 无销售单位联系人电话
        op.setServiceWebsit(newLCLS.getWebsitId());
        // 无服务单位电话信息 最好取websit表中的热线，先不取
        op.setBuyTime(newLCLS.getBuyTime());
        op.setRemark(mx.getBeiz());
        return op;
    }

    private void updateOrderProduct(OrderBase newLCLS,
                                    OrderProduct o,OrderProduct n,List<OrderInstallDetail> oids,
                                    List<OrderInstallDetail> oldOids) {
        n.setId(o.getId());
        // 查看有无要修改的机型信息
        if (!o.getProductName().equals(n.getProductName()) ||
                !o.getSmallName().equals(n.getSmallName()) ||
                !o.getInsideNum().equals(n.getInsideNum()) ||
                !o.getOutNum().equals(n.getOutNum())){
            n.setUpdateBy(newLCLS.getLastOperatorBy());
            n.setUpdateTime(newLCLS.getLastOperatorTime());
            // 更新明细表的名称
            for (OrderInstallDetail item:oldOids){
                if (item.getOrderProductId().equals(n.getProductId())){
                    item.setMainId(n.getMainId());
                    item.setMainName(n.getMainName());
                    item.setSmallId(n.getSmallId());
                    item.setSmallName(n.getSmallName());
                    item.setWebsitId(newLCLS.getWebsitId());
                    item.setSeriesId(n.getSeriesId());
                    item.setSeriesName(n.getSeriesName());
                    item.setProductName(n.getProductName());
                    oids.add(item);
                }
            }
        }
    }


    private void updateOrderProductBak(OrderBase newLCLS, List<OrderProduct> orderProductsUpdate, Boolean uf, OrderProduct o, OrderProduct n) {
        OrderProduct v = new OrderProduct();
        // 查看有无要修改的机型信息
        if (!o.getMainId().equals(n.getMainId())) {
            v.setMainId(n.getMainId());
            v.setMainName(n.getMainName());
            uf = Boolean.TRUE;
        }
        if (!o.getSmallId().equals(n.getSmallId())) {
            v.setSmallId(n.getSmallId());
            v.setSmallName(n.getSmallName());
            uf = Boolean.TRUE;
        }
        // 系列可不填写
        if (StringUtils.isNotEmpty(o.getSeriesId()) && StringUtils.isNotEmpty(n.getSeriesId())) {
            if (!o.getSeriesId().equals(n.getSeriesId())){
                v.setSeriesId(n.getSeriesId());
                v.setSeriesName(n.getSeriesName());
                uf = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(o.getSeriesId())) {
                v.setSeriesId("");
                v.setSeriesName("");
            } else {
                v.setSeriesId(n.getSeriesId());
                v.setSeriesName(n.getSeriesName());
            }
            uf = Boolean.TRUE;
        }
        if (!o.getProductId().equals(n.getProductId())) {
            v.setProductId(n.getProductId());
            v.setProductName(n.getProductName());
            uf = Boolean.TRUE;
        }
        if (StringUtils.isNotEmpty(o.getInsideCode()) && StringUtils.isNotEmpty(n.getInsideCode())) {
            if (!o.getInsideCode().equals(n.getInsideCode())){
                v.setInsideCode(n.getInsideCode());
                uf = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(o.getInsideCode())) {
                v.setInsideCode("");
            } else {
                v.setInsideCode(n.getInsideCode());
            }
            uf = Boolean.TRUE;
        }
        if (StringUtils.isNotEmpty(o.getOutCode()) && StringUtils.isNotEmpty(n.getOutCode())) {
            if (!o.getOutCode().equals(n.getOutCode())){
                v.setOutCode(n.getOutCode());
                uf = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(o.getOutCode())) {
                v.setOutCode("");
            } else {
                v.setOutCode(n.getOutCode());
            }
            uf = Boolean.TRUE;
        }
        if (o.getNum() !=null && n.getNum() !=null) {
            if (!o.getNum().equals(n.getNum())){
                v.setNum(n.getNum());
                uf = Boolean.TRUE;
            }
        } else {
            if (o.getNum() !=null) {
                v.setNum(null);
            } else {
                v.setNum(n.getNum());
            }
            uf = Boolean.TRUE;
        }
        if (o.getPrice() !=null && n.getPrice() !=null) {
            if (!o.getPrice().equals(n.getPrice())){
                v.setPrice(n.getPrice());
                uf = Boolean.TRUE;
            }
        } else {
            if (o.getPrice() !=null) {
                v.setPrice(null);
            } else {
                v.setPrice(n.getPrice());
            }
            uf = Boolean.TRUE;
        }
        if (StringUtils.isNotEmpty(o.getUnit()) && StringUtils.isNotEmpty(n.getUnit())) {
            if (!o.getUnit().equals(n.getUnit())){
                v.setUnit(n.getUnit());
                uf = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(o.getUnit())) {
                v.setUnit("");
            } else {
                v.setUnit(n.getUnit());
            }
            uf = Boolean.TRUE;
        }
        if (StringUtils.isNotEmpty(o.getMaterialNumber()) && StringUtils.isNotEmpty(n.getMaterialNumber())) {
            if (!o.getMaterialNumber().equals(n.getMaterialNumber())){
                v.setMaterialNumber(n.getMaterialNumber());
                uf = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(o.getMaterialNumber())) {
                v.setMaterialNumber("");
            } else {
                v.setMaterialNumber(n.getUnit());
            }
            uf = Boolean.TRUE;
        }
        if (!o.getInsideNum().equals(n.getInsideNum())) {
            v.setInsideNum(n.getInsideNum());
            uf = Boolean.TRUE;
        }
        if (!o.getOutNum().equals(n.getOutNum())) {
            v.setOutNum(n.getOutNum());
            uf = Boolean.TRUE;
        }
        if (!o.getUndoneNum().equals(n.getUndoneNum())) {
            v.setUndoneNum(n.getUndoneNum());
            uf = Boolean.TRUE;
        }
        if (StringUtils.isNotEmpty(o.getSaleWebsit()) && StringUtils.isNotEmpty(n.getSaleWebsit())) {
            if (!o.getSaleWebsit().equals(n.getSaleWebsit())){
                v.setSaleWebsit(n.getSaleWebsit());
                uf = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(o.getSaleWebsit())) {
                v.setSaleWebsit("");
            } else {
                v.setSaleWebsit(n.getSaleWebsit());
            }
            uf = Boolean.TRUE;
        }
        if (StringUtils.isNotEmpty(o.getServiceWebsit()) && StringUtils.isNotEmpty(n.getServiceWebsit())) {
            if (!o.getServiceWebsit().equals(n.getServiceWebsit())){
                v.setServiceWebsit(n.getServiceWebsit());
                uf = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(o.getServiceWebsit())) {
                v.setServiceWebsit("");
            } else {
                v.setServiceWebsit(n.getServiceWebsit());
            }
            uf = Boolean.TRUE;
        }

        if (uf){
            v.setId(o.getId());
            v.setUpdateBy(newLCLS.getLastOperatorBy());
            v.setUpdateTime(newLCLS.getLastOperatorTime());
            orderProductsUpdate.add(o);
        }
    }

    @NotNull
    private OrderBase getOrderBaseUp(OrderBase old, ItfTblAzAssignLcLsDownload item, OrderBase lclsNew) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("平台表数据时间 {}",sdf.format(old.getUpdateTime()));
        log.info("云售后表数据时间 {}",sdf.format(item.getLastModifiedDate()));

        // 本地订单已关闭 且总部的最后修改时间在本地数据修改时间之前 不可修改
        /*if (old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()) &&
                (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())<0)){
            synItfTblAzAssignLcLsDownload(item.getSynReqId(), 99, "本地工单已关闭或作废忽略更新");
            // 这里只是不修改订单主表，其他数据表接着执行
            return old;
        }
*/
        // 1.安装工单主表基础信息更新 需进行最后修改时间比较
        /*if (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())>0){
            log.info("修改工单主表基础信息");
            upBase(old, item, lclsNew);
        }*/
        // 去掉限制直接修改
        upBase(old, item, lclsNew);


        // 2:网点信息修改 已待服务人员处理，不允更新网点   6,7,10
        /*if (old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode())){
            // 售后网点
            old.setReceWebsitId(lclsNew.getReceWebsitId());
            old.setReceWebsitName(lclsNew.getReceWebsitName());
            // 安装
            old.setWebsitId(lclsNew.getWebsitId());
            old.setWebsitName(lclsNew.getWebsitName());
        }*/

        // 售后网点
        old.setReceWebsitId(lclsNew.getReceWebsitId());
        old.setReceWebsitName(lclsNew.getReceWebsitName());
        // 安装
        old.setWebsitId(lclsNew.getWebsitId());
        old.setWebsitName(lclsNew.getWebsitName());

        /*// 3:已预约不可更改预约时间 未预约总部为准
        OrderReAppointment ora = orderReAppointmentService.lambdaQuery()
                .eq(OrderReAppointment::getOrderBaseId,old.getId())
                .eq(OrderReAppointment::getFlag,1)
                .last("limit 1").one();
        // 已预约过 退回查询处理
        if (ora == null){
            old.setAppointmentTime(lclsNew.getAppointmentTime());
            old.setAppointmentEndTime(lclsNew.getAppointmentEndTime());
        }*/

        old.setAppointmentTime(lclsNew.getAppointmentTime());
        old.setAppointmentEndTime(lclsNew.getAppointmentEndTime());

        // 3.2天猫工单，允许天猫自已预约  这里去掉
        // upYyazsj(old, item, lclsNew);

        // 4:工单状态
        /*Boolean allowUpdate = getAllowUpdate(old, lclsNew);
        if (allowUpdate && (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())>0)){
            old.setOrderStatus(lclsNew.getOrderStatus());
            old.setOrderStatusTime(lclsNew.getOrderStatusTime());
            old.setLastOrderStatus(lclsNew.getLastOrderStatus());
            old.setDispatchStatus(lclsNew.getDispatchStatus());
            old.setDispatchTime(lclsNew.getDispatchTime());
        }*/

        old.setOrderStatus(lclsNew.getOrderStatus());
        old.setOrderStatusTime(lclsNew.getOrderStatusTime());
        old.setLastOrderStatus(lclsNew.getLastOrderStatus());
        old.setDispatchStatus(lclsNew.getDispatchStatus());
        old.setDispatchTime(lclsNew.getDispatchTime());

        // 5.预派工标志更新 -IsReservation
        if (old.getIsReservation().equals(1) &&
                (item.getSfwcps().equals("已配送") || lclsNew.getIsReservation().equals(0))){
            old.setIsReservation(0);
        }

        old.setOutUpdateSynReqTime(new Date());
        old.setUpdateTime(new Date());
        return old;
    }

    private void revertFun(OrderBase old, ItfTblAzAssignLcLsDownload item, OrderBase upInfo) {
        // 本地订单已关闭 且总部的最后修改时间在本地数据修改时间之前 不可修改
        if (old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()) &&
                (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())<0)){
            return ;
        }

        // 1.安装工单主表基础信息更新
        if (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())>0){
            upInfo.setSaleWebsitId("");
            upInfo.setSaleWebsitName("");
            upInfo.setSaleWebsitSysNumber("");
            if (StringUtils.isNotEmpty(item.getXsdwno())){
                upInfo.setSaleWebsitId(item.getXsdwno());
            }
            if (StringUtils.isNotEmpty(item.getXswdmc())){
                upInfo.setSaleWebsitName(item.getXswdmc());
            }
            if (StringUtils.isNotEmpty(item.getXsdwxtbh())){
                upInfo.setSaleWebsitSysNumber(item.getXsdwxtbh());
            }

        }

        // 2:网点信息修改 已待服务人员处理，不允更新网点   6,7,10
        if (old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode())){
            // 售后网点
            upInfo.setReceWebsitId("");
            upInfo.setReceWebsitName("");
            if (StringUtils.isNotEmpty(item.getJspgwdno())){
                upInfo.setReceWebsitId(item.getJspgwdno());
            }
            if (StringUtils.isNotEmpty(item.getJspgwdmc())){
                upInfo.setReceWebsitName(item.getJspgwdmc());
            }

            // 安装
            upInfo.setWebsitId("");
            upInfo.setWebsitName("");
            if (StringUtils.isNotEmpty(item.getAzwdno())){
                upInfo.setWebsitId(item.getAzwdno());
            }
            if (StringUtils.isNotEmpty(item.getAzwdmc())){
                upInfo.setWebsitName(item.getAzwdmc());
            }

            // 判断安装网点编号是否为空或者为公司，如果为空或为公司，就写入接收派工网点
            if (StringUtils.isEmpty(item.getAzwdno()) ||
                    item.getAzwdno().equals("S9219801") ||
                    item.getAzwdno().equals("S9219807")||
                    item.getAzwdno().equals("S9329829")){
                upInfo.setWebsitId(item.getJspgwdno());
                upInfo.setWebsitName(item.getJspgwdmc());
            }
        }
    }

    private void upBase(OrderBase old, ItfTblAzAssignLcLsDownload item, OrderBase lclsNew) {
        old.setOutUpdateSynReqId(item.getSynReqId());
        old.setUpdateTime(new Date());
        old.setUserMobile(lclsNew.getUserMobile());
        old.setUserMobile2(lclsNew.getUserMobile2());
        old.setUserName(lclsNew.getUserName());
        old.setLinkName(lclsNew.getLinkName());
        old.setAreaCode(lclsNew.getAreaCode());
        old.setTelPhone(lclsNew.getTelPhone());
        old.setGreeVirtualnumber(lclsNew.getGreeVirtualnumber());
        old.setAddress(lclsNew.getAddress());
        old.setProvince(lclsNew.getProvince());
        old.setProvinceId(lclsNew.getProvinceId());
        old.setCity(lclsNew.getCity());
        old.setCityId(lclsNew.getCityId());
        old.setArea(lclsNew.getArea());
        old.setAreaId(lclsNew.getAreaId());
        old.setStreet(lclsNew.getStreet());
        old.setStreetId(lclsNew.getStreetId());
        old.setRemark(lclsNew.getRemark());
        old.setTotalNum(lclsNew.getTotalNum());
        old.setUndoneNum(lclsNew.getUndoneNum());
        /*if (lclsNew.getUndoneNum()< old.getUndoneNum()){
            old.setUndoneNum(lclsNew.getUndoneNum());
        }*/
        old.setWorkerId(lclsNew.getWorkerId());
        old.setWorkerName(lclsNew.getWorkerName());
        // old.set(lclsNew.get());
        old.setWorkerMobile(lclsNew.getWorkerMobile());
        old.setWorkerIdcard(lclsNew.getWorkerIdcard());

        if (old.getDispatchTime()==null && item.getJspgwdsj() !=null){
            old.setDispatchTime(item.getJspgwdsj());
        }
        if (old.getReceTime()==null && item.getJspgwdsj() !=null){
            old.setReceTime(item.getJspgwdsj());
        }
        if (old.getWorkerReceTime()==null && item.getPgsj() !=null){
            old.setWorkerReceTime(item.getPgsj());
        }
        old.setSaleType(lclsNew.getSaleType());
        old.setSaleWebsitId(lclsNew.getSaleWebsitId());
        old.setSaleWebsitName(lclsNew.getSaleWebsitName());
        old.setSaleWebsitSysNumber(lclsNew.getSaleWebsitSysNumber());
        old.setCrossNo(lclsNew.getCrossNo());
        old.setUserAttrId(lclsNew.getUserAttrId());
        old.setUserAttr(lclsNew.getUserAttr());
        old.setSysWebsitNumber(lclsNew.getSysWebsitNumber());
        old.setInvoiceNo(lclsNew.getInvoiceNo());
        old.setInfoSource(lclsNew.getInfoSource());
        old.setInfoSourceId(lclsNew.getInfoSourceId());
        old.setBuyTime(lclsNew.getBuyTime());
        old.setExpectStartTime(lclsNew.getExpectStartTime());
        old.setExpectEndTime(lclsNew.getExpectStartTime());
        old.setBrandId(lclsNew.getBrandId());
        old.setBrandName(lclsNew.getBrandName());
        old.setRegion(lclsNew.getRegion());
    }


    @NotNull
    private OrderBase getOrderBaseUpBak(OrderBase old, ItfTblAzAssignLcLsDownload item, OrderBase newLCLS,Brand brand) {
        OrderBase upInfo = new OrderBase();

        // 本地订单已关闭 且总部的最后修改时间在本地数据修改时间之前 不可修改
        if (old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()) &&
                (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())<0)){
            synItfTblAzAssignLcLsDownload(item.getSynReqId(), 99, "本地工单已关闭或作废忽略更新");
            // 这里只是不修改订单主表，其他数据表接着执行
            return null;
        }

        // 1.安装工单主表基础信息更新
        if (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())>0){
            BeanUtils.copyProperties(newLCLS,upInfo);
            // upInfo = getAddOrderBaseUp(item, brand);
            //  未完成数量 取小
            if (upInfo.getUndoneNum()>old.getUndoneNum()){
                upInfo.setUndoneNum(old.getUndoneNum());
            }
        }


        // 2:网点信息修改 已待服务人员处理，不允更新网点   6,7,10 少6
        if (!(old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode()))){
            // 售后网点
            upInfo.setReceWebsitId(old.getReceWebsitId());
            upInfo.setReceWebsitName(old.getReceWebsitName());
            // 安装
            upInfo.setWebsitId(old.getWebsitId());
            upInfo.setWebsitName(old.getWebsitName());
        }

        // 3:已预约不可更改预约时间 未预约总部为准
        OrderReAppointment ora = orderReAppointmentService.lambdaQuery()
                .eq(OrderReAppointment::getOrderBaseId,old.getId())
                .eq(OrderReAppointment::getFlag,1)
                .last("limit 1").one();
        // 已预约过 退回查询处理
        if (ora != null){
            upInfo.setAppointmentTime(old.getAppointmentTime());
            upInfo.setAppointmentEndTime(old.getAppointmentEndTime());
        }

        // 3.2天猫工单，允许天猫自已预约
        upYyazsj(old, item, upInfo);

        // 4:工单状态
        Boolean allowUpdate = getAllowUpdate(old, newLCLS);
        // 不可修改退回去
        if (!(allowUpdate && (old.getUpdateTime()==null || item.getLastModifiedDate().compareTo(old.getUpdateTime())>0))){
            upInfo.setOrderStatus(old.getOrderStatus());
            upInfo.setOrderStatusTime(old.getOrderStatusTime());
            upInfo.setLastOrderStatus(old.getLastOrderStatus());
            upInfo.setDispatchStatus(old.getDispatchStatus());
            upInfo.setDispatchTime(old.getDispatchTime());
        }

        // 5.预派工标志更新 -IsReservation
        if (old.getIsReservation().equals(1) &&
                (item.getSfwcps().equals("已配送") ||(!upInfo.getIsReservation().equals(1)))){
            upInfo.setIsReservation(0);
        }

        upInfo.setId(old.getId());
        upInfo.setOutUpdateSynReqId(item.getSynReqId());
        upInfo.setOutUpdateSynReqTime(new Date());
        upInfo.setUpdateTime(new Date());
        return upInfo;
    }

    private void upYyazsj(OrderBase old, ItfTblAzAssignLcLsDownload item, OrderBase upInfo) {
        Boolean flag = Boolean.FALSE;
        // 1是天猫工单，2预约时间不相同
        if (upInfo.getExternalName2().equals("TBL_TMALL_ORDERINFO")){
            if (item.getYyazsj() !=null){
                if (old.getAppointmentTime().compareTo(upInfo.getAppointmentTime()) !=0){
                    if (old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_0.getCode()) ||
                            old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_1.getCode()) ||
                            old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()) ||
                            old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_0.getCode()) ||
                            old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_1.getCode()) ||
                            old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G5.getCode()) ||
                            old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode())){
                        // 要改
                        flag = Boolean.TRUE;
                    }
                }
            }
            // 需要改
            if (flag){
                old.setAppointmentTime(upInfo.getAppointmentTime());
                old.setAppointmentEndTime(upInfo.getAppointmentEndTime());
            }
        }
    }


    private void synItfTblAzAssignLcLsDownload(Long synReqId, Integer synStatus, String msg){
        ItfTblAzAssignLcLsDownload uplcls = new ItfTblAzAssignLcLsDownload();
        uplcls.setSynReqId(synReqId);
        uplcls.setSynStatus(synStatus);
        uplcls.setSynTime(new Date());
        uplcls.setSynErrMsg(msg);
        itfTblAzAssignLcLsDownloadService.updateById(uplcls);
    }


    @NotNull
    private Boolean getAllowUpdate(OrderBase old, OrderBase newLCLS) {
        // 判断是否可更新工单状态
        Boolean allowUpdate = Boolean.FALSE;
        // 待派
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G1_1.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_0.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_0.getCode()))){
            allowUpdate = Boolean.TRUE;
        }
        // 改派
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_0.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_0.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()))){
            allowUpdate = Boolean.TRUE;
        }
        // 待接单
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_0.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_0.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G8.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()))){
            allowUpdate = Boolean.TRUE;
        }
        // 已接单
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_0.getCode()) ||
                        old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_1.getCode())||
                        old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_2.getCode()) ||
                        old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_3.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G8.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()))){
            allowUpdate = Boolean.TRUE;
        }
        // 服务人员完工
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_4.getCode()) ||
                        old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_1.getCode())||
                        old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_2.getCode()) ||
                        old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_3.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G8.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()))){
            allowUpdate = Boolean.TRUE;
        }
        // 用户改约
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G5.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_5.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G8.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()))){
            allowUpdate = Boolean.TRUE;
        }
        // 作废申请
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_0.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_2.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_0.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()))){
            allowUpdate = Boolean.TRUE;
        }

        // 广佛作废时如果总部下载1121或1129也同步状态
        if (old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode())){
            if (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_0.getCode()) ||
                    newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()) ||
                    newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_0.getCode())){
                allowUpdate = Boolean.TRUE;
            } else {
                allowUpdate = Boolean.FALSE;
            }
        } else {
            allowUpdate = Boolean.TRUE;
        }
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()) ||
                old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode())) &&
                (old.getDispatchStatus().equals(DispatchStatusEnum.INSTALL_DISPATCH_STATUS_2.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_0.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode()))){
            allowUpdate = Boolean.TRUE;
        }

        // 广佛已自动派工，不根据总部状态更新
        if ((old.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode())) &&
                (newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_0.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()) ||
                        newLCLS.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()))){
            allowUpdate = Boolean.FALSE;
        }
        return allowUpdate;
    }


    private void getOldForNewProduct(ItfTblAzAssignLcLsDownload item, OrderBase orderBase,List<ItfGreeToFaDownloadTaskList> its) {
        // 这里为新增是一定没下载的 无需判断状态值
        if(orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE1.getCode()) ||
                orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE2.getCode()) ||
                orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE3.getCode())){

            ItfGreeToFaDownloadTaskList tl = new ItfGreeToFaDownloadTaskList();
            tl.setDownloadTaskNo(IdWorker.getIdStr());
            tl.setDownloadKeyValue(item.getPgguid());
            tl.setDownloadTaskType(2205);
            tl.setDownloadStatus(0);
            its.add(tl);

            ItfGreeToFaDownloadTaskList tlt = new ItfGreeToFaDownloadTaskList();
            tlt.setDownloadTaskNo(IdWorker.getIdStr());
            tlt.setDownloadKeyValue(item.getPgguid());
            tlt.setDownloadTaskType(2204);
            tlt.setDownloadStatus(0);
            its.add(tlt);

            orderBase.setYjhxDownloadFlag(1);
        }
    }

    private void getOldForNewProductt(ItfTblAzAssignLcLsDownload item, OrderBase orderBase,
                                      List<ItfGreeToFaDownloadTaskList> its, OrderBase old ) {
        // 这里为新增是一定没下载的 无需判断状态值
        if((orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE1.getCode()) ||
                orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE2.getCode()) ||
                orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE3.getCode())) &&
                old.getYjhxDownloadFlag().equals(0)){
            ItfGreeToFaDownloadTaskList tl = new ItfGreeToFaDownloadTaskList();
            tl.setDownloadTaskNo(IdWorker.getIdStr());
            tl.setDownloadKeyValue(item.getPgguid());
            tl.setDownloadTaskType(2205);
            tl.setDownloadStatus(0);
            its.add(tl);
            orderBase.setYjhxDownloadFlag(1);
        }

        if(orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE1.getCode()) ||
                orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE2.getCode()) ||
                orderBase.getSaleType().equals(OrderTypeEnum.ORDER_SALE_TYPE3.getCode())){
            ItfGreeToFaDownloadTaskList tlt = new ItfGreeToFaDownloadTaskList();
            tlt.setDownloadTaskNo(IdWorker.getIdStr());
            tlt.setDownloadKeyValue(item.getPgguid());
            tlt.setDownloadTaskType(2204);
            tlt.setDownloadStatus(0);
            its.add(tlt);
        }
    }

    /**
     * 工单基础表order_base,工单师傅表order_worker,工单机型表order_product,
     * 操作明细表order_install_operating_log,安装费用清单表order_install,用户预约改约信息表order_appointment,
     * 工单评价表order_appraise
     */
    public void addOrderData(OrderBase orderBase, OrderWorker orderWorker, OrderInstall orderInstall, List<OrderProduct> orderProducts,
                             List<OrderInstallOperatingLog> oiolList, List<OrderReAppointment> oa, List<OrderAppraise> oanew,
                             Long synReqId, List<Long> synReqIds,  List<Long> synReqFkMxIds, List<Long> synReqYfYyIds,
                             List<ItfTblAzAssignFeeDownload> fyqd, List<Long> getpjSynReqId,
                             List<FaGreeSms> faGreeSms,List<OrderAppeal> orderAppeal,
                             List<ItfGreeToFaDownloadTaskList> its,
                             List<OrderInstallDetail> oids,List<OrderDetailFile> odfs) {
        // 工单基础表
        if (orderBase != null) {
            orderBaseService.save(orderBase);
        }

        // 工单师傅表
        if (orderWorker != null) {
            orderWorkerService.save(orderWorker);
        }

        // 工单机型表
        if (orderProducts.size()>0){
            orderProductService.saveBatch(orderProducts);
            orderProducts.clear();
        }
        // 采集明细
        if (oids.size()>0){
            /*for (OrderInstallDetail item :oids){
                item.setOrderBaseId(orderBase.getId());
            }*/
            orderInstallDetailService.saveBatch(oids);
            oids.clear();
        }
        // 采集附件
        if (odfs.size()>0){
            /*for (OrderDetailFile item :odfs){
                item.setOrderBaseId(orderBase.getId());
            }*/
            orderDetailFileService.saveBatch(odfs);
            odfs.clear();
        }
        if (synReqIds.size()>0){
            upItfTblAzAssignMxDownload(synReqIds);
            synReqIds.clear();
        }
        // 操作明细表
        if (oiolList.size()>0){
            orderInstallOperatingLogService.saveBatch(oiolList);
            oiolList.clear();
        }
        if (synReqFkMxIds.size()>0){
            upItfTblAzAssignFkmxDownload(synReqFkMxIds);
            synReqFkMxIds.clear();
        }

        // 安装费用清单表
        if (orderInstall != null){
            orderInstallService.save(orderInstall);
        }
        if (CollectionUtils.isNotEmpty(fyqd)){
            upItfTblAzAssignFeeDownload(fyqd);
        }

        // 用户预约改约信息表
        if (oa.size()>0){
            orderReAppointmentService.saveBatch(oa);
            oa.clear();
        }
        if (synReqYfYyIds.size()>0){
            upItfTblAzAssignAppointment(synReqYfYyIds);
            synReqYfYyIds.clear();
        }

        // 差评给网点发短信
        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }

        // 生成申诉数据
        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }

        // 以旧换新
        if (its.size()>0){
            itfGreeToFaDownloadTaskListService.saveBatch(its);
            its.clear();
        }

        // 客户评价信息
        if (getpjSynReqId.size()>0){
            upItfTblAzAssignSatisfactionDownload(getpjSynReqId);
            getpjSynReqId.clear();
        }

        // 改派申请单

        // 修改同步状态
        upItfTblAzAssignLcLsDownload(synReqId);
    }



    private void upItfTblAzAssignFeeDownload(List<ItfTblAzAssignFeeDownload> fyqd) {
        List<ItfTblAzAssignFeeDownload> adds = new ArrayList<>();
        for (ItfTblAzAssignFeeDownload item:fyqd){
            ItfTblAzAssignFeeDownload add = new ItfTblAzAssignFeeDownload();
            add.setSynReqId(item.getSynReqId());
            add.setSynStatus(1);
            add.setSynTime(new Date());
            add.setSynErrMsg("成功");
            adds.add(add);
        }
        itfTblAzAssignFeeDownloadService.updateBatchById(adds);
    }

    private void upItfTblAzAssignMxDownload(List<Long> synReqIds) {
        List<ItfTblAzAssignMxDownload> sas =new ArrayList<>();
        for (int i = 0; i< synReqIds.size(); i++){
            ItfTblAzAssignMxDownload add = new ItfTblAzAssignMxDownload();
            add.setSynReqId(synReqIds.get(i));
            add.setSynStatus(1);
            add.setSynTime(new Date());
            add.setSynErrMsg("成功");
            sas.add(add);
        }
        itfTblAzAssignMxDownloadService.updateBatchById(sas);
    }

    private void upItfTblAzAssignFkmxDownload(List<Long> synReqFkMxIds) {
        List<ItfTblAzAssignFkmxDownload> sas =new ArrayList<>();
        for (int i = 0; i< synReqFkMxIds.size(); i++){
            ItfTblAzAssignFkmxDownload add = new ItfTblAzAssignFkmxDownload();
            add.setSynReqId(synReqFkMxIds.get(i));
            add.setSynStatus(1);
            add.setSynTime(new Date());
            add.setSynErrMsg("成功");
            sas.add(add);
        }
        itfTblAzAssignFkmxDownloadService.updateBatchById(sas);
    }

    private void upItfTblAzAssignAppointment(List<Long> synReqYfYYIds) {
        List<ItfTblAzAssignAppointmentDownload> sas =new ArrayList<>();
        for (int i = 0; i< synReqYfYYIds.size(); i++){
            ItfTblAzAssignAppointmentDownload add = new ItfTblAzAssignAppointmentDownload();
            add.setSynReqId(synReqYfYYIds.get(i));
            add.setSynStatus(1);
            add.setSynTime(new Date());
            add.setSynErrMsg("成功");
            sas.add(add);
        }
        itfTblAzAssignAppointmentDownloadService.updateBatchById(sas);
    }

    private void upItfTblAzAssignLcLsDownload(Long synReqId) {
        ItfTblAzAssignLcLsDownload add = new ItfTblAzAssignLcLsDownload();
        add.setSynReqId(synReqId);
        add.setSynStatus(1);
        add.setSynTime(new Date());
        add.setSynErrMsg("成功");
        itfTblAzAssignLcLsDownloadService.updateById(add);
    }

    private void getOrderAppraiseBack(OrderBase orderBase, Map<String, List<SysDictRef>> sysDictRefDLMap, List<OrderAppraise> oanew,
                                  String downloadTaskNo, List<Long> getSynReqId,
                                  List<FaGreeSms> faGreeSms,List<OrderAppeal> orderAppeal) {
        WebsitFWS websitFWS = new WebsitFWS();
        int jcaninsert=1;
        int cpflag=0;
        // 首评信息用于填写差评中的首评内容
        String spmessage="";
        OrderAppraise zpoa=null;
        String cpid="";
        List<ItfTblAzAssignSatisfactionDownload> sas = new ArrayList<>();
        List<OrderAppraise> oa = new ArrayList<>();
        Map<String,List<OrderAppraise>> oaMap = new HashMap<>();
        Date ssDate = new Date();
        Date jzDate = new Date();

        // 获取申诉单的截止申诉时间
        publicService.getExpireTime(orderBase, ssDate, jzDate);

        // 提取已同步的评价信息
        oa = orderAppraiseService.lambdaQuery()
                .eq(OrderAppraise::getOrderBaseId,orderBase.getId()).list();
        oaMap = oa.stream().collect(Collectors.groupingBy(OrderAppraise::getPid));

        // 提取待同步的评价数据
        sas = itfTblAzAssignSatisfactionDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignSatisfactionDownload::getDownloadTaskNo, downloadTaskNo)
                .eq(ItfTblAzAssignSatisfactionDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignSatisfactionDownload::getSynReqId)
                .list();
        // 获取首评+差评

        // 提取首评信息
        OrderAppraise oaOne = orderAppraiseService.lambdaQuery()
                .eq(OrderAppraise::getOrderBaseId,orderBase.getId())
                .eq(OrderAppraise::getType,0)
                .last("limit 1")
                .one();
        if (oaOne !=null){
            jcaninsert=0;
            spmessage = oaOne.getAppraiseContent();
        }

        // 提取差评申诉信息
        OrderAppeal oldcpss = orderAppealService.lambdaQuery()
                .eq(OrderAppeal::getOrderBaseId,orderBase.getId())
                .last("limit 1").one();

        for (ItfTblAzAssignSatisfactionDownload s :sas){
            getSynReqId.add(s.getSynReqId());
            // 首评内容
            if (s.getSxlx()==0){
                spmessage = s.getPjnr();
            }
            // 评价已同步，忽略更新
            if (oaMap.containsKey(s.getId())){
                continue;
            }
            // 只能有一条首评数据 存在首评不再插入 上面判断已生效，这里多一次判断也可
            if (jcaninsert == 0){
                if (s.getSxlx()==0){
                    continue;
                }
            }
            // 生成评价实体对像
            websitFWS = getOrderAppreise(orderBase, sysDictRefDLMap, oanew, s);
            // 提取追评信息
            if (zpoa==null){
                zpoa=oanew.get(oanew.size()-1);
            } else {
                if (zpoa.getCreateTime().before(oanew.get(oanew.size()-1).getCreateTime())){
                    zpoa=oanew.get(oanew.size()-1);
                }
            }

            // 生成首次评价后，置标识，不再生成新的
            if (s.getSxlx()==0){
                jcaninsert=0;
            }

            // 差评短信 + 差评申诉 仅一次
            if (oldcpss==null && cpflag==0) {
                // 生成差评短信实体对像 faGreeSms  也只发一次
                addcpsms(orderBase, s, websitFWS, faGreeSms,jzDate);
                // 生成差评申诉信息实体对像 只能申诉一次
                cpflag = getCp(orderBase, orderAppeal,s,ssDate);
                if (cpflag==1){
                    cpid=s.getId();
                }
            }
        }

        // 本次产生的差评申诉 补填首次评价内容(存在首评即差评的情况)
        getOrderAppeal(orderAppeal, cpflag, spmessage, cpid, zpoa, oldcpss);

    }

    private void getOrderAppraise(OrderBase orderBase, Map<String, List<SysDictRef>> sysDictRefDLMap,
                                  List<OrderAppraise> oanew,
                                  String downloadTaskNo, List<Long> getSynReqId,
                                  List<FaGreeSms> faGreeSms,List<OrderAppeal> orderAppeal) {
        WebsitFWS websitFWS = new WebsitFWS();
        int jcaninsert=1;
        int cpflag=0;
        int canappeal = 0;
        Boolean cppjly = Boolean.FALSE;
        List<ItfTblAzAssignSatisfactionDownload> sas = new ArrayList<>();
        List<OrderAppraise> oa = new ArrayList<>();
        Map<String,List<OrderAppraise>> oaMap = new HashMap<>();
        // 首评信息用于填写差评中的首评内容
        String spmessage="";
        String cpid="";
        OrderAppraise zpoa=null;
        Date ssDate = new Date();
        Date jzDate = new Date();

        // 获取申诉单的截止申诉时间
        publicService.getExpireTime(orderBase, ssDate, jzDate);

        // 提取待同步的评价数据
        sas = itfTblAzAssignSatisfactionDownloadService.lambdaQuery()
                .eq(ItfTblAzAssignSatisfactionDownload::getDownloadTaskNo, downloadTaskNo)
                .eq(ItfTblAzAssignSatisfactionDownload::getSynStatus,0)
                .orderByAsc(ItfTblAzAssignSatisfactionDownload::getHfsj)
                .list();

        // 提取首评信息 目的放在追评信息中的首评信息内
        spmessage = publicService.getSpmessage(orderBase, spmessage);

        // 提取差评申诉信息
        OrderAppeal oldcpss = orderAppealService.lambdaQuery()
                .eq(OrderAppeal::getOrderBaseId,orderBase.getId())
                .last("limit 1").one();

        for (ItfTblAzAssignSatisfactionDownload s :sas){
            // cppjly = Boolean.FALSE;
            // canappeal=0;
            jcaninsert=1;

            // 首评内容
            if (s.getSxlx()==0){
                spmessage = s.getPjnr();
            }

            // 评价短信已同步过不再同步
            if (checkRecord(orderBase, s)) {
                continue;
            }

            // 该记录前面已同步过，这里也不再同步
            if (checkFrontRecord(s)) {
                continue;
            }

            // 置能否申诉标识 canappeal=1可申诉 中差评均可申诉
            // 这里以后可能需要，不要删除
            cppjly = publicService.getCppjly(s.getPjly().trim());
            // 置可申诉标识 当前评价为中差评时看是否有已同步的差评，有不再产生申诉数据
            if (cppjly){
                OrderAppraise oldoat = orderAppraiseService.lambdaQuery()
                        .eq(OrderAppraise::getOrderBaseId,orderBase.getId())
                        .ne(OrderAppraise::getAppraiseStatus,"A").last("limit 1").one();
                if (oldoat==null){
                    canappeal=1;
                }
            }

            // 置可生成评价标识 jcaninsert 当前记录为首评且已同步记录表中存在首评时置 jcaninsert = 0 不能再插入首评
            if (s.getSynStatus().equals(0) && s.getSxlx().equals(0)){
                OrderAppraise oldoatt = orderAppraiseService.lambdaQuery()
                        .eq(OrderAppraise::getOrderBaseId,orderBase.getId())
                        .eq(OrderAppraise::getPid,s.getId())
                        .eq(OrderAppraise::getType,1)
                        .last("limit 1").one();
                if (oldoatt !=null){
                    jcaninsert=0;
                }
            }

            // 工单看用户电话和完工时间  未报完工不处理评价短信
            if (StringUtils.isEmpty(orderBase.getUserMobile()) &&
                    (orderBase.getOverTime()==null && orderBase.getWebsitOverTime()==null)){
                s.setSynStatus(9);
                s.setSynTime(new Date());
                s.setSynErrMsg("工单未报完工不处理评价短信");
                s.updateById();
                continue;
            }

            // 生成评价对像
            if (jcaninsert==1){
                websitFWS = getOrderAppreise(orderBase, sysDictRefDLMap, oanew, s);
                // 提取追评信息 即最后一条评价短信信息(一般来讲最后一条评价为好评，非好评时回访处理的事)
                if (zpoa==null){
                    zpoa=oanew.get(oanew.size()-1);
                } else {
                    if (zpoa.getCreateTime().before(oanew.get(oanew.size()-1).getCreateTime())){
                        zpoa=oanew.get(oanew.size()-1);
                    }
                }

                // 工单评价表直接插入
                if (oanew.size()>0){
                    orderAppraiseService.saveBatch(oanew);
                    oanew.clear();
                }

                // 若插入的为差评时且非中心网点时给网点负责人发短信
                addcpsms(orderBase, s, websitFWS, faGreeSms, jzDate);
            }

            // 同步工单主表的追评信息或首评信息
            setOrderAppraisemessage(orderBase, s);

            // 差评申诉 仅一次
            // 无申诉记录,看本次的评价是否为中差评为中差评时生成申诉对像并记下评价短信的ID目的是填写追评信息时不填写差评内容
            if (oldcpss==null && cpflag==0) {
                // 生成差评申诉信息实体对像 只能申诉一次
                cpflag = getCp(orderBase, orderAppeal,s,ssDate);
                if (cpflag==1){
                    cpid=s.getId();
                }
            }

            s.setSynStatus(1);
            s.setSynTime(new Date());
            s.updateById();
        }

        // 差评申诉增加首次评价及追评信息 差评申诉可能是本次产生的，也可能是上次已生成的
        // 本次产生的差评申诉 补填首次评价内容(存在首评即差评的情况)
        getOrderAppeal(orderAppeal, cpflag, spmessage, cpid, zpoa, oldcpss);
    }

    private void getOrderAppeal(List<OrderAppeal> orderAppeal, int cpflag, String spmessage, String cpid,
                                OrderAppraise zpoa, OrderAppeal oldcpss) {
        if (cpflag == 1) {
            orderAppeal.get(0).setFirstEvaluate(spmessage);
            // 补追评信息 可能存在追评 判断不是差评记录
            if (zpoa != null && !zpoa.getPid().equals(cpid)) {
                orderAppeal.get(0).setLastEvaluate(zpoa.getAppraiseContent());
            }
        }

        // 之前产生的差评申诉且本次有追评时添加追评信息
        if (oldcpss != null && zpoa != null) {
            oldcpss.setLastEvaluate(zpoa.getAppraiseContent());
            orderAppeal.clear();
            orderAppeal.add(oldcpss);
        }
    }

    private void setOrderAppraisemessage(OrderBase orderBase, ItfTblAzAssignSatisfactionDownload s) {
        if (orderBase.getAppraiseTime()==null &&
                (orderBase.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode()) ||
                        orderBase.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G10.getCode()))){
            // 首评
            // 首次评价
            orderBase.setAppraiseStatus(publicService.getAppraiseStatusT(s.getPjly().trim()));
            // 首次评价内容
            orderBase.setAppraiseContent(s.getPjly().trim());
            // 首次评价时间
            orderBase.setAppraiseTime(s.getCreatedDate());
            // 评价来源 无法区分
            // orderBase.setAppraiseSource();
        } else {
            // 追评评价状态
            orderBase.setSecondAppraiseStatus(publicService.getAppraiseStatusT(s.getPjly().trim()));
            // 追评评价内容
            orderBase.setSecondContent(s.getPjly().trim());
            // 追评评价时间
            orderBase.setSecondAppraiseTime(s.getCreatedDate());
        }
    }

    private boolean checkFrontRecord(ItfTblAzAssignSatisfactionDownload s) {
        ItfTblAzAssignSatisfactionDownload azas = itfTblAzAssignSatisfactionDownloadService.lambdaQuery()
                .lt(ItfTblAzAssignSatisfactionDownload::getSynReqId, s.getSynReqId())
                .eq(ItfTblAzAssignSatisfactionDownload::getPgguid, s.getPgguid())
                .eq(ItfTblAzAssignSatisfactionDownload::getId, s.getId())
                .lt(ItfTblAzAssignSatisfactionDownload::getLastModifiedDate, s.getLastModifiedDate())
                .eq(ItfTblAzAssignSatisfactionDownload::getPjly, s.getPjly())
                .last("limit 1").one();
        if (azas !=null){
            s.setSynStatus(9);
            s.setSynTime(new Date());
            s.setSynErrMsg("评价已同步，忽略更新");
            s.updateById();
            return true;
        }
        return false;
    }

    private boolean checkRecord(OrderBase orderBase, ItfTblAzAssignSatisfactionDownload s) {
        OrderAppraise oldoa = orderAppraiseService.lambdaQuery()
                .eq(OrderAppraise::getOrderBaseId, orderBase.getId())
                .eq(OrderAppraise::getPid, s.getId())
                .last("limit 1").one();
        if (oldoa !=null){
            s.setSynStatus(9);
            s.setSynTime(new Date());
            s.setSynErrMsg("评价已同步，忽略更新");
            s.updateById();
            return true;
        }
        return false;
    }

    private int getCp(OrderBase orderBase, List<OrderAppeal> orderAppeals,
                      ItfTblAzAssignSatisfactionDownload s, Date ssDate) {
        if (s.getPjnr().equals("3") || s.getPjnr().indexOf("不满意")>=0 || publicService.getCppjly(s.getPjly().trim())){
            OrderAppeal orderAppeal=new OrderAppeal();
            orderAppeal.setOrderBaseId(orderBase.getId());
            orderAppeal.setPgid(orderBase.getPgid());
            orderAppeal.setWorkerName(orderBase.getWorkerName());
            orderAppeal.setWorkerId(orderBase.getWorkerId());
            // 网点必填
            orderAppeal.setWebsitId(orderBase.getWebsitId());
            orderAppeal.setBadEvaluate(s.getPjnr());
            orderAppeal.setAppraiseStatus(publicService.getAppraiseStatusT(s.getPjly()));
            orderAppeal.setStatus(1);
            orderAppeal.setCanApply(Boolean.TRUE);
            orderAppeal.setCreateTime(new Date());
            orderAppeal.setCreateBy("system");
            orderAppeal.setEvaluateTime(ssDate);
            orderAppeals.add(orderAppeal);
            return 1;
        }
        return 0;
    }

    private void addcpsms(OrderBase order, ItfTblAzAssignSatisfactionDownload s, WebsitFWS websitFWS,
                          List<FaGreeSms> fsList, Date jzDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (s.getPjly().equals("3") || s.getPjnr().indexOf("不满意")>=0 || publicService.getCppjly(s.getPjly().trim())){
            if (StringUtils.isNotEmpty(s.getHfwdno()) && !s.getHfwdno().equals("99999999") && StringUtils.isNotEmpty(websitFWS.getWdlxdh())){
                FaGreeSms fs=new FaGreeSms();
                fs.setSynTaskNo(publicService.getUUID());
                fs.setWorkerOrderNo(order.getId());
                fs.setAzorwx(2);
                fs.setFjid(String.valueOf(s.getPgguid()));
                fs.setFjwd(s.getHfwdno());
                Random random = new Random(System.currentTimeMillis());
                fs.setFsma(String.valueOf(random.nextInt(10000)));
                fs.setFsnr("您收到一张客户的投诉工单，请及时处理！工单号：" + String.valueOf(order.getPgid()) +
                        ",服务人员：" + order.getWorkerName()+ ",首次申诉截止时间:" + sdf.format(jzDate));
                fs.setSjid(websitFWS.getWdlxdh());
                fs.setYhlb(2);
                fsList.add(fs);
            }
        }
    }

    private WebsitFWS getOrderAppreise(OrderBase orderBase, Map<String, List<SysDictRef>> sysDictRefDLMap,
                                       List<OrderAppraise> oanew, ItfTblAzAssignSatisfactionDownload s) {
        WebsitFWS websitFWS;
        OrderAppraise o = new OrderAppraise();
        // id为主键，放在pid 中
        o.setPid(s.getId());
        o.setPgguid(s.getPgguid());
        // 工单号
        o.setOrderBaseId(orderBase.getId());
        o.setPgid(orderBase.getPgid());

        o.setOrderType(orderBase.getOrderType());
        o.setWebsitId(orderBase.getWebsitId());
        o.setWebsitName(orderBase.getWebsitName());
        o.setWorkerId(orderBase.getWorkerId());
        o.setWorkerName(orderBase.getWorkerName());
        o.setUserName(orderBase.getUserName());
        o.setUserPhone(orderBase.getUserMobile());
        o.setAddress(orderBase.getAddress());
        // 产品大类
        o.setMainId(String.valueOf(s.getSplb()));
        o.setMainName("");
        if (sysDictRefDLMap.containsKey(String.valueOf(s.getSplb()))){
            o.setMainId(sysDictRefDLMap.get(String.valueOf(s.getSplb())).get(0).getDictCode());
            o.setMainName(sysDictRefDLMap.get(String.valueOf(s.getSplb())).get(0).getDictValue());
        }

        o.setAppraiseStatus(publicService.getAppraiseStatusT(s.getPjly()));

        o.setAppraiseContent(s.getPjnr());
        o.setSource("GREE");

        // 回访人id无
        o.setRvisitNickName(s.getHfren());
        // 回访人网点信息
        // 售后网点处理
        websitFWS = publicService.shshwdToptshwd(s.getHfwdno(), orderBase);
        if (StringUtils.isEmpty(websitFWS.getWebsitId())){
            websitFWS = publicService.shxswdToptxswd(s.getHfwdno(), orderBase);
        }
        o.setRvisitWebsitId(websitFWS.getWebsitId());
        o.setRvisitWebsitName(websitFWS.getWdmc());

        o.setRvisitTime(s.getHfsj());
        o.setNegativeType(s.getBmylx());
        o.setNegativeRemark(s.getBmybeiz());
        o.setNegativeTime(s.getCreatedDate());
        o.setAppointmentType(s.getMydlx());

        if (s.getSxlx().equals(0)){
            o.setType(1);
        } else {
            o.setType(2);
        }

        if (s.getCreatedBy()!=null){
            o.setCreateBy(s.getCreatedBy());
        }
        o.setCreateTime(new Date());
        if (s.getCreatedDate()!=null){
            o.setCreateTime(s.getCreatedDate());
        }

        if (StringUtils.isNotEmpty(s.getLastModifiedBy())){
            o.setUpdateBy(s.getLastModifiedBy());
        }
        if (s.getLastModifiedDate()!=null){
            o.setUpdateTime(s.getLastModifiedDate());
        }


        oanew.add(o);
        return websitFWS;
    }

    private void getOrderAppointment(OrderBase orderBase, List<OrderReAppointment> oa, List<ItfTblAzAssignAppointmentDownload> appointments) {
        for (ItfTblAzAssignAppointmentDownload a :appointments){
            OrderReAppointment v = new OrderReAppointment();
            v.setId(a.getId());
            v.setOrderBaseId(orderBase.getId());
            v.setOrderType(OrderTypeEnum.ORDER_TYPE_INSTALL.getCode());
            v.setWorkerId(orderBase.getWorkerId());
            v.setWorkerName(orderBase.getWorkerName());
            v.setWebsitId(orderBase.getWebsitId());
            v.setWebsitName(orderBase.getWebsitName());
            v.setNewAppointmentRemark(a.getBeiz());
            v.setUserName(orderBase.getUserName());
            v.setUserMobile(orderBase.getUserMobile());
            v.setCreateBy(a.getCzren());
            v.setCreateTime(a.getCzsj());
            v.setUpdateBy(a.getLastModifiedBy());
            v.setUpdateTime(a.getLastModifiedDate());
            v.setNewAppointmentTime(a.getKssj());
            v.setNewAppointmentEndTime(a.getJssj());
            v.setPgid(orderBase.getPgid());
            v.setExamineStatus("OK");
            oa.add(v);
        }
    }

    private OrderInstall getOrderInstall(OrderBase orderBase, ItfTblAzAssignLcLsDownload item,List<ItfTblAzAssignFeeDownload>  fyqd) {
        OrderInstall orderInstall = new OrderInstall();

        OrderPar request = new OrderPar();
        request.setMainSynReqId(item.getSynReqId());

        orderInstall = azGDFYQDDownloadMapper.getOrderFYQD(request);
        if (StringUtils.isNotEmpty(item.getCjwdno())){
            orderInstall.setShopNo(item.getCjwdno());
        }
        // 工单号
        orderInstall.setOrderBaseId(orderBase.getId());
        // 创建人,创建时间
        orderInstall.setCreateBy(orderBase.getCreateBy());
        orderInstall.setCreateTime(orderBase.getCreateTime());

        if (CollectionUtils.isNotEmpty(fyqd)){
            orderInstall.setBracket(fyqd.get(0).getAjia());
            orderInstall.setPipe(fyqd.get(0).getJcguan());
            orderInstall.setSwithFlag(fyqd.get(0).getKqkg());
            orderInstall.setHighAltitude(fyqd.get(0).getGkzy());
            orderInstall.setHole(fyqd.get(0).getYccxqk());
        }
        return orderInstall;
    }

    @NotNull
    private List<OrderInstallOperatingLog> getOrderInstallOperatingLogs(List<ItfTblAzAssignFkmxDownload> fkmxs, OrderBase orderBase, ItfTblAzAssignLcLsDownload item) {
        List<OrderInstallOperatingLog> oiolList = new ArrayList<>();
        WebsitFWS websitFWS = new WebsitFWS();
        for (ItfTblAzAssignFkmxDownload fkmx : fkmxs){
            OrderPar orderPar = new OrderPar();
            orderPar.setSynReqId(fkmx.getSynReqId());
            OrderInstallOperatingLog oiol = azGDFkMxDownloadMapper.getOrderFkMx(orderPar);

            // 反馈网点处理，先从售后网点查看
            websitFWS = publicService.shshwdToptshwd(oiol.getWebsitNumber(),orderBase);
            if (StringUtils.isEmpty(websitFWS.getWebsitId())){
                websitFWS = publicService.shxswdToptxswd(oiol.getWebsitNumber(),orderBase);
            }
            oiol.setOperateWebsit(websitFWS.getWebsitId());
            oiol.setWebsitNumber(websitFWS.getWdmc());

            // 工单号码
            oiol.setOrderBaseId(orderBase.getId());
            // 客户名称,客户联系电话
            oiol.setCustomerName(orderBase.getUserName());
            oiol.setCustomerPhone(orderBase.getUserMobile());
            oiol.setPgid(orderBase.getPgid());
            oiol.setUploadNotifyFlag(0);
            // websit_number及operate_websit 可能为空，需从销售网点再次查询
            if (StringUtils.isNotEmpty(fkmx.getWdno()) && StringUtils.isEmpty(oiol.getWebsitNumber())){
                websitFWS = publicService.shxswdToptxswd(oiol.getWebsitNumber(),orderBase);
                if (websitFWS !=null){
                    oiol.setOperateWebsit(websitFWS.getWebsitId());// 为售后网点
                    oiol.setWebsitNumber(websitFWS.getWdmc());// 为操作人员所属网点
                }
            }
            // 操作前工单状态,操作前派工状态,操作后工单状态,操作后派工状态 这些字段不处理
            oiolList.add(oiol);
        }
        return oiolList;
    }

    private void getOrderProductUp(OrderBase orderBase, List<OrderProduct> orderProducts, Map<String,
            List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                                   Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                                   List<ItfTblAzAssignMxDownload> orderMx) {

        // pgmxid主键
        // 生成工单产品对象
        /*for (ItfTblAzAssignMxDownload mx:orderMx){
            OrderProduct op = getOrderProduct(orderBase, orderProducts, sysDictRefDLMap, sysDictRefXLMap,
                    sysDictRefXiLieMap, mx);
        }*/
    }


    private void getOrderProduct(OrderBase orderBase, List<OrderProduct> orderProducts, Map<String,
            List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                                 Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                                 List<ItfTblAzAssignMxDownload> orderMx,List<OrderInstallDetail> oids,
                                 List<OrderDetailFile> odfs, Map<String,String> productMap) {
        int insertnum=1;
        int outid=1;


        for (ItfTblAzAssignMxDownload mx:orderMx){
            insertnum=1;
            outid=1;
            // 生成工单产品对象
            OrderProduct op = getOrderProduct(orderBase, orderProducts, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap, mx, productMap);
            // 生成采集明细数据+附件数据
            // 总数量一条条插入，内外机数量不再拆分
            // extracted(orderBase, oids, odfs, insertnum, outid, mx, op);
        }
    }

    private void extracted(OrderBase orderBase, List<OrderInstallDetail> oids, List<OrderDetailFile> odfs,
                           int insertnum, int outid, ItfTblAzAssignMxDownload mx, OrderProduct op) {
        // 记录产品数量
        int totalnum= mx.getShul();
        if (totalnum>100) {
            totalnum=1;
        }
        while (insertnum <=totalnum){
            OrderInstallDetail add = getOrderInstallDetail(orderBase, oids, outid, op,mx);
            insertnum++;
            outid++;

            // 安装工单采集附件表(仅商用空调的多联机、风管机)需要初始化
            if (add.getSmallName().equals("多联机") || add.getSmallName().equals("风管机")){
                getOrderDetailFile(orderBase, odfs, add, "室外机固定", 2);
                getOrderDetailFile(orderBase, odfs, add, "冷凝水管软接", 2);
                getOrderDetailFile(orderBase, odfs, add, "外机电源接线", 2);
                getOrderDetailFile(orderBase, odfs, add, "外机出管处封堵", 2);
                getOrderDetailFile(orderBase, odfs, add, "室内机安装完成", 3);
                getOrderDetailFile(orderBase, odfs, add, "冷凝水管通气孔", 3);
                getOrderDetailFile(orderBase, odfs, add, "室内机走管", 3);
                getOrderDetailFile(orderBase, odfs, add, "系统抽真空", 3);
            }
        }
    }

    private OrderProduct getOrderProduct(OrderBase orderBase, List<OrderProduct> orderProducts,
                                 Map<String, List<SysDictRef>> sysDictRefDLMap, Map<String, List<SysDictRef>> sysDictRefXLMap,
                                 Map<String, List<SysDictRef>> sysDictRefXiLieMap, ItfTblAzAssignMxDownload mx, Map<String,String> productMap) {
        OrderProduct op = new OrderProduct();
        op.setId(publicService.getUUID());
        op.setOrderBaseId(orderBase.getId());
        // pgmxid主键
        op.setPgmxid(mx.getPgmxid());
        op.setPgguid(mx.getPgguid());
        op.setMainId(String.valueOf(mx.getSpid()));
        op.setMainName(mx.getSpmc());

        if (sysDictRefDLMap.containsKey(String.valueOf(mx.getSpid()))){
            op.setMainId(sysDictRefDLMap.get(String.valueOf(mx.getSpid())).get(0).getDictCode());
            op.setMainName(sysDictRefDLMap.get(String.valueOf(mx.getSpid())).get(0).getDictValue());
        }
        op.setSmallId(String.valueOf(mx.getXlid()));
        op.setSmallName(mx.getXlmc());
        if (mx.getXlid()!=null && !mx.getXlid().equals(0L) && sysDictRefXLMap.containsKey(String.valueOf(mx.getXlid()))) {
            op.setSmallId(sysDictRefXLMap.get(String.valueOf(mx.getXlid())).get(0).getDictCode());
            op.setSmallName(sysDictRefXLMap.get(String.valueOf(mx.getXlid())).get(0).getDictValue());
        }

        op.setSeriesId(mx.getXiid());
        op.setSeriesName(mx.getXimc());
        if (StringUtils.isNotEmpty(mx.getXiid()) && !mx.getXiid().equals("0") && sysDictRefXiLieMap.containsKey(mx.getXiid())) {
            op.setSeriesId(sysDictRefXiLieMap.get(mx.getXiid()).get(0).getDictCode());
            op.setSeriesName(sysDictRefXiLieMap.get(mx.getXiid()).get(0).getDictValue());
        }

        // 改成 product 表中的 product_id
        // op.setProductId(mx.getJxno());
        op.setProductId("");
        if (productMap.containsKey(mx.getJxno())){
            op.setProductId(productMap.get(mx.getJxno()));
        }
        op.setOutJxno(mx.getJxno());

        op.setProductName(mx.getJxmc());
        op.setInsideCode(mx.getNjtm());
        op.setOutCode(mx.getWjtm());
        op.setNum(mx.getShul());
        if (op.getNum()>100){
            op.setNum(1);
        }
        op.setPrice(mx.getJiage());
        op.setUnit(mx.getDanw());
        op.setMaterialNumber(mx.getWldm());
        op.setInsideNum(mx.getNjsl());
        op.setOutNum(mx.getWjsl());
        // op.setUndoneNum(mx.getWwsl());
        op.setUndoneNum(op.getNum());
        op.setCreateTime(mx.getCjdt());
        op.setCreateBy(mx.getCreatedBy());
        // 销售单位
        op.setSaleWebsit(orderBase.getSaleWebsitId());
        // 无销售单位联系人电话
        op.setServiceWebsit(orderBase.getWebsitId());
        // 无服务单位电话信息 最好取websit表中的热线，先不取
        op.setBuyTime(orderBase.getBuyTime());
        op.setRemark(mx.getBeiz());
        orderProducts.add(op);
        return op;
    }

    @NotNull
    private OrderInstallDetail getOrderInstallDetail(OrderBase orderBase, List<OrderInstallDetail> oids,
                                                     int outid, OrderProduct op, ItfTblAzAssignMxDownload mx) {
        String pgwcmxid = publicService.getUUID();
        OrderInstallDetail add = new OrderInstallDetail();
        add.setId(IdWorker.getIdStr());
        add.setWebsitId(orderBase.getWebsitId());
        add.setOrderBaseId(orderBase.getId());
        add.setOrderProductId(op.getId());
        add.setCreateTime(new Date());
        add.setCreateBy("system");
        add.setMainId(op.getMainId());
        add.setMainName(op.getMainName());
        add.setSmallId(op.getSmallId());
        add.setSmallName(op.getSmallName());
        add.setSeriesId(op.getSeriesId());
        add.setSeriesName(op.getSeriesName());
        if (mx.getJxno()==null){
            add.setProductId("0");
        } else {
            add.setProductId(mx.getJxno());
        }
        //add.setProductId(op.getProductId());
        //add.setProductName(op.getProductName());
        if (mx.getJxmc()==null){
            add.setProductName("");
        } else {
            add.setProductName(mx.getJxmc());
        }

        add.setOutId(outid);
        add.setCodeIndex(outid);
        add.setInsideNum(op.getInsideNum());
        if (add.getInsideNum()>100){
            add.setInsideNum(1);
        }
        add.setOutNum(op.getOutNum());
        if (add.getOutNum()>100){
            add.setOutNum(1);
        }
        add.setPgguid(orderBase.getPgguid());
        add.setPgwcmxid(pgwcmxid);
        add.setPgmxid(op.getPgmxid());
        add.setBuyCertificatePicture("");
        add.setAfterBuyCertificatePicture("");
        add.setFirstTime(new Date());
        oids.add(add);
        return add;
    }

    private void getOrderDetailFile(OrderBase orderBase, List<OrderDetailFile> odfs, OrderInstallDetail add, String 室外机固定, Integer fileType) {
        OrderDetailFile a = new OrderDetailFile();
        a.setFjguid(IdWorker.getIdStr());
        a.setOrderBaseId(orderBase.getId());
        a.setOrderDetailId(add.getId());
        a.setPgwcmxid(publicService.getUUID());
        a.setFileName(室外机固定);
        a.setFileType(fileType);
        a.setCreateTime(new Date());
        a.setCreateBy("system");
        odfs.add(a);
    }


    private OrderWorker getOrderWorker(OrderBase orderBase) {
        if (StringUtils.isNotEmpty(orderBase.getWorkerName())){
            OrderWorker orderWorker = new OrderWorker();
            orderWorker.setOrderBaseId(orderBase.getId());
            orderWorker.setWorkerId(orderBase.getWorkerId());
            orderWorker.setWorkerName(orderBase.getWorkerName());
            orderWorker.setWorkerMobile(orderBase.getWorkerMobile());
            orderWorker.setWorkerIdcard(orderBase.getWorkerIdcard());
            orderWorker.setIsMaster(Boolean.TRUE);
            orderWorker.setBrandPgid(orderBase.getPgid());
            orderWorker.setPgguid(orderBase.getPgguid());
            orderWorker.setCreateTime(orderBase.getCreateTime());
            orderWorker.setCreateBy(orderBase.getCreateBy());
            orderWorker.setOutWorkerSource(Boolean.FALSE);

            return orderWorker;
        }

        return null;
    }

    private OrderBase getAddOrderBase(ItfTblAzAssignLcLsDownload item, Brand brand,
                                      List<ItfGreeToFaDownloadTaskList> its) {
        OrderBase orderBase = new OrderBase();
        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());

        // 生成工单基础表 对象
        orderBase = azGDLcLsDownloadMapper.getOrderBase(orderPar);


        orderBase.setId("33"+IdWorker.getIdStr());
        // 总部下来的工单新增时统一为待接收状态
        orderBase.setDispatchStatus("DJS");

        // 1500 挂起工单  先给A13081=非广佛作废
        if (item.getDqjd().equals(1500L)){
            orderBase.setOrderStatus("A13081");
        }

        //  预派工订单标识
        if (orderBase.getOrderStatus().equals(OrderStatusEnum.INSTALL_STATUS_A1100.getCode()) ||
                orderBase.getOrderStatus().equals(OrderStatusEnum.INSTALL_STATUS_A1122.getCode()) ||
                orderBase.getOrderStatus().equals(OrderStatusEnum.INSTALL_STATUS_A1130.getCode()) ){
            orderBase.setIsReservation(1);
        }
        // 重置部分数据 + 采集数据下载
        orderService.setPar(item, orderBase,its);

        // 赋值接收师傅信息
        Worker worker= publicService.getInstallOrderWorker(item.getAzrenid());
        if (worker !=null){
            // 提取网点师傅ID
            /*WebsitWorker ww = publicService.getOrderWebsitWorker(worker.getWorkerId(),orderBase.getWebsitId());
            if (ww !=null ){
                orderBase.setWorkerId(ww.getWebsitWorkerId());
                orderBase.setWorkerName(worker.getWorkerName());
                orderBase.setWorkerMobile(worker.getMobile());
                orderBase.setWorkerIdcard(worker.getIdcard());
            }*/
            orderBase.setWorkerId(worker.getWorkerId());
            orderBase.setWorkerName(worker.getWorkerName());
            orderBase.setWorkerMobile(worker.getMobile());
            orderBase.setWorkerIdcard(worker.getIdcard());
        }

        return orderBase;
    }

    private OrderBase getAddOrderBaseApi(ItfTblAzAssignLcLsDownload item, Brand brand,
                                      List<ItfGreeToFaDownloadTaskList> its) {
        OrderBase orderBase = new OrderBase();
        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());

        // 生成工单基础表 对象
        orderBase = azGDLcLsDownloadMapper.getOrderBase(orderPar);
        // 处理用户等级
        publicService.setUserLevel(orderBase);

        // 未完成数据修改 如果工单关闭就用wwsl，否则用安装数量
        if (!(item.getDqjd().equals(1304) || item.getDqjd().equals(1309))){
            orderBase.setUndoneNum(item.getAzsl());
        }

        orderBase.setSource("GREE");
        orderBase.setId("G" + IdWorker.getIdStr());
        // 总部下来的工单新增时统一为待接收状态
        orderBase.setDispatchStatus("DJS");

        // 1500 挂起工单  先给A13081=非广佛作废
        if (item.getDqjd().equals(1500L)){
            orderBase.setOrderStatus("A13081");
        }

        // 总部的为 1302 无对应关系，根据工单的过程处理
        if (StringUtils.isEmpty(orderBase.getOrderStatus())){
            orderBase.setOrderStatus("A1101");
        }
        //  预派工订单标识
        if (orderBase.getOrderStatus().equals(OrderStatusEnum.INSTALL_STATUS_A1100.getCode()) ||
                orderBase.getOrderStatus().equals(OrderStatusEnum.INSTALL_STATUS_A1122.getCode()) ||
                orderBase.getOrderStatus().equals(OrderStatusEnum.INSTALL_STATUS_A1130.getCode()) ){
            orderBase.setIsReservation(1);
        }
        // 重置部分数据 + 采集数据下载
        orderService.setParApi(item, orderBase,its);

        // 赋值接收师傅信息
        Worker worker= publicService.getInstallOrderWorker(item.getAzrenid());
        if (worker !=null){
            // 提取网点师傅ID
            /*WebsitWorker ww = publicService.getOrderWebsitWorker(worker.getWorkerId(),orderBase.getWebsitId());
            if (ww !=null ){
                orderBase.setWorkerId(ww.getWebsitWorkerId());
                orderBase.setWorkerName(worker.getWorkerName());
                orderBase.setWorkerMobile(worker.getMobile());
                orderBase.setWorkerIdcard(worker.getIdcard());
            }*/
            orderBase.setWorkerId(worker.getWorkerId());
            orderBase.setWorkerName(worker.getWorkerName());
            orderBase.setWorkerMobile(worker.getMobile());
            orderBase.setWorkerIdcard(worker.getIdcard());
        }


        return orderBase;
    }

    private OrderBase getAddOrderBaseUp(ItfTblAzAssignLcLsDownload item, Brand brand,List<ItfGreeToFaDownloadTaskList> its) {
        OrderBase orderBase = new OrderBase();
        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());
        // 生成工单基础表 对象
        orderBase = azGDLcLsDownloadMapper.getOrderBase(orderPar);


        // 重置部分数据
        orderService.setParUp(item, orderBase,its);

        // 赋值接收师傅信息
        Worker worker= publicService.getInstallOrderWorker(item.getAzrenid());
        if (worker !=null){
            // 提取网点师傅ID
            /*WebsitWorker ww = publicService.getOrderWebsitWorker(worker.getWorkerId(),orderBase.getWebsitId());
            if (ww !=null ){
                orderBase.setWorkerId(ww.getWebsitWorkerId());
                orderBase.setWorkerName(worker.getWorkerName());
                orderBase.setWorkerMobile(worker.getMobile());
                orderBase.setWorkerIdcard(worker.getIdcard());
            }*/
            orderBase.setWorkerId(worker.getWorkerId());
            orderBase.setWorkerName(worker.getWorkerName());
            orderBase.setWorkerMobile(worker.getMobile());
            orderBase.setWorkerIdcard(worker.getIdcard());
        }

        return orderBase;
    }

    private OrderBase getAddOrderBaseUpApi(ItfTblAzAssignLcLsDownload item, Brand brand,  List<ItfGreeToFaDownloadTaskList> its) {
        OrderBase orderBase = new OrderBase();
        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());
        // 生成工单基础表 对象
        orderBase = azGDLcLsDownloadMapper.getOrderBase(orderPar);
        // 处理用户等级
        publicService.setUserLevel(orderBase);

        // 总部的为 1302 无对应关系，根据工单的过程处理
        if (StringUtils.isEmpty(orderBase.getOrderStatus())){
            orderBase.setOrderStatus("A1101");
        }

        // 重置部分数据 + 生成采集数据下载数据 2201
        orderService.setParUpApi(item, orderBase,its);

        // 赋值接收师傅信息
        Worker worker= publicService.getInstallOrderWorker(item.getAzrenid());
        if (worker !=null){
            // 提取网点师傅ID
            /*WebsitWorker ww = publicService.getOrderWebsitWorker(worker.getWorkerId(),orderBase.getWebsitId());
            if (ww !=null ){
                orderBase.setWorkerId(ww.getWebsitWorkerId());
                orderBase.setWorkerName(worker.getWorkerName());
                orderBase.setWorkerMobile(worker.getMobile());
                orderBase.setWorkerIdcard(worker.getIdcard());
            }*/
            orderBase.setWorkerId(worker.getWorkerId());
            orderBase.setWorkerName(worker.getWorkerName());
            orderBase.setWorkerMobile(worker.getMobile());
            orderBase.setWorkerIdcard(worker.getIdcard());
        }

        return orderBase;
    }
}
