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.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.service.ProvinceCityAreaTownService;
import com.zfire.jiasm.syncdata.service.PublicService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProvinceCityAreaTownServiceImpl implements ProvinceCityAreaTownService {
    @Resource
    ItfTblProvinceDownloadService itfTblProvinceDownloadService;
    @Resource
    ItfTblCityDownloadService itfTblCityDownloadService;
    @Resource
    ItfTblCountyDownloadService itfTblCountyDownloadService;
    @Resource
    ItfTblCityJdxzDownloadService itfTblCityJdxzDownloadService;
    @Resource
    ProvinceService provinceService;
    @Resource
    CityService cityService;
    @Resource
    AreaService areaService;
    @Resource
    StreetService streetService;
    @Resource
    private PublicService publicService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedProvince(JSONArray jsonArray){
        List<ItfTblProvinceDownload> addRec = new ArrayList<>();
        List<ItfTblProvinceDownload> updateRec = new ArrayList<>();

        // 提取现有的数据信息
        List<ItfTblProvinceDownload> oldRec =  itfTblProvinceDownloadService.lambdaQuery().list();
        List<Long> oldRecsfid = oldRec.stream().map(ItfTblProvinceDownload::getSfid).collect(Collectors.toList());
        Map<Long, List<ItfTblProvinceDownload>> oldRecMap = oldRec.stream().collect(Collectors.groupingBy(ItfTblProvinceDownload::getSfid));

        String synTaskNo = publicService.getUUID();

        // 数据同步落到同步信息表
        extracted(addRec, updateRec, oldRecsfid, oldRecMap, jsonArray, synTaskNo);

        // 省份数据同步到本地表
        localextracted(addRec, updateRec);
        addRec.clear();
        updateRec.clear();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedCity(JSONArray jsonArray){
        List<ItfTblCityDownload> addRec = new ArrayList<>();
        List<ItfTblCityDownload> updateRec = new ArrayList<>();
        List<ItfTblCityDownload> addRecn = new ArrayList<>();
        List<ItfTblCityDownload> updateRecn = new ArrayList<>();

        List<ItfTblCityDownload> oldRec = new ArrayList<>();
        List<Long> oldRecCiid = new ArrayList<>();
        Map<Long, List<ItfTblCityDownload>> oldRecMap = new HashMap<>();

        String synTaskNo = publicService.getUUID();
        // 提取现有的数据信息
        oldRec =  itfTblCityDownloadService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(oldRec)){
            oldRecCiid = oldRec.stream().map(ItfTblCityDownload::getCiid).collect(Collectors.toList());
            oldRecMap = oldRec.stream().collect(Collectors.groupingBy(ItfTblCityDownload::getCiid));
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject aData = jsonArray.getJSONObject(i);
            ItfTblCityDownload item = JSON.toJavaObject(aData,ItfTblCityDownload.class);
            // 新增或修改
            extractedCityAddOrUpdate(addRec, updateRec, addRecn, updateRecn, synTaskNo, oldRecCiid, oldRecMap, item);
            // 数据同步落到同步信息表
            extractedLocalCityAddOrUpdata(addRecn, updateRecn);
        }

        if (addRecn.size()>0){
            itfTblCityDownloadService.saveBatch(addRecn);
            log.info("市信息同步新增插入了{}条数据", addRecn.size());
            addRecn.clear();
        }
        // 更新
        if (updateRecn.size()>0){
            itfTblCityDownloadService.updateBatchById(updateRecn);
            log.info("市信息同步更新修改了{}条数据", updateRecn.size());
            updateRecn.clear();
        }

        // 市数据同步到本地表
        extractedLoadlCityAddOrUpdate(addRec, updateRec);
        addRec.clear();
        updateRec.clear();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedCounty(JSONArray jsonArray) {
        List<ItfTblCountyDownload> addRec = new ArrayList<>();
        List<ItfTblCountyDownload> updateRec = new ArrayList<>();

        String synTaskNo = publicService.getUUID();

        // 数据同步落到同步信息表
        extractedCountyAddOrUpdate(addRec, updateRec, jsonArray, synTaskNo);

        // 区数据同步到本地表
        extractedLoaclAreaAddOrUpdate(addRec, updateRec);
        addRec.clear();
        updateRec.clear();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void extractedStreet(JSONArray jsonArray) throws ParseException {
        List<ItfTblCityJdxzDownload> addAllRec = new ArrayList<>();
        List<ItfTblCityJdxzDownload> updateRec = new ArrayList<>();

        // 数据同步落到同步信息表
        extractedCityJDXZAddOrUpdate(addAllRec, updateRec, jsonArray);

        // 提取区信息
        List<Area> areaRec =  areaService.lambdaQuery().list();
        List<String> areaRecName = areaRec.stream().map(Area::getArea).collect(Collectors.toList());
        Map<String, List<Area>> areaRecMap = areaRec.stream().collect(Collectors.groupingBy(Area::getArea));

        List<Street> addStreet = new ArrayList<>();
        List<Street> updateStreet = new ArrayList<>();

        // 获取新增的
        extractedStreetAdd(addAllRec, areaRecName, areaRecMap, addStreet);

        // 获取修改的
        extractedStreetUpdate(updateRec, areaRecName, areaRecMap, updateStreet);

        // 新增的插入到表
        if (addStreet.size()>0){
            streetService.saveOrUpdateBatch(addStreet);
            log.info("本地乡镇信息表新增插入了{}条数据",addStreet.size());
            addStreet.clear();
        }
        // 更新
        if (updateStreet.size()>0){
            streetService.saveOrUpdateBatch(updateStreet);
            log.info("本地乡镇信息表更新修改了{}条数据", updateStreet.size());
            updateStreet.clear();
        }

        addAllRec.clear();
        updateRec.clear();
    }

    private void extractedStreetAdd(List<ItfTblCityJdxzDownload> addAllRec, List<String> areaRecName,
                                    Map<String, List<Area>> areaRecMap, List<Street> addStreet) {
        if (addAllRec.size() > 0) {
            for (ItfTblCityJdxzDownload item : addAllRec) {
                // 提取区信息 若区不存在不新增
                if (areaRecName.contains(item.getCounty())) {
                    Street v = new Street();
                    v.setStreetId(item.getXzdm());
                    v.setStreet(item.getXzmc());
                    v.setAreaNo(item.getQuhao());
                    v.setPostalCode(item.getYzbm());
                    v.setDcCode(item.getQydm());
                    v.setOldDcCode(item.getJqydm());
                    if (areaRecMap.get(item.getCounty()).size() == 1) {
                        v.setAreaId(areaRecMap.get(item.getCounty()).get(0).getAreaId());
                        v.setArea(areaRecMap.get(item.getCounty()).get(0).getArea());
                        v.setCityId(areaRecMap.get(item.getCounty()).get(0).getCityId());
                        v.setCity(areaRecMap.get(item.getCounty()).get(0).getCity());
                        v.setProvinceId(areaRecMap.get(item.getCounty()).get(0).getProvinceId());
                        v.setProvince(areaRecMap.get(item.getCounty()).get(0).getProvince());
                    } else {
                        for (int i = 0; i < areaRecMap.get(item.getCounty()).size(); i++) {
                            Area x = areaRecMap.get(item.getCounty()).get(i);
                            // 省市相同时取值
                            if (x.getProvince().equals(item.getSfen()) && x.getCity().equals(item.getCity())) {
                                v.setAreaId(areaRecMap.get(item.getCounty()).get(0).getAreaId());
                                v.setArea(areaRecMap.get(item.getCounty()).get(0).getArea());
                                v.setCityId(areaRecMap.get(item.getCounty()).get(0).getCityId());
                                v.setCity(areaRecMap.get(item.getCounty()).get(0).getCity());
                                v.setProvinceId(areaRecMap.get(item.getCounty()).get(0).getProvinceId());
                                v.setProvince(areaRecMap.get(item.getCounty()).get(0).getProvince());
                            }
                        }
                    }
                    v.setStatus(Boolean.FALSE);
                    if (item.getStat() == 1) {
                        v.setStatus(Boolean.TRUE);
                    }
                    v.setCreateBy("system");
                    v.setCreateTime(new Date());
                    v.setInitial(PinyinUtil.getPinyin(v.getStreet().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                    addStreet.add(v);
                }

                // 新增的插入到表
                if (addStreet.size()>=500){
                    streetService.saveOrUpdateBatch(addStreet);
                    log.info("本地乡镇信息表新增插入了{}条数据",addStreet.size());
                    addStreet.clear();
                }
            }
        }
    }

    private void extractedStreetUpdate(List<ItfTblCityJdxzDownload> updateRec, List<String> areaRecName, Map<String, List<Area>> areaRecMap, List<Street> updateStreet) {
        if (updateRec.size() > 0) {
            for (ItfTblCityJdxzDownload item : updateRec) {
                // 提取区信息 若区信息不存在不修改
                if (areaRecName.contains(item.getCounty())) {
                    Street v = new Street();
                    v.setStreetId(item.getXzdm());
                    v.setStreet(item.getXzmc());
                    v.setStatus(Boolean.FALSE);
                    if (item.getStat() == 1){
                        v.setStatus(Boolean.TRUE);
                    }
                    v.setAreaNo(item.getQuhao());
                    v.setPostalCode(item.getYzbm());
                    v.setDcCode(item.getQydm());
                    v.setOldDcCode(item.getJqydm());

                    // 省市区取值
                    if (areaRecMap.get(item.getCounty()).size() == 1) {
                        v.setAreaId(areaRecMap.get(item.getCounty()).get(0).getAreaId());
                        v.setArea(areaRecMap.get(item.getCounty()).get(0).getArea());
                        v.setCityId(areaRecMap.get(item.getCounty()).get(0).getCityId());
                        v.setCity(areaRecMap.get(item.getCounty()).get(0).getCity());
                        v.setProvinceId(areaRecMap.get(item.getCounty()).get(0).getProvinceId());
                        v.setProvince(areaRecMap.get(item.getCounty()).get(0).getProvince());
                    } else {
                        for (int i = 0; i < areaRecMap.get(item.getCounty()).size(); i++) {
                            Area x = areaRecMap.get(item.getCounty()).get(i);
                            // 省市区相同时取值
                            if (x.getProvince().equals(item.getSfen()) && x.getCity().equals(item.getCity()) &&
                                    x.getArea().equals(item.getCounty())) {
                                v.setAreaId(x.getAreaId());
                                v.setArea(x.getArea());
                                v.setCityId(x.getCityId());
                                v.setCity(x.getCity());
                                v.setProvinceId(x.getProvinceId());
                                v.setProvince(x.getProvince());
                            }
                        }
                    }
                    v.setCreateBy("system");
                    v.setCreateTime(new Date());
                    v.setInitial(PinyinUtil.getPinyin(v.getStreet().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                    updateStreet.add(v);
                }

                // 更新
                if (updateStreet.size()>=500){
                    streetService.saveOrUpdateBatch(updateStreet);
                    log.info("本地乡镇信息表更新修改了{}条数据", updateStreet.size());
                    updateStreet.clear();
                }
            }
        }
    }

    private void extractedCityJDXZAddOrUpdate(List<ItfTblCityJdxzDownload> addAllRec, List<ItfTblCityJdxzDownload> updateRec, JSONArray jsonArray) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ItfTblCityJdxzDownload> addRec = new ArrayList<>();
        List<ItfTblCityJdxzDownload> updateRecn = new ArrayList<>();

        String synTaskNo = publicService.getUUID();

        // 提取现有的数据信息
        List<ItfTblCityJdxzDownload> oldRec =  itfTblCityJdxzDownloadService.lambdaQuery().list();
        List<String> oldRecXzdm = oldRec.stream().map(ItfTblCityJdxzDownload::getXzdm).collect(Collectors.toList());
        Map<String, List<ItfTblCityJdxzDownload>> oldRecMap = oldRec.stream().collect(Collectors.groupingBy(ItfTblCityJdxzDownload::getXzdm));

        Boolean flag = Boolean.FALSE;

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject aData = jsonArray.getJSONObject(i);
            ItfTblCityJdxzDownload item = JSON.toJavaObject(aData,ItfTblCityJdxzDownload.class);
            flag = Boolean.FALSE;


            // 修改
            if (oldRecXzdm.contains(item.getXzdm())){
                ItfTblCityJdxzDownload old = oldRecMap.get(item.getXzdm()).get(0);
                if (!old.getXzmc().equals(item.getXzmc())){
                    old.setXzmc(item.getXzmc());
                    flag = Boolean.TRUE;
                }
                if (!old.getSfen().equals(item.getSfen())){
                    old.setSfen(item.getSfen());
                    flag = Boolean.TRUE;
                }
                if (!old.getCity().equals(item.getCity())){
                    old.setCity(item.getCity());
                    flag = Boolean.TRUE;
                }
                if (!old.getCounty().equals(item.getCounty())){
                    old.setCounty(item.getCounty());
                    flag = Boolean.TRUE;
                }
                if (!old.getQuhao().equals(item.getQuhao())){
                    old.setQuhao(item.getQuhao());
                    flag = Boolean.TRUE;
                }
                if (!old.getQydm().equals(item.getQydm())){
                    old.setQydm(item.getQydm());
                    flag = Boolean.TRUE;
                }

                if (old.getJqydm() !=null || item.getJqydm()!=null){
                    if (old.getJqydm() !=null && item.getJqydm()!=null){
                        // 都有值时比较是否相同
                        if (!old.getJqydm().equals(item.getJqydm())){
                            old.setJqydm(item.getJqydm());
                            flag = Boolean.TRUE;
                        }
                    } else {
                        // 存在为null的值
                        old.setJqydm(item.getJqydm());
                        flag = Boolean.TRUE;
                    }
                }

                if (!old.getStat().equals(item.getStat())){
                    old.setStat(item.getStat());
                    flag = Boolean.TRUE;
                }
                if (flag){
                    updateRecn.add(old);
                }
            } else {
                // 新增
                if (item.getCjdt() !=null){
                    item.setCjdt(sdf.parse(sdf.format(item.getCjdt())));
                }
                item.setSynTaskNo(synTaskNo);
                item.setSynReqTime(new Date());
                item.setSynStatus(1);
                item.setSynTime(new Date());
                item.setSynTimes(0);
                addRec.add(item);
            }

            if (addRec.size()>=500){
                // 插入到表
                itfTblCityJdxzDownloadService.saveBatch(addRec);
                log.info("乡镇信息同步新增插入了{}条数据", addRec.size());
                addAllRec.addAll(addRec);
                addRec.clear();
            }

            if (updateRecn.size()>=500){
                // 插入到表
                itfTblCityJdxzDownloadService.saveBatch(updateRecn);
                log.info("乡镇信息同步更新修改了{}条数据", updateRecn.size());
                updateRec.addAll(updateRecn);
                updateRecn.clear();
            }
        }

        // 插入到表
        if (addRec.size()>0){
            // 插入到表
            itfTblCityJdxzDownloadService.saveBatch(addRec);
            log.info("乡镇信息同步新增插入了{}条数据", addRec.size());
            addAllRec.addAll(addRec);
            addRec.clear();
        }
        // 更新
        if (updateRecn.size()>0){
            itfTblCityJdxzDownloadService.updateBatchById(updateRecn);
            log.info("乡镇信息同步更新修改了{}条数据", updateRecn.size());
            updateRec.addAll(updateRecn);
            updateRecn.clear();
        }
    }


    // 省份数据同步到本地表
    private void localextracted(List<ItfTblProvinceDownload> addRec, List<ItfTblProvinceDownload> updateRec) {
        List<Province> addProvince = new ArrayList<>();
        List<Province> updateProvince = new ArrayList<>();
        // 获取新增的
        if (addRec.size()>0){
            for (ItfTblProvinceDownload item : addRec){
                Province v = new Province();
                v.setProvinceId(String.valueOf(item.getSfid()));
                v.setProvince(item.getSfen());
                v.setStatus(Boolean.FALSE);
                if (item.getStat()==2){
                    v.setStatus(Boolean.TRUE);
                }
                v.setCreateBy("system");
                v.setCreateTime(new Date());
                v.setInitial(PinyinUtil.getPinyin(v.getProvince().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                addProvince.add(v);
            }
        }
        // 获取修改的
        if (updateRec.size()>0){
            for (ItfTblProvinceDownload item : updateRec){
                Province v = new Province();
                v.setProvinceId(String.valueOf(item.getSfid()));
                v.setProvince(item.getSfen());
                v.setStatus(Boolean.FALSE);
                if (item.getStat()==2){
                    v.setStatus(Boolean.TRUE);
                }
                v.setCreateBy("system");
                v.setCreateTime(new Date());
                v.setInitial(PinyinUtil.getPinyin(v.getProvince().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                updateProvince.add(v);
            }
        }

        // 新增的插入到表
        if (addProvince.size()>0){
            provinceService.saveOrUpdateBatch(addProvince);
            log.info("本地省份信息表新增插入了{}条数据",addProvince.size());
            addProvince.clear();
        }
        // 更新
        if (updateProvince.size()>0){
            provinceService.saveOrUpdateBatch(updateProvince);
            log.info("本地省份信息表更新修改了{}条数据", updateProvince.size());
            updateProvince.clear();
        }
    }

    // 数据同步落到同步信息表
    private void extracted(List<ItfTblProvinceDownload> addRec, List<ItfTblProvinceDownload> updateRec,
                           List<Long> oldRecsfid, Map<Long, List<ItfTblProvinceDownload>> oldRecMap,
                           JSONArray jsonArray, String synTaskNo) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject aData = jsonArray.getJSONObject(i);
            ItfTblProvinceDownload item = JSON.toJavaObject(aData,ItfTblProvinceDownload.class);
            // 新增或修改数据
            getProvinceAddOrUpdate(addRec, updateRec, oldRecsfid, oldRecMap, synTaskNo, item);
        }
        // 新增的插入到表
        if (addRec.size()>0){
            itfTblProvinceDownloadService.saveBatch(addRec);
            log.info("省份信息同步新增插入了{}条数据",addRec.size());
        }
        // 更新
        if (updateRec.size()>0){
            itfTblProvinceDownloadService.updateBatchById(updateRec);
            log.info("省份信息同步更新修改了{}条数据", updateRec.size());
        }
    }

    // 新增或修改数据
    private void getProvinceAddOrUpdate(List<ItfTblProvinceDownload> addRec, List<ItfTblProvinceDownload> updateRec, List<Long> oldRecsfid, Map<Long, List<ItfTblProvinceDownload>> oldRecMap, String synTaskNo, ItfTblProvinceDownload item) {
        Boolean flag = Boolean.FALSE;

        if (oldRecsfid.contains(item.getSfid())){
            ItfTblProvinceDownload old = oldRecMap.get(item.getSfid()).get(0);
            if (!old.getSfen().equals(item.getSfen())){
                old.setSfen(item.getSfen());
                flag = Boolean.TRUE;
            }
            if (old.getStat() != item.getStat()){
                old.setStat(item.getStat());
                flag = Boolean.TRUE;
            }
            if (old.getQyjsbl() != item.getQyjsbl()){
                old.setQyjsbl(item.getQyjsbl());
                flag = Boolean.TRUE;
            }
            if (flag){
                old.setCzren(item.getCzren());
                old.setCzsj(item.getCzsj());
                updateRec.add(old);
            }
        } else {
            // 新增
            item.setSynTaskNo(synTaskNo);
            item.setSynReqTime(new Date());
            item.setSynTime(new Date());
            item.setSynStatus(1);
            item.setSynTimes(0);
            addRec.add(item);
        }
    }


    private void extractedLoadlCityAddOrUpdate(List<ItfTblCityDownload> addRec, List<ItfTblCityDownload> updateRec) {
        // 提取省份信息
        List<Province> provinceRec =  provinceService.lambdaQuery().list();
        List<String> provinceRecName = provinceRec.stream().map(Province::getProvince).collect(Collectors.toList());
        Map<String, List<Province>> provinceRecMap = provinceRec.stream().collect(Collectors.groupingBy(Province::getProvince));
        List<City> addCity = new ArrayList<>();
        List<City> updateCity = new ArrayList<>();


        // 获取新增的
        if (addRec.size()>0){
            for (ItfTblCityDownload item : addRec){
                // 提取省份ID 若省份不存在不新增
                if (provinceRecName.contains(item.getSfen())){
                    City v = new City();
                    v.setCityId(String.valueOf(item.getCiid()));
                    v.setCity(item.getCity());
                    v.setProvinceId(provinceRecMap.get(item.getSfen()).get(0).getProvinceId());
                    v.setProvince(item.getSfen());
                    v.setStatus(Boolean.FALSE);
                    if (item.getStat().compareTo(BigDecimal.valueOf(2)) == 0){
                        v.setStatus(Boolean.TRUE);
                    }
                    v.setCreateBy("system");
                    v.setCreateTime(new Date());
                    v.setInitial(PinyinUtil.getPinyin(v.getCity().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                    addCity.add(v);
                }

                // 新增的插入到表
                if (addCity.size()>=500){
                    cityService.saveOrUpdateBatch(addCity);
                    log.info("本地市信息表新增插入了{}条数据",addCity.size());
                    addCity.clear();
                }
            }
        }
        // 获取修改的
        if (updateRec.size()>0){
            for (ItfTblCityDownload item : updateRec){
                // 提取省份ID 若省份不存在不修改
                if (provinceRecName.contains(item.getSfen())){
                    City v = new City();
                    v.setCityId(String.valueOf(item.getCiid()));
                    v.setCity(item.getCity());
                    v.setProvince(item.getSfen());
                    v.setStatus(Boolean.FALSE);
                    if (item.getStat().compareTo(BigDecimal.valueOf(2)) == 0){
                        v.setStatus(Boolean.TRUE);
                    }
                    v.setProvinceId(provinceRecMap.get(item.getSfen()).get(0).getProvinceId());
                    v.setCreateBy("system");
                    v.setCreateTime(new Date());
                    v.setInitial(PinyinUtil.getPinyin(v.getCity().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                    updateCity.add(v);
                }

                // 更新
                if (updateCity.size()>=500){
                    cityService.saveOrUpdateBatch(updateCity);
                    log.info("本地市信息表更新修改了{}条数据", updateCity.size());
                    updateCity.clear();
                }
            }
        }

        // 新增的插入到表
        if (addCity.size()>0){
            cityService.saveOrUpdateBatch(addCity);
            log.info("本地市信息表新增插入了{}条数据",addCity.size());
            addCity.clear();
        }
        // 更新
        if (updateCity.size()>0){
            cityService.saveOrUpdateBatch(updateCity);
            log.info("本地市信息表更新修改了{}条数据", updateCity.size());
            updateCity.clear();
        }
    }

    private void extractedLocalCityAddOrUpdata(List<ItfTblCityDownload> addRec, List<ItfTblCityDownload> updateRec) {
        // 新增的插入到表
        if (addRec.size()>=500){
            itfTblCityDownloadService.saveBatch(addRec);
            log.info("市信息同步新增插入了{}条数据", addRec.size());
            addRec.clear();
        }
        // 更新
        if (updateRec.size()>=500){
            itfTblCityDownloadService.updateBatchById(updateRec);
            log.info("市信息同步更新修改了{}条数据", updateRec.size());
            updateRec.clear();
        }
    }

    private void extractedCityAddOrUpdate(List<ItfTblCityDownload> addRec, List<ItfTblCityDownload> updateRec,
                                          List<ItfTblCityDownload> addRecn, List<ItfTblCityDownload> updateRecn,
                                          String synTaskNo, List<Long> oldRecCiid, Map<Long, List<ItfTblCityDownload>> oldRecMap,
                                          ItfTblCityDownload item) {
        Boolean flag = Boolean.FALSE;

        // 修改
        if (oldRecCiid.contains(item.getCiid())){
            ItfTblCityDownload old = oldRecMap.get(item.getCiid()).get(0);
            if (!old.getSfen().equals(item.getSfen())){
                old.setSfen(item.getSfen());
                flag = Boolean.TRUE;
            }
            if (!old.getCity().equals(item.getCity())){
                old.setCity(item.getCity());
                flag = Boolean.TRUE;
            }
            if (!old.getStat().equals(item.getStat())){
                old.setStat(item.getStat());
                flag = Boolean.TRUE;
            }
            if (flag){
                old.setCzren(item.getCzren());
                old.setCzsj(item.getCzsj());
                updateRec.add(old);
                updateRecn.add(old);
            }
        } else {
            // 新增
            item.setSynTaskNo(synTaskNo);
            item.setSynReqTime(new Date());
            item.setSynStatus(1);
            item.setSynTime(new Date());
            item.setSynTimes(0);
            addRec.add(item);
            addRecn.add(item);
        }
    }

    private void extractedCountyAddOrUpdate(List<ItfTblCountyDownload> addRec, List<ItfTblCountyDownload> updateRec, JSONArray jsonArray, String synTaskNo) {
        Boolean flag = Boolean.FALSE;
        List<ItfTblCountyDownload> oldRec = new ArrayList<>();
        List<Long> oldRecCoid = new ArrayList<>();
        Map<Long, List<ItfTblCountyDownload>> oldRecMap = new HashMap<>();
        List<ItfTblCountyDownload> addRecn = new ArrayList<>();
        List<ItfTblCountyDownload> updateRecn = new ArrayList<>();

                // 提取现有的数据信息
        oldRec =  itfTblCountyDownloadService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(oldRec)){
            oldRecCoid = oldRec.stream().map(ItfTblCountyDownload::getCoid).collect(Collectors.toList());
        }
        oldRecMap = oldRec.stream().collect(Collectors.groupingBy(ItfTblCountyDownload::getCoid));

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject aData = jsonArray.getJSONObject(i);
            ItfTblCountyDownload item = JSON.toJavaObject(aData,ItfTblCountyDownload.class);
            flag = Boolean.FALSE;
            // 修改
            if (oldRecCoid.contains(item.getCoid())){
                ItfTblCountyDownload old = oldRecMap.get(item.getCoid()).get(0);
                if (!old.getSfen().equals(item.getSfen())){
                    old.setSfen(item.getSfen());
                    flag = Boolean.TRUE;
                }
                if (!old.getCity().equals(item.getCity())){
                    old.setCity(item.getCity());
                    flag = Boolean.TRUE;
                }
                if (!old.getCounty().equals(item.getCounty())){
                    old.setCounty(item.getCounty());
                    flag = Boolean.TRUE;
                }
                if (!old.getQuhao().equals(item.getQuhao())){
                    old.setQuhao(item.getQuhao());
                    flag = Boolean.TRUE;
                }
                if (!old.getQydm().equals(item.getQydm())){
                    old.setQydm(item.getQydm());
                    flag = Boolean.TRUE;
                }
                if (!old.getStat().equals(item.getStat())){
                    old.setStat(item.getStat());
                    flag = Boolean.TRUE;
                }
                if (flag){
                    old.setCzren(item.getCzren());
                    old.setCzsj(item.getCzsj());
                    updateRec.add(old);
                    updateRecn.add(old);
                }
            } else {
                // 新增
                item.setSynTaskNo(synTaskNo);
                item.setSynReqTime(new Date());
                item.setSynStatus(1);
                item.setSynTime(new Date());
                item.setSynTimes(0);
                addRec.add(item);
                addRecn.add(item);
            }

            // 新增的插入到表
            if (addRecn.size()>=500){
                itfTblCountyDownloadService.saveBatch(addRecn);
                log.info("区信息同步新增插入了{}条数据", addRecn.size());
                addRecn.clear();
            }
            // 更新
            if (updateRecn.size()>=500){
                itfTblCountyDownloadService.updateBatchById(updateRecn);
                log.info("区信息同步更新修改了{}条数据", updateRecn.size());
                updateRecn.clear();
            }


        }

        // 新增的插入到表
        if (addRecn.size()>0){
            itfTblCountyDownloadService.saveBatch(addRecn);
            log.info("区信息同步新增插入了{}条数据", addRecn.size());
            addRecn.clear();

        }
        // 更新
        if (updateRecn.size()>0){
            itfTblCountyDownloadService.updateBatchById(updateRecn);
            log.info("区信息同步更新修改了{}条数据", updateRecn.size());
            updateRecn.clear();
        }
    }

    private void extractedLoaclAreaAddOrUpdate(List<ItfTblCountyDownload> addRec, List<ItfTblCountyDownload> updateRec) {
        // 提取市信息
        List<City> cityRec =  cityService.lambdaQuery().list();
        List<String> cityRecName = cityRec.stream().map(City::getCity).collect(Collectors.toList());
        Map<String, List<City>>cityRecMap = cityRec.stream().collect(Collectors.groupingBy(City::getCity));

        List<Area> addArea = new ArrayList<>();
        List<Area> updateArea = new ArrayList<>();

        // 获取新增的
        getCountAdd(addRec, cityRecName, cityRecMap, addArea);
        // 获取修改的
        getCountUpdate(updateRec, cityRecName, cityRecMap, updateArea);

        // 新增的插入到表
        if (addArea.size()>0){
            areaService.saveOrUpdateBatch(addArea);
            log.info("本地区信息表新增插入了{}条数据",addArea.size());
            addArea.clear();
        }
        // 更新
        if (updateArea.size()>0){
            areaService.saveOrUpdateBatch(updateArea);
            log.info("本地区信息表更新修改了{}条数据", updateArea.size());
            updateArea.clear();
        }
    }

    private void getCountUpdate(List<ItfTblCountyDownload> updateRec, List<String> cityRecName,
                                Map<String, List<City>> cityRecMap, List<Area> updateArea) {
        if (updateRec.size() > 0) {
            for (ItfTblCountyDownload item : updateRec) {
                // 提取市信息 若市信息不存在不修改
                if (cityRecName.contains(item.getCity())) {
                    Area v = new Area();
                    v.setAreaId(String.valueOf(item.getCoid()));
                    v.setArea(item.getCounty());
                    // 省市取值
                    if (cityRecMap.get(item.getCity()).size() == 1) {
                        v.setCityId(cityRecMap.get(item.getCity()).get(0).getCityId());
                        v.setCity(cityRecMap.get(item.getCity()).get(0).getCity());
                        v.setProvinceId(cityRecMap.get(item.getCity()).get(0).getProvinceId());
                        v.setProvince(cityRecMap.get(item.getCity()).get(0).getProvince());
                    } else {
                        for (int i = 0; i < cityRecMap.get(item.getCity()).size(); i++) {
                            City x = cityRecMap.get(item.getCity()).get(i);
                            // 省市相同时取值
                            if (x.getProvince().equals(item.getSfen()) && x.getCity().equals(item.getCity())) {
                                v.setCityId(x.getCityId());
                                v.setCity(x.getCity());
                                v.setProvinceId(x.getProvinceId());
                                v.setProvince(x.getProvince());
                            }
                        }
                    }
                    v.setStatus(0);
                    if (item.getStat() == 2) {
                        v.setStatus(1);
                    }
                    v.setCreateBy("system");
                    v.setCreateTime(new Date());
                    v.setInitial(PinyinUtil.getPinyin(v.getArea().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                    updateArea.add(v);
                }

                // 更新
                if (updateArea.size()>=500){
                    areaService.saveOrUpdateBatch(updateArea);
                    updateArea.clear();
                    log.info("本地区信息表更新修改了{}条数据", updateArea.size());
                }
            }
        }
    }

    private void getCountAdd(List<ItfTblCountyDownload> addRec, List<String> cityRecName,
                             Map<String, List<City>> cityRecMap, List<Area> addArea) {
        if (addRec.size() > 0) {
            for (ItfTblCountyDownload item : addRec) {
                // 提取市信息 若市不存在不新增
                if (cityRecName.contains(item.getCity())) {
                    Area v = new Area();
                    v.setAreaId(String.valueOf(item.getCoid()));
                    v.setArea(item.getCounty());
                    if (cityRecMap.get(item.getCity()).size() == 1) {
                        v.setCityId(cityRecMap.get(item.getCity()).get(0).getCityId());
                        v.setCity(cityRecMap.get(item.getCity()).get(0).getCity());
                        v.setProvinceId(cityRecMap.get(item.getCity()).get(0).getProvinceId());
                        v.setProvince(cityRecMap.get(item.getCity()).get(0).getProvince());
                    } else {
                        for (int i = 0; i < cityRecMap.get(item.getCity()).size(); i++) {
                            City x = cityRecMap.get(item.getCity()).get(i);
                            // 省市相同时取值
                            if (x.getProvince().equals(item.getSfen()) && x.getCity().equals(item.getCity())) {
                                v.setCityId(x.getCityId());
                                v.setCity(x.getCity());
                                v.setProvinceId(x.getProvinceId());
                                v.setProvince(x.getProvince());
                            }
                        }
                    }
                    v.setStatus(0);
                    if (item.getStat() == 2) {
                        v.setStatus(1);
                    }
                    v.setCreateBy("system");
                    v.setCreateTime(new Date());
                    v.setInitial(PinyinUtil.getPinyin(v.getArea().substring(0,1)).substring(0,1).toUpperCase(Locale.ROOT));
                    addArea.add(v);

                    // 新增的插入到表
                    if (addArea.size()>=500){
                        areaService.saveOrUpdateBatch(addArea);
                        addArea.clear();
                        log.info("本地区信息表新增插入了{}条数据",addArea.size());
                    }
                }
            }
        }
    }
}
