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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zfire.jiasm.syncdata.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.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.utils.oss.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
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.util.*;
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;



    @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<>();
        Map<String,List<WorkerCert>> WorkerCertMaps = new HashMap<>();
        List<ItfTblWangdianWxgDownload> wxgDownladRecs = new ArrayList<>();
        // 身份证 + 姓名 + 手机号
        List<String> wxgs = new ArrayList<>();

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

        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));
        }

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

        // 提取现有已存在的证件信息的师傅信息
        List<WorkerCert> wc = workerCertService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(wc)){
            WorkerCertMaps = wc.stream().collect(Collectors.groupingBy(WorkerCert::getWorkerId));
        }


        for (ItfTblWangdianWxgDownload wxg :wxgDownladRecs){
            // 防止 ItfTblWangdianWxgDownload表有重复记录
            if (wxgs.contains(wxg.getSfzen() + wxg.getWxgmc() + wxg.getYddh())){
                continue;
            }

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

            // 有证件信息的师傅不再新增
            if (WorkerCertMaps.containsKey(workerId)){
                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);

                try {
                    // 同步-新增证件信息
                    getCertInfo(wvos, addList, workerId, workerWorkeridMap.get(workerId).get(0).getWorkerName());
                    // 新增或修改(证件)
                    addDataCert(addList);
                    wxgs.add(wxg.getSfzen() + wxg.getWxgmc() + wxg.getYddh());
                } catch (Exception ex) {
                    log.info("工程师证件照信息同步失败-师傅证件信息:{}", wxg.getSfzen());
                }
            }
        }

        wxgs.clear();
    }

    private String checkIsGreeWroker(Map<String, List<Worker>> workerIdcardMap, ItfTblWangdianWxgDownload wxg) {
        String workerId="";
        if (workerIdcardMap.containsKey(wxg.getSfzen())){
            for (Worker w: workerIdcardMap.get(wxg.getSfzen())){
                if (w.getWorkerName().equals(wxg.getWxgmc()) && w.getMobile().equals(wxg.getYddh())){
                    workerId = w.getWorkerId();
                    break;
                }
            }
        }
        return workerId;
    }

    @Override
    public void extractedAddCategory() throws Exception {
        List<WorkerBrandAccount> workerBrandAccounts = new ArrayList<>();
        Map<String,List<Worker>> Worker_Idcards = new HashMap<>();
        Map<String, List<WorkerServiceCategoryDetail>> workerServiceCategoryDetailMap = new HashMap<>();
        Map<String, List<SysDictRef>> sysDictRefMap = new HashMap<>();
        List<SysDictRef> sysDictRef = new ArrayList<>();
        List<WorkerServiceCategoryDetail> wxgCategoryRec = 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 sysDict =  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 (sysDict == 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<ItfTblWangdianWxgDownload> wxgRecs =  itfTblWangdianWxgDownloadService.lambdaQuery()
                .select(ItfTblWangdianWxgDownload::getWxgid,
                        ItfTblWangdianWxgDownload::getWxgno,
                        ItfTblWangdianWxgDownload::getWdno,
                        ItfTblWangdianWxgDownload::getSfzen,
                        ItfTblWangdianWxgDownload::getWxgmc,
                        ItfTblWangdianWxgDownload::getYddh,
                        ItfTblWangdianWxgDownload::getFlag)
                // .eq(ItfTblWangdianWxgDownload::getWxgno,"S21A00200023")// 测试用 todo
                .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();
        // 这里提取对应的商户网点信息

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

        for (ItfTblWangdianWxgDownload wxgDownload :wxgRecs){
            // 状态无效不处理
            if (wxgDownload.getFlag() != null){
                if (!wxgDownload.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                    continue;
                }
            }

            // 师傅在平台中不存在时不处理
            String workerId = checkIsGreeWroker(Worker_Idcards, wxgDownload);
            if (workerId.length()<1) {
                continue;
            }

            wxgCategoryQueryAdd(wxgDownload,workerBrandAccounts,workerServiceCategoryDetailMap,sysDict,sysDictRefMap);
        }
    }

    @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), 1);
            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), 1);
                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()>1000){
            itfTblWangdianPositionDownloadService.saveBatch(wdwxgadd);
            wdwxgadd.clear();
        }
    }

    private void addWorkerStreet(WangdianWxgVos wvos, String brandId, List<WorkerStreet> ws, String sfzen) {
        WorkerStreet n = new WorkerStreet();
        n.setId(UUID.randomUUID().toString());
        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){
            workerCertService.saveBatch(addList);
            addList.clear();
        }
    }

    @NotNull
    private String putCert(String image) throws Exception {
        String id = IdWorker.getIdStr()+".jpeg";
        baseService.saveToFile(greeLogic.greeFileUrl(image), id);
        String file = id;
        ossUtil.uploadFile(id, new File(file));

        return id;
    }

    private void workercertAdd(WangdianWxgVos wvos, List<WorkerCert> addList, String workerId, ZJInfo zj, String workerName) throws Exception {
        // 新增
        WorkerCert add = new WorkerCert();
        add.setId(UUID.randomUUID().toString());
        add.setWorkerId(workerId);
        add.setCertName(zj.getZjmc());
        add.setName(workerName);

        if (zj.getZjlj().contains(",")){
            List<String> result = Arrays.asList(zj.getZjlj().split(","));
            add.setOutFileUrl(result.get(0));
            add.setOutFileUrl2(result.get(1));
            // 上传图片
            String id = putCert(result.get(0));
            add.setFileUrl(id);
            String id2 = putCert(result.get(1));
            add.setFileUrl2(id2);
            new File(id).delete();
            new File(id2).delete();
        } else {
            add.setOutFileUrl(zj.getZjlj());
            String id = putCert(zj.getZjlj());
            add.setFileUrl(id);
            new File(id).delete();
        }
        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());

        addList.add(add);
    }


    private void getCertInfo(WangdianWxgVos wvos, List<WorkerCert> addList, String workerId,String workerName) throws Exception {
        // 同步-新增证件信息
        for (ZJInfo zj: wvos.getZjInfoList()){
            workercertAdd(wvos, addList, workerId, zj, workerName);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void wxgCategoryQueryAdd(ItfTblWangdianWxgDownload wxgDownload,
                                    List<WorkerBrandAccount> workerBrandAccounts,
                                    Map<String,List<WorkerServiceCategoryDetail>> workerServiceCategoryDetailMap,
                                    SysDict sysDict,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<>();

        for (WorkerBrandAccount i:workerBrandAccounts){
            // 提取本地商户师傅信息 网点｜师傅编号不存在不处理 修改处已做了处理 这里只新增(前提是找到师傅所在网点信息)
            WorkerBrandAccount workerBrandAccount = getWorkerBrandAccountData(workerBrandAccounts, wxgDownload);
            if (workerBrandAccount == null){
                continue;
            }

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

            // 参数 获取网点维修工信息
            getParameter(wxgDownload.getWdno(), wxgDownload.getWxgno(), req);
            log.info("req: {}",req);
            // 格力总部查询工程师信息
            GreeResponseHelper response = greeLogic.greePost(wdqyapi, JSONObject.toJSONString(req), 1);
            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(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));
                    }
                }

                try {
                    // 同步-师傅服务的类目信息 无则插入
                    getServiceCategory(wvos, wscList, wscdList, sysDict, wxgDownload, wxgCategoryTypeRecs, sysDictRefMap);

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

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

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

    private void extractedCaretory(List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList,
                                   Map<String, List<WorkerServiceCategoryDetail>> oldWxgCategoryRecMap, ItfTblWangdianWxgDownload wxg) {
        if (oldWxgCategoryRecMap.containsKey(wxg.getSfzen())){
            oldWxgCategoryRecMap.get(wxg.getSfzen()).addAll(wscdList);
        }

        wscList.clear();
        wscdList.clear();
    }

    public void addDataCategory(List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList) {

        // 师傅服务类目新增
        if (wscList.size()>0){
            workerServiceCategoryService.saveBatch(wscList);
        }
        if (wscdList.size()>0){
            workerServiceCategoryDetailService.saveBatch(wscdList);
        }
    }


    private void getServiceCategory(WangdianWxgVos wvos, List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList,
                                    SysDict sysDict, ItfTblWangdianWxgDownload wxg,
                                    Map<String,List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs,
                                    Map<String, List<SysDictRef>> sysDictRefMap) {
        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);
            }
        }
        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);
            }
        }
    }

    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(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,
                           String s, String type,Map<String, List<SysDictRef>> sysDictRefMap) {
        if ( !complete.contains(s + syitem.getSpdl())){
            // 提取品牌商对应的大类信息
            SysDictRef sysDictRef = sysDictRefMap.get(String.valueOf(syitem.getSpdl())).get(0);

            if (s.equals(ServiceCategoryEnum.INSTALL_TYPE.getText())){
                getAddInfo(wscList, wscdList, sysDict, wxg, wxgCategoryTypeRecs,
                        sysDictRef,ServiceCategoryEnum.INSTALL_TYPE.getCode(),type);
            } else if (s.equals(ServiceCategoryEnum.REPAIR_TYPE.getText())){
                getAddInfo(wscList, wscdList, sysDict, wxg, wxgCategoryTypeRecs,
                        sysDictRef,ServiceCategoryEnum.REPAIR_TYPE.getCode(),type);
            } else if (s.equals(ServiceCategoryEnum.DELIVERY_TYPE.getText())){
                getAddInfo(wscList, wscdList, sysDict, wxg, wxgCategoryTypeRecs,
                        sysDictRef,ServiceCategoryEnum.DELIVERY_TYPE.getCode(),type);
            }
            // 新增过的无需再次新增
            complete.add(s + syitem.getSpdl());
        }
    }

    private void getAddInfo(List<WorkerServiceCategory> wscList, List<WorkerServiceCategoryDetail> wscdList, SysDict sysDict,
                            ItfTblWangdianWxgDownload wxg, Map<String, List<WorkerServiceCategoryDetail>> wxgCategoryTypeRecs,
                            SysDictRef sysDictRef, String code, String type) {
        Boolean include = Boolean.FALSE;
        // 看师傅是否已有（服务类型 INSTALL=安装 REPAIR=维修  DELIVERY=配送）对应的大类信息 如有不做任何处理
        if (wxgCategoryTypeRecs !=null && wxgCategoryTypeRecs.size()>0){
            if (wxgCategoryTypeRecs.containsKey(code)){
                for (WorkerServiceCategoryDetail category : wxgCategoryTypeRecs.get(code)){
                    if (category.getMainId().equals(sysDictRef.getDictCode())){
                        include = Boolean.TRUE;
                        break;
                    }
                }
            }
        }

        if (!include){
            // 新增
            // 看 worker_service_category 有无数据，无数据新增
            if (wxgCategoryTypeRecs ==null || wxgCategoryTypeRecs.size()<1 || !wxgCategoryTypeRecs.containsKey(code) ){
                WorkerServiceCategory wsc = new WorkerServiceCategory();
                wsc.setId(IdWorker.getIdStr());
                wsc.setWorkerId(String.valueOf(wxg.getSfzen()));
                wsc.setServiceCategoryId(sysDict.getDictCode());
                wsc.setServiceCategoryName(sysDict.getDictValue());
                wsc.setFlag(type);
                wsc.setType(code);
                wsc.setCreateTime(new Date());
                wscList.add(wsc);

                // WorkerServiceCategoryDetail 新增
                WorkerServiceCategoryDetail wscd = new WorkerServiceCategoryDetail();
                wscd.setId(IdWorker.getIdStr());
                wscd.setWorkerServiceCategoryId(wsc.getId());
                wscd.setWorkerId(String.valueOf(wxg.getSfzen()));
                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);

            } else {
                // WorkerServiceCategoryDetail 新增
                WorkerServiceCategoryDetail wscd = new WorkerServiceCategoryDetail();
                wscd.setId(IdWorker.getIdStr());
                wscd.setWorkerServiceCategoryId(wxgCategoryTypeRecs.get(code).get(0).getServiceCategoryId());
                wscd.setWorkerId(String.valueOf(wxg.getSfzen()));
                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);
            }
        }
    }
}
