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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.zfire.jiasm.syncdata.base.BaseService;
import com.zfire.jiasm.syncdata.constant.DictTypeEnum;
import com.zfire.jiasm.syncdata.constant.ServiceCategoryEnum;
import com.zfire.jiasm.syncdata.gree.GreeLogic;
import com.zfire.jiasm.syncdata.helper.GreeResponseHelper;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.request.SignSplb;
import com.zfire.jiasm.syncdata.request.ZJInfo;
import com.zfire.jiasm.syncdata.request.ZJInfoBX;
import com.zfire.jiasm.syncdata.request.ZJInfoC;
import com.zfire.jiasm.syncdata.response.WangdianWxgVos;
import com.zfire.jiasm.syncdata.response.WxgQueryInfo;
import com.zfire.jiasm.syncdata.service.GLPPWXGQueryAddService;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.test;
import com.zfire.jiasm.syncdata.utils.MyBeanUtils;
import com.zfire.jiasm.syncdata.utils.oss.OSSUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@Service
public class GLPPWXGQueryAddServiceImpl implements GLPPWXGQueryAddService {
    String wdqyapi = "/outapp/wxg/list";

    @Resource
    BaseService baseService;
    @Resource
    GreeLogic greeLogic;
    @Resource
    OSSUtil ossUtil;
    @Resource
    ItfTblWangdianWxgDownloadService itfTblWangdianWxgDownloadService;
    @Resource
    ItfTblXinWangdianDownloadService itfTblXinWangdianDownloadService;
    @Resource
    WorkerBrandAccountService workerBrandAccountService;
    @Resource
    WorkerCertService workerCertService;
    @Resource
    WorkerStreetService workerStreetService;
    @Resource
    ProvinceService provinceService;
    @Resource
    BrandLbsRelateService brandLbsRelateService;
    @Resource
    WorkerServiceCategoryService workerServiceCategoryService;
    @Resource
    WorkerServiceCategoryDetailService workerServiceCategoryDetailService;
    @Resource
    SysDictRefService sysDictRefService;
    @Resource
    SysDictService sysDictService;
    @Resource
    CustomerInformationWebsitService customerInformationWebsitService;
    @Resource
    WebsitService websitService;
    @Resource
    WorkerService workerService;
    @Resource
    ItfTblWangdianPositionDownloadService itfTblWangdianPositionDownloadService;
    @Resource
    PublicService publicService;
    @Resource
    WebsitWorkerService websitWorkerService;
    @Resource
    InsureWorkerCommercialService insureWorkerCommercialService;
    @Resource
    InsureWorkerCommercialFileService insureWorkerCommercialFileService;
    @Resource
    OrderDetailFileService orderDetailFileService;
    @Resource
    OrderInstallDetailCodeService orderInstallDetailCodeService;
    @Resource
    WorkerCertGreeService workerCertGreeService;



    @Override
    public void extractedCertGreeInfo() throws Exception {
        WangdianWxgVos wvos = new WangdianWxgVos();
        Map<String,Object> req = new HashMap<>();
        Map<String,List<Worker>> workerIdcardMap = new HashMap<>();
        List<ItfTblWangdianWxgDownload> wxgDownladRecs = new ArrayList<>();
        List<WorkerCertGree> wcgs = new ArrayList<>();
        Map<String,String> wcgids = new HashMap<>();
        Map<String,String> wcgzjs = new HashMap<>();


        List<WorkerCertGree> wcgsold = workerCertGreeService.lambdaQuery().list();
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(wcgsold)){
            wcgsold.stream().forEach(event->{
                wcgids.put(event.getWorkerId() + event.getBrandWebsitId() + event.getCertName(),
                        event.getWorkerCertGreeId());
                wcgzjs.put(event.getWorkerId() + event.getBrandWebsitId() + event.getCertName(),
                        event.getOutFileUrl() + event.getOutFileUrl2());
            });
            wcgsold.clear();
        }


        List<Worker> oldWorkerRec =  workerService.lambdaQuery()
                .select(Worker::getIdcard,Worker::getWorkerId,Worker::getWorkerName,Worker::getMobile).list();
        if (CollectionUtils.isNotEmpty(oldWorkerRec)){
            workerIdcardMap = oldWorkerRec.stream().collect(Collectors.groupingBy(Worker::getIdcard));
            oldWorkerRec.clear();
        }

        // 提取格力现有的网点师傅数据信息
        wxgDownladRecs =  itfTblWangdianWxgDownloadService.lambdaQuery()
                .eq(ItfTblWangdianWxgDownload::getGreeStatus,0)
                // .eq(ItfTblWangdianWxgDownload::getSfzen,"441283199209162787")// 测试用
                .like(ItfTblWangdianWxgDownload::getWdno,"S%").list();


        for (ItfTblWangdianWxgDownload wxg :wxgDownladRecs){
            // 无效的数据不新增
            /*if (wxg.getFlag() != null){
                if (wxg.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_OFF.getCode())){
                    continue;
                }
            }*/
            // 平台师傅信息不包含格力总部的数据不处理(包含的为格力的师傅信息同步时已生成了worker)
            // 这里用身份证来做包含关系(测试环境身份证隐藏* 需加名称及手机号)
            String workerId = checkIsGreeWroker(workerIdcardMap, wxg);
            if (workerId.length()<1) {
                continue;
            }

            // 参数 获取网点维修工信息
            getParameter(wxg.getWdno(), wxg.getWxgno(), req);
            try {
                // 格力总部查询工程师信息
                GreeResponseHelper response = greeLogic.greePost(wdqyapi, JSONObject.toJSONString(req), publicService.getCompanyId(wxg.getWdno()));
                // 失败不处理
                if (response.getStatus() == 200){
                    wxg.setGreeStatus(1);
                    WxgQueryInfo resultDatax = JSONObject.parseObject(response.getData().toString(), WxgQueryInfo.class);
                    // 无证件不处理
                    if ( resultDatax.getWangdianWxgVos().size()<1){
                        wxg.updateById();
                        continue;
                    }
                    wvos = resultDatax.getWangdianWxgVos().get(0);

                    // 同步-新增证件信息
                    for (ZJInfo zj: wvos.getZjInfoList()){
                        // 保险证
                        if (zj.getZjmc().trim().equals("保险证")){
                            // 获取保险证件数据
                            getgetWorkerCertGreeBx(wcgs, wcgids, wxg, workerId, zj, wcgzjs);
                            continue;
                        }
                                               
                        // 生成其他证件信息
                        getWorkerCertGreeOther(wcgs, wcgids, wcgzjs, wxg, workerId, zj);                        
                    }

                    if (wcgs.size()>0){
                        workerCertGreeService.saveOrUpdateBatch(wcgs);
                        wcgs.clear();
                    }
                    wxg.updateById();
                } else {
                    log.info("接口同步获取总部网点师傅证件信息失败-师傅证件信息:{} - {}", wxg.getSfzen(),response.getMsg());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                log.info("同步获取总部网点师傅证件信息失败-师傅证件信息:{}", wxg.getSfzen());
                throw new Exception("同步获取总部网点师傅证件信息失败");
            }
        }
    }

    private void getWorkerCertGreeOther(List<WorkerCertGree> wcgs, Map<String, String> wcgids, Map<String, String> wcgzjs, ItfTblWangdianWxgDownload wxg, String workerId, ZJInfo zj) throws ParseException {
        // 证件无变化时不修改
        if (wcgzjs.containsKey(workerId + wxg.getWdno() + zj.getZjmc()) &&
                wcgzjs.get(workerId + wxg.getWdno() + zj.getZjmc()).equals(zj.getZjlj())){
            return;
        }

        // 平台数据不存在且源数据无数据时不新增
        if (! wcgzjs.containsKey(workerId + wxg.getWdno() + zj.getZjmc()) && StringUtils.isEmpty(zj.getZjlj())){
            return;
        }

        // 生成其他证件对像
        workerCertGreeOther(wcgs, wcgids, wxg, workerId, zj);
    }

    private void workerCertGreeOther(List<WorkerCertGree> wcgs, Map<String, String> wcgids, ItfTblWangdianWxgDownload wxg, String workerId, ZJInfo zj) throws ParseException {
        String files="";
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(workerId);
        awc.setBrandWebsitId(wxg.getWdno());
        awc.setCertName(zj.getZjmc());
        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            awc.setCertNo(result.get(1));
        } else {
            awc.setCertNo(zj.getZjbh());
        }
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            awc.setStartTime(publicService.subOneYear(baseService.utcToDateStr(zj.getZjyxq())));
            awc.setExpireTime(baseService.utcToDateStr(zj.getZjyxq()));
        }
        if (StringUtils.isNotEmpty(zj.getZjfssj())){
            awc.setReviewTime(baseService.utcToDateStr(zj.getZjfssj()));
        }

        awc.setCreateTime(new Date());
        if (zj.getZjlj().contains(",")){
            List<String> result = Arrays.asList(zj.getZjlj().split(","));
            awc.setOutFileUrl(result.get(0));
            if (result.size() == 2){
                awc.setOutFileUrl2(result.get(1));
            } else {
                for (int i=1;i<result.size();i++){
                    files = files + result.get(i) + ",";
                }
                awc.setOutFileUrl2(files.substring(0,files.length()-1));
            }
        } else {
            awc.setOutFileUrl(zj.getZjlj());
        }

        publicService.setCertFlag(zj.getZjmc(), awc);
        // 存在进行修改
        publicService.setWorkerCertGreeId(awc, wcgids);
        wcgs.add(awc);
    }

    private void getgetWorkerCertGreeBx(List<WorkerCertGree> wcgs,
                                        Map<String, String> wcgids, ItfTblWangdianWxgDownload wxg,
                                        String workerId, ZJInfo zj, Map<String,String> wcgzjs) throws ParseException {
        // 证件无变化时不修改
        if (wcgzjs.containsKey(workerId + wxg.getWdno() + zj.getZjmc()) &&
                wcgzjs.get(workerId + wxg.getWdno() + zj.getZjmc()).equals(zj.getZjlj())){
            return;
        }
        
        // 平台数据不存在且源数据无数据时不新增
        if (! wcgzjs.containsKey(workerId + wxg.getWdno() + zj.getZjmc()) && StringUtils.isEmpty(zj.getZjlj())){
            return;
        }
        
        // 生成保险证件数据对像
        WorkerCertGreeBx(wcgs, wcgids, wxg, workerId, zj);
    }

    private void WorkerCertGreeBx(List<WorkerCertGree> wcgs, Map<String, String> wcgids,
                                  ItfTblWangdianWxgDownload wxg, String workerId, ZJInfo zj) throws ParseException {
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(workerId);
        awc.setBrandWebsitId(wxg.getWdno());
        awc.setCertName("保险证");
        awc.setSafeCompany("人保");
        // 保险公司及编号
        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            awc.setSafeCompany(result.get(0));
            awc.setCertNo(result.get(1));
        } else {
            awc.setCertNo(zj.getZjbh());
        }

        // 有效期
        awc.setStartTime(publicService.getYearFirstDay(new Date()));
        awc.setExpireTime(publicService.getYearLastDay(new Date()));
        awc.setReviewTime(publicService.getYearLastDay(new Date()));
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            awc.setStartTime(publicService.subOneYear(baseService.utcToDateStr(zj.getZjyxq())));
            awc.setExpireTime(baseService.utcToDateStr(zj.getZjyxq()));
        }
        if (StringUtils.isNotEmpty(zj.getZjfssj())){
            awc.setReviewTime(baseService.utcToDateStr(zj.getZjfssj()));
        }

        awc.setCreateTime(new Date());
        if (StringUtils.isNotEmpty(zj.getZjlj())){
            awc.setOutFileUrl(zj.getZjlj());
        }
        // 保险证
        awc.setCertFlag(2);
        // 存在进行修改
        publicService.setWorkerCertGreeId(awc, wcgids);
        wcgs.add(awc);
    }


    @Override
    public void extractedCertInfo() throws Exception {
        WangdianWxgVos wvos = new WangdianWxgVos();
        List<WorkerCert> addList = new ArrayList<>();
        Map<String,Object> req = new HashMap<>();
        Map<String,List<Worker>> workerIdcardMap = new HashMap<>();
        Map<String,List<Worker>> workerWorkeridMap = new HashMap<>();
        List<ItfTblWangdianWxgDownload> wxgDownladRecs = new ArrayList<>();
        Map<String,WorkerCert> workerIdCertNamesObjMaps = new HashMap<>();
        List<WebsitWorker> upWebsitWorkers = new ArrayList<>();

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

        // 提取现有的师傅证件信息
        List<WorkerCert> wcs = workerCertService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(wcs)){
            wcs.stream().forEach(event->{
                workerIdCertNamesObjMaps.put(event.getWorkerId() + event.getCertName(),event);
            });
            wcs.clear();
        }

        List<Worker> oldWorkerRec =  workerService.lambdaQuery()
                .select(Worker::getIdcard,Worker::getWorkerId,Worker::getWorkerName,Worker::getMobile).list();
        if (CollectionUtils.isNotEmpty(oldWorkerRec)){
            workerIdcardMap = oldWorkerRec.stream().collect(Collectors.groupingBy(Worker::getIdcard));
            workerWorkeridMap = oldWorkerRec.stream().collect(Collectors.groupingBy(Worker::getWorkerId));
            oldWorkerRec.clear();
        }

        List<WebsitWorker> wws = websitWorkerService.lambdaQuery().list();
//        if (CollectionUtils.isNotEmpty(wws)){
//            wws.stream().forEach(event->{
//                websitWorderwidwdidMap.put(event.getWorkerId() + event.getWebsitId(),event);
//            });
//            wws.clear();
//        }

        // 提取格力现有的网点师傅数据信息
        wxgDownladRecs =  itfTblWangdianWxgDownloadService.lambdaQuery()
                .eq(ItfTblWangdianWxgDownload::getCertStatus,0)
                .le(ItfTblWangdianWxgDownload::getCertTimes,10)
                // .eq(ItfTblWangdianWxgDownload::getSfzen,"421102198705313212")// 测试用
                // .eq(ItfTblWangdianWxgDownload::getWdno,"S2106139")// 测试用
                .like(ItfTblWangdianWxgDownload::getWdno,"S%").list();


        for (ItfTblWangdianWxgDownload wxg :wxgDownladRecs){
            // 平台师傅信息不包含格力总部的数据不处理(包含的为格力的师傅信息同步时已生成了worker)
            // 这里用身份证来做包含关系(测试环境身份证隐藏* 需加名称及手机号)
            String workerId = checkIsGreeWroker(workerIdcardMap, wxg);
            if (workerId.length()<1) {
                continue;
            }
            // 参数 获取网点维修工信息
            getParameter(wxg.getWdno(), wxg.getWxgno(), req);
            // log.info("总部获取的工程师证件照信息wdno :{}", wxg.getWdno());

            try {
                // 格力总部查询工程师信息
                GreeResponseHelper response = greeLogic.greePost(wdqyapi, JSONObject.toJSONString(req), publicService.getCompanyId(wxg.getWdno()));
                // log.info("总部获取的工程师证件照信息 response :{}", JSONObject.toJSONString(response));
                // 失败不处理
                if (response.getStatus() == 200){
                    wxg.setCertStatus(1);
                    WxgQueryInfo resultDatax = JSONObject.parseObject(response.getData().toString(), WxgQueryInfo.class);
                    // 无证件不处理
                    if ( resultDatax.getWangdianWxgVos().size()<1){
                        wxg.updateById();
                        continue;
                    }

                    wvos = resultDatax.getWangdianWxgVos().get(0);
                    // log.info("总部获取的工程师证件照信息wvos:{}", JSONObject.toJSONString(wvos));

                    // 同步-新增证件信息
                    getCertInfo(wvos, addList, workerId, wxg.getWdno(),
                            workerWorkeridMap, wws,
                            upWebsitWorkers, workerIdCertNamesObjMaps);

                    // 新增或修改(证件)
                    addDataCert(addList);
                    // 修改保险信息
                    upWebsitWorker(upWebsitWorkers);
                    wxg.setCertTimes(0);
                    // log.info("工程师证件照信息同步成功-师傅证件信息:{}", wxg.getSfzen());
                } else {
                    wxg.setCertTimes(wxg.getCertTimes() + 1);
                    log.info("获取工程师证件照信息失败-师傅证件信息:{} {}", wxg.getSfzen(),response.getMsg());
                    wxg.setCertSynErrMsg(response.getMsg());
                    if (response.getMsg().length()>128){
                        wxg.setCertSynErrMsg(response.getMsg().substring(0,126));
                    }
                }
                wxg.updateById();
            } catch (Exception ex) {
                ex.printStackTrace();
                log.info("工程师证件照信息同步失败-师傅证件信息:{}", wxg.getSfzen());
                wxg.setCertTimes(wxg.getCertTimes() + 1);
                wxg.updateById();
                throw new Exception("工程师证件照信息同步失败");
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void addBxInfoBak(@NotNull List<InsureWorkerCommercial> insurecs, List<InsureWorkerCommercialFile> insurefiles) {
        if (insurecs.size()>0){
            insureWorkerCommercialService.saveOrUpdateBatch(insurecs);
            insurecs.clear();
        }
        if (insurefiles.size()>0){
            insureWorkerCommercialFileService.saveOrUpdateBatch(insurefiles);
            insurefiles.clear();
        }
    }

    @Override
    public void extractedCert() {

        //测试用
        //List<String> workerIds = Arrays.asList("S13430387965","S18229336122");

        List<WorkerCert> workerCertList = new ArrayList<>();
        List<WorkerCert> workerCertUpList = new ArrayList<>();
        // 提取需要处理的证件照数据

        workerCertList = workerCertService.lambdaQuery()
                .eq(WorkerCert::getOutZjljProcess,0)
                //.in(WorkerCert::getWorkerId,workerIds)
                // .eq(WorkerCert::getWorkerId,"S18229336122")// 测试用
                .isNotNull(WorkerCert::getOutZjlj)
                .list();

        for (WorkerCert item :workerCertList){
            try{
                // 生成图片
                processCertInfo(item);
                workerCertUpList.add(item);
                updateWorkerCertInfo(workerCertUpList, 10);
            } catch (Exception ex) {
                ex.printStackTrace();
                updateWorkerCertInfo(workerCertUpList, 0);
                log.info("生成师傅证件照信息失败worker_cert.id= {}",item.getId());
            }
        }

        updateWorkerCertInfo(workerCertUpList, 0);
    }

    @Override
    public void extractedBxBak(){
        List<InsureWorkerCommercialFile> iwcfiles = new ArrayList<>();
        List<InsureWorkerCommercialFile> iwcfilesUpList = new ArrayList<>();
        // 提取需要处理的证件照数据

        iwcfiles = insureWorkerCommercialFileService.lambdaQuery()
                .eq(InsureWorkerCommercialFile::getOutZjljProcess,0)
                // .in(InsureWorkerCommercialFile::getId,"1696844130739736578","1696844133302456321","1696844133449256965")// 测试用
                .isNotNull(InsureWorkerCommercialFile::getOutZjlj).list();

        for (InsureWorkerCommercialFile item :iwcfiles){
            try{
                // 生成图片
                processBxInfoBak(item);
                iwcfilesUpList.add(item);

                updateBxInfoBak(iwcfilesUpList, 100);
            } catch (Exception ex) {
                ex.printStackTrace();
                updateBxInfoBak(iwcfilesUpList, 0);
                log.info("生成师傅证件照信息失败worker_cert.id= {}",item.getId());
            }
        }

        updateBxInfoBak(iwcfilesUpList, 0);
    }

    @Override
    public void extractedBx(){
        //测试用
        //List<String> workerIds = Arrays.asList("S13430387965","S18229336122");

        List<WebsitWorker> websitWorkers = new ArrayList<>();
        List<WebsitWorker> websitWorkerUpList = new ArrayList<>();

        // 提取需要处理的证件照数据
        websitWorkers = websitWorkerService.lambdaQuery()
                .eq(WebsitWorker::getOutZjljProcess,0)
                // .in(WebsitWorker::getWorkerId,"S18229336122")// 测试用
                .isNotNull(WebsitWorker::getOutZjlj).list();

        for (WebsitWorker item :websitWorkers){
            try{
                // 生成图片
                processBxInfo(item);
                websitWorkerUpList.add(item);

                updateBxInfo(websitWorkerUpList, 50);
            } catch (Exception ex) {
                ex.printStackTrace();
                updateBxInfo(websitWorkerUpList, 0);
                log.info("生成师傅证件照信息失败 websit_worker.websit_worker_id= {}",item.getWebsitWorkerId());
            }
        }

        updateBxInfo(websitWorkerUpList, 0);
    }

    @Override
    public void extractedMXFile(){
        List<OrderDetailFile> odfiles = new ArrayList<>();
        List<OrderDetailFile> odfilesUpList = new ArrayList<>();

        odfiles = orderDetailFileService.lambdaQuery()
                .eq(OrderDetailFile::getOutZjljProcess,0)
                .isNotNull(OrderDetailFile::getOutPicture).list();

        for (OrderDetailFile item :odfiles){
            try{
                // 生成图片
                processMXFileInfo(item);
                odfilesUpList.add(item);

                updateMXFile(odfilesUpList, 10);
            } catch (Exception ex) {
                ex.printStackTrace();
                updateMXFile(odfilesUpList, 0);
                log.info("生成商户到平台采集图信息失败order_detail_file.id= {}",item.getId());
            }
        }

        updateMXFile(odfilesUpList, 0);
    }

    @Override
    public void extractedTMSYFile(){
        List<OrderInstallDetailCode> odfiles = new ArrayList<>();
        List<OrderInstallDetailCode> odfilesUpList = new ArrayList<>();

        odfiles = orderInstallDetailCodeService.lambdaQuery()
                .eq(OrderInstallDetailCode::getOutZjljProcess,0)
                .isNotNull(OrderInstallDetailCode::getOutPicture).list();

        for (OrderInstallDetailCode item :odfiles){
            try{
                // 生成图片
                processSYTMFileInfo(item);
                odfilesUpList.add(item);

                updateSYTMFile(odfilesUpList, 10);
            } catch (Exception ex) {
                ex.printStackTrace();
                updateSYTMFile(odfilesUpList, 0);
                log.info("生成商户到平台采集条码图信息失败order_install_detail_code.id= {}",item.getId());
            }
        }

        updateSYTMFile(odfilesUpList, 0);
    }


    private void updateWorkerCertInfo(List<WorkerCert> workerCertUpList, int i) {
        if (workerCertUpList.size() > i) {
            for (WorkerCert x:workerCertUpList){
                if (x.getId().length()==19){
                    log.info("证件图师傅ID出错 B: {}",x.getWorkerId());
                }
            }

            workerCertService.updateBatchById(workerCertUpList);
            workerCertUpList.clear();
        }
    }

    private void updateBxInfoBak(List<InsureWorkerCommercialFile> iwcfilesUpList, int i) {
        if (iwcfilesUpList.size() > i) {
            insureWorkerCommercialFileService.updateBatchById(iwcfilesUpList);
            iwcfilesUpList.clear();
        }
    }

    private void updateBxInfo(List<WebsitWorker> websitWorkerUpList, int i) {
        if (websitWorkerUpList.size() > i) {
            websitWorkerService.updateBatchById(websitWorkerUpList);
            websitWorkerUpList.clear();
        }
    }

    private void updateMXFile(List<OrderDetailFile> iwcfilesUpList, int i) {
        if (iwcfilesUpList.size() > i) {
            orderDetailFileService.updateBatchById(iwcfilesUpList);
            iwcfilesUpList.clear();
        }
    }

    private void updateSYTMFile(List<OrderInstallDetailCode> iwcfilesUpList, int i) {
        if (iwcfilesUpList.size() > i) {
            orderInstallDetailCodeService.updateBatchById(iwcfilesUpList);
            iwcfilesUpList.clear();
        }
    }

    private void upWebsitWorker(List<WebsitWorker> websitWorkerUp) {
        if (websitWorkerUp.size()>0){
            websitWorkerService.saveOrUpdateBatch(websitWorkerUp);
            websitWorkerUp.clear();
        }
    }

    private String checkIsGreeWroker(Map<String, List<Worker>> workerIdcardMap, ItfTblWangdianWxgDownload wxg) {
        String workerId="";
        if (workerIdcardMap.containsKey(wxg.getSfzen())){
            workerId = workerIdcardMap.get(wxg.getSfzen()).get(0).getWorkerId();
        }
        return workerId;
    }

    @Override
    public void extractedAddCategory() throws Exception {
        List<WorkerBrandAccount> workerBrandAccounts = new ArrayList<>();
        Map<String,List<Worker>> Worker_Idcards = new HashMap<>();
        Map<String, List<SysDictRef>> sysDictRefMap = new HashMap<>();
        List<SysDictRef> sysDictRef = new ArrayList<>();
        // 提取品牌信息
        Brand brand = baseService.getBrand();
        if (brand == null) {
            return;
        }

        // 提取品牌商对应的大类信息
        sysDictRef =  sysDictRefService.lambdaQuery()
                .select(SysDictRef::getDictCode,SysDictRef::getDictValue,SysDictRef::getRefDictCode)
                .eq(SysDictRef::getBrandId, brand.getBrandId())
                .eq(SysDictRef::getDictType, DictTypeEnum.DICT_TYPE_MAIN_TYPE.getCode())
                .list();
        if (CollectionUtils.isNotEmpty(sysDictRef)){
            sysDictRefMap = sysDictRef.stream().
                    collect(Collectors.groupingBy(SysDictRef::getRefDictCode));
        }

        // 字典表中查出ID 格力只有-家电售后
        SysDict serviceCategoryDict =  sysDictService.lambdaQuery()
                .eq(SysDict::getDictType, ServiceCategoryEnum.DICT_TYPE_SERVICE_CATEGORY.getCode())
                .eq(SysDict::getDictValue,ServiceCategoryEnum.DICT_TYPE_SERVICE_CATEGORY.getText())
                .last("limit 1")
                .one();
        if (serviceCategoryDict == null) {
            return;
        }

        List<Worker> oldWorkerRec =  workerService.lambdaQuery()
                .select(Worker::getIdcard,Worker::getWorkerId,Worker::getWorkerName,Worker::getMobile).list();
        if (CollectionUtils.isNotEmpty(oldWorkerRec)){
            Worker_Idcards = oldWorkerRec.stream().collect(Collectors.groupingBy(Worker::getIdcard));
        }

        List<WorkerServiceCategoryDetail> workerServiceCategoryDetailList = workerServiceCategoryDetailService.list();

        // 提取格力现有的网点师傅数据信息
        List<ItfTblWangdianWxgDownload> wxgRecs =  itfTblWangdianWxgDownloadService.lambdaQuery()
                .eq(ItfTblWangdianWxgDownload::getCategoryStatus,0)
                // .eq(ItfTblWangdianWxgDownload::getWdno,"S21A0365")// 测试用
                // .eq(ItfTblWangdianWxgDownload::getSfzen,"441229197909100475")// 测试用
                .eq(ItfTblWangdianWxgDownload::getFlag,DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())
                .like(ItfTblWangdianWxgDownload::getWdno,"S%").list();


        //本地提取商户师傅网点信息  商户网点对应平台网点存在一对多关系
        workerBrandAccounts = workerBrandAccountService.lambdaQuery()
                .eq(WorkerBrandAccount::getGroupCompanyId, brand.getBrandId())
                .eq(WorkerBrandAccount::getBrandWorkerStatus,"ON")
                .eq(WorkerBrandAccount::getDel,0)
                .isNotNull(WorkerBrandAccount::getBrandWorkerNumber)
                .isNotNull(WorkerBrandAccount::getBrandWebsitId)
                .list();
//        if (CollectionUtils.isNotEmpty(workerBrandAccounts)){
//            workerBrandAccountsMap = workerBrandAccounts.stream().collect(Collectors.groupingBy(WorkerBrandAccount::getBrandWorkerId));
//            workerBrandAccounts.clear();
//        }
        // 这里提取对应的商户网点信息

        // 提取所有师傅的服务大类信息 先内存中查询
//        wxgCategoryRec = workerServiceCategoryDetailService.lambdaQuery().list();
//        if (CollectionUtils.isNotEmpty(wxgCategoryRec)){
//            workerServiceCategoryDetailMap = wxgCategoryRec.stream().collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getWebsitWorkerId));
//        }

        for (final ItfTblWangdianWxgDownload wxgDownload :wxgRecs){
            long count = workerBrandAccounts.stream()
                    .filter(v -> StringUtils.equals(v.getBrandWorkerId(), String.valueOf(wxgDownload.getWxgid()))).count();
            if(count == 0)
                continue;

            // 状态无效不处理
            if (wxgDownload.getFlag() != null){
                if (!wxgDownload.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                    wxgDownload.setCategoryStatus(1);
                    wxgDownload.updateById();
                    continue;
                }
            }
            // 师傅在平台中不存在时不处理
            String workerId = checkIsGreeWroker(Worker_Idcards, wxgDownload);
            if (StringUtils.isBlank(workerId)) {
                continue;
            }

            wxgCategoryQueryAdd(wxgDownload,workerBrandAccounts,workerServiceCategoryDetailList,serviceCategoryDict,sysDictRefMap);
            wxgDownload.setCategoryStatus(1);
            wxgDownload.updateById();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void addData(List<WorkerBrandAccount> wbaaddList, List<WorkerStreet> ws) {
        // 师傅所在品牌商网点信息同步
        if (wbaaddList.size()>0){
            workerBrandAccountService.saveBatch(wbaaddList);
        }

        // 同步-师傅地理位置
        if (ws.size()>0){
            workerStreetService.saveBatch(ws);
        }

        wbaaddList.clear();
        ws.clear();
    }


    @Override
    public void extractedwxgQueryAdd() throws Exception {
        WangdianWxgVos wvos = new WangdianWxgVos();
        List<WorkerBrandAccount> wbaaddList = new ArrayList<>();
        List<WorkerBrandAccount> wbarecs = new ArrayList<>();
        Map<String,Object> req = new HashMap<>();
        List<WorkerStreet> ws = new ArrayList<>();
        Map<String, List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs = new HashMap<>();

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

        // 网点对应关系
        List<CustomerInformationWebsit> ciws = customerInformationWebsitService.lambdaQuery()
                .select(CustomerInformationWebsit::getWebsitId,
                        CustomerInformationWebsit::getRefWebsitId).list();
        if (ciws ==null || ciws.size()<1){
            return;
        }

        List<Worker> oldWorkerRec =  workerService.lambdaQuery()
                .select(Worker::getWorkerId).list();
        List<String> oldWorkers = oldWorkerRec.stream().map(Worker::getWorkerId).collect(Collectors.toList());

        // 提取对应的服务商网点信息
        List<Websit> websits = websitService.lambdaQuery()
                .select(Websit::getWebsitId,
                        Websit::getWebsitName)
                .in(Websit::getWebsitId,ciws.stream().map(CustomerInformationWebsit::getWebsitId).collect(Collectors.toList()))
                .list();

        // 提取格力所有的网点信息
        List<ItfTblXinWangdianDownload> wdRecs = itfTblXinWangdianDownloadService.lambdaQuery()
                .select(ItfTblXinWangdianDownload::getPkGuid,
                        ItfTblXinWangdianDownload::getWdno).list();
        Map<String, List<ItfTblXinWangdianDownload>> mapWdRes = wdRecs.stream().
                collect(Collectors.groupingBy(ItfTblXinWangdianDownload::getWdno));

        // 提取格力现有的网点师傅数据信息
        List<ItfTblWangdianWxgDownload> wxgRecs =  itfTblWangdianWxgDownloadService.lambdaQuery()
                .select(ItfTblWangdianWxgDownload::getWxgid,
                        ItfTblWangdianWxgDownload::getWxgno,
                        ItfTblWangdianWxgDownload::getWdno,
                        ItfTblWangdianWxgDownload::getSfzen)
                // .eq(ItfTblWangdianWxgDownload::getWxgno,"S21A00200023")// 测试用 todo
                .like(ItfTblWangdianWxgDownload::getWdno,"S%").list();

        //本地提取商户师傅网点信息
        wbarecs = workerBrandAccountService.lambdaQuery()
                .eq(WorkerBrandAccount::getGroupCompanyId, brand.getBrandId())
                .eq(WorkerBrandAccount::getBrandWorkerStatus,"ON")
                .eq(WorkerBrandAccount::getDel,0)
                .isNotNull(WorkerBrandAccount::getBrandWorkerNumber)
                .isNotNull(WorkerBrandAccount::getBrandWebsitId)
                .list();

        // 提取品牌商对应的大类信息
        List<SysDictRef> sysDictRef =  sysDictRefService.lambdaQuery()
                .select(SysDictRef::getDictCode,SysDictRef::getDictValue,SysDictRef::getRefDictCode)
                .eq(SysDictRef::getBrandId, brand.getBrandId())
                .eq(SysDictRef::getDictType, DictTypeEnum.DICT_TYPE_MAIN_TYPE.getCode())
                .list();
        Map<String, List<SysDictRef>> sysDictRefMap = sysDictRef.stream().
                collect(Collectors.groupingBy(SysDictRef::getRefDictCode));

        // 提取所有师傅的服务大类信息 先内存中查询
        List<WorkerServiceCategoryDetail> wxgCategoryRec = workerServiceCategoryDetailService.lambdaQuery().list();
        Map<String, List<WorkerServiceCategoryDetail>> oldWxgCategoryRecMap = wxgCategoryRec.stream().collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getWorkerId));

        for (ItfTblWangdianWxgDownload wxg :wxgRecs){
            // 无效的数据不新增
            if (wxg.getFlag() != null){
                if (!wxg.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                    continue;
                }
            }
            if (!oldWorkers.contains(wxg.getSfzen())){
                continue;
            }

            // 提取本地商户师傅信息 按品牌，网点，师傅编号  存在对象不处理
            WorkerBrandAccount workerBrandAccount = getWorkerBrandAccountData(wbarecs, wxg);
            if (workerBrandAccount != null) {
                continue;
            }

            // 参数 获取网点维修工信息
            getParameter(wxg.getWdno(), wxg.getWxgno(), req);
            // 格力总部查询工程师信息
            GreeResponseHelper response = greeLogic.greePost(wdqyapi, JSONObject.toJSONString(req), publicService.getCompanyId(wxg.getWdno()));
            if (response.getStatus() == 200){
                WxgQueryInfo resultDatax = JSONObject.parseObject(response.getData().toString(), WxgQueryInfo.class);
                // 无信息不处理
                if ( resultDatax.getWangdianWxgVos().size()<1){
                    continue;
                }

                wvos = resultDatax.getWangdianWxgVos().get(0);

                // 提取师傅的服务大类信息 先内存中查询
                if (oldWxgCategoryRecMap.containsKey(wxg.getSfzen())){
                    wxgCategoryTypeRecs = oldWxgCategoryRecMap.get(wxg.getSfzen()).stream().
                            collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getType));

                } else {
                    List<WorkerServiceCategoryDetail> wxgCategoryRecs = workerServiceCategoryDetailService.lambdaQuery()
                            .eq(WorkerServiceCategoryDetail::getWorkerId, wxg.getSfzen()).list();

                    // 服务类型 INSTALL=安装 REPAIR=维修  DELIVERY=配送
                    wxgCategoryTypeRecs = wxgCategoryRecs.stream().
                            collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getType));
                }

                try {

                    // 生成师傅所在品牌商网点信息
                    if (getwbaInfo(wvos, wbaaddList, brand, ciws, websits, wxg, mapWdRes)) {
                        continue;
                    }

                    // 同步-新增师傅地理位置 生成对象失败不处理
                    if (getwz(wvos, ws, brand, wxg.getSfzen())){
                        continue;
                    }

                    // 新增或修改(证件,师傅地理位置,师傅服务的类目)
                    addData(wbaaddList, ws);

                } catch (Exception ex) {
                    log.info("工程师信息同步失败:{}", ex);
                }
            }
        }
    }


    @Override
    public void extracteWxgQueryAddWXGInfo() throws Exception {
        Map<String,Object> req = new HashMap<>();
        WangdianWxgVos wvos = new WangdianWxgVos();
        List<ItfTblWangdianPositionDownload> wdwxgadd = new ArrayList<>();

        List<Worker> oldWorkerRec =  workerService.lambdaQuery()
                .select(Worker::getWorkerId).list();
        List<String> oldWorkers = oldWorkerRec.stream().map(Worker::getWorkerId).collect(Collectors.toList());

        // 提取格力现有的网点师傅数据信息
        List<ItfTblWangdianWxgDownload> wxgRecs =  itfTblWangdianWxgDownloadService.lambdaQuery()
                .select(ItfTblWangdianWxgDownload::getWxgid,
                        ItfTblWangdianWxgDownload::getWxgno,
                        ItfTblWangdianWxgDownload::getWdno,
                        ItfTblWangdianWxgDownload::getSfzen,
                        ItfTblWangdianWxgDownload::getFlag)
                .like(ItfTblWangdianWxgDownload::getWdno,"S%").list();

        try {
            for (ItfTblWangdianWxgDownload wxg :wxgRecs) {
                // 无效的数据不新增
                if (wxg.getFlag() != null) {
                    if (!wxg.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())) {
                        continue;
                    }
                }

                // 师傅不存在不处理
                if (!oldWorkers.contains(wxg.getSfzen())) {
                    continue;
                }
                // 参数 获取网点维修工信息
                getParameter(wxg.getWdno(), wxg.getWxgno(), req);
                // 格力总部查询工程师信息
                GreeResponseHelper response = greeLogic.greePost(wdqyapi, JSONObject.toJSONString(req), publicService.getCompanyId(wxg.getWdno()));
                if (response.getStatus() == 200) {
                    WxgQueryInfo resultDatax = JSONObject.parseObject(response.getData().toString(), WxgQueryInfo.class);
                    // 无信息不处理
                    if (resultDatax.getWangdianWxgVos().size() < 1) {
                        continue;
                    }
                    wvos = resultDatax.getWangdianWxgVos().get(0);
                    // 新增
                    getwdwxdInfo(wvos, wdwxgadd);
                }
            }
            // 新增
            if (wdwxgadd.size() > 0) {
                itfTblWangdianPositionDownloadService.saveBatch(wdwxgadd);
                wdwxgadd.clear();
            }
        } catch (Exception ex) {
            log.info("同步网点维修工数据信息失败:{}", ex);
        }
    }

    private void getwdwxdInfo(WangdianWxgVos wvos, List<ItfTblWangdianPositionDownload> wdwxgadd) {
        ItfTblWangdianPositionDownload item = new ItfTblWangdianPositionDownload();
        BeanUtils.copyProperties(wvos,item);
        wdwxgadd.add(item);
        if (wdwxgadd.size()>=500){
            itfTblWangdianPositionDownloadService.saveBatch(wdwxgadd);
            wdwxgadd.clear();
        }
    }

    private void addWorkerStreet(WangdianWxgVos wvos, String brandId, List<WorkerStreet> ws, String sfzen) {
        WorkerStreet n = new WorkerStreet();
        n.setId(publicService.getUUID());
        n.setProvinceId("");
        n.setCityId("");
        n.setAreaId("");
        n.setStreetId("");
        n.setWorkerId(sfzen);
        n.setCreateTime(new Date());
        n.setCreateBy("system");


        // 提取省信息
        if (StringUtils.isNotEmpty(wvos.getSfen())){
            Province province = provinceService.lambdaQuery()
                    .eq(Province::getProvince, wvos.getSfen())
                    .last("limit 1")
                    .one();
            if (province !=null){
                List<BrandLbsRelate> bra = brandLbsRelateService.lambdaQuery()
                        .eq(BrandLbsRelate::getProvinceId,province.getProvinceId())
                        .eq(BrandLbsRelate::getDel,0)
                        .eq(BrandLbsRelate::getBrandId,brandId).list();
                if (bra != null && bra.size()>0){
                    for (BrandLbsRelate br :bra){
                        if (StringUtils.isNotEmpty(br.getLbsProvinceId()) && StringUtils.isEmpty(n.getProvinceId())){
                            n.setProvinceId(br.getLbsProvinceId());
                            n.setProvince(br.getLbsProvinceName());
                        }
                        if (StringUtils.isNotEmpty(br.getLbsCityId()) && StringUtils.isEmpty(n.getCityId())){
                            n.setCityId(br.getLbsCityId());
                            n.setCity(br.getLbsCityName());
                        }
                        if (StringUtils.isNotEmpty(br.getLbsDistrictId()) && StringUtils.isEmpty(n.getAreaId())){
                            n.setAreaId(br.getLbsDistrictId());
                            n.setArea(br.getLbsDistrictName());
                        }
                        if (StringUtils.isNotEmpty(br.getLbsStreetId()) && StringUtils.isEmpty(n.getStreetId())){
                            n.setStreet(br.getLbsStreetId());
                            n.setStreetId(br.getLbsStreetName());
                            break;
                        }
                    }
                    ws.add(n);
                }
            }
        }
    }

    private Boolean getwz(WangdianWxgVos wvos, List<WorkerStreet> ws, Brand brand, String sfzen) {
        // 师傅省市区街道信息
        List<WorkerStreet> wsOld = workerStreetService.lambdaQuery()
                .eq(WorkerStreet::getWorkerId, sfzen).list();
        // 不存在新增
        if (wsOld ==null || wsOld.size()<1){
            addWorkerStreet(wvos, brand.getBrandId(), ws,sfzen);
            if (ws.size()<1){
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }


    private boolean getwbaInfo(WangdianWxgVos wvos, List<WorkerBrandAccount> wbaaddList, Brand brand,
                               List<CustomerInformationWebsit> ciws, List<Websit> websits,
                               ItfTblWangdianWxgDownload wxg, Map<String, List<ItfTblXinWangdianDownload>> mapWdRes) {
        String websitId ="";
        String websitName ="";

        // 品牌网点与商户网点对关系表中提取品牌方的网点信息  无数据不处理，对应关系需要人为操作
        for (CustomerInformationWebsit wd: ciws){
            if (wd.getRefWebsitId().equals(wxg.getWdno())){
                websitId=wd.getWebsitId();
            }
        }
        if (StringUtils.isEmpty(websitId)){
            return true;
        }

        for (Websit wets: websits){
            if (wets.getWebsitId().equals(websitId)){
                websitName = wets.getWebsitName();
                break;
            }
        }

        // 新增 WorkerBrandAccount todo
        WorkerBrandAccount n = new WorkerBrandAccount();
        n.setId(IdWorker.getIdStr());
        // n.setWorkerId(wxg.getSfzen());
        n.setWebsitId(websitId);
        n.setWebsitName(websitName);
        n.setGroupCompanyId(brand.getBrandId());
        n.setBrandWorkerId(String.valueOf(wxg.getWxgid()));
        n.setBrandWorkerNumber(wxg.getWxgno());
        if (mapWdRes.get(wxg.getWdno()).size()>0){
            n.setBrandWebsitName(mapWdRes.get(wxg.getWdno()).get(0).getWdmc());
        }
        n.setBrandWebsitId(wxg.getWdno());
        n.setBrandWorkerStatus("ON");
        if (wvos.getFlag().equals("无效")){
            n.setBrandWorkerStatus("OFF");
        }
        n.setExpireTime(new Date());
        n.setCreateTime(new Date());
        n.setCreateBy("system");
        wbaaddList.add(n);
        return false;
    }

    public void addDataCert(List<WorkerCert> addList) {
        // 证件同步
        if (addList.size()>0){
            for (WorkerCert i:addList){
                if (i.getId().length()==19){
                    log.info("证件图师傅ID出错 {}",i.getWorkerId());
                }
            }



            workerCertService.saveOrUpdateBatch(addList);
            addList.clear();
        }
    }

    private String putCert(String image) throws IOException {
        String fileId = "";
        String id = publicService.path(image);
        File newFile = publicService.createf(id);

        try{
            baseService.saveToFile(greeLogic.greeFileUrl(image), newFile);
            ossUtil.uploadFile(id, newFile);
            fileId = id;
            return fileId;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("生成师傅证件照信息失败" + image);
        }
        return fileId;
    }

    private void workerBXAdd(ZJInfoBX bx, List<WebsitWorker> websitWorkerUp) throws Exception {
        ZJInfo zj = new ZJInfo();
        zj=bx.getZjInfo();

        // 保单号+名称
        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            bx.getWebsitWorker().setSafeCompany(result.get(0));
            bx.getWebsitWorker().setSafeNo(result.get(1));
        } else {
            bx.getWebsitWorker().setSafeNo(zj.getZjbh());
        }

        // 有效期
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            bx.getWebsitWorker().setGmbxyxq(baseService.utcToDateStr(zj.getZjyxq()));
        }

        // 保险照
        String id = putCert(zj.getZjlj());
        if (StringUtils.isNotEmpty(id)){
            bx.getWebsitWorker().setOutInsureCert(id);
        }
        new File(id).delete();

        websitWorkerUp.add(bx.getWebsitWorker());
    }

    private void workercertAdd(WangdianWxgVos wvos, List<WorkerCert> addList, String workerId,
                               ZJInfoC zjinfo, String workerName) throws Exception {
        ZJInfo zj = new ZJInfo();
        zj=zjinfo.getZjInfo();

        // 新增
        WorkerCert add = new WorkerCert();
        if (zjinfo.getWorkerCert() !=null){
            MyBeanUtils.copyProperties(zjinfo.getWorkerCert(),add);
        } else {
            setAdd(wvos, workerId, workerName, zj, add);
        }

        if (zj.getZjlj().contains(",")){
            List<String> result = Arrays.asList(zj.getZjlj().split(","));
            // 上传图片
            String id = putCert(result.get(0));
            if (StringUtils.isNotEmpty(id)){
                add.setFileUrl(id);
                add.setOutFileUrl(result.get(0));
            }

            String id2 = putCert(result.get(1));
            if (StringUtils.isNotEmpty(id2)){
                add.setFileUrl2(id2);
                add.setOutFileUrl2(result.get(1));
            }
            new File(id).delete();
            new File(id2).delete();
        } else {
            String id = putCert(zj.getZjlj());
            if (StringUtils.isNotEmpty(id)){
                add.setFileUrl(id);
                add.setOutFileUrl(zj.getZjlj());
            }
            new File(id).delete();
        }
        addList.add(add);
    }


    private void processCertInfo(WorkerCert workerCert) throws Exception {
        String files = "";
        String fileos = "";
        String id2 = "";
        if (workerCert.getOutZjlj().contains(",")){
            Boolean flag = Boolean.TRUE;
            List<String> result = Arrays.asList(workerCert.getOutZjlj().split(","));
            // 上传图片
            if (StringUtils.isNotEmpty(result.get(0)) && StringUtils.isEmpty(workerCert.getFileUrl())){
                String id = putCert(result.get(0));
                if (StringUtils.isNotEmpty(id)){
                    workerCert.setFileUrl(id);
                    workerCert.setOutFileUrl(result.get(0));
                    new File(id).delete();
                } else {
                    flag = Boolean.FALSE;
                    workerCert.setOutSyncErrorMsg("生成师傅证件照信息失败:" + result.get(0));
                }
            }
            if (StringUtils.isNotEmpty(result.get(1)) && StringUtils.isEmpty(workerCert.getFileUrl2())){
                // 这里可能存在多个证件
                if (result.size() == 2){
                    id2 = putCert(result.get(1));
                    if (StringUtils.isNotEmpty(id2)){
                        workerCert.setFileUrl2(id2);
                        workerCert.setOutFileUrl2(result.get(1));
                        new File(id2).delete();
                    } else {
                        flag = Boolean.FALSE;
                        workerCert.setOutSyncErrorMsg("生成师傅证件照信息失败:" + result.get(1));
                    }
                } else {
                    for (int i=1;i<result.size();i++){
                        id2 = putCert(result.get(i));
                        if (StringUtils.isNotEmpty(id2)){
                            files = files + id2 + ",";
                            fileos = fileos + result.get(i);
                            new File(id2).delete();
                        } else {
                            flag = Boolean.FALSE;
                            workerCert.setOutSyncErrorMsg("生成师傅证件照信息失败:" + result.get(i));
                            break;
                        }
                    }
                    if (StringUtils.isNotEmpty(files)){
                        workerCert.setFileUrl2(files.substring(0,files.length()-1));
                        workerCert.setOutFileUrl2(fileos.substring(0,fileos.length()-1));
                    }
                }
            }

            if (flag){
                workerCert.setOutZjljProcess(1);
            }
            workerCert.setOutSyncTime(new Date());
        } else {
            if (StringUtils.isNotEmpty(workerCert.getOutZjlj()) && StringUtils.isEmpty(workerCert.getFileUrl())){
                String id = putCert(workerCert.getOutZjlj());
                if (StringUtils.isNotEmpty(id)){
                    workerCert.setFileUrl(id);
                    workerCert.setOutFileUrl(workerCert.getOutZjlj());
                    workerCert.setOutZjljProcess(1);
                    workerCert.setOutSyncTime(new Date());
                    new File(id).delete();
                } else {
                    workerCert.setOutSyncErrorMsg("生成师傅证件照信息失败:" + workerCert.getOutZjlj());
                }
            }
        }
    }

    private void processBxInfoBak(InsureWorkerCommercialFile iwcfile) throws IOException {
        if (StringUtils.isNotEmpty(iwcfile.getOutZjlj()) && StringUtils.isEmpty(iwcfile.getFileUrl())){
            String id = putCert(iwcfile.getOutZjlj());
            if (StringUtils.isNotEmpty(id)){
                iwcfile.setFileUrl(id);
                iwcfile.setOutZjljProcess(1);
                iwcfile.setCreateTime(new Date());
                new File(id).delete();
            }
        } else {
            iwcfile.setOutZjljProcess(1);
            iwcfile.setCreateTime(new Date());
        }
    }

    private void processBxInfo(WebsitWorker websitWorker) throws IOException {
        if (StringUtils.isNotEmpty(websitWorker.getOutZjlj())){
            // 多个附件处理
            if (websitWorker.getOutZjlj().contains(",")){
                Boolean flag = Boolean.TRUE;
                int num=0;
                String insureFiles = "";
                String outInsureCert = "";

                List<String> result = Arrays.asList(websitWorker.getOutZjlj().split(","));

                // 上传图片
                for (String p:result){
                    String id = putCert(p);
                    if (StringUtils.isNotEmpty(id)){
                        if (num==0){
                            insureFiles=id;
                            outInsureCert=p;
                        } else {
                            insureFiles=insureFiles+","+id;
                            outInsureCert=outInsureCert+","+p;
                        }
                        websitWorker.setInsureFiles(insureFiles);
                        websitWorker.setOutInsureCert(outInsureCert);
                        new File(id).delete();
                    } else {
                        flag = Boolean.FALSE;
                        websitWorker.setSyncErrorMsg("生成师傅保险证件照信息失败:" + p);
                    }
                    num = num +1 ;
                }
                if (flag){
                    websitWorker.setOutZjljProcess(1);
                }
            } else {
                String id = putCert(websitWorker.getOutZjlj());
                if (StringUtils.isNotEmpty(id)){
                    websitWorker.setInsureFiles(id);
                    websitWorker.setOutInsureCert(websitWorker.getOutZjlj());
                    websitWorker.setOutZjljProcess(1);
                    new File(id).delete();
                } else {
                    websitWorker.setSyncErrorMsg("生成师傅保险证件照信息失败:" + websitWorker.getOutZjlj());
                }
            }
        }
    }

    private void processMXFileInfo(OrderDetailFile iwcfile) throws IOException {
        if (StringUtils.isNotEmpty(iwcfile.getOutPicture())){
            String id = putCert(iwcfile.getOutPicture());
            if (StringUtils.isNotEmpty(id)){
                iwcfile.setFilePath(id);
                iwcfile.setBrandFilePath(iwcfile.getOutPicture());
                iwcfile.setOutZjljProcess(1);
                iwcfile.setCreateTime(new Date());
                new File(id).delete();
            }

        } else {
            iwcfile.setOutZjljProcess(1);
        }
    }

    private void processSYTMFileInfo(OrderInstallDetailCode iwcfile) throws IOException {
        if (StringUtils.isNotEmpty(iwcfile.getOutPicture())){
            String id = putCert(iwcfile.getOutPicture());
            if (StringUtils.isNotEmpty(id)){
                iwcfile.setPath(id);
                iwcfile.setGreeImageId(iwcfile.getOutPicture());
                iwcfile.setOutZjljProcess(1);
                iwcfile.setCreateTime(new Date());
                new File(id).delete();
            }

        } else {
            iwcfile.setOutZjljProcess(1);
        }
    }

    private void setAdd(WangdianWxgVos wvos, String workerId, String workerName, ZJInfo zj, WorkerCert add) throws ParseException {
        add.setId(publicService.getUUID());
        add.setWorkerId(workerId);
        add.setCertName(zj.getZjmc().trim());
        add.setName(workerName);


        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            add.setCertNo(result.get(1));
        } else {
            add.setCertNo(zj.getZjbh());
        }
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            add.setExpireTime(baseService.utcToDateStr(zj.getZjyxq()));
        }
        if (StringUtils.isNotEmpty(zj.getZjfssj())){
            add.setReviewTime(baseService.utcToDateStr(zj.getZjfssj()));
        }
        // add.setExamineStatus("OK");
        add.setSex(wvos.getXingb());
        add.setOutSyncStatus(1);
        add.setOutSyncTime(new Date());
    }

    private void getCertInfo(WangdianWxgVos wvos, List<WorkerCert> addList, String workerId,
                             String wdno, Map<String,List<Worker>> workerWorkeridMap,
                             List<WebsitWorker> websitWorkers,
                             List<WebsitWorker> upWebsitWorkers, Map<String,WorkerCert> workerIdCertNamesObjMaps) throws ParseException {
        Map<String, WebsitWorker> websitWorderwidwdidMap = websitWorkers.stream()
                .collect(Collectors.toMap(v -> v.getWorkerId()+v.getWebsitId(),Function.identity()));
        // 同步-新增证件信息
        for (ZJInfo zj: wvos.getZjInfoList()){
            // 保险证
            if (zj.getZjmc().trim().equals("保险证")){
                /*// 师傅所在网点数据未下载保险证件时才可以下载
                if (!addBxWorkers.containsKey(workerId)){
                    continue;
                }*/
                // 同家用、同总包、同自建或合作共用保险数据，使用其中有效期最大的

                // 获取保险证件数据
                produceBXInfo(workerId, wdno,  zj,websitWorderwidwdidMap, upWebsitWorkers);

                continue;
            }

            // 生成其他证件信息
            produceCert(wvos, addList, workerId, workerWorkeridMap, zj, workerIdCertNamesObjMaps);
        }
    }



    private void produceCert(WangdianWxgVos wvos, List<WorkerCert> addList, String workerId,
                             Map<String, List<Worker>> workerWorkeridMap, ZJInfo zj,
                             Map<String,WorkerCert> workerIdCertNamesObjMaps) throws ParseException {

        // 证件名称锁定重复   证件照相同，有效期相同不更新
        // 这里的证件有总部的，也有平台自建的，总部同步的一定会放在OutZjlj，自建的一定是file_url有值OutZjlj为空
        if (workerIdCertNamesObjMaps.containsKey(workerId + zj.getZjmc())){
            if (checkParameter(workerId, zj, workerIdCertNamesObjMaps)) {
                return;
            }
        }
        // 新增或修改
        addNewWorkerCert(wvos, addList, workerId, workerWorkeridMap.get(workerId).get(0).getWorkerName(), workerIdCertNamesObjMaps, zj);
    }

    private boolean checkParameter(String workerId, ZJInfo zj, Map<String, WorkerCert> workerIdCertNamesObjMaps) throws ParseException {
        // 证件内容相同有效期相同不同步
        WorkerCert wc = workerIdCertNamesObjMaps.get(workerId + zj.getZjmc());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ptzjlj = "";
        String ptzjbh = "";
        String ptzjfssj = "";
        String ptzjyxq = "";
        String zjbh = "";
        String zjfssj = "";
        String zjyxq = "";
        if (StringUtils.isNotEmpty(wc.getOutZjlj())){
            ptzjlj = wc.getOutZjlj();
        }
        if (StringUtils.isNotEmpty(wc.getCertNo())){
            ptzjbh = wc.getCertNo();
        }
        if (wc.getReviewTime() != null){
            ptzjfssj = sdf.format(wc.getReviewTime());
        }
        if (StringUtils.isNotEmpty(zj.getZjfssj())){
            zjfssj = sdf.format(baseService.utcToDateStr(zj.getZjfssj()));
        }
        if (wc.getExpireTime() != null){
            ptzjyxq = sdf.format(wc.getExpireTime());
        }
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            zjyxq = sdf.format(baseService.utcToDateStr(zj.getZjyxq()));
        }
        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            zjbh = result.get(1);
        } else {
            zjbh = zj.getZjbh();
        }

        // 总部有证件，平台有自建证件
        // 总同步下来的证件 如无变动不更新   (OutZjlj有值即来自总部)
        // 1:OutZjlj有值;2:证件相同;3:证件编号相同;4:证件复审时间;5:证件有效期
        if (StringUtils.isNotEmpty(ptzjlj) &&
                StringUtils.isNotEmpty(zj.getZjlj()) && zj.getZjlj().equals(ptzjlj) &&
                ptzjbh.equals(zjbh) &&
                ptzjfssj.equals(zjfssj) &&
                ptzjyxq.equals(zjyxq)){
            return true;
        }
        // 若存在有效期，有效期需变大才可以更新
        if (StringUtils.isNotEmpty(zj.getZjlj()) && zj.getZjlj().equals(ptzjlj) &&
                ptzjbh.equals(zjbh) &&
                ptzjfssj.equals(zjfssj) &&
                ptzjyxq.compareTo(zjyxq)>0){
            return true;
        }
        return false;
    }

    /**
     * 保险证单独处理 只有修改无需新增操作
     * websit.category_type决定保险类型 自建+不为商用(家用)其他商用
     * 家用 insure_worker_record
     * 商用 insure_worker_commercial 商用才操作，最有效期最后的那个
     * websit_worker
     *
     * 统一入商用保险，有多少份入多少份
     */
//    private boolean produceBXInfoBak(String workerId, String wdno, Map<String, List<Worker>> workerWorkeridMap,
//                                  List<InsureWorkerCommercial> insurecs, List<InsureWorkerCommercialFile> insurefiles,
//                                  List<String> insureworkeridandWebsitids, ZJInfo zj,
//                                  Map<String, WebsitWorker> websitWorderwidwdidMap, Insure insure) throws ParseException {
//        // 提取商户售后网点对应的平台售后网点信息 存在一对多的关系 无对应关系退出不处理
//        List<WebsitOrderSign> wos = publicService.shShwdToptshwdByBrandWebsitNo(wdno);
//        if (CollectionUtils.isEmpty(wos)){
//            return true;
//        }
//
//        // 生成商用保险对像 网点多对1时每个网点放一份
//        for (WebsitOrderSign item : wos){
//            // 防重
//            if (insureworkeridandWebsitids.contains(workerId +item.getWebsitId())){
//                continue;
//            }
//
//            // 对于在商户网点师傅都为无效的状态时在平台网点师傅表中可能是不存在的 需要排除掉
//            String websitWorkerId = checkWebsitWorker(workerId, websitWorderwidwdidMap, item);
//            if (websitWorkerId == null) {
//                continue;
//            }
//
//            // 生成商用保险对像
//            InsureWorkerCommercial a = getInsureWorkerCommercial(workerId, workerWorkeridMap, insurecs, zj, item,websitWorkerId, insure);
//
//            // 生成附件对像
//            getInsureWorkerCommercialFile(insurefiles, zj, a);
//
//            insureworkeridandWebsitids.add(workerId +item.getWebsitId());
//        }
//        return false;
//    }

    private void produceBXInfo(String workerId, String wdno, ZJInfo zj,
                                  Map<String, WebsitWorker> websitWorderwidwdidMap,
                                  List<WebsitWorker> upWebsitWorkers) throws ParseException {
        // 提取商户售后网点对应的平台售后网点信息 存在一对多的关系 无对应关系退出不处理
        List<WebsitOrderSign> wos = publicService.shShwdToptshwdByBrandWebsitNo(wdno);
        if (CollectionUtils.isEmpty(wos)){
            return;
        }

        // 生成保险对像 网点多对1时每个网点放一份
        for (WebsitOrderSign item : wos){
            // 防重  进行修改
            /*if (bxWorkerIdWebsitIds.contains(workerId +item.getWebsitId())){
                continue;
            }*/

            // 对于在商户网点师傅都为无效的状态时在平台网点师傅表中可能是不存在的 需要排除掉
            String websitWorkerId = checkWebsitWorker(workerId, websitWorderwidwdidMap, item);
            if (websitWorkerId == null) {
                continue;
            }

            /*// 提取师傅所在网点数据进行修改
            for (WebsitWorker w:addBxWorkers.get(workerId)){
                // 网点对应
                if (w.getWebsitId().equals(item.getWebsitId())){
                    // 获取师傅保险信息
                    getWebsitWorkerInfo(zj, upWebsitWorkers, w);
                    break;
                }
            }*/

            ///////////////////////////////////////////////////
            // 保险数据无变化时不处理
            WebsitWorker ww = getWebsitWorker(workerId, zj, websitWorderwidwdidMap, item);
            if (ww == null) {
                continue;
            }

            // 家用、同总包、同自建共用一份保险


            // 获取师傅保险信息
            getWebsitWorkerInfo(zj, upWebsitWorkers, ww, websitWorderwidwdidMap);
            //////////////////////////////////////////////////////
        }
    }

    @Nullable
    private WebsitWorker getWebsitWorker(String workerId, ZJInfo zj, Map<String, WebsitWorker> websitWorderwidwdidMap, WebsitOrderSign item) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ptzjlj = "";
        String ptzjbh = "";
        String ptSafeCompany = "";
        String ptzjyxq = "";
        String zjbh = "";
        String safeCompany = "";
        String zjyxq = "";

        WebsitWorker ww = websitWorderwidwdidMap.get(workerId + item.getWebsitId());

        if (StringUtils.isNotEmpty(ww.getOutZjlj())){
            ptzjlj = ww.getOutZjlj();
        }
        if (StringUtils.isNotEmpty(ww.getSafeNo())){
            ptzjbh = ww.getSafeNo();
        }
        if (StringUtils.isNotEmpty(ww.getSafeCompany())){
            ptSafeCompany = ww.getSafeCompany();
        }
        if (ww.getGmbxyxq() != null){
            ptzjyxq = sdf.format(ww.getGmbxyxq());
        }


        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            safeCompany = result.get(0);
            zjbh = result.get(1);
        } else {
            zjbh = zj.getZjbh();
        }
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            zjyxq = sdf.format(baseService.utcToDateStr(zj.getZjyxq()));
        }

        // 保险数据无变化时不处理
        // 总部有，平台有自建
        // 总同步下来的无变动不更新 (OutZjlj有值即来自总部)
        // 1:OutZjlj有值;2:证件相同;3:证件编号相同;4:保险公司相同;5:证件有效期相同
        if (StringUtils.isNotEmpty(ww.getOutZjlj()) &&
                StringUtils.isNotEmpty(zj.getZjlj()) && zj.getZjlj().equals(ptzjlj) &&
                ptzjbh.equals(zjbh) &&
                ptSafeCompany.equals(safeCompany) &&
                ptzjyxq.equals(zjyxq)){
            return null;
        }
        // 若存在有效期，有效期需变大才可以更新
        if (StringUtils.isNotEmpty(zj.getZjlj()) && zj.getZjlj().equals(ptzjlj) &&
                ptzjbh.equals(zjbh) &&
                ptSafeCompany.equals(safeCompany) &&
                ptzjyxq.compareTo(zjyxq)>0){
            return null;
        }
        return ww;
    }

    private void getWebsitWorkerInfo(ZJInfo zj, List<WebsitWorker> upWebsitWorkers, WebsitWorker w,
                                     Map<String, WebsitWorker> websitWorderwidwdidMap) throws ParseException {
        WebsitWorker upwwinfo = new WebsitWorker();
        MyBeanUtils.copyProperties(w,upwwinfo);


        upwwinfo.setInsureStatus(0);

        // 有效期
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            //upwwinfo.setInsureStartTime(publicService.subOneYear(baseService.utcToDateStr(zj.getZjyxq())));
            upwwinfo.setGmbxyxq(baseService.utcToDateStr(zj.getZjyxq()));
            //因总部没开始时间，直接以1年前set进去
            if(upwwinfo.getGmbxyxq() != null){
                upwwinfo.setInsureStartTime(DateUtil.offsetMonth(upwwinfo.getGmbxyxq(),-12));
            }
            Date n = new Date();
            if ((upwwinfo.getInsureStartTime().compareTo(n)<=0) &&
                    (upwwinfo.getGmbxyxq().compareTo(n)>=0)){
                upwwinfo.setInsureStatus(2);
            }
        }

        upwwinfo.setInsureName("意外险");
        // 保险公司及编号
        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            upwwinfo.setSafeCompany(result.get(0));
            upwwinfo.setSafeNo(result.get(1));
        } else {
            upwwinfo.setSafeNo(zj.getZjbh());
        }


        if (StringUtils.isEmpty(zj.getZjlj())){
            upwwinfo.setOutZjljProcess(-1);
        } else {
            upwwinfo.setOutZjlj(zj.getZjlj());
            upwwinfo.setOutZjljProcess(0);
        }

        // 看证件图是否需要更新
        setOutZjljProcess(zj, w, upwwinfo);

        // 更新或添加进来
        websitWorderwidwdidMap.put(w.getWorkerId() + w.getWebsitId(),upwwinfo);

        upWebsitWorkers.add(upwwinfo);
    }

    private void setOutZjljProcess(ZJInfo zj, WebsitWorker w, WebsitWorker upwwinfo) {
        String ptzjlj = "";
        String zjlj = "";
        // 取证件信息 ptzjlj
        // outZjlj为空可能为平台自建或是自建已上传总部取 out_insure_cert值与总部返回的值比较相同不修改图
        if (StringUtils.isEmpty(w.getOutZjlj())){
            if (StringUtils.isNotEmpty(w.getOutInsureCert())) {
                ptzjlj = w.getOutInsureCert();
            }
        } else {
            ptzjlj = w.getOutZjlj();
        }
        if (StringUtils.isNotEmpty(zj.getZjlj())){
            zjlj = zj.getZjlj();
        }

        // 不相同 就修改
        if (! zjlj.equals(ptzjlj)){
            upwwinfo.setOutZjlj(zj.getZjlj());
            upwwinfo.setOutZjljProcess(0);
        } else {
            upwwinfo.setOutZjlj(zj.getZjlj());
            upwwinfo.setOutZjljProcess(1);
        }
    }

    @Nullable
    private String checkWebsitWorker(String workerId, Map<String, WebsitWorker> websitWorderwidwdidMap,
                                     WebsitOrderSign item) {
        String websitWorkerId="";
        if (!websitWorderwidwdidMap.containsKey(workerId + item.getWebsitId())){
            return null;
        }
        // 提取 websitWorkerId
        if (websitWorderwidwdidMap.get(workerId + item.getWebsitId()).getWebsitId().equals(item.getWebsitId())){
            websitWorkerId=websitWorderwidwdidMap.get(workerId + item.getWebsitId()).getWebsitWorkerId();
        }

        if (StringUtils.isEmpty(websitWorkerId)){
            return null;
        }
        return websitWorkerId;
    }

    @NotNull
    private InsureWorkerCommercial getInsureWorkerCommercial(String workerId, Map<String, List<Worker>> workerWorkeridMap,
                                                             List<InsureWorkerCommercial> insurecs, ZJInfo zj,
                                                             WebsitOrderSign item, String websitWorkerId, Insure insure) throws ParseException {
        InsureWorkerCommercial a = new InsureWorkerCommercial();
        a.setId(IdWorker.getIdStr());
        a.setWorkerId(workerId);
        a.setWorkerName(workerWorkeridMap.get(workerId).get(0).getWorkerName());
        a.setWorkerMobile(workerWorkeridMap.get(workerId).get(0).getMobile());
        a.setWebsitId(item.getWebsitId());
        a.setWebsitWorkerId(websitWorkerId);
        a.setIdcard(workerWorkeridMap.get(workerId).get(0).getIdcard());
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            a.setStartTime(publicService.subOneYear(baseService.utcToDateStr(zj.getZjyxq())));
            a.setEndTime(baseService.utcToDateStr(zj.getZjyxq()));
        }
        a.setExamineStatus("OK");

        if (insure !=null){
            a.setInsureBill(insure.getId());
            a.setInsureName(insure.getName());
        } else {
            if (zj.getZjbh().contains("/")){
                List<String> result = Arrays.asList(zj.getZjbh().split("/"));
                a.setInsureName(result.get(0));
                a.setInsureCompany(result.get(0));
                a.setInsureBill(result.get(1));
            } else {
                a.setInsureBill(zj.getZjbh());
            }
        }
        insurecs.add(a);
        return a;
    }

    private void getInsureWorkerCommercialFile(List<InsureWorkerCommercialFile> insurefiles, ZJInfo zj, InsureWorkerCommercial a) {
        List<String> zjs = new ArrayList<>();
        if (StringUtils.isEmpty(zj.getZjlj())){
            InsureWorkerCommercialFile icf = new InsureWorkerCommercialFile();
            icf.setId(IdWorker.getIdStr());
            icf.setInsureWorkerCommercialId(a.getId());
            icf.setCreateBy("system");
            icf.setCreateTime(new Date());
            icf.setOutZjlj("");
            icf.setOutZjljProcess(-1);
            insurefiles.add(icf);
            return;
        }

        if (zj.getZjlj().contains(",")){
            zjs = Arrays.asList(zj.getZjlj().split(","));
        } else {
            zjs.add(zj.getZjlj());
        }
        for (String fileurl:zjs){
            InsureWorkerCommercialFile icf = new InsureWorkerCommercialFile();
            icf.setId(IdWorker.getIdStr());
            icf.setInsureWorkerCommercialId(a.getId());
            icf.setCreateBy("system");
            icf.setCreateTime(new Date());
            icf.setOutZjlj(fileurl);
            insurefiles.add(icf);
        }
    }

    private void addNewWorkerCert(WangdianWxgVos wvos, List<WorkerCert> addList, String workerId, String workerName,
                                  Map<String,WorkerCert> workerIdCertNamesObjMaps, ZJInfo zj) throws ParseException {
        WorkerCert add = new WorkerCert();
        add.setId(publicService.getUUID());
        add.setWorkerId(workerId);
        add.setCertName(zj.getZjmc());
        add.setName(workerName);
        if (StringUtils.isNotEmpty(zj.getZjlj())){
            add.setOutZjlj(zj.getZjlj());
        } else {
            add.setOutZjljProcess(-1);
        }

        if (zj.getZjbh().contains("/")){
            List<String> result = Arrays.asList(zj.getZjbh().split("/"));
            add.setCertNo(result.get(1));
        } else {
            add.setCertNo(zj.getZjbh());
        }
        if (StringUtils.isNotEmpty(zj.getZjyxq())){
            add.setStartTime(publicService.subOneYear(baseService.utcToDateStr(zj.getZjyxq())));
            add.setExpireTime(baseService.utcToDateStr(zj.getZjyxq()));
        }
        if (StringUtils.isNotEmpty(zj.getZjfssj())){
            add.setReviewTime(baseService.utcToDateStr(zj.getZjfssj()));
        }
        // add.setExamineStatus("OK");
        add.setSex(wvos.getXingb());
        add.setOutSyncStatus(1);
        add.setOutSyncTimes(0);
        add.setOutSyncTime(new Date());

        // 看新增还是修改
        if (workerIdCertNamesObjMaps.containsKey(workerId + zj.getZjmc())){
            // 看证件图是否需要更新
            setOutZjljProcessOther(workerId, workerIdCertNamesObjMaps, zj, add);
            WorkerCert o = workerIdCertNamesObjMaps.get(workerId + zj.getZjmc());
            add.setId(o.getId());
        }

        workerIdCertNamesObjMaps.put(workerId + zj.getZjmc(),add);

        addList.add(add);
    }

    private void setOutZjljProcessOther(String workerId, Map<String, WorkerCert> workerIdCertNamesObjMaps, ZJInfo zj, WorkerCert add) {
        String ptzjlj = "";
        String zjlj = "";
        WorkerCert wc = workerIdCertNamesObjMaps.get(workerId + zj.getZjmc());

        // 取证件信息 ptzjlj
        // outZjlj为空可能为平台自建或是自建已上传总部取 out_insure_cert值与总部返回的值比较相同不修改图
        if (StringUtils.isEmpty(wc.getOutZjlj())){
            if (StringUtils.isNotEmpty(wc.getOutFileUrl())) {
                ptzjlj = wc.getOutFileUrl();
                if (StringUtils.isNotEmpty(wc.getOutFileUrl2())) {
                    ptzjlj = ptzjlj+ "," + wc.getOutFileUrl2();
                }
            } else {
                if (StringUtils.isNotEmpty(wc.getOutFileUrl2())) {
                    ptzjlj = wc.getOutFileUrl2();
                }
            }
        } else {
            ptzjlj = wc.getOutZjlj();
        }
        if (StringUtils.isNotEmpty(zj.getZjlj())){
            zjlj = zj.getZjlj();
        }

        // 不相同 就修改
        if (! zjlj.equals(ptzjlj)){
            add.setOutZjlj(zj.getZjlj());
            add.setFileUrl("");
            add.setFileUrl2("");
            add.setOutFileUrl("");
            add.setOutFileUrl2("");
            add.setOutZjljProcess(0);
        }
    }

    // 返回null时不处理
    private ZJInfoBX checkBxCertInfo(String workerId, Map<String,List<WebsitWorker>> websitWorkerWorkerIdMap,
                                     ZJInfo zj, String wdno) {
        ZJInfo resultZjinfo = new ZJInfo();
        ZJInfoBX zjinfo = new ZJInfoBX();
        Map<String,List<WebsitOrderSign>> wosWebsitidMap = new HashMap<>();
        WebsitWorker item = new WebsitWorker();

        // 装入总部同步的保险数据
        zjinfo.setZjInfo(zj);

        // 提取商户售后网点对应的平台售后网点信息 存在一对多的关系
        List<WebsitOrderSign> wos = publicService.shShwdToptshwdByBrandWebsitNo(wdno);
        // 找不到对应关系时不再处理保险证数据
        if (CollectionUtils.isEmpty(wos)){
            return null;
        }
        wosWebsitidMap = wos.stream().collect(Collectors.groupingBy(WebsitOrderSign::getWebsitId));
        wos.clear();

        // 找出师傅所在网点的保险证记录数据
        Boolean flag = Boolean.TRUE;
        for (WebsitWorker i:websitWorkerWorkerIdMap.get(workerId)){
            if (wosWebsitidMap.containsKey(i.getWebsitId())){
                MyBeanUtils.copyProperties(i,item);
                flag = Boolean.FALSE;
                break;
            }
        }

        // 无保险记录时也不需要处理，这里不用关心记录的事，网点服务人员下载时已生成了数据
        if (flag){
            return null;
        }

        // 有保险数据不处理
        if (StringUtils.isNotEmpty(item.getOutInsureCert())){
            return null;
        }

        //取保险记录
        zjinfo.setWebsitWorker(item);

        if (zj.getZjlj().contains(",")){
            List<String> result = Arrays.asList(zj.getZjlj().split(","));
            MyBeanUtils.copyProperties(zj,resultZjinfo);
            resultZjinfo.setZjlj(result.get(0));
            zjinfo.setZjInfo(resultZjinfo);
        }

        return zjinfo;
    }

    private ZJInfoC checkCertInfo(String workerId,Map<String,List<WorkerCert>> WorkerCertWorkerIdMaps,ZJInfo zj) {
        ZJInfo resultZjinfo = new ZJInfo();
        ZJInfoC zjinfo = new ZJInfoC();

        zjinfo.setZjInfo(zj);

        // 不存在时直接新增
        if (!WorkerCertWorkerIdMaps.containsKey(workerId)){
            return zjinfo;
        }

        // 已有证件信息，看是否已全部同步(相同证件名且证件照不为空)
        for (WorkerCert item:WorkerCertWorkerIdMaps.get(workerId)){
            // 名称相同 即表中已存在，只能是修改
            if (item.getCertName().equals(zj.getZjmc())){
                zjinfo.setWorkerCert(item);
                //证件信息不为空不处理
                // 两个证件照时
                if (zj.getZjlj().contains(",")){
                    // 都存在该证件照不同步
                    if (StringUtils.isNotEmpty(item.getFileUrl()) && StringUtils.isNotEmpty(item.getFileUrl2())){
                        zjinfo.setZjInfo(null);
                        return zjinfo;
                    }
                    List<String> result = Arrays.asList(zj.getZjlj().split(","));
                    // 未同步时直接返回新增
                    if (StringUtils.isEmpty(item.getFileUrl()) && StringUtils.isEmpty(item.getFileUrl2())){
                        zjinfo.setZjInfo(zj);
                        return zjinfo;
                    }
                    // 只有一个未同步时新增也是修改
                    MyBeanUtils.copyProperties(zj,resultZjinfo);
                    resultZjinfo.setZjlj(result.get(0));
                    if (StringUtils.isEmpty(item.getFileUrl2())){
                        resultZjinfo.setZjlj(result.get(1));
                    }
                    zjinfo.setZjInfo(resultZjinfo);
                    return zjinfo;
                }
                // 只有一个证件时 已同步不处理
                if (StringUtils.isNotEmpty(item.getFileUrl())){
                    zjinfo.setZjInfo(null);
                    return zjinfo;
                }

                return zjinfo;
            }
        }

        zjinfo.setWorkerCert(null);

        return zjinfo;
    }

    // 25号后 ljf改
/*
    @Transactional(rollbackFor = Exception.class)
    public void wxgCategoryQueryAddBak(ItfTblWangdianWxgDownload wxgDownload,
                                    Map<String, List<WorkerBrandAccount>> workerBrandAccountsMap,
                                    Map<String,List<WorkerServiceCategoryDetail>> workerServiceCategoryDetailMap,
                                    SysDict sysDict,Map<String, List<SysDictRef>> sysDictRefMap,
                                    List<String> workerServiceCategoryDetailList) throws Exception {
        Map<String,Object> req = new HashMap<>();
        WangdianWxgVos wvos = new WangdianWxgVos();
        Map<String, List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs = new HashMap<>();
        List<WorkerServiceCategory> wscList = new ArrayList<>();
        List<WorkerServiceCategoryDetail> wscdList = new ArrayList<>();
        // 提取本地商户师傅信息 网点｜师傅编号不存在不处理 修改处已做了处理 这里只新增(前提是找到师傅所在网点信息)
        for (WorkerBrandAccount workerBrandAccount:workerBrandAccountsMap.get(String.valueOf(wxgDownload.getWxgid()))){

            // 师傅对应的网点服务类目信息已存在不处理 只做插入
            if (workerServiceCategoryDetailMap.containsKey(workerBrandAccount.getWebsitWorkerId())){
                continue;
            }

            // 师傅对应的网点服务类目信息已存在不处理 只做插入
            if (workerServiceCategoryDetailList.contains(workerBrandAccount.getWebsitWorkerId())){
                continue;
            }

            // 参数 获取网点维修工信息
            getParameter(wxgDownload.getWdno(), wxgDownload.getWxgno(), req);
            try {
                // 格力总部查询工程师信息
                GreeResponseHelper response = greeLogic.greePost(wdqyapi, JSONObject.toJSONString(req), publicService.getCompanyId(wxgDownload.getWdno()));
                if (response.getStatus() == 200){
                    WxgQueryInfo resultDatax = JSONObject.parseObject(response.getData().toString(), WxgQueryInfo.class);
                    // 无信息不处理
                    if ( resultDatax.getWangdianWxgVos().size()<1){
                        continue;
                    }

                    wvos = resultDatax.getWangdianWxgVos().get(0);

                    // 提取师傅的服务大类信息 先内存中查询
                    if (workerServiceCategoryDetailMap.containsKey(String.valueOf(wxgDownload.getWxgid()))){
                        wxgCategoryTypeRecs = workerServiceCategoryDetailMap.get(workerBrandAccount.getWebsitWorkerId()).stream().
                                collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getType));
                    } else {
                        List<WorkerServiceCategoryDetail> wxgCategoryRecs = workerServiceCategoryDetailService.lambdaQuery()
                                .eq(WorkerServiceCategoryDetail::getWebsitWorkerId, workerBrandAccount.getWebsitWorkerId()).list();

                        // 服务类型 INSTALL=安装 REPAIR=维修  DELIVERY=配送
                        if (CollectionUtils.isNotEmpty(wxgCategoryRecs)){
                            wxgCategoryTypeRecs = wxgCategoryRecs.stream().
                                    collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getType));
                        }
                    }
                    // 同步-师傅服务的类目信息 无则插入
                    getServiceCategory(wvos, wscList, wscdList, sysDict, wxgDownload, wxgCategoryTypeRecs,
                            sysDictRefMap, workerBrandAccount, workerServiceCategoryDetailList);
                    // 新增或修改(师傅服务的类目)
                    addDataCategory(wscList, wscdList);

                    // 清理缓存，把新增的服务类目加到缓存中
                    extractedCaretory(wscList, wscdList, workerServiceCategoryDetailMap, workerBrandAccount);
                }  else {
                    log.info("工程师信息同步失败:{}", JSONObject.toJSONString(req));
                    log.info("msg:{}", response.getMsg());
                }
            } catch (Exception ex) {
                log.info("工程师信息同步失败:{}", ex);
            }

        }
    }
    */


    /**
     * 同步师傅服务类目、品类、工单类型等信息
     * @param wxgDownload 师傅信息
     * @param workerBrandAccounts 对应的师傅信息
     * @param workerServiceCategoryDetails 对应的师傅服务类目资质
     * @param serviceCategoryDict 服务类目字典
     * @param sysDictRefMap 服务类目对应字典（暂不用）
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void wxgCategoryQueryAdd(ItfTblWangdianWxgDownload wxgDownload,
                                    List<WorkerBrandAccount> workerBrandAccounts,
                                    List<WorkerServiceCategoryDetail> workerServiceCategoryDetails,
                                    SysDict serviceCategoryDict,Map<String, List<SysDictRef>> sysDictRefMap) throws Exception {
        Map<String,Object> req = new HashMap<>();
        WangdianWxgVos wvos = new WangdianWxgVos();
        Map<String, List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs = new HashMap<>();
//        List<WorkerServiceCategory> wscList = new ArrayList<>();
//        List<WorkerServiceCategoryDetail> wscdList = new ArrayList<>();

        //brandWorkerId = wxgid
        //师傅对应关系 key = brandWorkerId value = 师傅对应关系列表
        Map<String, List<WorkerBrandAccount>> workerBrandAccountsMap = workerBrandAccounts.stream()
                .collect(Collectors.groupingBy(WorkerBrandAccount::getBrandWorkerId));

        //师傅服务资质 key = 网点师傅id，value=资质明细
        Map<String, List<WorkerServiceCategoryDetail>> workerServiceCategoryDetailMap = workerServiceCategoryDetails
                .stream().collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getWebsitWorkerId));
//        String brandWorkerIdo = "294773";
//        String brandWorkerIdt = "990003185";

        // 提取本地商户师傅信息 网点｜师傅编号不存在不处理 修改处已做了处理 这里只新增(前提是找到师傅所在网点信息)
        for (WorkerBrandAccount workerBrandAccount:workerBrandAccountsMap.get(String.valueOf(wxgDownload.getWxgid()))){

            // 师傅对应的网点服务类目信息已存在不处理 只做插入
            if (workerServiceCategoryDetailMap.containsKey(workerBrandAccount.getWebsitWorkerId())){
                continue;
            }

            /*if (brandWorkerIdo.equals(workerBrandAccount.getBrandWorkerId()) || brandWorkerIdt.equals(workerBrandAccount.getBrandWorkerId())){
                log.info("workerBrandAccount {}",workerBrandAccount);
                log.info("wxgDownload {}",wxgDownload);
            }*/

            // 参数 获取网点维修工信息
            getParameter(wxgDownload.getWdno(), wxgDownload.getWxgno(), req);
            try {
                // 格力总部查询工程师信息
                GreeResponseHelper response = greeLogic.greePost(wdqyapi, JSONObject.toJSONString(req), publicService.getCompanyId(wxgDownload.getWdno()));

                if (response.getStatus() == 200){

                    WxgQueryInfo resultDatax = JSONObject.parseObject(response.getData().toString(), WxgQueryInfo.class);
                    // 无信息不处理
                    if ( resultDatax.getWangdianWxgVos().size()<1){
                        continue;
                    }
                    //网点维修工基础资料
                    wvos = resultDatax.getWangdianWxgVos().get(0);

                    // 提取师傅的服务大类信息 先内存中查询
//                if (workerServiceCategoryDetailMap.containsKey(String.valueOf(wxgDownload.getWxgid()))){
//                    wxgCategoryTypeRecs = workerServiceCategoryDetailMap.get(workerBrandAccount.getWebsitWorkerId()).stream().
//                            collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getType));
//                } else {
//                    List<WorkerServiceCategoryDetail> wxgCategoryRecs = workerServiceCategoryDetailService.lambdaQuery()
//                            .eq(WorkerServiceCategoryDetail::getWebsitWorkerId, workerBrandAccount.getWebsitWorkerId()).list();
//
//                    // 服务类型 INSTALL=安装 REPAIR=维修  DELIVERY=配送
//                    if (CollectionUtils.isNotEmpty(wxgCategoryRecs)){
//                        wxgCategoryTypeRecs = wxgCategoryRecs.stream().
//                                collect(Collectors.groupingBy(WorkerServiceCategoryDetail::getType));
//                    }
//                }
                    // 同步-师傅服务的类目信息 无则插入
                    getServiceCategory(wvos, serviceCategoryDict, wxgDownload, wxgCategoryTypeRecs,
                            sysDictRefMap, workerBrandAccount);

                    // 新增或修改(师傅服务的类目)
                    //addDataCategory(wscList, wscdList);

                    // 清理缓存，把新增的服务类目加到缓存中
                    //extractedCaretory(wscList, wscdList, workerServiceCategoryDetailMap, workerBrandAccount);

                } else {
                    log.error("工程师服务类目信息同步失败:{}", JSONObject.toJSONString(req));
                    log.error("工程师服务类目信息同步失败msg:{}", response.getMsg());
                }
            } catch (Exception ex) {
                log.info("工程师信息同步失败:{}", ex);
            }

        }
    }

//    private void extractedCaretory(List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList,
//                                   Map<String, List<WorkerServiceCategoryDetail>> oldWxgCategoryRecMap, WorkerBrandAccount workerBrandAccount) {
//        if (!oldWxgCategoryRecMap.containsKey(workerBrandAccount.getWebsitWorkerId())){
//            oldWxgCategoryRecMap.put(workerBrandAccount.getWebsitWorkerId(),wscdList);
//        }
//
//        wscList.clear();
//        wscdList.clear();
//    }
//
//    public void addDataCategory(List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList) {
//
//
//        // 师傅服务类目新增
//        if (wscList.size()>0){
//            workerServiceCategoryService.saveBatch(wscList);
//            wscList.clear();
//        }
//        if (wscdList.size()>0){
//            workerServiceCategoryDetailService.saveBatch(wscdList);
//            wscdList.clear();
//        }
//    }


    /*private void getServiceCategoryBak(WangdianWxgVos wvos, List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList,
                                    SysDict sysDict, ItfTblWangdianWxgDownload wxg,
                                    Map<String,List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs,
                                    Map<String, List<SysDictRef>> sysDictRefMap,WorkerBrandAccount workerBrandAccount,
                                    List<String> workerServiceCategoryDetailList) {
        List<String> complete = new ArrayList<>();
        // 先处理商用
        for (SignSplb syitem: wvos.getSySignSplbList()){
            // 扫描每个大类
            for (String s :syitem.getFwlbList()){
                // 师傅服务的大类中查看是否存在 不存在新增
                extracted(wscList, wscdList, complete, sysDict, wxg, wxgCategoryTypeRecs,
                        syitem, s, ServiceCategoryEnum.COMMERCIAL_TYPE.getCode(), sysDictRefMap,
                        workerBrandAccount, workerServiceCategoryDetailList);
            }
        }
        complete.clear();

        // 处理家用
        for (SignSplb syitem: wvos.getJySignSplbList()){
            // 扫描每个大类
            for (String s :syitem.getFwlbList()){
                // 师傅服务的大类中查看是否存在 不存在新增
                extracted(wscList, wscdList, complete, sysDict, wxg, wxgCategoryTypeRecs,
                        syitem, s,ServiceCategoryEnum.HOME_TYPE.getCode(), sysDictRefMap,
                        workerBrandAccount, workerServiceCategoryDetailList);
            }
        }
    }*/

    private void getServiceCategory(WangdianWxgVos wvos,
                                    SysDict sysDict, ItfTblWangdianWxgDownload wxg,
                                    Map<String,List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs,
                                    Map<String, List<SysDictRef>> sysDictRefMap,WorkerBrandAccount workerBrandAccount) {
        Map<String,List<SignSplb>> signSplbMap = new HashMap<>();
        signSplbMap.put(ServiceCategoryEnum.COMMERCIAL_TYPE.getCode(),wvos.getSySignSplbList());
        signSplbMap.put(ServiceCategoryEnum.HOME_TYPE.getCode(),wvos.getJySignSplbList());

        List<WorkerServiceCategory> workerServiceCategoryList = new ArrayList<>();
        List<WorkerServiceCategoryDetail> workerServiceCategoryDetailList = new ArrayList<>();
        // 新增或修改(师傅服务的类目)
        //addDataCategory(wscList, wscdList);

        //处理家用和商用的品类
        for (String serviceFlag: signSplbMap.keySet()){
            List<SignSplb> signSplbs = signSplbMap.get(serviceFlag);
            if(CollectionUtils.isEmpty(signSplbs)){
                continue;
            }
            for(SignSplb syitem : signSplbs) {
                //中文名的工单类型
                List<String> orderTypeTexts = syitem.getFwlbList().stream().distinct().collect(Collectors.toList());
                // 扫描每个工单类型
                for (String s : orderTypeTexts) {
                    // 师傅服务的大类中查看是否存在 不存在新增
                    ServiceCategoryEnum serviceCategoryEnum = ServiceCategoryEnum.valueToEnum(s);
                    if (serviceCategoryEnum == null) {
                        log.error("【同步师傅服务资质】工单类型枚举匹配失败," + s);
                        continue;
                    }
                    // 提取品牌商对应的大类信息
                    SysDictRef sysDictRef = sysDictRefMap.get(String.valueOf(syitem.getSpdl())).get(0);

                    this.getAddInfo(workerServiceCategoryList,workerServiceCategoryDetailList,sysDict,wxgCategoryTypeRecs,
                            sysDictRef, serviceCategoryEnum.getCode(), serviceFlag, workerBrandAccount);
                }
            }
        }
        if(CollectionUtils.isNotEmpty(workerServiceCategoryList))
            workerServiceCategoryService.saveBatch(workerServiceCategoryList);
        if(CollectionUtils.isNotEmpty(workerServiceCategoryDetailList))
            workerServiceCategoryDetailService.saveBatch(workerServiceCategoryDetailList);
    }





    private void getParameter(String wdno, String wxgno, Map<String, Object> req) {
        req.put("wdno", wdno);
        req.put("wxgno", wxgno);
        req.put("page", 1);
        req.put("size", 20);
        req.put("xsgsshstat", 2);
    }

    private WorkerBrandAccount getWorkerBrandAccountData(List<WorkerBrandAccount> wbarecs, ItfTblWangdianWxgDownload wxg){
        WorkerBrandAccount workerBrandAccount = null;

        for (WorkerBrandAccount wba: wbarecs){
            if (wba.getBrandWorkerId().equals(String.valueOf(wxg.getWxgid()))){
                workerBrandAccount = wba;
                break;
            }
        }

        return workerBrandAccount;
    }


//    private void extracted(List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList,
//                           List<String> complete, SysDict sysDict, ItfTblWangdianWxgDownload wxg,
//                           Map<String,List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs, SignSplb syitem,
//                           ServiceCategoryEnum serviceCategoryEnum,String type,Map<String, List<SysDictRef>> sysDictRefMap,
//                           WorkerBrandAccount workerBrandAccount) {
//        if ( !complete.contains(serviceCategoryEnum.getText() + syitem.getSpdl())){
//            // 提取品牌商对应的大类信息
//            SysDictRef sysDictRef = sysDictRefMap.get(String.valueOf(syitem.getSpdl())).get(0);
//
//            this.getAddInfo(wscList, wscdList, sysDict, wxg, wxgCategoryTypeRecs,
//                    sysDictRef,serviceCategoryEnum.getCode(),
//                    type,workerBrandAccount);
//
////            if (s.equals(ServiceCategoryEnum.INSTALL_TYPE.getText())){
////                getAddInfo(wscList, wscdList, sysDict, wxg, wxgCategoryTypeRecs,
////                        sysDictRef,ServiceCategoryEnum.INSTALL_TYPE.getCode(),
////                        type,workerBrandAccount);
////            } else if (s.equals(ServiceCategoryEnum.REPAIR_TYPE.getText())){
////                getAddInfo(wscList, wscdList, sysDict, wxg, wxgCategoryTypeRecs,
////                        sysDictRef,ServiceCategoryEnum.REPAIR_TYPE.getCode(),
////                        type,workerBrandAccount);
////            } else if (s.equals(ServiceCategoryEnum.DELIVERY_TYPE.getText())){
////                getAddInfo(wscList, wscdList, sysDict, wxg, wxgCategoryTypeRecs,
////                        sysDictRef,ServiceCategoryEnum.DELIVERY_TYPE.getCode(),
////                        type,workerBrandAccount);
////            }
//            // 新增过的无需再次新增
//            complete.add(serviceCategoryEnum.getText() + syitem.getSpdl());
//        }
//    }

    private void getAddInfo(List<WorkerServiceCategory> wscList,List<WorkerServiceCategoryDetail> wscdList,
                            SysDict sysDict,Map<String, List<WorkerServiceCategoryDetail>> wxgCategoryDetails,
                            SysDictRef sysDictRef, String code, String type, WorkerBrandAccount workerBrandAccount) {
        // 新增
        // 看 worker_service_category 有无数据，无数据新增
        if(wxgCategoryDetails != null && wxgCategoryDetails.containsKey(code)){
            List<WorkerServiceCategoryDetail> workerServiceCategoryDetails = wxgCategoryDetails.get(code);
            long count = workerServiceCategoryDetails.stream()
                    .filter(v -> StringUtils.equals(v.getWebsitWorkerId(), workerBrandAccount.getWebsitWorkerId())).count();
            if(count > 0)
                return;
        }

        //去重，判断是否存在
        List<WorkerServiceCategory> hasWorkerServiceCategory = wscList.stream().filter(v ->
                StringUtils.equals(v.getWebsitWorkerId(), workerBrandAccount.getWebsitWorkerId())
                        && StringUtils.equals(v.getFlag(), type)
                        && StringUtils.equals(v.getType(), code)
        ).collect(Collectors.toList());

        WorkerServiceCategory wsc = null;
        if(CollectionUtils.isNotEmpty(hasWorkerServiceCategory)){
            wsc = hasWorkerServiceCategory.get(0);
        }else {
            wsc = new WorkerServiceCategory();
            wsc.setId(IdWorker.getIdStr());
            wsc.setWorkerId(workerBrandAccount.getWorkerId());
            wsc.setWebsitId(workerBrandAccount.getWebsitId());
            wsc.setWebsitWorkerId(workerBrandAccount.getWebsitWorkerId());
            wsc.setServiceCategoryId(sysDict.getDictCode());
            wsc.setServiceCategoryName(sysDict.getDictValue());
            wsc.setFlag(type);
            wsc.setType(code);
            wsc.setCreateTime(new Date());
            wscList.add(wsc);
        }

        //去重，判断是否存在
        long count = wscdList.stream().filter(v ->
                StringUtils.equals(v.getWebsitWorkerId(), workerBrandAccount.getWebsitWorkerId())
                        && StringUtils.equals(v.getFlag(), type)
                        && StringUtils.equals(v.getType(), code)
                        && StringUtils.equals(v.getMainId(),sysDictRef.getDictCode())
        ).count();
        if(count == 0) {
            // WorkerServiceCategoryDetail 新增
            WorkerServiceCategoryDetail wscd = new WorkerServiceCategoryDetail();
            wscd.setId(IdWorker.getIdStr());
            wscd.setWorkerServiceCategoryId(wsc.getId());
            wscd.setWorkerId(workerBrandAccount.getWorkerId());
            wscd.setWebsitId(workerBrandAccount.getWebsitId());
            wscd.setWebsitWorkerId(workerBrandAccount.getWebsitWorkerId());
            wscd.setServiceCategoryId(sysDict.getDictCode());
            wscd.setServiceCategoryName(sysDict.getDictValue());
            wscd.setFlag(type);
            wscd.setType(code);
            wscd.setMainId(sysDictRef.getDictCode());
            wscd.setMainName(sysDictRef.getDictValue());
            wscd.setCreateTime(new Date());
            wscdList.add(wscd);
        }
    }
}
