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

import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.text.SimpleDateFormat;
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 extractedTMSC(JSONArray jsonArray){
        // 数据同步落到同步信息表
        extractedAddOrUpdate(jsonArray);
    }

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


    @Override
    public void inputWorkerData(){
        // 新增师傅数据 只新增不修改  修改为支持修改
        inputDataWorker();
    }

    @Override
    public void inputWebsitWorkerData(){
        // 添加网点师傅数据及平台与商户网点师傅数据  worker_brand_account(师傅网点对应品牌网点信息表) + websit_worker(网点师傅信息表))
        inputDataWebsitWorker();
    }

    void inputDataWebsitWorker(){
        List<String> sfzs = new ArrayList<>();
        List<String> recouts = new ArrayList<>();
        List<ItfTblWangdianWxgDownload> recs = new ArrayList<>();
        Map<Long,ItfTblWangdianWxgDownload> uprecs = new HashMap<>();


        // 提取所有的数据  身份证作为唯一 (有效与无效的只要有效的)
        extracted(sfzs, recouts);

        // 先同步有效的数据
        if (CollectionUtils.isNotEmpty(sfzs)){
            recs = itfTblWangdianWxgDownloadService.lambdaQuery()
                    .eq(ItfTblWangdianWxgDownload::getWebsitWorkerStatus,0)
                    .in(ItfTblWangdianWxgDownload::getSfzen,sfzs).list();
            // 新增网点师傅 websit_worker(商户网点师傅信息) 存在修改，不存在新增
            // 只做新增，不做修改动作，现调整为存在则修改
            addWebsitWorkerBrandAccountsInfo(recs, uprecs);
        }

        // 测试用
        /*recs = itfTblWangdianWxgDownloadService.lambdaQuery()
                .in(ItfTblWangdianWxgDownload::getSfzen,"420704199507165270").list();
        // 新增网点师傅 websit_worker(商户网点师傅信息) 存在修改，不存在新增
        // 只做新增，不做修改动作
        addWebsitWorkerBrandAccountsInfo(recs, uprecs);*/



        // 同步无效的数据
        if (CollectionUtils.isNotEmpty(recouts)){
            recs = itfTblWangdianWxgDownloadService.lambdaQuery()
                    .eq(ItfTblWangdianWxgDownload::getWebsitWorkerStatus,0)
                    .in(ItfTblWangdianWxgDownload::getSfzen,recouts).list();
            addWebsitWorkerBrandAccountsInfo(recs, uprecs);
        }

        if (uprecs.size()>0){
            List<ItfTblWangdianWxgDownload> wxgs = new ArrayList<>();
            uprecs.entrySet().stream()
                    .forEach(entry -> wxgs.add(entry.getValue()));
            itfTblWangdianWxgDownloadService.updateBatchById(wxgs);
            wxgs.clear();
        }

    }

    void inputDataWorker(){
        List<String> sfzs = new ArrayList<>();
        List<String> recouts = new ArrayList<>();
        List<ItfTblWangdianWxgDownload> recs = new ArrayList<>();
        Map<Long,ItfTblWangdianWxgDownload> uprecs = new HashMap<>();

        extracted(sfzs, recouts);

        // 先同步有效的数据
        if (CollectionUtils.isNotEmpty(sfzs)){
            recs = itfTblWangdianWxgDownloadService.lambdaQuery()
                    .eq(ItfTblWangdianWxgDownload::getSynStatus,0)
                    .in(ItfTblWangdianWxgDownload::getSfzen,sfzs).list();
            // 新增或修改师傅数据 worker:师傅信息表
            addInOutWorker(recs,Boolean.TRUE,uprecs);
        }

        // 同步无效的数据
        if (CollectionUtils.isNotEmpty(recouts)){
            recs = itfTblWangdianWxgDownloadService.lambdaQuery()
                    .eq(ItfTblWangdianWxgDownload::getSynStatus,0)
                    .in(ItfTblWangdianWxgDownload::getSfzen,recouts).list();
            // 新增或修改师傅数据 worker:师傅信息表
            addInOutWorker(recs,Boolean.FALSE,uprecs);
        }

        if (uprecs.size()>0){
            List<ItfTblWangdianWxgDownload> wxgs = new ArrayList<>();
            uprecs.entrySet().stream()
                    .forEach(entry -> wxgs.add(entry.getValue()));
            itfTblWangdianWxgDownloadService.updateBatchById(wxgs);
            wxgs.clear();
        }

    }

    private void extracted(List<String> sfzs, List<String> recouts) {
        List<ItfTblWangdianWxgDownload> recs;// 提取所有的数据  身份证作为唯一 (有效与无效的只要有效的)
        List<String> recins = new ArrayList<>();

        // 有效
        recs = itfTblWangdianWxgDownloadService.lambdaQuery()
                .select(ItfTblWangdianWxgDownload::getSfzen)
                // .eq(ItfTblWangdianWxgDownload::getSfzen,"440221198908132726")// 测试用
                .ne(ItfTblWangdianWxgDownload::getFlag, "无效").list();
        recs.stream().forEach(wba -> {
            recins.add(wba.getSfzen());
        });
        // 去重
        dupRemoval(recins);

        //无效
        recs = itfTblWangdianWxgDownloadService.lambdaQuery()
                .select(ItfTblWangdianWxgDownload::getSfzen)
                // .eq(ItfTblWangdianWxgDownload::getSfzen,"440221198908132726")// 测试用
                .eq(ItfTblWangdianWxgDownload::getFlag, "无效").list();
        recs.stream().forEach(wba -> {
            recouts.add(wba.getSfzen());
        });
        // 去重
        dupRemoval(recouts);
        // 有效的
        sfzs.addAll(recins);
        //交
        recins.retainAll(recouts);
        //差 无效的
        recouts.removeAll(recins);
    }

    private void dupRemoval(List<String> recins) {
        Set set = new HashSet();
        set.addAll(recins);
        recins.clear();
        recins.addAll(set);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addWebsitWorkerBrandAccountsInfo(List<ItfTblWangdianWxgDownload> addRec,Map<Long,ItfTblWangdianWxgDownload> uprecs) {
        // 新增网点师傅 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>> ptPpWebsitMap = 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));
            oldWorkerRec.clear();
        }

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

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

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

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

            // 新增品牌师傅网点信息
            if (addwbas.size()>0){
                workerBrandAccountService.saveBatch(addwbas);
                log.info("新增了品牌商网点师傅数据:{}",addwbas.size());
                addwbas.clear();
            }

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




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

        for (ItfTblWangdianWxgDownload m : addRec){
            // 只有存在网点对应关系才可以新增师傅到网点信息中来 存在品牌网点对应平台多网点
            if (!websitOrderSignMap.containsKey(m.getWdno())){
                continue;
            }

            // 看师傅+网点信息 在品牌商网点信息是否存在 存在修改，不存在新增 会存在多条记录
            // 1：按总部师傅已同步并写入表处理
            oldwbas = workerBrandAccountService.lambdaQuery()
                    .eq(WorkerBrandAccount::getBrandWebsitId,m.getWdno())
                    .eq(WorkerBrandAccount::getBrandWorkerId,m.getWxgid()).list();

            // 无数据时 会存在平台已添加了师傅入驻对应的网点但并未同步到总部时需再次查询
            if (oldwbas.size()<=0){
                if (workerIdCardMap.containsKey(m.getSfzen().trim())){
                    oldwbas = workerBrandAccountService.lambdaQuery()
                            .eq(WorkerBrandAccount::getWorkerId,workerIdCardMap.get(m.getSfzen().trim()).get(0).getWorkerId())
                            .eq(WorkerBrandAccount::getBrandWebsitId,m.getWdno()).list();
                }
            }

            // 存在只修改师傅帐号状态 + 网点编号因为平台会删除
            if (oldwbas.size()>0){
                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());
                        }
                    }
                    // 网点编号
                    if (StringUtils.isEmpty(wba.getBrandWorkerNumber())){
                        wba.setBrandWorkerNumber(m.getWxgno());
                    }
                    wba.setOutSyncTime(new Date());
                }
                upWorkerBrandAccounts.addAll(oldwbas);
                // 修改平台网点师傅信息 要求存在就不修改只新增
                m.setWebsitWorkerStatus(1);
            } 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;
                    }

                    // 平台的网点也必须在平台网点中存在
                    if (!ptPpWebsitMap.containsKey(i.getWebsitId())){
                        continue;
                    }

                    // 生成品牌师傅网点信息对像
                    WorkerBrandAccount add = getWorkerBrandAccount(workerIdCardMap, ptPpWebsitMap, m, addwbas, i);
                    // 主键： worker_id + websit_id  已添加过就不再添加
                    if (WebsitWorkers.contains(add.getWorkerId()+add.getWebsitId())){
                        m.setWebsitWorkerStatus(1);
                        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, ptPpWebsitMap, m, websitWorkeradd, i, add);
                    }
                    m.setWebsitWorkerStatus(1);
                }
            }

            if (m.getWebsitWorkerStatus().equals(1)){
                uprecs.put(m.getSynReqId(),m);
            }

            // 修改品牌商网点师傅数据
            if (upWorkerBrandAccounts.size()>100){
                workerBrandAccountService.updateBatchById(upWorkerBrandAccounts);
                log.info("修改了品牌商网点师傅数据:{}",upWorkerBrandAccounts.size());
                upWorkerBrandAccounts.clear();
            }

            // 新增品牌师傅网点信息
            if (addwbas.size()>100){
                workerBrandAccountService.saveBatch(addwbas);
                log.info("新增了品牌商网点师傅数据:{}",upWorkerBrandAccounts.size());
                addwbas.clear();
            }

            // 新增师傅所在平台网点信息
            if (websitWorkeradd.size()>100){
                websitWorkerService.saveBatch(websitWorkeradd);
                log.info("新增了师傅所在平台网点信息:{}",upWorkerBrandAccounts.size());
                websitWorkeradd.clear();
            }
        }
        WebsitWorkers.clear();
    }

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

    private void getWebsitWorker(Map<String, List<Worker>> workerIdCardMap, Map<String, List<Websit>> ptPpWebsitMap,
                                 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(ptPpWebsitMap.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());
        }*/

        v.setWorkerName(workerIdCardMap.get(m.getSfzen()).get(0).getWorkerName());

        // v.setWorkerName(workerIdCardMap.get(m.getSfzen()).get(0).getWorkerName());

        v.setReceOrderStatus(DictTypeEnum.DICT_TYPE_ON.getCode());
        if (m.getFlag() != null){
            if (!m.getFlag().trim().equals(DictTypeEnum.DICT_TYPE_FLAG_ON.getCode())){
                v.setReceOrderStatus(DictTypeEnum.DICT_TYPE_OFF.getCode());
            }
        }

        v.setStatus("ON");

        // 工程师类型
        // v.setWorkerType();
        // v.setBirthDate();
        v.setGender(m.getXingb());
        v.setMobile(m.getYddh());
        v.setIdcard(m.getSfzen().trim());
        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>> ptPpWebsitMap,
                                                     ItfTblWangdianWxgDownload m,
                                                     List<WorkerBrandAccount> addwbas, WebsitOrderSign i) {
        WorkerBrandAccount add = new WorkerBrandAccount();

        add.setWorkerId(workerIdCardMap.get(m.getSfzen().trim()).get(0).getWorkerId());
        // add.setWorkerId(workerIdCardMap.get(m.getSfzen()).get(0).getWorkerId());

        // 自生成 一定要与websit_worker.websit_worker_id相同
        // websitId + 手机号
        // 存放总部的师傅编号
        add.setWebsitWorkerId(m.getWxgno());

        add.setGroupCompanyId(i.getGroupCompanyId());
        add.setGroupCompanyName(i.getGroupCompanyName());
        add.setWebsitId(i.getWebsitId());
        // 网点名称
        add.setWebsitName(ptPpWebsitMap.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.getLastModifiedDate() != null){
            add.setUpdateTime(m.getLastModifiedDate());
        }

        /*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 getWorkerBak(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().trim()) && w.getMobile().equals(m.getYddh())){
                    v.setWorkerId(w.getWorkerId());
                    flag = Boolean.TRUE;
                    break;
                }
            }
        }
        v.setWorkerName(m.getWxgmc().trim());
        //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().trim() + m.getYddh());
    }

    private Worker addWorkerInfo(ItfTblWangdianWxgDownload m,Boolean flag, String workerId) {
        Worker v = new Worker();
        //  S + 手机号
        // v.setWorkerId(IdWorker.getIdStr());
        // v.setWorkerId("S" + m.getYddh());
        v.setWorkerId("W" + workerId);


        v.setWorkerName(m.getWxgmc().trim());
        v.setFirstWord(PinyinUtil.getPinyin(v.getWorkerName().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
        v.setCreateBy("system");
        v.setUpdateBy("system");
        v.setCreateTime(new Date());
        v.setUpdateTime(new Date());
        v.setStatus("ON");
        if (flag){
            v.setTestFlag("合格");
        }


        if (m.getCreatedDate() != null){
            v.setCreateTime(m.getCreatedDate());
        }

        if (m.getLastModifiedDate() != null){
            v.setUpdateTime(m.getLastModifiedDate());
        }


        /*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());
        }*/
        v.setGender(m.getXingb());
        v.setMobile(m.getYddh().trim());
        v.setIdcard(m.getSfzen().trim());
        v.setAge(m.getNianl());
        v.setEducation(m.getXueli());
        v.setNvq(m.getZgzh());
        v.setSafeNo(m.getGmbxdh());
        v.setSkillLevel(m.getJsdj());
        v.setRemark(m.getBeiz());
        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.setCarNo(m.getCphm());
        v.setGpsMachineId(m.getGpsid());
        v.setVipFlag(m.getVipflag());
        v.setSyncFlag(1);

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

        if (m.getHmdbz() != null){
            v.setBlackListRemark(m.getHmdbz());
        }


        return v;
    }

    private void upWorkerInfo(List<Worker> addWorkerRec, ItfTblWangdianWxgDownload m, Worker v) {
        Worker o = new Worker();
        MyBeanUtils.copyProperties(v,o);
        Boolean uflag = Boolean.FALSE;
        if (StringUtils.isNotEmpty(v.getWorkerName()) && StringUtils.isNotEmpty(m.getWxgmc().trim())){
            if (! v.getWorkerName().equals(m.getWxgmc().trim())){
                v.setWorkerName(m.getWxgmc().trim());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getWxgmc().trim())){
                v.setWorkerName(m.getWxgmc().trim());
                uflag = Boolean.TRUE;
            }
         }

        if (StringUtils.isNotEmpty(v.getGender()) && StringUtils.isNotEmpty(m.getXingb())){
            if (! v.getGender().equals(m.getXingb())){
                v.setGender(m.getXingb());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getXingb())){
                v.setGender(m.getXingb());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getMobile()) && StringUtils.isNotEmpty(m.getYddh())){
            if (! v.getMobile().equals(m.getYddh())){
                v.setMobile(m.getYddh());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getYddh())){
                v.setMobile(m.getYddh());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getIdcard()) && StringUtils.isNotEmpty(m.getSfzen())){
            if (! v.getIdcard().equals(m.getSfzen())){
            v.setIdcard(m.getSfzen());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getSfzen())){
                v.setIdcard(m.getSfzen());
                uflag = Boolean.TRUE;
            }
        }

        if (! v.getAge().equals(m.getNianl())){
            v.setAge(m.getNianl());
            uflag = Boolean.TRUE;
        }

        if (StringUtils.isNotEmpty(v.getEducation()) && StringUtils.isNotEmpty(m.getXueli())){
            if (! v.getEducation().equals(m.getXueli())){
            v.setEducation(m.getXueli());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getXueli())){
                v.setEducation(m.getXueli());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getNvq()) && StringUtils.isNotEmpty(m.getZgzh())){
            if (! v.getNvq().equals(m.getZgzh())){
            v.setNvq(m.getZgzh());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getZgzh())){
                v.setNvq(m.getZgzh());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getSafeNo()) && StringUtils.isNotEmpty(m.getGmbxdh())){
            if (! v.getSafeNo().equals(m.getGmbxdh())){
            v.setSafeNo(m.getGmbxdh());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getGmbxdh())){
                v.setSafeNo(m.getGmbxdh());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getSkillLevel()) && StringUtils.isNotEmpty(m.getJsdj())){
            if (! v.getSkillLevel().equals(m.getJsdj())){
            v.setSkillLevel(m.getJsdj());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getJsdj())){
                v.setSkillLevel(m.getJsdj());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getRemark()) && StringUtils.isNotEmpty(m.getBeiz())){
            if (! v.getRemark().equals(m.getBeiz())){
            v.setRemark(m.getBeiz());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getBeiz())){
                v.setRemark(m.getBeiz());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getIsZst()) && StringUtils.isNotEmpty(m.getSfzst())){
            if (m.getSfzst().trim().equals(DictTypeEnum.ZST_TYPE_YES.getText())){
                if (!v.getIsZst().equals(DictTypeEnum.ZST_TYPE_YES.getCode())) {
                    v.setIsZst(DictTypeEnum.ZST_TYPE_YES.getCode());
                    uflag = Boolean.TRUE;
                }
            } else {
                if (!v.getIsZst().equals(DictTypeEnum.ZST_TYPE_NO.getCode())) {
                    v.setIsZst(DictTypeEnum.ZST_TYPE_NO.getCode());
                    uflag = Boolean.TRUE;
                }
            }
        } else {
            if (StringUtils.isNotEmpty(m.getSfzst())){
                v.setIsZst(DictTypeEnum.ZST_TYPE_NO.getCode());
                if (!m.getSfzst().trim().equals(DictTypeEnum.ZST_TYPE_YES.getText())){
                    v.setIsZst(DictTypeEnum.ZST_TYPE_YES.getCode());
                }
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getZstExamineRemark()) && StringUtils.isNotEmpty(m.getShyj())){
            if (! v.getZstExamineRemark().equals(m.getShyj())){
            v.setZstExamineRemark(m.getShyj());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getShyj())){
                v.setZstExamineRemark(m.getShyj());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getCarNo()) && StringUtils.isNotEmpty(m.getCphm())){
            if (! v.getCarNo().equals(m.getCphm())){
            v.setCarNo(m.getCphm());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getCphm())){
                v.setCarNo(m.getCphm());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getGpsMachineId()) && StringUtils.isNotEmpty(m.getGpsid())){
            if (! v.getGpsMachineId().equals(m.getGpsid())){
            v.setGpsMachineId(m.getGpsid());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getGpsid())){
                v.setGpsMachineId(m.getGpsid());
                uflag = Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(v.getVipFlag()) && StringUtils.isNotEmpty(m.getVipflag())){
            if (! v.getVipFlag().equals(m.getVipflag())) {
                v.setVipFlag(m.getVipflag());
                uflag = Boolean.TRUE;
            }
        } else {
            if (StringUtils.isNotEmpty(m.getVipflag())){
                v.setVipFlag(m.getVipflag());
                uflag = Boolean.TRUE;
            }
        }

        if (uflag){
            v.setUpdateBy("system");
            v.setUpdateTime(new Date());
            if (m.getLastModifiedBy() != null){
                v.setUpdateBy(m.getLastModifiedBy());
            }
            if (m.getLastModifiedDate() != null){
                v.setUpdateTime(m.getLastModifiedDate());
            }

            addWorkerRec.add(v);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void extractedWorkerAddNewInOut(List<ItfTblWangdianWxgDownload> addRec, Boolean flag,
                                           Map<Long,ItfTblWangdianWxgDownload> uprecs) {
        // 身份证 作为唯一 (有效与无效的只要有效)
        List<String> sfzens = new ArrayList<>();
        List<String> mobiles = new ArrayList<>();
        List<Worker> addWorkerRec = new ArrayList<>();
        List<Worker> uupWorkerRec = new ArrayList<>();
        Map<String,Worker> workerIdCardMap = new HashMap<>();
        List<String> workdids = new ArrayList<>();
        List<String> workdidsUp = new ArrayList<>();

        // 提取原有的信息
        List<Worker> oldWorkerRec =  workerService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(oldWorkerRec)){
            oldWorkerRec.stream().forEach(wba->{
                sfzens.add(wba.getIdcard());
                mobiles.add(wba.getMobile());
                workerIdCardMap.put(wba.getIdcard(),wba);
            });
            oldWorkerRec.clear();
        }

        for (ItfTblWangdianWxgDownload m : addRec){
            m.setSynStatus(1);
            uprecs.put(m.getSynReqId(),m);
            /*// 已处理过不再处理 因为这里是网点师傅会存在重复数据
            if (sfzens.contains(m.getSfzen().trim())){
                continue;
            }
            */

            // 生成对象
            Worker v = addWorkerInfo(m, flag,workdids.get(0));

            // 存在修改，不存在新增
            if (sfzens.contains(m.getSfzen().trim())){
                // 最后修改日期比较 或 新数据为黑名单时一定要修改
                if (v.getUpdateTime().compareTo(workerIdCardMap.get(v.getIdcard()).getUpdateTime())>0 ||
                        (v.getIsBlackList().equals(DictTypeEnum.HMD_TYPE_YES.getText()) &&
                        workerIdCardMap.get(m.getSfzen().trim()).getIsBlackList().equals(DictTypeEnum.HMD_TYPE_NO.getText()))){
                    v.setWorkerId(workerIdCardMap.get(m.getSfzen().trim()).getWorkerId());
                    workerIdCardMap.put(v.getIdcard(),v);
                    uupWorkerRec.add(v);
                }
            } else {
                // S + 手机号 作为ID主键，手机号是不能重的 不再新增，会报错主键冲突
                /*if (mobiles.contains(m.getYddh().trim())){
                    continue;
                }*/
                workdidsUp.add(workdids.get(0));
                workdids.remove(0);
                sfzens.add(m.getSfzen().trim());
                mobiles.add(m.getYddh().trim());
                addWorkerRec.add(v);
                workerIdCardMap.put(v.getIdcard(),v);
            }

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

            // 修改的
            if (uupWorkerRec.size()>=500){
                workerService.updateBatchById(uupWorkerRec);
                log.info("本地网点维修工人员信息表修改了{}条数据", uupWorkerRec.size());
                uupWorkerRec.clear();
            }
        }

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

        // 修改的
        if (uupWorkerRec.size()>=500){
            workerService.updateBatchById(uupWorkerRec);
            log.info("本地网点维修工人员信息表修改了{}条数据", uupWorkerRec.size());
            uupWorkerRec.clear();
        }
        
        // 修改被使用状态
        if (uupWorkerRec.size()>=500){
            workerService.updateBatchById(uupWorkerRec);
            log.info("本地网点维修工人员信息表修改了{}条数据", uupWorkerRec.size());
            uupWorkerRec.clear();
        }

        sfzens.clear();
        mobiles.clear();
        workerIdCardMap.clear();
    }


    public void addInOutWorker(List<ItfTblWangdianWxgDownload> Recs,Boolean flag, Map<Long,ItfTblWangdianWxgDownload> uprecs) {
        if (Recs.size()>0){
            // worker:师傅信息
            extractedWorkerAddNewInOut(Recs, flag, uprecs);
        }
    }


    private void extractedAddOrUpdate(JSONArray jsonArray) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String synTaskNo = publicService.getUUID();
        List<ItfTblWangdianWxgDownload> add = new ArrayList<>();
        List<ItfTblWangdianWxgDownload> update = new ArrayList<>();
        List<Long> oldRecWxgId = new ArrayList<>();
        Map<Long, ItfTblWangdianWxgDownload> oldRecMap = new HashMap<>();
        List<ItfTblWangdianWxgDownload> oldRec = new ArrayList<>();
        String newdate = "";
        String olddate = "";

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

            oldRec.clear();
        }

        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());
                // 时间比较
                if (item.getLastModifiedDate() != null){
                    newdate = sdf.format(item.getLastModifiedDate());
                    olddate = sdf.format(old.getLastModifiedDate());
                    if (newdate.compareTo(olddate)<=0){
                        continue;
                    }
                } else {
                    item.setLastModifiedDate(new Date());
                }

                item.setSynTaskNo(synTaskNo);
                item.setSynReqTime(new Date());
                item.setSynStatus(0);
                item.setSynTime(new Date());
                item.setSynTimes(0);
                item.setSynReqId(old.getSynReqId());

                update.add(item);
                if (update.size()>1000){
                    itfTblWangdianWxgDownloadService.updateBatchById(update);
                    log.info("网点维修工基础资料信息同步更新修改了{}条数据", update.size());
                    update.clear();
                }
            } else {
                // 新增
                item.setSynTaskNo(synTaskNo);
                item.setSynReqTime(new Date());
                item.setSynStatus(0);
                item.setSynTime(new Date());
                item.setSynTimes(0);
                if (item.getLastModifiedDate() == null){
                    item.setLastModifiedDate(new Date());
                }
                add.add(item);

                oldRecWxgId.add(item.getWxgid());
                oldRecMap.put(item.getWxgid(),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();
        }

        oldRecMap.clear();
        oldRecWxgId.clear();
    }

}
