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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zfire.jiasm.syncdata.api.OrderAddBeanDTO;
import com.zfire.jiasm.syncdata.base.BaseService;
import com.zfire.jiasm.syncdata.constant.DictTypeEnum;
import com.zfire.jiasm.syncdata.constant.GDOrderStatusEnum;
import com.zfire.jiasm.syncdata.constant.OrderTypeEnum;
import com.zfire.jiasm.syncdata.constant.ServiceCategoryEnum;
import com.zfire.jiasm.syncdata.dao.mapper.*;
import com.zfire.jiasm.syncdata.parameter.OrderPar;
import com.zfire.jiasm.syncdata.parameter.ReAppointment;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.response.WebsitFWS;
import com.zfire.jiasm.syncdata.service.AddRepairBusinessService;
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.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 AddRepairBusinessServiceImpl implements AddRepairBusinessService {
    @Resource
    ItfTblAssignDownloadService itfTblAssignDownloadService;
    @Resource
    RepairDownloadMapper repairDownloadMapper;
    @Resource
    OrderBaseService orderBaseService;
    @Resource
    OrderService orderService;
    @Resource
    AssignDownloadMapper assignDownloadMapper;
    @Resource
    ItfTblAssignMxDownloadService itfTblAssignMxDownloadService;
    @Resource
    RepairMxDownloadMapper repairMxDownloadMapper;
    @Resource
    PublicService publicService;
    @Resource
    OrderProductService orderProductService;
    @Resource
    ItfTblAssignFkmxDownloadService itfTblAssignFkmxDownloadService;
    @Resource
    OrderRepairOperatingLogService orderRepairOperatingLogService;
    @Resource
    ItfTblAssignSatisfactionDownloadService itfTblAssignSatisfactionDownloadService;
    @Resource
    OrderAppraiseService orderAppraiseService;
    @Resource
    AppraiseMapper appraiseMapper;
    @Resource
    AssignSatisfactionDownloadMapper assignSatisfactionDownloadMapper;
    @Resource
    FaGreeSmsService faGreeSmsService;
    @Resource
    ItfTblAssignXzydDownloadService itfTblAssignXzydDownloadService;
    @Resource
    OrderInformationService orderInformationService;
    @Resource
    ItfTblAssignAppointmentDownloadService itfTblAssignAppointmentDownloadService;
    @Resource
    OrderRepairDetailService orderRepairDetailService;
    @Resource
    OrderRepairService orderRepairService;
    @Resource
    RepairLogMapper repairLogMapper;
    @Resource
    GDOrderBaseMapper gdOrderBaseMapper;
    @Resource
    OrderAppealService orderAppealService;
    @Autowired
    JiasmApi jiasmApi;
    @Resource
    BaseService baseService;
    @Resource
    BrandService brandService;
    @Resource
    TestService testService;
    @Resource
    ItfGreeToFaDownloadTaskListService itfGreeToFaDownloadTaskListService;
    @Resource
    SyncCreateOrderService syncCreateOrderService;




    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRapairOrder(Brand brand, ItfTblAssignDownload item,
                         Map<String, List<SysDictRef>> sysDictRefDLMap,
                         Map<String, List<SysDictRef>> sysDictRefXLMap,
                         Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                         Map<String, List<SysDictRef>> sysDictRefDLMapXq,
                         Map<String, List<SysDictRef>> sysDictRefXLMapXq, Map<String,String> productMap) {
        List<ItfTblAssignXzydDownload> yds = itfTblAssignXzydDownloadService.lambdaQuery()
                .eq(ItfTblAssignXzydDownload::getDownloadTaskNo,item.getDownloadTaskNo()).list();

        // 新增 TL_SynDataFrom_tbl_assign_batch
        // TL_SynDataFrom_tbl_assign 主单的 syn_req_id
        // 处理维修工单主表数据
        OrderBase order = generateOrder(brand, item, yds);
        // 处理工单师傅
        publicService.getOrderWorker(order);
        // 获取工单扩展信息
        getOrderInstall(item, order, sysDictRefXLMapXq);
        // 处理维修单明细表 TL_SynDataFrom_tbl_assign_mx
        generateMx(brand, item, order, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap);
        // 处理维修单过程反馈表 放入操作日志表 TL_SynDataFrom_tbl_assign_fkmx
        generateFkmx(item, order);
        // 处理用户评价数据 TL_SynDataFrom_tbl_assign_satisfaction
        generateSstisfaction(item, sysDictRefDLMap, order);
        // 阅读要求数据处理 TL_SynDataFrom_tbl_assign_xzyd
        generateXzyd(yds, order);
        // 用户预约改约数据处理 TL_SynDataFrom_tbl_assign_appointment
        generateAppointment(item, order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRapairOrder(Brand brand, Map<String, List<SysDictRef>> sysDictRefDLMap,
                                  Map<String, List<SysDictRef>> sysDictRefXLMap,
                                  Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                                  @NotNull ItfTblAssignDownload item,
                                  Map<String, List<SysDictRef>> sysDictRefDLMapXq,
                                  Map<String, List<SysDictRef>> sysDictRefXLMapXq, Map<String,String> productMap) {
        List<ItfTblAssignXzydDownload> yds = itfTblAssignXzydDownloadService.lambdaQuery()
                .eq(ItfTblAssignXzydDownload::getDownloadTaskNo, item.getDownloadTaskNo()).list();

        // TL_SynDataFrom_tbl_assign_batch
        // TL_SynDataFrom_tbl_assign 主单的 syn_req_id
        // 处理维修工单主表数据
        modifyOrderBase(brand, sysDictRefDLMap, item);

        OrderBase order = orderBaseService.lambdaQuery()
                .eq(OrderBase::getPgid, item.getPgid())
                .eq(OrderBase::getOrderType, OrderTypeEnum.ORDER_TYPE_REPAIR.getCode())
                .last("limit 1")
                .one();

        // 工单师傅信息更新
        upOrderWorker(order);
        // 工单扩展信息更新
        getOrderInstall(item, order,sysDictRefXLMapXq);
        // 维修单明细表更新 TL_SynDataFrom_tbl_assign_mx
        generateMxUpdate(brand, item, order, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap, productMap);
        // 处理维修单过程反馈(只新增不修改)  放入操作日志表 TL_SynDataFrom_tbl_assign_fkmx
        generateFkmxUpdate(item, order);
        // 处理用户评价数据 TL_SynDataFrom_tbl_assign_satisfaction
        generateSstisfaction(item, sysDictRefDLMap, order);
        // 阅读要求数据处理 TL_SynDataFrom_tbl_assign_xzyd
        generateXzydUpdate(yds, order);
        // 用户预约改约数据处理 TL_SynDataFrom_tbl_assign_appointment
        generateAppointmentUpdate(item, order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRapairOrderApi(Brand brand, ItfTblAssignDownload item,
                         Map<String, List<SysDictRef>> sysDictRefDLMap,
                         Map<String, List<SysDictRef>> sysDictRefXLMap,
                         Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                         Map<String, List<SysDictRef>> sysDictRefDLMapXq,
                         Map<String, List<SysDictRef>> sysDictRefXLMapXq,
                                     Boolean flag, Map<String,String> productMap) throws Exception {
        OrderWorker orderWorker = new OrderWorker();
        OrderRepair or = new OrderRepair();
        List<OrderProduct> addmx = new ArrayList<>();
        List<ItfTblAssignMxDownload> ups = new ArrayList<>();
        List<ItfTblAssignSatisfactionDownload> pjups = new ArrayList<>();
        List<OrderAppeal> orderAppeal = new ArrayList<>();
        List<OrderAppraise> oanew = new ArrayList<>();
        List<FaGreeSms> faGreeSms = new ArrayList<>();
        List<OrderInformation> oilist = new ArrayList<>();
        List<ItfTblAssignXzydDownload> ydups = new ArrayList<>();
        List<ItfTblAssignFkmxDownload> fkmxups = new ArrayList<>();
        List<ItfTblAssignAppointmentDownload> us = new ArrayList<>();
        List<OrderRepairOperatingLog> orols = new ArrayList<>();
        List<ItfGreeToFaDownloadTaskList> its = new ArrayList<>();

        List<ItfTblAssignXzydDownload> yds = itfTblAssignXzydDownloadService.lambdaQuery()
                .eq(ItfTblAssignXzydDownload::getDownloadTaskNo,item.getDownloadTaskNo()).list();

        // 新增 TL_SynDataFrom_tbl_assign_batch
        // TL_SynDataFrom_tbl_assign 主单的 syn_req_id
        // 处理维修工单主表数据 + 采集数据下载
        OrderBase order = generateOrderApi(brand, item, yds,its);
        // 生成工单师傅对像
        orderWorker = publicService.getOrderWorkerApi(order);
        // 获取工单扩展信息 需求大小类在这里处理
        getOrderInstallApi(item, order, sysDictRefDLMapXq, sysDictRefXLMapXq,or);
        // 处理维修单明细表 TL_SynDataFrom_tbl_assign_mx
        generateMxApi(brand, item, order, sysDictRefDLMap, sysDictRefXLMap,
                sysDictRefXiLieMap, addmx, ups, productMap);
        // 处理维修单过程反馈表 放入操作日志表 TL_SynDataFrom_tbl_assign_fkmx
        generateFkmxApi(item, fkmxups, orols, order);
        // 处理用户评价数据 TL_SynDataFrom_tbl_assign_satisfaction
        generateSstisfactionApi(item, sysDictRefDLMap, order);
        // 阅读要求数据处理 TL_SynDataFrom_tbl_assign_xzyd
        generateXzydApi(yds, order, oilist, ydups);
        // 用户预约改约数据处理 TL_SynDataFrom_tbl_assign_appointment
        generateAppointmentApi(item, us);

        // 还原网点转换信息
        publicService.revertRepairFun(order,item);

        // 生成工单
        return createRepairOrder(item, orderWorker, or, addmx, ups, pjups, orderAppeal, oanew,
                faGreeSms, oilist, ydups, fkmxups, orols , us, order,flag,its);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRepairOrderApi(Brand brand, Map<String, List<SysDictRef>> sysDictRefDLMap,
                            Map<String, List<SysDictRef>> sysDictRefXLMap,
                            Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                            ItfTblAssignDownload item,
                            Map<String, List<SysDictRef>> sysDictRefDLMapXq,
                            Map<String, List<SysDictRef>> sysDictRefXLMapXq,Boolean flag, Map<String,String> productMap) throws Exception {
        String orderStatus="";
        List<OrderProduct> addmx = new ArrayList<>();
        List<ItfTblAssignMxDownload> upMxd = new ArrayList<>();
        List<OrderRepairOperatingLog> orols = new ArrayList<>();
        List<ItfTblAssignFkmxDownload> fkmxd = new ArrayList<>();
        List<ItfTblAssignSatisfactionDownload> pjups = new ArrayList<>();
        List<OrderAppeal> orderAppeal = new ArrayList<>();
        List<OrderAppraise> oanew = new ArrayList<>();
        List<FaGreeSms> faGreeSms = new ArrayList<>();
        List<OrderInformation> oilist = new ArrayList<>();
        List<OrderInformation> oilistUp = new ArrayList<>();
        List<ItfTblAssignXzydDownload> upyds = new ArrayList<>();
        List<ItfTblAssignAppointmentDownload> upappointds = new ArrayList<>();
        OrderWorker orderWorker = new OrderWorker();
        OrderRepair or = new OrderRepair();
        List<ItfGreeToFaDownloadTaskList> its = new ArrayList<>();
        OrderBase orderr = new OrderBase();

        List<ItfTblAssignXzydDownload> yds = itfTblAssignXzydDownloadService.lambdaQuery()
                .eq(ItfTblAssignXzydDownload::getDownloadTaskNo, item.getDownloadTaskNo()).list();

        OrderBase order = orderBaseService.lambdaQuery()
                .eq(OrderBase::getPgid, item.getPgid())
                .eq(OrderBase::getOrderType, OrderTypeEnum.ORDER_TYPE_REPAIR.getCode())
                .last("limit 1")
                .one();
        orderStatus = order.getOrderStatus();
        MyBeanUtils.copyProperties(order,orderr);

        // TL_SynDataFrom_tbl_assign_batch
        // TL_SynDataFrom_tbl_assign 主单的 syn_req_id
        // 处理维修工单主表数据 + 采集数据下载 41,102
        modifyOrderBaseApi(brand, sysDictRefDLMap, item, order, its);
        // 修改工单改派申请表 该表更换不处理
        // upOrderApplyDispatchApi(item, orderStatus, order);
        // 修改同步状态
        upItfTblAssignDownloadStatus(item, order);
        // 工单师傅信息更新
        // upOrderWorker(order);
        orderWorker = publicService.getOrderWorkerApi(order);
        // 工单扩展信息更新
        getOrderInstallApi(item, order,sysDictRefDLMapXq,sysDictRefXLMapXq,or);
        // 维修单明细表更新 TL_SynDataFrom_tbl_assign_mx
        generateMxUpdateApi(brand, item, order, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap, addmx, upMxd , productMap);
        // 处理维修单过程反馈(只新增不修改)  放入操作日志表 TL_SynDataFrom_tbl_assign_fkmx
        generateFkmxUpdateApi(item, order, orols, fkmxd);

        // 处理用户评价数据 TL_SynDataFrom_tbl_assign_satisfaction
        generateSstisfactionApi(item, sysDictRefDLMap, order);
        // 阅读要求数据处理 TL_SynDataFrom_tbl_assign_xzyd
        generateXzydUpdateApi(yds, order, oilist, oilistUp, upyds);
        // 用户预约改约数据处理 TL_SynDataFrom_tbl_assign_appointment
        generateAppointmentUpdateApi(item, order,upappointds);

        // 网点转换还原
        modifyOrderBaseWebsit(item,orderr,order);

        // 接口修改维修工单
        return updateRepairApi(item, addmx, upMxd, orols, fkmxd, pjups, orderAppeal, oanew, faGreeSms,
                oilist, oilistUp, upappointds, orderWorker, or, order,flag, its);
    }

    @NotNull
    public Boolean updateRepairApi(ItfTblAssignDownload item, List<OrderProduct> addmx, List<ItfTblAssignMxDownload> upMxd,
                                    List<OrderRepairOperatingLog> orols, List<ItfTblAssignFkmxDownload> fkmxd,
                                    List<ItfTblAssignSatisfactionDownload> pjups, List<OrderAppeal> orderAppeal,
                                    List<OrderAppraise> oanew, List<FaGreeSms> faGreeSms, List<OrderInformation> oilist,
                                    List<OrderInformation> oilistUp, List<ItfTblAssignAppointmentDownload> upappointds,
                                    OrderWorker orderWorker, OrderRepair or, OrderBase order,Boolean flag,
                                   List<ItfGreeToFaDownloadTaskList> its) throws Exception {
        // 创建工单
        OrderAddBeanDTO orderApi = new OrderAddBeanDTO();
        // 工单机型
        List<OrderProduct> orderProductList = new ArrayList<>();
        // 工单辅材表
        List<OrderMaterial> orderMaterialList = new ArrayList<>();
        // 工单清洗项目
        List<OrderCleanItem> orderCleanItems = new ArrayList<>();

        // 工单主表、机型、辅材、清洗、预约改约记录、师傅、创建日志、生成采集数据不要
        getOrderApi(item, addmx, order, orderWorker, or, orderApi, orderProductList, orderMaterialList, orderCleanItems,flag);
        log.info("修改维修工单 request:{}", JSONObject.toJSONString(orderApi));
        ResponseHelper respone = jiasmApi.orderAdd(orderApi);
        log.info("修改维修工单 respone:{}", JSONObject.toJSONString(respone));
        if (respone.getCode()==200){
            // 同步更新状态
            updateSynStatus(addmx, upMxd, orols, fkmxd, pjups, orderAppeal, oanew, faGreeSms, oilist, oilistUp, upappointds, its);
            return Boolean.TRUE;
        } else {
            String msg = publicService.getErrormessage(respone);
            log.info(msg);
            // 抛异常目的是把前期的数据修改回滚
            throw new Exception(msg);
            /*item.setSynErrMsg(msg);
            if (msg.length()>1020){
                item.setSynErrMsg(msg.substring(0,1020));
            }
            itfTblAssignDownloadService.updateById(item);
            return Boolean.FALSE;*/
        }
    }


    private void updateSynStatus(List<OrderProduct> addmx, List<ItfTblAssignMxDownload> upMxd, List<OrderRepairOperatingLog> orols,
                                 List<ItfTblAssignFkmxDownload> fkmxd, List<ItfTblAssignSatisfactionDownload> pjups,
                                 List<OrderAppeal> orderAppeal, List<OrderAppraise> oanew, List<FaGreeSms> faGreeSms,
                                 List<OrderInformation> oilist, List<OrderInformation> oilistUp,
                                 List<ItfTblAssignAppointmentDownload> upappointds,
                                 List<ItfGreeToFaDownloadTaskList> its) {
        /*if (addmx.size()>0){
            orderProductService.saveBatch(addmx);
            addmx.clear();
        }*/
        if (upMxd.size()>0){
            itfTblAssignMxDownloadService.updateBatchById(upMxd);
            upMxd.clear();
        }

        if (orols.size()>0){
            orderRepairOperatingLogService.saveBatch(orols);
            orols.clear();
        }
        if (fkmxd.size()>0){
            itfTblAssignFkmxDownloadService.updateBatchById(fkmxd);
            fkmxd.clear();
        }

        // 修改同步状态
        if (pjups.size()>0){
            itfTblAssignSatisfactionDownloadService.updateBatchById(pjups);
            pjups.clear();
        }
        // 差评申诉
        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }

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

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

        if (oilist.size()>0){
            orderInformationService.saveBatch(oilist);
            oilist.clear();
        }
        if (oilistUp.size()>0){
            orderInformationService.updateBatchById(oilistUp);
            oilistUp.clear();
        }

        if (upappointds.size()>0){
            itfTblAssignAppointmentDownloadService.updateBatchById(upappointds);
            upappointds.clear();
        }

        if (its.size()>0){
            itfGreeToFaDownloadTaskListService.saveBatch(its);
            its.clear();
        }
    }

    @NotNull
    private Boolean createRepairOrder(ItfTblAssignDownload item, OrderWorker orderWorker, OrderRepair or, List<OrderProduct> addmx,
                                      List<ItfTblAssignMxDownload> ups, List<ItfTblAssignSatisfactionDownload> pjups,
                                      List<OrderAppeal> orderAppeal, List<OrderAppraise> oanew, List<FaGreeSms> faGreeSms,
                                      List<OrderInformation> oilist, List<ItfTblAssignXzydDownload> ydups, List<ItfTblAssignFkmxDownload> fkmxups,
                                      List<OrderRepairOperatingLog> orols,List<ItfTblAssignAppointmentDownload> us, OrderBase order,Boolean flag,
                                      List<ItfGreeToFaDownloadTaskList> its) throws Exception {
        // 创建工单
        OrderAddBeanDTO orderApi = new OrderAddBeanDTO();
        // 工单机型
        List<OrderProduct> orderProductList = new ArrayList<>();
        // 工单辅材表
        List<OrderMaterial> orderMaterialList = new ArrayList<>();
        // 工单清洗项目
        List<OrderCleanItem> orderCleanItems = new ArrayList<>();

        // 工单主表、机型、辅材、清洗、预约改约记录、师傅、创建日志、生成采集数据不要
        getOrderApi(item, addmx, order, orderWorker, or, orderApi, orderProductList, orderMaterialList, orderCleanItems,flag);
        log.info("创建维修工单 request:{}", JSONObject.toJSONString(orderApi));
        ResponseHelper respone = jiasmApi.orderAdd(orderApi);
        log.info("创建维修工单 respone:{}", JSONObject.toJSONString(respone));
        if (respone.getCode()==200){
            if (flag){
                SyncCreateOrder sco = new SyncCreateOrder();
                sco.setId(publicService.getUUID());
                sco.setOrderBaseId(orderApi.getGreeId());
                sco.setPgidOrPgguid(String.valueOf(item.getPgid()));
                sco.setOrderJson(JSONObject.toJSONString(orderApi));
                sco.setCreateTime(new Date());
                syncCreateOrderService.save(sco);
            }
            // 同步更新状态
            synStatus(item, ups, pjups, orderAppeal, oanew, faGreeSms, oilist, ydups, fkmxups, orols, us, order,its);
            return Boolean.TRUE;
        } else {
            String msg = publicService.getErrormessage(respone);
            log.info(msg);
            // 抛异常目的是把前期的数据修改回滚
            throw new Exception(msg);
            /*
            item.setSynErrMsg(msg);
            if (msg.length()>1020){
                item.setSynErrMsg(msg.substring(0,1020));
            }
            itfTblAssignDownloadService.updateById(item);
            return Boolean.FALSE;*/
        }
    }



    private void synStatus(ItfTblAssignDownload item, List<ItfTblAssignMxDownload> ups,
                           List<ItfTblAssignSatisfactionDownload> pjups, List<OrderAppeal> orderAppeal,
                           List<OrderAppraise> oanew, List<FaGreeSms> faGreeSms, List<OrderInformation> oilist,
                           List<ItfTblAssignXzydDownload> ydups, List<ItfTblAssignFkmxDownload> fkmxups,List<OrderRepairOperatingLog> orols,
                           List<ItfTblAssignAppointmentDownload> us, OrderBase order, List<ItfGreeToFaDownloadTaskList> its) {
        // 修改同步状态
        upItfTblAssignDownloadStatus(item, order);

        // 处理维修单明细表
        /*if (addmx.size()>0){
            orderProductService.saveBatch(addmx);
            addmx.clear();
        }*/

        if (ups.size()>0){
            itfTblAssignMxDownloadService.updateBatchById(ups);
            ups.clear();
        }

        if (orols.size()>0){
            orderRepairOperatingLogService.saveBatch(orols);
            orols.clear();
        }

        // 过程反馈
        if (fkmxups.size()>0){
            itfTblAssignFkmxDownloadService.updateBatchById(fkmxups);
            fkmxups.clear();
        }

        // 工单评价表
        if (oanew.size()>0){
            orderAppraiseService.saveBatch(oanew);
            oanew.clear();
        }
        // 预约改约-总部短信发送请求
        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }
        // 差评申诉
        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }
        // 修改同步状态
        if (pjups.size()>0){
            itfTblAssignSatisfactionDownloadService.updateBatchById(pjups);
            pjups.clear();
        }

        // 工单子信息阅读要求
        if (oilist.size()>0){
            orderInformationService.saveBatch(oilist);
            oilist.clear();
        }
        if (ydups.size()>0){
            itfTblAssignXzydDownloadService.updateBatchById(ydups);
            ydups.clear();
        }

        // 用户预约改约下载记录
        if (CollectionUtils.isNotEmpty(us)){
            itfTblAssignAppointmentDownloadService.updateBatchById(us);
            us.clear();
        }

        if (its.size()>0){
            itfGreeToFaDownloadTaskListService.saveBatch(its);
            its.clear();
        }

    }

    private void getOrderApi(ItfTblAssignDownload item, List<OrderProduct> orderProducts, OrderBase orderBase,
                             OrderWorker orderWorker, OrderRepair 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 (orderWorker !=null){
            List<String> workerIds = new ArrayList<>();
            workerIds.add(orderWorker.getWorkerId());
            createOrder.getWebsitWorkerIds().addAll(workerIds);
        }
        createOrder.setLinkName(orderBase.getUserName());
    }


    private void upOrderWorker(OrderBase order) {
        if (StringUtils.isEmpty(order.getWorkerName())){
            // 清理师傅表
            publicService.deleteWorker(order.getId());
        } else {
            // 提取现有的师傅信息
            List<OrderWorker> ows = publicService.getWorker(order.getWorkerId(), order.getId());
            // 看是工单师傅是否在内，如不在内说明重新指派了师傅
            Boolean flag = Boolean.FALSE;
            for (OrderWorker ow :ows){
                if (ow.getWorkerId().equals(order.getWorkerId())){
                    flag = Boolean.TRUE;
                }
            }
            if (!flag){
                // 清理师傅表，重新生新新师傅数据
                if (ows !=null && ows.size()>0){
                    publicService.deleteWorker(order.getId());
                }
                publicService.getOrderWorker(order);
            }
        }
    }

    private void modifyOrderBase(Brand brand, Map<String, List<SysDictRef>> sysDictRefDLMap, ItfTblAssignDownload item) {
        String orderStatus="";
        Integer cjDowFlag=0;
        // TL_SynDataFrom_tbl_assign_batch
        // TL_SynDataFrom_tbl_assign 主单的 syn_req_id
        // 提取基础表数据
        OrderBase oldOrder = orderBaseService.lambdaQuery()
                .eq(OrderBase::getPgid, item.getPgid())
                .eq(OrderBase::getOrderType, OrderTypeEnum.ORDER_TYPE_REPAIR.getCode())
                .last("limit 1")
                .one();
        orderStatus = oldOrder.getOrderStatus();
        cjDowFlag = oldOrder.getOutCjDownloadFlag();
        // 批量关闭的工单 同步下载无需再修改
        if (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G13.getCode())){
            upItfTblAssignDownload(item.getSynReqId(),99,"last_modified_by = CLIENT__autoapp 本地已作废/关闭,忽略下载处理");
            return;
        }
        // 基础表数据同步 总部的修改时间必须晚于本地系统时间才可以修改
        if (oldOrder.getUpdateTime() ==null || item.getLastModifiedDate().compareTo(oldOrder.getUpdateTime())>0){
            upOrderBase(brand, item, oldOrder);
        }
        // 网点信息更新
        updateWebsit(item, oldOrder);

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

        // 用户期望上门时间信息更新
        updateYhqwsmsj(item, oldOrder);
        // 状态信息更新
        upOrderStatus(brand, item, oldOrder);
        // 更新 工单机型
        upOrderProduct(oldOrder);
        // 更新 维修数据采集表
        upOrderRepairDetail(oldOrder);
        // 生成改派申请数据
        if (oldOrder.getOrderStatus().equals("B5")){
            // generateDispatch(oldOrder);
        }
        // 修改工单改派申请表
        upOrderApplyDispatch(item, orderStatus, oldOrder);

        // 增加判断是否有未处理的待改派，如果广佛有待改派但总部工单不是待改派，直接更新改派标志
        // 无删除标识，暂不处理

        // 增加处理采集数据下载 41,102
        if ((oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G8.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G14.getCode())) && cjDowFlag ==0){
            List<OrderRepairDetail> ords = orderRepairDetailService.lambdaQuery()
                    .eq(OrderRepairDetail::getOrderBaseId,oldOrder.getId())
                    .ne(OrderRepairDetail::getStatus,0).list();
            // 已存在状态为"已采集"的记录暂时忽略下载
            if (!(ords !=null && ords.size()>0)){
                // 清除待采集数据
                delOrderRepairDetail(oldOrder);
                // 向表内写数据，另起任务下载数据
                // 这里向itf_gree_to_fa_download_task_list表的任务类型写入6601 并不会下载，这里无需处理
                // 修改基础表已采集下载标识
                OrderBase up = new OrderBase();
                up.setId(oldOrder.getId());
                up.setOutCjDownloadFlag(1);
                orderBaseService.updateById(up);
            }
        }

        // 如果是家用的工单，且工单状态是待中心派工或待网点派工时，写入派嘉讯茂
        // 写入操作日志
        addOperatingLog(sysDictRefDLMap, item, oldOrder);

        // 修改同步状态
        upItfTblAssignDownloadStatus(item, oldOrder);
    }

    private void modifyOrderBaseApi(Brand brand, Map<String, List<SysDictRef>> sysDictRefDLMap, ItfTblAssignDownload item,
                                    OrderBase oldOrder,List<ItfGreeToFaDownloadTaskList> its) {

        Integer cjDowFlag=0;
        cjDowFlag = oldOrder.getOutCjDownloadFlag();
        // 批量关闭的工单 同步下载无需再修改
        if (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G13.getCode())){
            upItfTblAssignDownload(item.getSynReqId(),99,"last_modified_by = CLIENT__autoapp 本地已作废/关闭,忽略下载处理");
            return;
        }
        // 1：基础表数据同步 总部的修改时间必须晚于本地系统时间才可以修改
        /*if (oldOrder.getUpdateTime() ==null || item.getLastModifiedDate().compareTo(oldOrder.getUpdateTime())>0){
            upOrderBaseApi(brand, item, oldOrder);
        }*/

        upOrderBaseApi(brand, item, oldOrder);

        //2：网点信息更新
        updateWebsitApi(item, oldOrder);

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

        // 3：用户期望上门时间信息更新
        updateYhqwsmsjApi(item, oldOrder);
        //4：状态信息更新
        upOrderStatusApi(brand, item, oldOrder);
        // 更新 工单机型
        // upOrderProduct(oldOrder);

        // 更新 维修数据采集表
        // upOrderRepairDetail(oldOrder);

        // 生成改派申请数据 OrderApplyDispatch addn
        /*if (oldOrder.getOrderStatus().equals("B5")){
            generateDispatchApi(oldOrder,addn);
        }*/

        // 增加处理采集数据下载 41,102
        putDownloadTaskList(item, oldOrder, its, cjDowFlag);

        // 如果是家用的工单，且工单状态是待中心派工或待网点派工时，写入派嘉讯茂
        // 写入操作日志
        // addOperatingLog(sysDictRefDLMap, item, oldOrder);

    }

    private void modifyOrderBaseWebsit(ItfTblAssignDownload item,OrderBase oldOrder,OrderBase upOrder) {
        // 批量关闭的工单 同步下载无需再修改
        if (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G13.getCode())){
            return;
        }
        // 1：基础表数据同步 总部的修改时间必须晚于本地系统时间才可以修改
        if (oldOrder.getUpdateTime() ==null || item.getLastModifiedDate().compareTo(oldOrder.getUpdateTime())>0){
            upOrder.setSaleWebsitId(item.getXswdno());
            upOrder.setSaleWebsitName(item.getXswdmc());
        }
        //2：网点信息更新
        // 看网点更新的条件
        Boolean flag = getaBoolean(item, oldOrder);
        // 更新网点信息
        if (flag){
            upOrder.setReceWebsitId(item.getXjwdno());
            upOrder.setReceWebsitName(item.getXjwdmc());

            if (StringUtils.isNotEmpty(item.getWxwdno())){
                upOrder.setWebsitId(item.getWxwdno());
            } else if (StringUtils.isNotEmpty(item.getXjwdno())){
                upOrder.setWebsitId(item.getXjwdno());
            }
            if (StringUtils.isNotEmpty(item.getWxwdmc())){
                upOrder.setWebsitName(item.getWxwdmc());
            }
        }
    }

    private void putDownloadTaskList(ItfTblAssignDownload item, OrderBase oldOrder, List<ItfGreeToFaDownloadTaskList> its,
                                     Integer cjDowFlag) {
        if ((oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G8.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G14.getCode())) && cjDowFlag ==0){
            List<OrderRepairDetail> ords = orderRepairDetailService.lambdaQuery()
                    .eq(OrderRepairDetail::getOrderBaseId, oldOrder.getId())
                    .ne(OrderRepairDetail::getStatus,0).list();
            // 已存在状态为"已采集"的记录暂时忽略下载
            if (CollectionUtils.isEmpty(ords)){
                // 这里少采集发送标识 cj_send_flag
                // 清除待采集数据
                delOrderRepairDetail(oldOrder);
                // 向表内写数据，另起任务下载数据
                // 这里向itf_gree_to_fa_download_task_list表的任务类型写入6601 并不会下载，这里无需处理
                ItfGreeToFaDownloadTaskList tl = new ItfGreeToFaDownloadTaskList();
                tl.setDownloadTaskNo(IdWorker.getIdStr());
                tl.setDownloadKeyValue(String.valueOf(item.getPgid()));
                tl.setDownloadTaskType(6601);
                tl.setDownloadStatus(0);
                its.add(tl);
                // 修改基础表已采集下载标识
                oldOrder.setOutCjDownloadFlag(1);
            }
        }
    }

    private void addOperatingLog(Map<String, List<SysDictRef>> sysDictRefDLMap, ItfTblAssignDownload item, OrderBase oldOrder) {
        if (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G2.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G3.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G4.getCode())){
            // 大类存在，且相同 非商用
            if (StringUtils.isNotEmpty(oldOrder.getMainId()) && StringUtils.isNotEmpty(String.valueOf(item.getSpid())) &&
                    !oldOrder.getMainId().equals(item.getSpid()) &&
                    (!item.getSpid().equals(DictTypeEnum.DICT_TYPE_SY_102.getCode())) &&
                    (!item.getSpid().equals(DictTypeEnum.DICT_TYPE_SY_109.getCode())) ){
                List<OrderRepairOperatingLog> orlog = orderRepairOperatingLogService.lambdaQuery()
                        .eq(OrderRepairOperatingLog::getOrderBaseId, oldOrder.getId())
                        .eq(OrderRepairOperatingLog::getType,"指派服务商").list();
                if (CollectionUtils.isEmpty(orlog)){
                    OrderPar request = new OrderPar();
                    request.setOrderNo(oldOrder.getId());
                    OrderRepairOperatingLog orolog = repairLogMapper.getUpdatetime(request);
                    if (orolog == null){
                        orolog = repairLogMapper.getUpdatetimeT(request);
                    }
                    // 存在处理
                    if (orolog != null){
                        OrderPar orderPar = new OrderPar();
                        orderPar.setOrderNo(oldOrder.getId());
                        OrderRepairOperatingLog addlog = gdOrderBaseMapper.getOrderBaseLog(orderPar);
                        orderRepairOperatingLogService.save(addlog);
                    }
                    //
                    if ((!("S9219801".equals(item.getWxwdno())) && !("S9219807".equals(item.getWxwdno()))) &&
                            (!("S9219801".equals(item.getXjwdno())) && !("S9219807".equals(item.getXjwdno())))){
                        OrderPar orderPar = new OrderPar();
                        orderPar.setOrderNo(oldOrder.getId());
                        OrderRepairOperatingLog addlog = gdOrderBaseMapper.getOrderBaseLogT(orderPar);
                        orderRepairOperatingLogService.save(addlog);
                    }
                }
            }
        }
    }

    private void delOrderRepairDetail(OrderBase oldOrder) {
        QueryWrapper dWrapper = new QueryWrapper<OrderRepairDetail>()
                .eq("order_base_id", oldOrder.getId())
                .eq("status",0);
        orderRepairDetailService.remove(dWrapper);
    }

    private void upOrderApplyDispatch(ItfTblAssignDownload item, String orderStatus, OrderBase oldOrder) {
        // 原 本地维修单表状态为5 待审批  同步过来的工单状态不是待审批时
        // 修改工单改派申请 自动审核  新增时条件不成立的
        if (orderStatus.equals(GDOrderStatusEnum.REPAIR_STATUS_G5.getCode()) && !item.getStat().equals(5L)){
        }
    }

    private void upOrderApplyDispatchApi(ItfTblAssignDownload item, String orderStatus, OrderBase oldOrder) {
        // 原 本地维修单表状态为5 待审批  同步过来的工单状态不是待审批时
        // 修改工单改派申请 自动审核  新增时条件不成立的
        if (orderStatus.equals(GDOrderStatusEnum.REPAIR_STATUS_G5.getCode()) && !item.getStat().equals(5L)){

        }
    }

    private void upOrderRepairDetail(OrderBase oldOrder) {
        OrderRepairDetail ord = new OrderRepairDetail();
        ord.setInstallWebsitId(oldOrder.getWebsitId());
        ord.setInstallWebsitName(oldOrder.getWebsitName());
        QueryWrapper upWrapper = new QueryWrapper<OrderRepairDetail>()
                .eq("order_base_id", oldOrder.getId());
        orderRepairDetailService.update(ord,upWrapper);
    }

    private void upOrderProduct(OrderBase oldOrder) {
        OrderProduct op = new OrderProduct();
        op.setServiceWebsit(oldOrder.getWebsitId());
        op.setServiceWebsitMobile(publicService.getSHWDPhone(oldOrder.getWebsitId()));
        QueryWrapper upWrapper = new QueryWrapper<OrderProduct>()
                .eq("order_base_id", oldOrder.getId());
        orderProductService.update(op,upWrapper);
    }

    private void upOrderStatus(Brand brand, ItfTblAssignDownload item, OrderBase oldOrder) {
        // 查看是否可更新
        Boolean allowUpdate = getaBoolean(item, oldOrder);
        if (allowUpdate){
            // 这里差 派工状态
            OrderPar orderPar = new OrderPar();
            orderPar.setSynReqId(item.getSynReqId());
            orderPar.setBrandId(brand.getBrandId());
            OrderBase order = repairDownloadMapper.getOrderBaseStatus(orderPar);
            order.setId(oldOrder.getId());
            orderBaseService.updateById(order);
            MyBeanUtils.copyProperties(order,oldOrder);
        }
    }

    private void upOrderStatusApi(Brand brand, ItfTblAssignDownload item, OrderBase oldOrder) {
        // 查看是否可更新
        /*Boolean allowUpdate = getaBoolean(item, oldOrder);
        if (allowUpdate){
            // 这里差 派工状态
            OrderPar orderPar = new OrderPar();
            orderPar.setSynReqId(item.getSynReqId());
            orderPar.setBrandId(brand.getBrandId());
            OrderBase order = repairDownloadMapper.getOrderBaseStatus(orderPar);
            MyBeanUtils.copyProperties(order,oldOrder);
        }*/

        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());
        OrderBase order = repairDownloadMapper.getOrderBaseStatus(orderPar);
        MyBeanUtils.copyProperties(order,oldOrder);
    }

    @NotNull
    private Boolean getaBoolean(ItfTblAssignDownload item, OrderBase oldOrder) {
        Boolean allowUpdate = Boolean.TRUE;

        if (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G9.getCode())){
            allowUpdate = Boolean.FALSE;
        }
        if (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G7.getCode()) &&
                (item.getStat().equals(4L) || item.getStat().equals(18L))){
            allowUpdate = Boolean.FALSE;
        }
        if (!oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G1_1.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_0.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G4_0.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G5.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G6.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G7.getCode()) &&
                item.getStat()<=4L){
            allowUpdate = Boolean.TRUE;
        }
        if (item.getStat().equals(2L) && (!oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G1_1.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G2_0.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G3.getCode()))){
            allowUpdate = Boolean.FALSE;
        }
        if (item.getStat().equals(2L) && (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.INSTALL_STATUS_G5.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G11.getCode()))){
            allowUpdate = Boolean.TRUE;
        }
        return allowUpdate;
    }

    private void updateYhqwsmsj(ItfTblAssignDownload item, OrderBase oldOrder) {
        // 如何判断工单已预约 首次预约人信息不为空即为已预约
        if (StringUtils.isEmpty(oldOrder.getFirstAppointmentId())){
            OrderBase upOrder = new OrderBase();
            upOrder.setId(oldOrder.getId());
            upOrder.setExpectStartTime(item.getYhqwsmsj());
            upOrder.setExpectEndTime(item.getQwsmjssj());
            orderBaseService.updateById(upOrder);
        }
    }

    private void updateYhqwsmsjApi(ItfTblAssignDownload item, OrderBase oldOrder) {
        // 如何判断工单已预约 首次预约人信息不为空即为已预约
        if (StringUtils.isEmpty(oldOrder.getFirstAppointmentId())){
            oldOrder.setExpectStartTime(item.getYhqwsmsj());
            oldOrder.setExpectEndTime(item.getQwsmjssj());
        }
    }

    private void updateWebsit(ItfTblAssignDownload item, OrderBase oldOrder) {
        // 看网点更新的条件
        Boolean flag = getUpBoolean(item, oldOrder);
        // 更新网点信息
        if (flag){
            // 字段赋值
            getOrderBase(item, oldOrder);
            orderBaseService.updateById(oldOrder);
        }
    }

    private void updateWebsitApi(ItfTblAssignDownload item, OrderBase oldOrder) {
        // 看网点更新的条件
        /*Boolean flag = getUpBoolean(item, oldOrder);
        // 更新网点信息
        if (flag){
            // 字段赋值
            getOrderBase(item, oldOrder);
        }*/
        getOrderBase(item, oldOrder);
    }

    @NotNull
    private void getOrderBase(ItfTblAssignDownload item, OrderBase upOrder) {
        WebsitFWS websitFWS = new WebsitFWS();

        if (StringUtils.isNotEmpty(item.getXxlb())){
            upOrder.setInfoType(item.getXxlb());
        } else {
            upOrder.setInfoType("");
        }
        if (StringUtils.isNotEmpty(String.valueOf(item.getXxlbid()))){
            upOrder.setInfoTypeId(String.valueOf(item.getXxlbid()));
        } else {
            upOrder.setInfoTypeId("101");
        }
        // 维修网点
        String wdno ="";
        if (StringUtils.isEmpty(item.getWxwdno())){
            wdno = item.getXjwdno();
        } else {
            wdno = item.getWxwdno();
        }
        WebsitFWS resultData = publicService.shshwdToptshwd(wdno, upOrder);
        upOrder.setWebsitId(resultData.getWebsitId());
        upOrder.setWebsitName(resultData.getWdmc());


        if (StringUtils.isNotEmpty(item.getXjwdno())){
            WebsitFWS res = publicService.shshwdToptshwd(item.getXjwdno(), upOrder);
            upOrder.setReceWebsitId(res.getWebsitId());
            upOrder.setReceWebsitName(res.getWdmc());
        } else {
            upOrder.setReceWebsitId("");
            upOrder.setReceWebsitName("");
        }

        // 结算主体
        // (wxwdno、xjwdno)维修网点与派下级网点同时为空时  (cjwdno、xswdno)创建网点与销售网点都有值
        /*if (StringUtils.isNotEmpty(upOrder.getWebsitId())){
            websitFWS = publicService.shshwdToptshwd(wdno,upOrder);
        } else {
            websitFWS = publicService.shxswdToptxswd(item.getXswdno(),upOrder);
        }*/

        websitFWS = publicService.shxswdToptxswd(item.getXswdno(),upOrder);
        // 结算主体为销售网点对应的接算主休息
        upOrder.setBrandId(websitFWS.getBrandId());
        upOrder.setBrandName(websitFWS.getBrandName());

        // jspgwdno 引入中心网点 S9219807,S9219801,S9329829
        /*if (item.getXjwdno().equals("S9219807") ||
                item.getXjwdno().equals("S9219801") ||
                item.getXjwdno().equals("S9329829")){
            websitFWS = publicService.shshwdToptshwdZX(item.getXjwdno(), upOrder);
            upOrder.setCreateWebsitId(websitFWS.getWebsitId());
            upOrder.setCreateWebsitName(websitFWS.getWdmc());
            upOrder.setReceWebsitId(websitFWS.getWebsitId());
            upOrder.setReceWebsitName(websitFWS.getWdmc());
            upOrder.setWebsitId(websitFWS.getWebsitId());
            upOrder.setWebsitName(websitFWS.getWdmc());

            Belongcompany bc = publicService.getBelongCompany(item.getXjwdno());
            websitFWS = publicService.shxswdToptxswd(bc.getBelongCompanySale(),upOrder);
            upOrder.setBrandId(websitFWS.getBrandId());
            upOrder.setBrandName(websitFWS.getBrandName());
        }

        // 结算主体重置 维修网点一般是不填销售单位的通过售后网点来查结算主体   (a.xjwdno,''),a.wxwdno) as websit_id
        String wdnoq = item.getXjwdno();
        if (StringUtils.isEmpty(wdno)){
            wdnoq = item.getWxwdno();
        }

        if (StringUtils.isEmpty(upOrder.getBrandId())){
            websitFWS = publicService.shshwdToptshwd(wdnoq,upOrder);
            upOrder.setBrandId(websitFWS.getBrandId());
            upOrder.setBrandName(websitFWS.getBrandName());
        }*/

        // 格力中心的单直接下沉到总包商户(先查WebsitOrderSign 无数据再查CustomerInformationWebsit)
        /*if (item.getXjwdno().equals("S9219807") ||
                item.getXjwdno().equals("S9219801") ||
                item.getXjwdno().equals("S9329829")){
            publicService.getZXINFO(item.getXjwdno(), upOrder);
        }*/

        // 格力中心的单直接下沉到总包商户 改成下沉到总包服务商(websit_order_sign)
        if (item.getXjwdno().equals("S9219807") ||
                item.getXjwdno().equals("S9219801") ||
                item.getXjwdno().equals("S9329829")){
            publicService.getZXPTZBINFO(item.getXjwdno(), upOrder);
        }


        // 结算主体重置 维修网点一般是不填销售单位的通过售后网点来查结算主体   (a.xjwdno,''),a.wxwdno) as websit_id
        if (upOrder.getOrderType().equals(ServiceCategoryEnum.REPAIR_TYPE.getCode()) &&
                StringUtils.isEmpty(upOrder.getBrandId())){
            String wdnoq = item.getXjwdno();
            if (StringUtils.isEmpty(wdnoq)){
                wdnoq = item.getWxwdno();
            }
            websitFWS = publicService.shshwdToptshwd(wdnoq,upOrder);
            upOrder.setBrandId(websitFWS.getBrandId());
            upOrder.setBrandName(websitFWS.getBrandName());
        }
    }

    @NotNull
    private Boolean getUpBoolean(ItfTblAssignDownload item, OrderBase oldOrder) {
        Boolean flag = Boolean.FALSE;
        if ((oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G1.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G2.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G3.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G4.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G5.getCode()) ||
                oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G6.getCode())) ||
                (oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G7.getCode()) &&
                        !oldOrder.getDispatchStatus().equals("YCJ") &&
                        !oldOrder.getDispatchStatus().equals("YBWG"))){
            flag = Boolean.TRUE;
        }
        if ((!oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G1.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G2.getCode()) &&
                !oldOrder.getOrderStatus().equals(GDOrderStatusEnum.REPAIR_STATUS_G3.getCode())) && item.getStat() == 2){
            flag = Boolean.FALSE;
        }
        // op.setMainId(sysDictRefDLMap.get(String.valueOf(rec.getSpid())).get(0).getDictCode());
        if (StringUtils.isNotEmpty(oldOrder.getMainId()) && StringUtils.isNotEmpty(String.valueOf(item.getSpid())) &&
                !oldOrder.getMainId().equals(item.getSpid())){
            flag = Boolean.TRUE;
        }
        return flag;
    }

    private OrderBase upOrderBase(Brand brand, ItfTblAssignDownload item,OrderBase oldOrder) {
        // 获取维修工单主表要修改的数据
        OrderBase upOrder = getUpOrderBase(brand, item, oldOrder);
        // 省市区单独处理
        // orderService.shPositionTopt(upOrder);
        publicService.installOrderSSQJ(upOrder);
        MyBeanUtils.copyProperties(upOrder,oldOrder);
        orderBaseService.updateById(oldOrder);
        return oldOrder;
    }

    private OrderBase upOrderBaseApi(Brand brand, ItfTblAssignDownload item,OrderBase oldOrder) {
        // 获取维修工单主表要修改的数据
        OrderBase upOrder = getUpOrderBase(brand, item, oldOrder);
        // 省市区单独处理
        // orderService.shPositionTopt(upOrder);
        publicService.installOrderSSQJ(upOrder);

        MyBeanUtils.copyProperties(upOrder,oldOrder);
        return oldOrder;
    }

    @NotNull
    private OrderBase getUpOrderBase(Brand brand, ItfTblAssignDownload item, OrderBase oldOrder) {
        WebsitFWS websitFWS = new WebsitFWS();
        OrderPar orderPar = new OrderPar();

        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());
        OrderBase upOrder = repairDownloadMapper.getUpOrderBase(orderPar);
        // 处理用户等级
        publicService.setUserLevel(upOrder);

        // 消息来源不能为空，为空时默认电话
        if (StringUtils.isEmpty(upOrder.getInfoSource())){
            upOrder.setInfoSource("电话");
        }
        upOrder.setInfoSourceId(baseService.getxxly(upOrder.getInfoSource()));

        upOrder.setId(oldOrder.getId());
        upOrder.setOutUpdateSynReqId(item.getSynReqId());
        upOrder.setOutUpdateSynReqTime(new Date());

        // 销售网点处理
        websitFWS = publicService.shxswdToptxswd(upOrder.getSaleWebsitId(),oldOrder);
        upOrder.setSaleWebsitId(websitFWS.getWebsitId());
        upOrder.setSaleWebsitName(websitFWS.getWdmc());
        // 这里为商户的系统网点编号
        upOrder.setSaleWebsitSysNumber(websitFWS.getBrandSysWebsitNumber());

        // gpsaddress
        if (StringUtils.isEmpty(upOrder.getGpsAddress()) && StringUtils.isNotEmpty(oldOrder.getGpsAddress())){
            upOrder.setGpsAddress(oldOrder.getGpsAddress());
        }

        // upOrder.setUpdateTime(new Date());
        return upOrder;
    }

    private void generateAppointment(ItfTblAssignDownload item, OrderBase order) {
        OrderBase up = new OrderBase();
        List<ItfTblAssignAppointmentDownload> us = new ArrayList<>();
        // 新增工单，直接修改主表预约时间最近一次的数据修改
        List<ItfTblAssignAppointmentDownload> appoint = itfTblAssignAppointmentDownloadService.lambdaQuery()
                .eq(ItfTblAssignAppointmentDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .orderByAsc(ItfTblAssignAppointmentDownload::getSynReqId).list();
        for (ItfTblAssignAppointmentDownload a:appoint){
            up.setId(order.getId());
            // 这里填写首次预约人信息同时也方便其他地方以此来判断该订单是否已预约
            up.setFirstAppointmentId(a.getCzren());
            up.setExpectStartTime(a.getKssj());
            up.setExpectEndTime(a.getJssj());

            ItfTblAssignAppointmentDownload u = new ItfTblAssignAppointmentDownload();
            u.setSynReqId(a.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            us.add(u);
        }
        if (appoint !=null && appoint.size()>0){
            orderBaseService.updateById(up);
            itfTblAssignAppointmentDownloadService.updateBatchById(us);
            us.clear();
        }
    }

    private void generateAppointmentApi(ItfTblAssignDownload item, List<ItfTblAssignAppointmentDownload> us) {
        // 新增工单，直接修改主表预约时间最近一次的数据修改
        List<ItfTblAssignAppointmentDownload> appoint = itfTblAssignAppointmentDownloadService.lambdaQuery()
                .eq(ItfTblAssignAppointmentDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .orderByAsc(ItfTblAssignAppointmentDownload::getSynReqId).list();
        for (ItfTblAssignAppointmentDownload a:appoint){
            ItfTblAssignAppointmentDownload u = new ItfTblAssignAppointmentDownload();
            u.setSynReqId(a.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            us.add(u);
        }
    }

    private void generateAppointmentUpdate(ItfTblAssignDownload item, OrderBase order) {
        OrderBase up = new OrderBase();
        List<ItfTblAssignAppointmentDownload> us = new ArrayList<>();
        // 新增工单，直接修改主表预约时间最近一次的数据修改
        List<ItfTblAssignAppointmentDownload> appoint = itfTblAssignAppointmentDownloadService.lambdaQuery()
                .eq(ItfTblAssignAppointmentDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .orderByAsc(ItfTblAssignAppointmentDownload::getSynReqId).list();
        for (ItfTblAssignAppointmentDownload a:appoint){
            up.setId(order.getId());
            // 这里填写首次预约人信息同时也方便其他地方以此来判断该订单是否已预约
            up.setFirstAppointmentId(a.getCzren());
            up.setExpectStartTime(a.getKssj());
            up.setExpectEndTime(a.getJssj());

            ItfTblAssignAppointmentDownload u = new ItfTblAssignAppointmentDownload();
            u.setSynReqId(a.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            us.add(u);
        }
        if (appoint !=null && appoint.size()>0){
            if (StringUtils.isEmpty(order.getFirstAppointmentId())){
                orderBaseService.updateById(up);
            }
            itfTblAssignAppointmentDownloadService.updateBatchById(us);
            us.clear();
        }
    }

    private void generateAppointmentUpdateApi(ItfTblAssignDownload item, OrderBase order,List<ItfTblAssignAppointmentDownload> upappointds) {
        OrderBase up = new OrderBase();
        // 新增工单，直接修改主表预约时间最近一次的数据修改
        List<ItfTblAssignAppointmentDownload> appoint = itfTblAssignAppointmentDownloadService.lambdaQuery()
                .eq(ItfTblAssignAppointmentDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .orderByAsc(ItfTblAssignAppointmentDownload::getSynReqId).list();
        for (ItfTblAssignAppointmentDownload a:appoint){
            up.setId(order.getId());
            // 这里填写首次预约人信息同时也方便其他地方以此来判断该订单是否已预约
            up.setFirstAppointmentId(a.getCzren());
            up.setExpectStartTime(a.getKssj());
            up.setExpectEndTime(a.getJssj());

            ItfTblAssignAppointmentDownload u = new ItfTblAssignAppointmentDownload();
            u.setSynReqId(a.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            upappointds.add(u);
        }
        if (appoint !=null && appoint.size()>0){
            if (StringUtils.isEmpty(order.getFirstAppointmentId())){
                order.setFirstAppointmentId(up.getFirstAppointmentId());
                order.setExpectStartTime(up.getExpectStartTime());
                order.setExpectEndTime(up.getExpectEndTime());
            }
        }
    }

    private void generateXzyd(List<ItfTblAssignXzydDownload> yds, OrderBase order) {
        List<OrderInformation> oilist = new ArrayList<>();
        List<ItfTblAssignXzydDownload> ups = new ArrayList<>();

        for (ItfTblAssignXzydDownload yd: yds){
            // 获取阅读要求数据
            getAddOrderInfor(order, oilist, yd);

            ItfTblAssignXzydDownload up = new ItfTblAssignXzydDownload();
            up.setSynReqId(yd.getSynReqId());
            up.setSynStatus(1);
            up.setSynTime(new Date());
            ups.add(up);
        }
        if (oilist.size()>0){
            orderInformationService.saveBatch(oilist);
            oilist.clear();
        }
        if (ups.size()>0){
            itfTblAssignXzydDownloadService.updateBatchById(ups);
            ups.clear();
        }
    }

    private void generateXzydApi(List<ItfTblAssignXzydDownload> yds, OrderBase order,
                                 List<OrderInformation> oilist,
                                 List<ItfTblAssignXzydDownload> ydups) {
        for (ItfTblAssignXzydDownload yd: yds){
            // 获取阅读要求数据
            getAddOrderInfor(order, oilist, yd);

            ItfTblAssignXzydDownload up = new ItfTblAssignXzydDownload();
            up.setSynReqId(yd.getSynReqId());
            up.setSynStatus(1);
            up.setSynTime(new Date());
            ydups.add(up);
        }
    }

    private void generateXzydUpdate(List<ItfTblAssignXzydDownload> yds, OrderBase order) {
        List<OrderInformation> oilist = new ArrayList<>();
        List<OrderInformation> oilistUp = new ArrayList<>();
        List<ItfTblAssignXzydDownload> ups = new ArrayList<>();
        Map<Long,List<OrderInformation>> oisMap = new HashMap<>();
        // 提取原有的数据
        List<OrderInformation> ois = orderInformationService.lambdaQuery()
                .eq(OrderInformation::getOrderBaseId,order.getId()).list();
        oisMap = ois.stream().collect(Collectors.groupingBy(OrderInformation::getXzid));


        for (ItfTblAssignXzydDownload yd: yds){
            // 存在修改，不存在新增
            if (oisMap.containsKey(yd.getXzid())){
                getUpOrderInfor(oilistUp, yd, order);
            } else {
                getAddOrderInfor(order, oilist, yd);
            }

            ItfTblAssignXzydDownload up = new ItfTblAssignXzydDownload();
            up.setSynReqId(yd.getSynReqId());
            up.setSynStatus(1);
            up.setSynTime(new Date());
            ups.add(up);
        }
        if (oilist.size()>0){
            orderInformationService.saveBatch(oilist);
            oilist.clear();
        }
        if (oilistUp.size()>0){
            orderInformationService.updateBatchById(oilistUp);
            oilistUp.clear();
        }
        if (ups.size()>0){
            itfTblAssignXzydDownloadService.updateBatchById(ups);
            ups.clear();
        }
    }

    private void generateXzydUpdateApi(List<ItfTblAssignXzydDownload> yds, OrderBase order,List<OrderInformation> oilist,
                                       List<OrderInformation> oilistUp,
                                       List<ItfTblAssignXzydDownload> upyds) {
        Map<Long,List<OrderInformation>> oisMap = new HashMap<>();
        // 提取原有的数据
        List<OrderInformation> ois = orderInformationService.lambdaQuery()
                .eq(OrderInformation::getOrderBaseId,order.getId()).list();
        oisMap = ois.stream().collect(Collectors.groupingBy(OrderInformation::getXzid));


        for (ItfTblAssignXzydDownload yd: yds){
            // 存在修改，不存在新增
            if (oisMap.containsKey(yd.getXzid())){
                getUpOrderInfor(oilistUp, yd, order);
            } else {
                getAddOrderInfor(order, oilist, yd);
            }

            ItfTblAssignXzydDownload up = new ItfTblAssignXzydDownload();
            up.setSynReqId(yd.getSynReqId());
            up.setSynStatus(1);
            up.setSynTime(new Date());
            upyds.add(up);
        }
    }

    private void getUpOrderInfor(List<OrderInformation> oilistUp,
                                 ItfTblAssignXzydDownload yd, OrderBase order) {
        OrderInformation up = new OrderInformation();

        OrderInformation old = orderInformationService.lambdaQuery()
                .eq(OrderInformation::getOrderBaseId,order.getId())
                .eq(OrderInformation::getXzid,yd.getXzid())
                .last("limit 1")
                .one();

        up.setId(old.getId());
        up.setXzid(yd.getXzid());
        up.setAskCategoryId(yd.getXzyqlb());
        up.setRemark(yd.getXzyq());
        up.setReadStatus(yd.getYdbz());
        up.setReadTime(yd.getYdsj());
        up.setReadName(yd.getYdrmc());
        WebsitFWS websitFWS = publicService.shshwdToptshwd(yd.getWdno(), order);
        up.setWebsitId(websitFWS.getWebsitId());
        up.setWebsitName(websitFWS.getWdmc());
        oilistUp.add(up);
    }

    private void getAddOrderInfor(OrderBase order, List<OrderInformation> oilist, ItfTblAssignXzydDownload yd) {
        OrderInformation add = new OrderInformation();
        add.setXzid(yd.getXzid());
        add.setAskCategoryId(yd.getXzyqlb());
        add.setRemark(yd.getXzyq());
        add.setOrderBaseId(order.getId());
        add.setCreateBy(yd.getCreatedBy());
        add.setCreateTime(yd.getCreatedDate());
        add.setUpdateBy(yd.getLastModifiedBy());
        add.setUpdateTime(yd.getLastModifiedDate());
        add.setReadStatus(yd.getYdbz());
        add.setReadName(yd.getYdrmc());
        add.setReadTime(yd.getYdsj());
        WebsitFWS websitFWS = publicService.shshwdToptshwd(yd.getWdno(), order);
        add.setWebsitId(websitFWS.getWebsitId());
        add.setWebsitName(websitFWS.getWdmc());
        oilist.add(add);
    }

    private void generateSstisfactionback(ItfTblAssignDownload item, Map<String, List<SysDictRef>> sysDictRefDLMap, OrderBase order) {
        // 提取已同步的数据
        List<OrderAppraise> oa = new ArrayList<>();
        List<ItfTblAssignSatisfactionDownload> upsatis = new ArrayList<>();
        Map<String,List<OrderAppraise>> oaMap = new HashMap<>();
        List<OrderAppeal> orderAppeal = new ArrayList<>();
        int jcaninsert=1;
        int cpflag=0;
        // 首评信息用于填写差评中的首评内容
        String spmessage="";
        List<OrderAppraise> oanew = new ArrayList<>();
        List<FaGreeSms> faGreeSms = new ArrayList<>();
        OrderAppraise zpoa=null;
        String cpid="";
        Date ssDate = new Date();
        Date jzDate = new Date();

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


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

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

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


        List<ItfTblAssignSatisfactionDownload> satis = itfTblAssignSatisfactionDownloadService.lambdaQuery()
                .eq(ItfTblAssignSatisfactionDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .orderByAsc(ItfTblAssignSatisfactionDownload::getHfsj)
                .list();

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

            // 评价已同步，忽略更新
            if (oaMap.containsKey(s.getId())){
                upSyncstatus(s.getSynReqId(), 9, "评价已同步，忽略更新");
                continue;
            }

            // 只能有一条首评数据 存在首评不再插入 上面判断已生效，这里多一次判断也可
            if (jcaninsert == 0){
                if (s.getSxlx()==0){
                    continue;
                }
            }

            // 生成评价实体对像
            WebsitFWS websitFWS = getWebsitFWS(sysDictRefDLMap, order, 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(order, s, websitFWS, faGreeSms,jzDate);
                // 生成差评申诉信息实体对像 只能申诉一次
                cpflag = getCp(order, orderAppeal,s);
                if (cpflag==1){
                    cpid=s.getId();
                }
            }

            // 本次产生的差评申诉 补填首次评价内容(存在首评即差评的情况)
            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);
            }

            s.setSynReqId(s.getSynReqId());
            s.setSynStatus(1);
            s.setSynTime(new Date());
            upsatis.add(s);
        }

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

        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }

        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }

        // 修改同步状态
        if (upsatis.size()>0){
            itfTblAssignSatisfactionDownloadService.updateBatchById(upsatis);
            upsatis.clear();
        }

    }

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

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

        // 提取待同步的评价数据
        List<ItfTblAssignSatisfactionDownload> satis = itfTblAssignSatisfactionDownloadService.lambdaQuery()
                .eq(ItfTblAssignSatisfactionDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .orderByAsc(ItfTblAssignSatisfactionDownload::getHfsj)
                .list();

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

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

        for (ItfTblAssignSatisfactionDownload s:satis){
            jcaninsert=1;

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

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

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

            // 置可生成评价标识 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 (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);

        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }

        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }
    }

    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 int getCp(OrderBase orderBase, List<OrderAppeal> orderAppeals,
                      ItfTblAssignSatisfactionDownload s, Date ssDate) {
        if (s.getPjnr().equals("3") || s.getPjnr().indexOf("不满意")>=0 || getCppjly(s)){
            OrderAppeal orderAppeal=new OrderAppeal();
            orderAppeal.setOrderBaseId(orderBase.getId());
            orderAppeal.setPgid(orderBase.getPgid());
            orderAppeal.setWorkerName(orderBase.getWorkerName());
            orderAppeal.setWorkerId("");
            if (StringUtils.isNotEmpty(orderBase.getWorkerId())){
                orderAppeal.setWorkerId(orderBase.getWorkerId());
            }
            orderAppeal.setBadEvaluate(s.getPjnr());
            orderAppeal.setAppraiseStatus(getAppraiseStatus(s.getPjly()));
            orderAppeal.setStatus(1);
            orderAppeal.setCanApply(Boolean.TRUE);
            orderAppeal.setCreateTime(new Date());
            orderAppeal.setCreateBy("system");
            orderAppeal.setEvaluateTime(ssDate);
            orderAppeal.setWebsitId(orderBase.getWebsitId());
            orderAppeals.add(orderAppeal);

            return 1;
        }
        return 0;
    }

    // 首次评价(A:好评,B:中评,C:差评,N:未评价,O:其他
    private String getAppraiseStatus(String pjly){
        String appraiseStatus="";
        if (pjly.equals("1") || pjly.indexOf("满意")>=0){
            appraiseStatus="A";
        } else if (pjly.equals("2") || pjly.indexOf("一般")>=0){
            appraiseStatus="B";
        } else if (pjly.equals("3") || pjly.indexOf("不满意")>=0){
            appraiseStatus="C";
        } else {
            // 这里需要增加一个表用来查询确认是否为不满意
            appraiseStatus="O";
        }

        return appraiseStatus;
    }

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

    // 看是否为中差评
    @NotNull
    private Boolean getCppjly(ItfTblAssignSatisfactionDownload s) {
        Boolean cppjly;
        if (s.getPjly().trim().equals("1") || s.getPjly().trim().indexOf("满意")>=0){
            cppjly = Boolean.FALSE;
        } else if (s.getPjly().trim().equals("2") || s.getPjly().trim().indexOf("一般")>=0){
            cppjly = Boolean.TRUE;
        } else if (s.getPjly().trim().equals("3") || s.getPjly().trim().indexOf("不满意")>=0){
            cppjly = Boolean.TRUE;
        } else {
            cppjly = publicService.checkEvaluatemessage(s.getPjly());
        }
        return cppjly;
    }

    private void addcpsms(OrderBase order, ItfTblAssignSatisfactionDownload 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 || getCppjly(s)){
            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.getPgid()));
                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(1);
                fsList.add(fs);
            }
        }
    }

    private WebsitFWS getOrderAppreise(OrderBase orderBase, Map<String, List<SysDictRef>> sysDictRefDLMap,
                                       List<OrderAppraise> oanew, ItfTblAssignSatisfactionDownload s) {
        WebsitFWS websitFWS;
        OrderAppraise o = new OrderAppraise();
        // id为主键，放在pid 中
        o.setPid(s.getId());
        o.setPgguid(orderBase.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(getAppraiseStatus(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 boolean checkFrontRecord(ItfTblAssignSatisfactionDownload s) {
        ItfTblAssignSatisfactionDownload azas = itfTblAssignSatisfactionDownloadService.lambdaQuery()
                .lt(ItfTblAssignSatisfactionDownload::getSynReqId, s.getSynReqId())
                .eq(ItfTblAssignSatisfactionDownload::getPgid, s.getPgid())
                .eq(ItfTblAssignSatisfactionDownload::getId, s.getId())
                .lt(ItfTblAssignSatisfactionDownload::getLastModifiedDate, s.getLastModifiedDate())
                .eq(ItfTblAssignSatisfactionDownload::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, ItfTblAssignSatisfactionDownload 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 String getSpmessage(OrderBase orderBase, String spmessage) {
        OrderAppraise oaOne = orderAppraiseService.lambdaQuery()
                .eq(OrderAppraise::getOrderBaseId, orderBase.getId())
                .eq(OrderAppraise::getType,1)
                .last("limit 1")
                .one();
        if (oaOne !=null){
            spmessage = oaOne.getAppraiseContent();
        }
        return spmessage;
    }

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

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

        // 提取待同步的评价数据
        List<ItfTblAssignSatisfactionDownload> satis = itfTblAssignSatisfactionDownloadService.lambdaQuery()
                .eq(ItfTblAssignSatisfactionDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .orderByAsc(ItfTblAssignSatisfactionDownload::getHfsj)
                .list();

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

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

        for (ItfTblAssignSatisfactionDownload s:satis){
            jcaninsert=1;

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

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

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

            // 置可生成评价标识 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 (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);

        if (faGreeSms.size()>0){
            faGreeSmsService.saveBatch(faGreeSms);
            faGreeSms.clear();
        }

        if (orderAppeal.size()>0){
            orderAppealService.saveOrUpdateBatch(orderAppeal);
            orderAppeal.clear();
        }
    }



    @NotNull
    private WebsitFWS getWebsitFWS(Map<String, List<SysDictRef>> sysDictRefDLMap, OrderBase order, List<OrderAppraise> oanew, ItfTblAssignSatisfactionDownload s) {
        WebsitFWS websitFWS;
        OrderAppraise o = new OrderAppraise();
        // id为主键，放在pid 中
        o.setPid(s.getId());
        o.setPgguid(String.valueOf(s.getPgid()));
        // 工单号
        o.setOrderBaseId(order.getId());

        o.setOrderType(order.getOrderType());
        o.setWebsitId(order.getWebsitId());
        o.setWebsitName(order.getWebsitName());
        o.setUserName(order.getUserName());
        o.setUserPhone(order.getUserMobile());
        o.setAddress(order.getAddress());

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

        o.setRvisitTime(s.getHfsj());
        o.setNegativeType(s.getBmylx());
        o.setNegativeRemark(s.getBmybeiz());
        o.setNegativeTime(s.getBmysj());
        // 产品大类
        o.setMainId(sysDictRefDLMap.get(String.valueOf(s.getSplb())).get(0).getDictCode());
        o.setMainName(sysDictRefDLMap.get(String.valueOf(s.getSplb())).get(0).getDictValue());

        o.setAppointmentType(s.getMydlx());
        o.setType(s.getSxlx());
        o.setCreateBy(s.getCreatedBy());
        o.setCreateTime(new Date());
        if (s.getCreatedDate()!=null){
            o.setCreateTime(s.getCreatedDate());
        }
        oanew.add(o);
        return websitFWS;
    }

    private int getCp(OrderBase orderBase, List<OrderAppeal> orderAppeals, ItfTblAssignSatisfactionDownload s) {
        if (s.getPjnr().equals("3") || s.getPjnr().indexOf("不满意")>=0){
            OrderAppeal orderAppeal=new OrderAppeal();
            orderAppeal.setOrderBaseId(orderBase.getId());
            orderAppeal.setPgid(orderBase.getPgid());
            orderAppeal.setWorkerName(orderBase.getWorkerName());
            orderAppeal.setWorkerId(orderBase.getWorkerId());
            orderAppeal.setBadEvaluate(s.getPjnr());
            orderAppeal.setStatus(1);
            orderAppeal.setCanApply(Boolean.TRUE);
            orderAppeal.setCreateTime(new Date());
            orderAppeal.setCreateBy("system");
            orderAppeals.add(orderAppeal);
            return 1;
        }
        return 0;
    }


    @NotNull
    private WebsitFWS addappraise(OrderBase order, Map<String, List<SysDictRef>> sysDictRefDLMap, ItfTblAssignSatisfactionDownload s) {
        Boolean canAppeal = Boolean.TRUE;
        Integer appeal = 0;
        ReAppointment rq = new ReAppointment();
        WebsitFWS websitFWS = new WebsitFWS();

        if(StringUtils.isNotEmpty(s.getPjnr())){
            if (s.getPjnr().equals("1") || s.getPjnr().equals("满意")){
                canAppeal=Boolean.FALSE;
            }
        }
        // 检查上一条记录是否为中差评，如果是则新插入的不需要再申诉
        if (canAppeal){
            ReAppointment req = new ReAppointment();
            req.setId(String.valueOf(s.getPgid()));
            OrderAppraise id = appraiseMapper.getOldId(req);
            if (id !=null){
                appeal = 0;
            } else {
                appeal = 1;
            }
        }

        rq.setId(String.valueOf(s.getSynReqId()));
        OrderAppraise add = assignSatisfactionDownloadMapper.getOrderAppraise(rq);

        // rvisit_websit_id 单独处理
        websitFWS = publicService.shshwdToptshwd(s.getHfwdno(), order);
        if (StringUtils.isEmpty(websitFWS.getWebsitId())){
            websitFWS = publicService.shxswdToptxswd(s.getHfwdno(), order);
        }
        add.setRvisitWebsitId(websitFWS.getWebsitId());
        add.setRvisitWebsitName(websitFWS.getWdmc());
        // splb 商品大类  单独处理
        add.setMainId(sysDictRefDLMap.get(String.valueOf(s.getSplb())).get(0).getDictCode());
        // can_appeal 是否可发起申诉   单独处理
        // add.setCanAppeal(appeal);
        orderAppraiseService.save(add);
        return websitFWS;
    }

    private void upOrderBasePJ(OrderBase order, ItfTblAssignSatisfactionDownload s) {
        OrderBase upOrder = new OrderBase();
        upOrder.setId(order.getId());
        upOrder.setAppraiseTime(s.getCreatedDate());
        // 原 评价:1=差评,2=中评,3=好评,0=未评价,4=剔除,5=其他
        if (StringUtils.isEmpty(s.getPjnr())){
            upOrder.setAppraiseStatus("N");
        }
        if (s.getPjnr().equals("1") || s.getPjnr().equals("满意")){
            upOrder.setAppraiseStatus("A");
        } else if (s.getPjnr().equals("2") || s.getPjnr().equals("一般")){
            upOrder.setAppraiseStatus("B");
        } else if (s.getPjnr().equals("3") || s.getPjnr().equals("不满意") ||
                s.getPjnr().indexOf("差")>=0 || s.getPjnr().indexOf("不满")>=0){
            upOrder.setAppraiseStatus("C");
        } else {
            upOrder.setAppraiseStatus("O");
        }
        orderBaseService.updateById(upOrder);
    }

    private void upSatisfactionSynstatus(ItfTblAssignSatisfactionDownload s) {
        ItfTblAssignSatisfactionDownload ups = new ItfTblAssignSatisfactionDownload();
        ups.setSynReqId(s.getSynReqId());
        ups.setSynStatus(1);
        ups.setSynTime(new Date());
        itfTblAssignSatisfactionDownloadService.updateById(ups);
    }

    private void upSyncstatus(Long synReqId, Integer synStatus ,
                              String msg) {
        ItfTblAssignSatisfactionDownload up = new ItfTblAssignSatisfactionDownload();
        up.setSynReqId(synReqId);
        up.setSynStatus(synStatus);
        up.setSynTime(new Date());
        up.setSynErrMsg(msg);
        itfTblAssignSatisfactionDownloadService.updateById(up);
    }

    private void generateFkmx(ItfTblAssignDownload item, OrderBase order) {
        List<ItfTblAssignFkmxDownload> fkmxRec = new ArrayList<>();
        List<OrderRepairOperatingLog> orols = new ArrayList<>();
        List<ItfTblAssignFkmxDownload> ups = new ArrayList<>();

        fkmxRec = itfTblAssignFkmxDownloadService.lambdaQuery()
                .eq(ItfTblAssignFkmxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAssignFkmxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignFkmxDownload::getCreatedDate,ItfTblAssignFkmxDownload::getFkid)
                .list();
        for (ItfTblAssignFkmxDownload fkmx :fkmxRec){
            // 获取操作明细数据
            getoroldata(order, orols, fkmx);
            ItfTblAssignFkmxDownload u = new ItfTblAssignFkmxDownload();
            u.setSynReqId(fkmx.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            ups.add(u);
        }
        if (orols.size()>0){
            orderRepairOperatingLogService.saveBatch(orols);
            orols.clear();
            itfTblAssignFkmxDownloadService.updateBatchById(ups);
            ups.clear();
        }
    }

    private void generateFkmxApi(ItfTblAssignDownload item, List<ItfTblAssignFkmxDownload> fkmxups,
                                 List<OrderRepairOperatingLog> orols, OrderBase order) {
        List<ItfTblAssignFkmxDownload> fkmxRec = new ArrayList<>();

        fkmxRec = itfTblAssignFkmxDownloadService.lambdaQuery()
                .eq(ItfTblAssignFkmxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAssignFkmxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignFkmxDownload::getCreatedDate,ItfTblAssignFkmxDownload::getFkid)
                .list();
        for (ItfTblAssignFkmxDownload fkmx :fkmxRec){
            // 获取操作明细数据
            getoroldata(order, orols, fkmx);
            ItfTblAssignFkmxDownload u = new ItfTblAssignFkmxDownload();
            u.setSynReqId(fkmx.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            fkmxups.add(u);
        }
    }

    private void generateFkmxUpdate(ItfTblAssignDownload item, OrderBase order) {
        List<ItfTblAssignFkmxDownload> fkmxRec = new ArrayList<>();
        List<OrderRepairOperatingLog> orols = new ArrayList<>();
        List<ItfTblAssignFkmxDownload> ups = new ArrayList<>();
        Map<String, List<OrderRepairOperatingLog>> orolMap = new HashMap<>();

        // 提取已有的，有则更新，无则新增
        List<OrderRepairOperatingLog> olds = orderRepairOperatingLogService.lambdaQuery()
                .eq(OrderRepairOperatingLog::getOrderBaseId,order.getId()).list();
        orolMap = olds.stream().collect(Collectors.groupingBy(OrderRepairOperatingLog::getFkid));

        fkmxRec = itfTblAssignFkmxDownloadService.lambdaQuery()
                .eq(ItfTblAssignFkmxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAssignFkmxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignFkmxDownload::getCreatedDate,ItfTblAssignFkmxDownload::getFkid)
                .list();
        for (ItfTblAssignFkmxDownload fkmx :fkmxRec){
            // 存在不做更新？过程是这样写的
            if (!orolMap.containsKey(fkmx.getFkid())){
                getoroldata(order, orols, fkmx);
            }

            ItfTblAssignFkmxDownload u = new ItfTblAssignFkmxDownload();
            u.setSynReqId(fkmx.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            ups.add(u);
        }
        if (orols.size()>0){
            orderRepairOperatingLogService.saveBatch(orols);
            orols.clear();
        }
        if (ups.size()>0){
            itfTblAssignFkmxDownloadService.updateBatchById(ups);
            ups.clear();
        }
    }

    private void generateFkmxUpdateApi(ItfTblAssignDownload item, OrderBase order,
                                       List<OrderRepairOperatingLog> orols,
                                       List<ItfTblAssignFkmxDownload> fkmxd) {
        List<ItfTblAssignFkmxDownload> fkmxRec = new ArrayList<>();
        Map<String, List<OrderRepairOperatingLog>> orolMap = new HashMap<>();

        // 提取已有的，有则更新，无则新增
        List<OrderRepairOperatingLog> olds = orderRepairOperatingLogService.lambdaQuery()
                .eq(OrderRepairOperatingLog::getOrderBaseId,order.getId()).list();
        orolMap = olds.stream().collect(Collectors.groupingBy(OrderRepairOperatingLog::getFkid));

        fkmxRec = itfTblAssignFkmxDownloadService.lambdaQuery()
                .eq(ItfTblAssignFkmxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAssignFkmxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignFkmxDownload::getCreatedDate,ItfTblAssignFkmxDownload::getFkid)
                .list();
        for (ItfTblAssignFkmxDownload fkmx :fkmxRec){
            // 存在不做更新？过程是这样写的
            if (!orolMap.containsKey(String.valueOf(fkmx.getFkid()))){
                getoroldata(order, orols, fkmx);
            }

            ItfTblAssignFkmxDownload u = new ItfTblAssignFkmxDownload();
            u.setSynReqId(fkmx.getSynReqId());
            u.setSynStatus(1);
            u.setSynTime(new Date());
            fkmxd.add(u);
        }
    }

    private void getoroldata(OrderBase order, List<OrderRepairOperatingLog> orols, ItfTblAssignFkmxDownload fkmx) {
        OrderRepairOperatingLog add = new OrderRepairOperatingLog();
        String scwj=fkmx.getScwj().replace("||",",");
        WebsitFWS websitFWS = new WebsitFWS();
        add.setWebsitName(order.getWebsitName());
        add.setWebsitId(order.getWebsitId());
        add.setOrderBaseId(order.getId());
        add.setCustomerName(order.getUserName());
        add.setCustomerPhone(order.getUserMobile());
        add.setType(fkmx.getFklb());
        add.setContent(fkmx.getFknr());
        add.setFeedback(fkmx.getFkjg());
        add.setOperator(fkmx.getFkren());
        add.setOperatorNumber(fkmx.getFkrenmc());
        websitFWS = publicService.shshwdToptshwd(fkmx.getFkwdno(), order);
        if (StringUtils.isEmpty(websitFWS.getWebsitId())){
            websitFWS = publicService.shxswdToptxswd(fkmx.getFkwdno(), order);
        }
        add.setOperateWebsit(websitFWS.getWdmc());
        add.setWebsitPhone(websitFWS.getWdlxdh());
        add.setWorkerOrderStatus(order.getOrderStatus());// 反馈时的工单状态
        add.setBeforeOrderStatus(order.getLastOrderStatus());// 操作前工单状态 - 上一流程状态
        add.setBeforeDispatchStatus(order.getDispatchStatus());// 操作前派工状态
        add.setOrderStatus("DJS"); // 操作后工单状态
        // 总部下来的工单统一为待接收状态-派工状态
        add.setDispatchStatus("DJS"); // 操作后派工状态
        // 附件地址 todo
        add.setPgguid(order.getPgguid());
        add.setFkmxguid(fkmx.getFkmxguid());
        add.setFkid(String.valueOf(fkmx.getFkid()));
        add.setPgid(fkmx.getPgid());

        add.setBrandFileName(fkmx.getScid());
        // add.setBrandFileId(scwj);
        add.setOutZjljProcess(-1);
        if (StringUtils.isNotEmpty(scwj)){
            add.setOutZjlj(scwj);
            add.setOutZjljProcess(0);
        }

        add.setWjid(fkmx.getWjid());
        add.setReqSourceNum(fkmx.getQqlyxh());
        add.setUploadNotifyFlag(0);
        add.setCreateTime(new Date());
        add.setUpdateTime(new Date());
        if (fkmx.getCreatedDate() !=null){
            add.setCreateTime(fkmx.getCreatedDate());
        } else if (fkmx.getFksj() !=null){
            add.setCreateTime(fkmx.getFksj());
        }
        if (fkmx.getLastModifiedDate() !=null){
            add.setUpdateTime(fkmx.getLastModifiedDate());
        }

        add.setCreateBy(fkmx.getCreatedBy());
        add.setUpdateBy(fkmx.getLastModifiedBy());
        orols.add(add);
    }

    private void getOrderInstall(ItfTblAssignDownload item, OrderBase order,
                                 Map<String, List<SysDictRef>> sysDictRefXLMapXq) {
        OrderRepair or = new OrderRepair();

        // 查看是否存在
        OrderRepair oldor = orderRepairService.lambdaQuery()
                .eq(OrderRepair::getOrderBaseId,order.getId())
                .last("limit 1")
                .one();

        if (oldor !=null){
            or.setId(oldor.getId());
        }
        or.setOrderBaseId(order.getId());
        or.setCxyzm(item.getCxyzm());
        or.setSffswx(item.getSffswx());
        or.setChaoshiqe(item.getChaoshiqe());
        or.setZbby(item.getZbby());
        or.setZptype(item.getZptype());
        or.setYhif(item.getYhif());
        or.setTsdengji(item.getTsdengji());
        // 需求大类 未找到放原有的值
        or.setDemandTypeId(String.valueOf(item.getSpid()));
        or.setDemandTypeName(item.getSpmc());

        if (sysDictRefXLMapXq.containsKey(String.valueOf(item.getSpid()))){
            or.setDemandTypeId(sysDictRefXLMapXq.get(String.valueOf(item.getSpid())).get(0).getDictCode());
            or.setDemandTypeName(sysDictRefXLMapXq.get(String.valueOf(item.getSpid())).get(0).getDictValue());
        }

        // 需求小类
        or.setDemandSmallTypeId("");
        or.setDemandSmallTypeName("");
        if (!item.getXqxiaolei().equals(0L) && sysDictRefXLMapXq.containsKey(item.getXqxiaolei())) {
            or.setDemandSmallTypeId(sysDictRefXLMapXq.get(item.getXqxiaolei()).get(0).getDictCode());
            or.setDemandSmallTypeName(sysDictRefXLMapXq.get(item.getXqxiaolei()).get(0).getDictValue());
        }
        or.setExtendField1(item.getExtjson1());
        or.setExtendField2(item.getExtjson2());
        or.setExtendField3(item.getExtjson3());
        or.setExtendField4(item.getExtjson4());
        or.setExtendField5(item.getExtjson5());
        or.setCreateBy(order.getCreateBy());
        or.setCreateTime(order.getCreateTime());
        or.setUpdateBy(order.getUpdateBy());
        or.setUpdateTime(order.getUpdateTime());
        orderRepairService.saveOrUpdate(or);
    }

    private void getOrderInstallApi(ItfTblAssignDownload item, OrderBase order,Map<String, List<SysDictRef>> sysDictRefDLMapXq,
                                 Map<String, List<SysDictRef>> sysDictRefXLMapXq,OrderRepair or) {
        // 查看是否存在 这里不需自生成表数据，去掉
        /*OrderRepair oldor = orderRepairService.lambdaQuery()
                .eq(OrderRepair::getOrderBaseId,order.getId())
                .last("limit 1")
                .one();

        if (oldor !=null){
            or.setId(oldor.getId());
        }*/

        or.setOrderBaseId(order.getId());
        or.setCxyzm(item.getCxyzm());
        or.setSffswx(item.getSffswx());
        or.setChaoshiqe(item.getChaoshiqe());
        or.setZbby(item.getZbby());
        or.setZptype(item.getZptype());
        or.setYhif(item.getYhif());
        or.setTsdengji(item.getTsdengji());

        // 需求大类 未找到放原有的值
        or.setDemandTypeId("");
        or.setDemandTypeName("");
        if (item.getXxlbid() !=null && sysDictRefDLMapXq.containsKey(String.valueOf(item.getXxlbid()))){
            or.setDemandTypeId(sysDictRefDLMapXq.get(String.valueOf(item.getXxlbid())).get(0).getDictCode());
            or.setDemandTypeName(sysDictRefDLMapXq.get(String.valueOf(item.getXxlbid())).get(0).getDictValue());
        }

        // 需求小类
        or.setDemandSmallTypeId("");
        or.setDemandSmallTypeName("");
        if (StringUtils.isNotEmpty(item.getXqxiaolei()) && sysDictRefXLMapXq.containsKey(item.getXqxiaolei())) {
            or.setDemandSmallTypeId(sysDictRefXLMapXq.get(item.getXqxiaolei()).get(0).getDictCode());
            or.setDemandSmallTypeName(sysDictRefXLMapXq.get(item.getXqxiaolei()).get(0).getDictValue());
        }

        or.setExtendField1(item.getExtjson1());
        or.setExtendField2(item.getExtjson2());
        or.setExtendField3(item.getExtjson3());
        or.setExtendField4(item.getExtjson4());
        or.setExtendField5(item.getExtjson5());
        or.setCreateBy(order.getCreateBy());
        or.setCreateTime(order.getCreateTime());
        or.setUpdateBy(order.getUpdateBy());
        or.setUpdateTime(order.getUpdateTime());
    }

    private void generateMx(Brand brand, ItfTblAssignDownload item, OrderBase order,
                            Map<String, List<SysDictRef>> sysDictRefDLMap,
                            Map<String, List<SysDictRef>> sysDictRefXLMap,
                            Map<String, List<SysDictRef>> sysDictRefXiLieMap) {
        List<ItfTblAssignMxDownload> mxRec = new ArrayList<>();
        List<OrderProduct> addmx = new ArrayList<>();
        List<ItfTblAssignMxDownload> ups = new ArrayList<>();
        WebsitFWS websitFWS = new WebsitFWS();

        // 提取明细表数据
        mxRec = itfTblAssignMxDownloadService.lambdaQuery()
                .eq(ItfTblAssignMxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAssignMxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignMxDownload::getSynStatus)
                .list();
        for (ItfTblAssignMxDownload rec:mxRec){
            // 提取维修工单明细数据对象
            OrderPar mxreq = new OrderPar();
            mxreq.setSynReqId(Long.valueOf(rec.getSynReqId()));
            mxreq.setBrandId(brand.getBrandId());
            OrderProduct op = repairMxDownloadMapper.getMx(mxreq);
            // 销售单位处理 sale_websit
            websitFWS = publicService.shxswdToptxswd(op.getSaleWebsit(),order);
            op.setSaleWebsit(websitFWS.getWebsitId());

            // 服务单位处理 service_websit
            websitFWS = publicService.shshwdToptshwd(op.getServiceWebsit(),order);
            op.setServiceWebsit(websitFWS.getWebsitId());

            // 其他部分参数赋值
            op.setOrderBaseId(order.getId());
            op.setPgguid(item.getPgguid());
            op.setMainId(order.getMainId());
            op.setMainName(order.getMainName());

            if (sysDictRefDLMap.containsKey(rec.getSpid())){
                op.setMainId(sysDictRefDLMap.get(rec.getSpid()).get(0).getDictCode());
                op.setMainName(sysDictRefDLMap.get(rec.getSpid()).get(0).getDictValue());
            }

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

            if (!rec.getXiid().equals("0") && sysDictRefXiLieMap.containsKey(rec.getXiid())){
                op.setSeriesId(sysDictRefXiLieMap.get(rec.getXiid()).get(0).getDictCode());
                op.setSeriesName(sysDictRefXiLieMap.get(rec.getXiid()).get(0).getDictValue());
            } else {
                op.setSeriesId(rec.getXiid());
                op.setSeriesName(rec.getXimc());
            }
            addmx.add(op);

            ItfTblAssignMxDownload up = new ItfTblAssignMxDownload();
            up.setSynReqId(rec.getSynReqId());
            up.setSynStatus(1);
            up.setSynReqTime(new Date());
            ups.add(up);
        }

        if (addmx.size()>0){
            orderProductService.saveBatch(addmx);
            addmx.clear();
            itfTblAssignMxDownloadService.updateBatchById(ups);
            ups.clear();
        }
    }

    private void generateMxApi(Brand brand, ItfTblAssignDownload item, OrderBase order,
                            Map<String, List<SysDictRef>> sysDictRefDLMap,
                            Map<String, List<SysDictRef>> sysDictRefXLMap,
                            Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                               List<OrderProduct> addmx,
                               List<ItfTblAssignMxDownload> ups, Map<String,String> productMap) {
        List<ItfTblAssignMxDownload> mxRec = new ArrayList<>();
        WebsitFWS websitFWS = new WebsitFWS();

        // 提取明细表数据
        mxRec = itfTblAssignMxDownloadService.lambdaQuery()
                .eq(ItfTblAssignMxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAssignMxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignMxDownload::getSynStatus)
                .list();
        for (ItfTblAssignMxDownload rec:mxRec){
            // 提取维修工单明细数据对象
            OrderPar mxreq = new OrderPar();
            mxreq.setSynReqId(Long.valueOf(rec.getSynReqId()));
            mxreq.setBrandId(brand.getBrandId());
            OrderProduct op = repairMxDownloadMapper.getMx(mxreq);

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


            // 销售单位处理 sale_websit
            websitFWS = publicService.shxswdToptxswd(op.getSaleWebsit(),order);
            op.setSaleWebsit(websitFWS.getWebsitId());

            // 服务单位处理 service_websit
            websitFWS = publicService.shshwdToptshwd(op.getServiceWebsit(),order);
            op.setServiceWebsit(websitFWS.getWebsitId());

            // 其他部分参数赋值
            op.setOrderBaseId(order.getId());
            op.setPgguid(item.getPgguid());
            op.setMainId(order.getMainId());
            op.setMainName(order.getMainName());

            if (sysDictRefDLMap.containsKey(rec.getSpid())){
                op.setMainId(sysDictRefDLMap.get(rec.getSpid()).get(0).getDictCode());
                op.setMainName(sysDictRefDLMap.get(rec.getSpid()).get(0).getDictValue());
            }

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

            if (!rec.getXiid().equals("0") && sysDictRefXiLieMap.containsKey(rec.getXiid())){
                op.setSeriesId(sysDictRefXiLieMap.get(rec.getXiid()).get(0).getDictCode());
                op.setSeriesName(sysDictRefXiLieMap.get(rec.getXiid()).get(0).getDictValue());
            } else {
                op.setSeriesId(rec.getXiid());
                op.setSeriesName(rec.getXimc());
            }
            addmx.add(op);

            ItfTblAssignMxDownload up = new ItfTblAssignMxDownload();
            up.setSynReqId(rec.getSynReqId());
            up.setSynStatus(1);
            up.setSynReqTime(new Date());
            ups.add(up);
        }
    }

    private void generateMxUpdate(Brand brand, ItfTblAssignDownload item, OrderBase order,
                                  Map<String, List<SysDictRef>> sysDictRefDLMap,
                                  Map<String, List<SysDictRef>> sysDictRefXLMap,
                                  Map<String, List<SysDictRef>> sysDictRefXiLieMap, Map<String,String> productMap) {
        List<ItfTblAssignMxDownload> mxRec = new ArrayList<>();
        List<OrderProduct> addmx = new ArrayList<>();
        List<OrderProduct> upmx = new ArrayList<>();
        List<ItfTblAssignMxDownload> ups = new ArrayList<>();
        Map<String, List<OrderProduct>> opsMap = new HashMap<>();

        // 提取现有的数据
        List<OrderProduct> ops = orderProductService.lambdaQuery()
                .eq(OrderProduct::getOrderBaseId,order.getId()).list();

        opsMap = ops.stream().collect(Collectors.groupingBy(OrderProduct::getPgmxid));

        // 提取明细表数据
        mxRec = itfTblAssignMxDownloadService.lambdaQuery()
                .eq(ItfTblAssignMxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                .eq(ItfTblAssignMxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignMxDownload::getSynStatus)
                .list();

        for (ItfTblAssignMxDownload rec:mxRec){
            // 提取维修工单明细数据对象
            OrderPar mxreq = new OrderPar();
            mxreq.setSynReqId(Long.valueOf(rec.getSynReqId()));
            mxreq.setBrandId(brand.getBrandId());
            OrderProduct op = getOrderProduct(item, order, sysDictRefDLMap, sysDictRefXLMap,
                    sysDictRefXiLieMap, rec, mxreq, productMap);

            // 存在修改
            if (opsMap.containsKey(op.getPgmxid())){
                getupop(upmx, opsMap, op);
            } else {
                addmx.add(op);
            }

            ItfTblAssignMxDownload up = new ItfTblAssignMxDownload();
            up.setSynReqId(rec.getSynReqId());
            up.setSynStatus(1);
            up.setSynReqTime(new Date());
            ups.add(up);
        }

        if (addmx.size()>0){
            orderProductService.saveBatch(addmx);
            addmx.clear();
        }
        if (upmx.size()>0){
            orderProductService.updateBatchById(upmx);
            upmx.clear();
        }
        if (ups.size()>0){
            itfTblAssignMxDownloadService.updateBatchById(ups);
            ups.clear();
        }

    }

    public void generateMxUpdateApi(Brand brand, ItfTblAssignDownload item, OrderBase order,
                                  Map<String, List<SysDictRef>> sysDictRefDLMap,
                                  Map<String, List<SysDictRef>> sysDictRefXLMap,
                                  Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                                     List<OrderProduct> addmx,
                                     List<ItfTblAssignMxDownload> upMxd, Map<String,String> productMap) {
        List<ItfTblAssignMxDownload> mxRec = new ArrayList<>();

        // 提取明细表数据
        mxRec = itfTblAssignMxDownloadService.lambdaQuery()
                .eq(ItfTblAssignMxDownload::getDownloadTaskNo, item.getDownloadTaskNo())
                // .eq(ItfTblAssignMxDownload::getSynStatus,0)
                .orderByAsc(ItfTblAssignMxDownload::getSynStatus)
                .list();

        for (ItfTblAssignMxDownload rec:mxRec){
            // 提取维修工单明细数据对象
            OrderPar mxreq = new OrderPar();
            mxreq.setSynReqId(Long.valueOf(rec.getSynReqId()));
            mxreq.setBrandId(brand.getBrandId());
            OrderProduct op = getOrderProduct(item, order, sysDictRefDLMap, sysDictRefXLMap, sysDictRefXiLieMap,
                    rec, mxreq, productMap);
            addmx.add(op);

            ItfTblAssignMxDownload up = new ItfTblAssignMxDownload();
            up.setSynReqId(rec.getSynReqId());
            up.setSynStatus(1);
            up.setSynReqTime(new Date());
            upMxd.add(up);
        }
    }

    private void getupop(List<OrderProduct> upmx, Map<String, List<OrderProduct>> opsMap, OrderProduct op) {
        OrderProduct up = new OrderProduct();
        up.setId(opsMap.get(op.getPgmxid()).get(0).getId());
        up.setMainId(op.getMainId());
        up.setMainName(op.getMainName());
        up.setSmallId(op.getSmallId());
        up.setSmallName(op.getSmallName());
        up.setSeriesId(op.getSeriesId());
        up.setSeriesName(op.getSeriesName());
        up.setProductId(op.getProductId());
        up.setProductName(op.getProductName());
        up.setUrgency(op.getUrgency());
        up.setSaleWebsit(op.getSaleWebsit());
        up.setServiceWebsit(op.getServiceWebsit());
        up.setSaleWebsitMobile(op.getSaleWebsitMobile());
        up.setServiceWebsitMobile(op.getServiceWebsitMobile());
        up.setBuyTime(op.getBuyTime());
        upmx.add(up);
    }

    @NotNull
    private OrderProduct getOrderProduct(ItfTblAssignDownload item, OrderBase order,
                                         Map<String, List<SysDictRef>> sysDictRefDLMap,
                                         Map<String, List<SysDictRef>> sysDictRefXLMap,
                                         Map<String, List<SysDictRef>> sysDictRefXiLieMap,
                                         ItfTblAssignMxDownload rec, OrderPar mxreq, Map<String,String> productMap) {
        WebsitFWS websitFWS = new WebsitFWS();
        OrderProduct op = repairMxDownloadMapper.getMx(mxreq);

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

        // 其他部分参数赋值
        // 销售单位处理 sale_websit
        websitFWS = publicService.shxswdToptxswd(op.getSaleWebsit(),order);
        op.setSaleWebsit(websitFWS.getWebsitId());
        // 服务单位处理 service_websit
        websitFWS = publicService.shshwdToptshwd(op.getServiceWebsit(),order);
        op.setServiceWebsit(websitFWS.getWebsitId());

        op.setOrderBaseId(order.getId());

        op.setPgguid(item.getPgguid());
        op.setMainId(rec.getSpid());
        op.setMainName(rec.getSpmc());
        if (sysDictRefDLMap.containsKey(rec.getSpid())){
            op.setMainId(sysDictRefDLMap.get(rec.getSpid()).get(0).getDictCode());
            op.setMainName(sysDictRefDLMap.get(rec.getSpid()).get(0).getDictValue());
        }

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

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

        return op;
    }

    private OrderBase generateOrder(Brand brand, ItfTblAssignDownload item, List<ItfTblAssignXzydDownload> yds) {
        Boolean isChildInfo = Boolean.FALSE;

        if (yds !=null && yds.size()>0){
            isChildInfo = Boolean.TRUE;
        }

        OrderBase order = saveOrderBase(brand, item, isChildInfo);

        // 总部维修单为待审批改派时 若本地表无改派数据则生成改派数据
        if (order.getOrderStatus().equals("B5")){
            // generateDispatch(order);
        }
        // 如果是家用的工单，且工单状态是待中心派工或待网点派工时，写入派嘉讯茂  不做

        // 修改同步状态
        upItfTblAssignDownloadStatus(item, order);

        return order;
    }

    private OrderBase generateOrderApi(Brand brand, ItfTblAssignDownload item, List<ItfTblAssignXzydDownload> yds,
                                       List<ItfGreeToFaDownloadTaskList> its) {
        Boolean isChildInfo = Boolean.FALSE;

        if (yds !=null && yds.size()>0){
            isChildInfo = Boolean.TRUE;
        }

        OrderBase order = getOrderBaseApi(brand, item, isChildInfo);
        order.setSource("GREE");

        // 总部维修单为待审批改派时 若本地表无改派数据则生成改派数据
        /*if (order.getOrderStatus().equals("B5")){
            generateDispatchApi(order,addn);
        }*/

        // 如果是家用的工单，且工单状态是待中心派工或待网点派工时，写入派嘉讯茂  不做

        // 增加处理采集数据下载 41,102
        Integer cjDowFlag=0;
        putDownloadTaskList(item, order, its, cjDowFlag);

        return order;
    }

    private OrderBase getOrderBaseApi(Brand brand, ItfTblAssignDownload item, Boolean isChildInfo) {
        // 获取维修工单主表数据
        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());
        OrderBase order = repairDownloadMapper.getOrderBase(orderPar);
        // 处理用户等级
        publicService.setUserLevel(order);


        order.setId("G" + IdWorker.getIdStr());
        if (isChildInfo){
            order.setIsChildInfo("YES");
        }

        // 消息来源不能为空，为空时默认电话
        if (StringUtils.isEmpty(order.getInfoSource())){
            order.setInfoSource("电话");
        }
        order.setInfoSourceId(baseService.getxxly(order.getInfoSource()));

        // 部分属性值重置
        orderService.setParame(brand, order, item);

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

        // 新增
        // orderBaseService.save(order);
        return order;
    }


    private OrderBase getOrderBaseUpdateApi(Brand brand, ItfTblAssignDownload item) {
        // 获取维修工单主表数据
        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());
        OrderBase order = repairDownloadMapper.getOrderBase(orderPar);
        // 部分属性值重置
        orderService.setParameUpdate(brand, order, item);

        return order;
    }

    private OrderBase saveOrderBase(Brand brand, ItfTblAssignDownload item, Boolean isChildInfo) {
        // 获取维修工单主表数据
        OrderPar orderPar = new OrderPar();
        orderPar.setSynReqId(item.getSynReqId());
        orderPar.setBrandId(brand.getBrandId());
        OrderBase order = repairDownloadMapper.getOrderBase(orderPar);
        order.setId("77"+ IdWorker.getIdStr());
        if (isChildInfo){
            order.setIsChildInfo("YES");
        }
        // 部分属性值重置
        orderService.setParame(brand, order, item);
        // 新增
        orderBaseService.save(order);
        return order;
    }

    public void upItfTblAssignDownloadStatus(ItfTblAssignDownload item, OrderBase order){
        upItfTblAssignDownload(item.getSynReqId(),1,"成功");

        OrderPar prepar = new OrderPar();
        prepar.setSynReqId(item.getSynReqId());
        prepar.setPgid(order.getPgid());
        assignDownloadMapper.updateStatus(prepar);
    }

    private void upItfTblAssignDownload(Long synReqId, Integer synStatus, String synErrMsg) {
        ItfTblAssignDownload up = new ItfTblAssignDownload();
        up.setSynReqId(synReqId);
        up.setSynStatus(synStatus);
        up.setSynTime(new Date());
        up.setSynErrMsg(synErrMsg);
        itfTblAssignDownloadService.updateById(up);
    }

    // //////////////////////////////////////////
    @Override
    // @Transactional(rollbackFor = Exception.class)
    public Boolean csfun() throws Exception {
        List<Brand> addmx = new ArrayList<>();
        List<Brand> upMxd = new ArrayList<>();
        List<Test> ttt = new ArrayList<>();
        List<Test> tx = new ArrayList<>();

        try {
            try{
                Test tt = new Test();
                tt.setId("1");
                tx.add(tt);
                testService.saveBatch(tx);
            } catch (Exception ex) {
                log.error("A失败：", ex);
            }

            Test t = new Test();
            t.setId("2");
            ttt.add(t);
            testService.saveBatch(ttt);


        } catch (Exception ex) {
            log.error("B失败：", ex);
        }






        // 网络请求
        // csfunbc();
        return Boolean.FALSE;
    }

    @NotNull
    public Boolean csfunbc() throws Exception {
        // 创建工单
        OrderAddBeanDTO orderApi = new OrderAddBeanDTO();

        ResponseHelper respone = jiasmApi.orderAdd(orderApi);
        log.info("修改维修工单 respone:{}", JSONObject.toJSONString(respone));
        if (respone.getCode()==200){
            return Boolean.TRUE;
        } else {
            log.info("网络失败 {}",respone.getMessage());
            throw new Exception("msg");
        }
    }


    private Boolean csfunb(List<Brand> addmx,List<Brand> upMxd,List<Test> ttt){
        if (upMxd.size()>0){
            brandService.updateBatchById(upMxd);
        }

        if (ttt.size()>0){
            testService.saveBatch(ttt);
        }

        return Boolean.TRUE;
    }

    public void csfuna(List<Brand> upMxd,List<Test> ttt) {
        List<Brand> mxRec = new ArrayList<>();

        // 提取明细表数据
        mxRec = brandService.lambdaQuery()
                .eq(Brand::getBrand, "格力")
                .list();

        for (Brand rec:mxRec){
            Brand up = new Brand();
            up.setBrandId(rec.getBrandId());
            up.setBrand("格力格");
            upMxd.add(up);
        }

        Test t = new Test();
        t.setId("88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888");
        ttt.add(t);

    }




    //  /////////////////////////////////////////////////////////////////////////////

}
