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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zfire.jiasm.syncdata.constant.DictTypeEnum;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.service.GLPPGFWebsitWorkerService;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.utils.MyBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
public class GLPPGFWebsitWorkerServiceImpl implements GLPPGFWebsitWorkerService {
    @Resource
    ItfTblWangdianWxgDownloadService itfTblWangdianWxgDownloadService;
    @Resource
    WebsitWorkerService websitWorkerService;
    @Resource
    WorkerService workerService;
    @Resource
    PublicService publicService;
    @Resource
    WorkerBrandAccountService workerBrandAccountService;
    @Resource
    WebsitService websitService;




    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedFSXS(JSONArray jsonArray) {
        // 数据同步落到同步信息表
        extractedAddOrUpdate(jsonArray);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedGZXS(JSONArray jsonArray){
        // 数据同步落到同步信息表
        extractedAddOrUpdate(jsonArray);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedFSSH(JSONArray jsonArray){
        // 数据同步落到同步信息表
        extractedAddOrUpdate(jsonArray);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedGZSH(JSONArray jsonArray){
        // 数据同步落到同步信息表
        extractedAddOrUpdate(jsonArray);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void inputData(){
        // 提取所有的数据
        List<ItfTblWangdianWxgDownload> recs = new ArrayList<>();
        recs = itfTblWangdianWxgDownloadService.lambdaQuery().list();

        // 新增或修改师傅数据 worker:师傅信息表
        addWorker(recs);

        // 新增网点师傅 websit_worker+商户网点师傅信息 存在修改，不存在新增
        addWebsitWorkerBrandAccountsInfo(recs);
        recs.clear();
    }

    private void addWebsitWorkerBrandAccountsInfo(List<ItfTblWangdianWxgDownload> addRec) {
        // 新增网点师傅 websit_worker+商户网点师傅信息 存在修改，不存在新增
        Map<String,List<WebsitOrderSign>> websitOrderSignMap = new HashMap<>();
        Map<String, List<Worker>> workerIdCardMap = new HashMap<>();
        List<Websit> websitrec = new ArrayList<>();
        Map<String,List<Websit>> websitMap = new HashMap<>();
        List<WorkerBrandAccount> addwbas = new ArrayList<>();
        List<WebsitWorker> websitWorkeradd = new ArrayList<>();
        List<WorkerBrandAccount> upWorkerBrandAccount = new ArrayList<>();

        // 提取平台师傅信息
        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));
        }

        // 平台服务商网点信息
        websitrec = websitService.lambdaQuery()
                .select(Websit::getWebsitId,Websit::getServiceId,Websit::getWebsitName).list();
        if (CollectionUtils.isNotEmpty(websitrec)){
            websitMap = websitrec.stream().collect(Collectors.groupingBy(Websit::getWebsitId));
        }

        // 查看品牌网点与平台网点是否存在对应关系 （存在品牌网点对应平台多网点）
        List<WebsitOrderSign> wos = publicService.SyncshshwdToptshwd();
        if (CollectionUtils.isNotEmpty(wos)){
            websitOrderSignMap = wos.stream().collect(Collectors.groupingBy(WebsitOrderSign::getBrandWebsitId));
        }

        if (addRec.size()>0){
            // 生成平台网点及品牌商网点师傅数据
            getWebsitWorkerBrandAccounts(addRec, websitOrderSignMap, workerIdCardMap, websitMap, addwbas,
                    websitWorkeradd, upWorkerBrandAccount);

            // 修改品牌商网点师傅数据
            if (upWorkerBrandAccount.size()>0){
                workerBrandAccountService.updateBatchById(upWorkerBrandAccount);
                upWorkerBrandAccount.clear();
            }

            // 新增品牌师傅网点信息
            if (addwbas.size()>0){
                workerBrandAccountService.saveBatch(addwbas);
                addwbas.clear();
            }

            // 新增师傅所在平台网点信息
            if (websitWorkeradd.size()>0){
                websitWorkerService.saveBatch(websitWorkeradd);
                websitWorkeradd.clear();
            }
        }
    }


    private void addWebsitWorkerBrandAccounts(List<ItfTblWangdianWxgDownload> addRec, List<ItfTblWangdianWxgDownload> updateRec) {
        // 新增网点师傅 websit_worker+商户网点师傅信息 存在修改，不存在新增
        Map<String,List<WebsitOrderSign>> websitOrderSignMap = new HashMap<>();
        Map<String, List<Worker>> workerIdCardMap = new HashMap<>();
        List<Websit> websitrec = new ArrayList<>();
        Map<String,List<Websit>> websitMap = new HashMap<>();
        List<WorkerBrandAccount> addwbas = new ArrayList<>();
        List<WebsitWorker> websitWorkeradd = new ArrayList<>();
        List<WorkerBrandAccount> upWorkerBrandAccount = new ArrayList<>();

        // 提取平台师傅信息
        List<Worker> oldWorkerRec =  workerService.lambdaQuery()
                .select(Worker::getIdcard,Worker::getWorkerId,Worker::getWorkerName).list();
        if (CollectionUtils.isNotEmpty(oldWorkerRec)){
            workerIdCardMap = oldWorkerRec.stream().collect(Collectors.groupingBy(Worker::getIdcard));
        }

        websitrec = websitService.lambdaQuery()
                .select(Websit::getWebsitId,Websit::getServiceId,Websit::getWebsitName).list();
        if (CollectionUtils.isNotEmpty(websitrec)){
            websitMap = websitrec.stream().collect(Collectors.groupingBy(Websit::getWebsitId));
        }

        // 查看品牌网点与平台网点是否存在对应关系 （存在品牌网点对应平台多网点）
        List<WebsitOrderSign> wos = publicService.SyncshshwdToptshwd();
        if (CollectionUtils.isNotEmpty(wos)){
            websitOrderSignMap = wos.stream().collect(Collectors.groupingBy(WebsitOrderSign::getBrandWebsitId));
        }

        if (addRec.size()>0){
            // 生成平台网点及品牌商网点师傅数据
            getWebsitWorkerBrandAccounts(addRec, websitOrderSignMap, workerIdCardMap, websitMap, addwbas,
                    websitWorkeradd, upWorkerBrandAccount);

            // 修改品牌商网点师傅数据
            if (upWorkerBrandAccount.size()>0){
                workerBrandAccountService.updateBatchById(upWorkerBrandAccount);
                upWorkerBrandAccount.clear();
            }

            // 新增品牌师傅网点信息
            if (addwbas.size()>0){
                workerBrandAccountService.saveBatch(addwbas);
                addwbas.clear();
            }

            // 新增师傅所在平台网点信息
            if (websitWorkeradd.size()>0){
                websitWorkerService.saveBatch(websitWorkeradd);
                websitWorkeradd.clear();
            }

        }

        if (updateRec.size()>0){
            // 生成平台网点及品牌商网点师傅数据
            getWebsitWorkerBrandAccounts(updateRec, websitOrderSignMap, workerIdCardMap, websitMap,
                    addwbas, websitWorkeradd, upWorkerBrandAccount);

            // 修改品牌商网点师傅数据
            if (upWorkerBrandAccount.size()>0){
                workerBrandAccountService.updateBatchById(upWorkerBrandAccount);
                upWorkerBrandAccount.clear();
            }

            // 新增品牌师傅网点信息
            if (addwbas.size()>0){
                workerBrandAccountService.saveBatch(addwbas);
                addwbas.clear();
            }

            // 新增师傅所在平台网点信息
            if (websitWorkeradd.size()>0){
                websitWorkerService.saveBatch(websitWorkeradd);
                websitWorkeradd.clear();
            }
        }
    }

    @Nullable
    private void getWebsitWorkerBrandAccounts(List<ItfTblWangdianWxgDownload> addRec,
                                                                  Map<String, List<WebsitOrderSign>> websitOrderSignMap,
                                                                  Map<String, List<Worker>> workerIdCardMap,
                                                                  Map<String, List<Websit>> websitMap,
                                                                  List<WorkerBrandAccount> addwbas,
                                                                  List<WebsitWorker> websitWorkeradd,
                                                                  List<WorkerBrandAccount> upWorkerBrandAccounts) {
        List<String> WebsitWorkers = new ArrayList<>();

        for (ItfTblWangdianWxgDownload m : addRec){
            // 只有存在网点对应关系才可以新增师傅到网点信息中来 存在品牌网点对应平台多网点
            if (!websitOrderSignMap.containsKey(m.getWdno())){
                continue;
            }
            // 看师傅+网点信息 在品牌商网点信息是否存在 存在修改，不存在新增 会存在多条记录
            List<WorkerBrandAccount>  oldwbas = workerBrandAccountService.lambdaQuery()
                    .eq(WorkerBrandAccount::getBrandWebsitId,m.getWdno())
                    .eq(WorkerBrandAccount::getBrandWorkerId,m.getWxgid()).list();

            // 存在修只改师傅帐号状态
            if (CollectionUtils.isNotEmpty(oldwbas)){
                for (WorkerBrandAccount wba : oldwbas){
                    // 修改网点师傅信息
                    wba.setBrandWorkerStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
                    if (m.getFlag() != null){
                        if (m.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                            wba.setBrandWorkerStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
                        }
                    }
                    wba.setOutSyncTime(new Date());
                }
                upWorkerBrandAccounts.addAll(oldwbas);
                // 修改平台网点师傅信息 要求存在就不修改只新增
            } else {
                // 新增师傅所在品牌、商户网点信息
                List<WebsitOrderSign> wosrec = new ArrayList<>();
                wosrec = websitOrderSignMap.get(m.getWdno());
                // 存在品牌网点对应平台多网点 平台网点信息
                for (WebsitOrderSign i : wosrec){
                    // 若师傅没找到说明师傅信息未同步到师傅信息表，不处理 等下次处理即可
                    String workerId = checkIsGreeWroker(workerIdCardMap, m);
                    if (workerId.length()<1) {
                        continue;
                    }

                    // 生成品牌师傅网点信息对像
                    WorkerBrandAccount add = getWorkerBrandAccount(workerIdCardMap, websitMap, m, addwbas, i);
                    // 主键： worker_id + websit_id  已添加过就不再添加
                    if (WebsitWorkers.contains(add.getWorkerId()+add.getWebsitId())){
                        continue;
                    }
                    WebsitWorkers.add(add.getWorkerId()+add.getWebsitId());
                    // 生成师傅所在平台网点信息对像(如已存在不再新增 即不修改平台网点师傅信息)
                    WebsitWorker ww = websitWorkerService.lambdaQuery()
                            .eq(WebsitWorker::getWorkerId,add.getWorkerId())
                            .eq(WebsitWorker::getWebsitId,i.getWebsitId())
                            .last("limit 1")
                            .one();

                    if (ww == null){
                        getWebsitWorker(workerIdCardMap, websitMap, m, websitWorkeradd, i, add);
                    }
                }
            }
            // 修改品牌商网点师傅数据
            if (upWorkerBrandAccounts.size()>1000){
                workerBrandAccountService.updateBatchById(upWorkerBrandAccounts);
                upWorkerBrandAccounts.clear();
            }

            // 新增品牌师傅网点信息
            if (addwbas.size()>1000){
                workerBrandAccountService.saveBatch(addwbas);
                addwbas.clear();
            }

            // 新增师傅所在平台网点信息
            if (websitWorkeradd.size()>1000){
                websitWorkerService.saveBatch(websitWorkeradd);
                websitWorkeradd.clear();
            }
        }
        WebsitWorkers.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;
    }

    private void getWebsitWorker(Map<String, List<Worker>> workerIdCardMap, Map<String, List<Websit>> websitrecMap,
                                 ItfTblWangdianWxgDownload m, List<WebsitWorker> websitWorkeradd,
                                 WebsitOrderSign i, WorkerBrandAccount add) {
        WebsitWorker v = new WebsitWorker();
        // 一定要与worker_brand_account.websit_worker_id相同
        v.setWebsitWorkerId(add.getWebsitWorkerId());
        v.setServiceId(websitrecMap.get(i.getWebsitId()).get(0).getServiceId());
        v.setWebsitId(add.getWebsitId());
        v.setWorkerId(add.getWorkerId());
        v.setCreateBy("system");
        v.setUpdateBy("system");
        v.setCreateTime(new Date());
        v.setUpdateTime(new Date());
        if (m.getCreatedBy() != null){
            v.setCreateBy(m.getCreatedBy());
        }
        if (m.getCreatedDate() != null){
            v.setCreateTime(m.getCreatedDate());
        }
        if (m.getLastModifiedBy() != null){
            v.setUpdateBy(m.getLastModifiedBy());
        }
        if (m.getLastModifiedDate() != null){
            v.setUpdateTime(m.getLastModifiedDate());
        }

        for (Worker w:workerIdCardMap.get(m.getSfzen())){
            if (w.getMobile().equals(m.getYddh())){
                v.setWorkerName(w.getWorkerName());
                break;
            }
        }
        // v.setWorkerName(workerIdCardMap.get(m.getSfzen()).get(0).getWorkerName());

        v.setStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
        if (m.getFlag() != null){
            if (!m.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                v.setStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
            }
        }
        // 工程师类型
        // v.setWorkerType();
        // v.setBirthDate();
        v.setGender(m.getXingb());
        v.setMobile(m.getYddh());
        v.setIdcard(m.getSfzen());
        v.setAge(m.getNianl());
        v.setEducation(m.getXueli());
        // v.setAddress();

        v.setIsSmsNotice(DictTypeEnum.RECEIVE_TYPE_NO.getCode());
        if (m.getIfmessage() != null){
            if (!m.getIfmessage().trim().equals(DictTypeEnum.RECEIVE_TYPE_YES.getText())){
                v.setIsSmsNotice(DictTypeEnum.RECEIVE_TYPE_YES.getCode());
            }
        }
        v.setIsBlackList(DictTypeEnum.HMD_TYPE_NO.getCode());
        if (m.getSfhmd() != null){
            if (!m.getSfhmd().trim().equals(DictTypeEnum.HMD_TYPE_YES.getText())){
                v.setIsBlackList(DictTypeEnum.HMD_TYPE_YES.getCode());
            }
        }
        v.setBlackListRemark(m.getHmdbz());
        v.setExamineStatus(v.getStatus());


        v.setNvq(m.getZgzh());
        v.setSafeNo(m.getGmbxdh());
        v.setTrain(m.getPxqk());
        v.setSkillLevel(m.getJsdj());
        v.setRemark(m.getBeiz());

        // 不能用
        // v.setAdminUserId(m.getUsid());

        v.setIsZst(DictTypeEnum.ZST_TYPE_NO.getCode());
        if (m.getSfzst() != null){
            if (!m.getSfzst().trim().equals(DictTypeEnum.ZST_TYPE_YES.getText())){
                v.setIsZst(DictTypeEnum.ZST_TYPE_YES.getCode());
            }
        }
        v.setZstExamineRemark(m.getShyj());
        v.setZstTime(m.getZstsj());

        v.setSafeCompany(m.getGmbxgs());
        v.setGmbxyxq(m.getGmbxyxq());

        v.setNewOldFlag(m.getXjflag());
        v.setCollectNum(m.getMrcjgdl());
        v.setCollectEnginNum(m.getMrcjgcjgdl());
        v.setCollectLimitNum(m.getYxcjgdl());
        v.setCollectEnginLimitNum(m.getYxcjgcjgdl());
        v.setMrdate(m.getMrdate());
        v.setSaleExamineBy(m.getXsgsshren());
        v.setSaleExamineTime(m.getXsgsshsj());
        v.setSaleExamineStatus(m.getXsgsshstat());
        v.setSaleExamineRemark(m.getXsgsshbeiz());
        v.setSaleZstExamineBy(m.getZstshren());
        v.setScore(m.getWxfensu());
        v.setOldMobile(m.getYddhold());

        v.setHasFace(m.getHasface());
        v.setFacePath(m.getFacepath());
        v.setFaceCheck(m.getFacecheck());

        v.setCarNo(m.getCphm());
        v.setGpsMachineId(m.getGpsid());
        v.setVipFlag(m.getVipflag());

        v.setSyncFlag(1);

        websitWorkeradd.add(v);
    }

    @NotNull
    private WorkerBrandAccount getWorkerBrandAccount(Map<String, List<Worker>> workerIdCardMap,
                                                     Map<String, List<Websit>> websitrecMap,
                                                     ItfTblWangdianWxgDownload m,
                                                     List<WorkerBrandAccount> addwbas, WebsitOrderSign i) {
        WorkerBrandAccount add = new WorkerBrandAccount();

        for (Worker w:workerIdCardMap.get(m.getSfzen())){
            if (w.getWorkerName().equals(m.getWxgmc()) && w.getMobile().equals(m.getYddh())){
                add.setWorkerId(w.getWorkerId());
                break;
            }
        }
        // add.setWorkerId(workerIdCardMap.get(m.getSfzen()).get(0).getWorkerId());

        // 自生成 一定要与websit_worker.websit_worker_id相同
        add.setWebsitWorkerId(IdWorker.getIdStr());
        add.setGroupCompanyId(i.getGroupCompanyId());
        add.setGroupCompanyName(i.getGroupCompanyName());
        add.setWebsitId(i.getWebsitId());
        // 网点名称
        add.setWebsitName(websitrecMap.get(i.getWebsitId()).get(0).getWebsitName());
        add.setBrandWebsitId(i.getBrandWebsitId());
        add.setBrandWebsitName(i.getBrandWebsitName());
        add.setBrandWorkerId(String.valueOf(m.getWxgid()));
        add.setBrandWorkerNumber(m.getWxgno());
        add.setBrandWorkerStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
        if (m.getFlag() != null){
            if (m.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                add.setBrandWorkerStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
            }
        }
        add.setCreateBy("system");
        add.setUpdateBy("system");
        add.setCreateTime(new Date());
        add.setUpdateTime(new Date());
        if (m.getCreatedBy() != null){
            add.setCreateBy(m.getCreatedBy());
        }
        if (m.getCreatedDate() != null){
            add.setCreateTime(m.getCreatedDate());
        }
        if (m.getLastModifiedBy() != null){
            add.setUpdateBy(m.getLastModifiedBy());
        }
        if (m.getLastModifiedDate() != null){
            add.setUpdateTime(m.getLastModifiedDate());
        }
        add.setOutSyncTime(new Date());
        addwbas.add(add);
        return add;
    }

    private void getWorker(List<Worker> addWorkerRec, List<String> sfzens, ItfTblWangdianWxgDownload m,
                           Map<String, List<Worker>> workerIdcardMap) {
        Boolean flag = Boolean.FALSE;
        Worker v = new Worker();
        v.setWorkerId(IdWorker.getIdStr());
        // 师傅身份证,名称，电话 已存在为修改
        if (workerIdcardMap.containsKey(m.getSfzen())){
            // v.setWorkerId(workerIdcardMap.get(m.getSfzen()).get(0).getWorkerId());
            for (Worker w:workerIdcardMap.get(m.getSfzen())){
                if (w.getWorkerName().equals(m.getWxgmc()) && w.getMobile().equals(m.getYddh())){
                    v.setWorkerId(w.getWorkerId());
                    flag = Boolean.TRUE;
                    break;
                }
            }
        }
        v.setWorkerName(m.getWxgmc());
        //v.setIsReal("YES");
        // v.setFddReal("NO");
        // v.setFddSerialNo();
        v.setCreateBy("system");
        v.setUpdateBy("system");
        v.setCreateTime(new Date());
        v.setUpdateTime(new Date());
        if (m.getCreatedBy() != null){
            v.setCreateBy(m.getCreatedBy());
        }
        if (m.getCreatedDate() != null){
            v.setCreateTime(m.getCreatedDate());
        }
        if (m.getLastModifiedBy() != null){
            v.setUpdateBy(m.getLastModifiedBy());
        }
        if (m.getLastModifiedDate() != null){
            v.setUpdateTime(m.getLastModifiedDate());
        }
        // 这里为网点师傅状态并不能同步
        /*if (m.getFlag() != null){
            if (!m.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                v.setStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
            }
        }*/
        // v.setBirthDate();
        v.setGender(m.getXingb());
        v.setMobile(m.getYddh());
        v.setIdcard(m.getSfzen());
        v.setAge(m.getNianl());
        // v.setNameLevel();
        // v.setIntegralLevel();
        // v.setUserNameLevel();
        // v.setIntegralFree()
        // v.setServiceIntegral();
        v.setEducation(m.getXueli());
        // v.setAddress();
        // 为网点数据不能同步
        /*v.setIsSmsNotice(DictTypeEnum.RECEIVE_TYPE_NO.getCode());
        if (m.getIfmessage() != null){
            if (!m.getIfmessage().trim().equals(DictTypeEnum.RECEIVE_TYPE_YES.getText())){
                v.setIsSmsNotice(DictTypeEnum.RECEIVE_TYPE_YES.getCode());
            }
        }
        v.setIsBlackList(DictTypeEnum.HMD_TYPE_NO.getCode());
        if (m.getSfhmd() != null){
            if (!m.getSfhmd().trim().equals(DictTypeEnum.HMD_TYPE_YES.getText())){
                v.setIsBlackList(DictTypeEnum.HMD_TYPE_YES.getCode());
            }
        }
        v.setBlackListRemark(m.getHmdbz());
        v.setExamineStatus(v.getStatus());*/

        v.setNvq(m.getZgzh());
        // v.setWebsitNumber(m.getWdno());
        v.setSafeNo(m.getGmbxdh());
        // v.setTrain(m.getPxqk());
        v.setSkillLevel(m.getJsdj());
        v.setRemark(m.getBeiz());

        // 不能用
        // v.setAdminUserId(m.getUsid());

        v.setIsZst(DictTypeEnum.ZST_TYPE_NO.getCode());
        if (m.getSfzst() != null){
            if (!m.getSfzst().trim().equals(DictTypeEnum.ZST_TYPE_YES.getText())){
                v.setIsZst(DictTypeEnum.ZST_TYPE_YES.getCode());
            }
        }
        v.setZstExamineRemark(m.getShyj());
        v.setZstTime(m.getZstsj());
        /*v.setTrainStatus(Boolean.FALSE);
        if (m.getSfpxhg()>0){
            v.setTrainStatus(Boolean.TRUE);
        }
        v.setHasFace(m.getHasface());
        v.setFacePath(m.getFacepath());
        v.setFaceCheck(m.getFacecheck());*/
        v.setCarNo(m.getCphm());
        v.setGpsMachineId(m.getGpsid());
        v.setVipFlag(m.getVipflag());
        // 修改时不变动来源
        if (!flag){
            v.setSyncFlag(1);
        }
        addWorkerRec.add(v);
        sfzens.add(m.getSfzen() + m.getWxgmc() + m.getYddh());
    }

    private void extractedWorkerAddNew(List<ItfTblWangdianWxgDownload> addRec, List<Worker> addWorkerRec) {
        // 身份证 + 姓名 + 手机号
        List<String> sfzens = new ArrayList<>();
        Map<String, List<Worker>> workerIdcardMap = new HashMap<>();
        // 提取原有的信息
        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));
        }

        for (ItfTblWangdianWxgDownload m : addRec){
            // 已处理过不再处理 因为这里是网点师傅会存在重复数据
            if (sfzens.contains(m.getSfzen() + m.getWxgmc() + m.getYddh())){
                continue;
            }
            // 生成对象
            getWorker(addWorkerRec, sfzens, m, workerIdcardMap);

            // 新增的插入到表
            if (addWorkerRec.size()>=1000){
                workerService.saveOrUpdateBatch(addWorkerRec);
                log.info("本地网点维修工人员信息表新增插入了{}条数据", addWorkerRec.size());
                addWorkerRec.clear();
            }
        }

        sfzens.clear();
    }

    private void addWorkerInfo(List<ItfTblWangdianWxgDownload> addRec, List<ItfTblWangdianWxgDownload> updateRec, List<Worker> addWorkerRec) {
        // 获取新增的
        if (addRec.size()>0){
            // worker:师傅信息
            extractedWorkerAddNew(addRec, addWorkerRec);

            // 新增的插入到表
            if (addWorkerRec.size()>0){
                workerService.saveOrUpdateBatch(addWorkerRec);
                log.info("本地网点维修工人员信息表新增插入了{}条数据", addWorkerRec.size());
                addWorkerRec.clear();
            }
        }
        if (updateRec.size()>0){
            // worker:师傅信息
            extractedWorkerAddNew(updateRec, addWorkerRec);

            // 新增的插入到表
            if (addWorkerRec.size()>0){
                workerService.saveOrUpdateBatch(addWorkerRec);
                log.info("本地网点维修工人员信息表新增插入了{}条数据", addWorkerRec.size());
                addWorkerRec.clear();
            }
        }
    }

    private void addWorker(List<ItfTblWangdianWxgDownload> Recs) {
        List<Worker> addWorkerRec = new ArrayList<>();
        // 新增的
        if (Recs.size()>0){
            // worker:师傅信息
            extractedWorkerAddNew(Recs, addWorkerRec);

            // 新增的插入到表
            if (addWorkerRec.size()>0){
                workerService.saveOrUpdateBatch(addWorkerRec);
                log.info("本地网点维修工人员信息表新增插入了{}条数据", addWorkerRec.size());
                addWorkerRec.clear();
            }
        }
    }

    private void extractedLocalAddOrUpdate(List<ItfTblWangdianWxgDownload> addRec, List<ItfTblWangdianWxgDownload> updateRec) {

        List<Worker> addWorkerRec = new ArrayList<>();

        // 新增师傅数据 worker:师傅信息表
        addWorkerInfo(addRec, updateRec, addWorkerRec);

        // 新增 品牌网点师傅信息(worker_brand_account) + 平台网点师傅信息(websit_worker)
        addWebsitWorkerBrandAccounts(addRec, updateRec);
    }


    private void extractedAddOrUpdate(JSONArray jsonArray) {
        String synTaskNo = UUID.randomUUID().toString();
        List<ItfTblWangdianWxgDownload> add = new ArrayList<>();
        List<ItfTblWangdianWxgDownload> update = new ArrayList<>();
        List<Long> oldRecWxgId = new ArrayList<>();
        Map<Long, List<ItfTblWangdianWxgDownload>> oldRecMap = new HashMap<>();
        List<ItfTblWangdianWxgDownload> oldRec = new ArrayList<>();

        // 提取现有的数据信息
        oldRec =  itfTblWangdianWxgDownloadService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(oldRec)){
            oldRecWxgId = oldRec.stream().map(ItfTblWangdianWxgDownload::getWxgid).collect(Collectors.toList());
            oldRecMap = oldRec.stream().collect(Collectors.groupingBy(ItfTblWangdianWxgDownload::getWxgid));
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject aData = jsonArray.getJSONObject(i);
            ItfTblWangdianWxgDownload item = JSON.toJavaObject(aData,ItfTblWangdianWxgDownload.class);
            // 新增或修改数据
            // 修改
            if (oldRecWxgId.contains(item.getWxgid())){
                ItfTblWangdianWxgDownload old = oldRecMap.get(item.getWxgid()).get(0);
                MyBeanUtils.copyProperties(item,old);
                update.add(old);
                if (update.size()>1000){
                    itfTblWangdianWxgDownloadService.updateBatchById(update);
                    log.info("网点维修工基础资料信息同步更新修改了{}条数据", update.size());
                    update.clear();
                }
            } else {
                // 新增
                item.setSynTaskNo(synTaskNo);
                item.setSynReqTime(new Date());
                item.setSynStatus(1);
                item.setSynTime(new Date());
                item.setSynTimes(0);
                add.add(item);

                if (add.size()>1000){
                    itfTblWangdianWxgDownloadService.saveBatch(add);
                    log.info("网点维修工基础资料信息同步新增插入了{}条数据", add.size());
                    add.clear();
                }
            }
        }

        // 新增的插入到表
        if (add.size()>0){
            itfTblWangdianWxgDownloadService.saveBatch(add);
            log.info("网点维修工基础资料信息同步新增插入了{}条数据", add.size());
            add.clear();
        }
        // 更新
        if (update.size()>0){
            itfTblWangdianWxgDownloadService.updateBatchById(update);
            log.info("网点维修工基础资料信息同步更新修改了{}条数据", update.size());
            update.clear();
        }
    }
}
