package com.tofly.watermeter.custom.service.sxj.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tofly.common.core.util.StringUtil;
import com.tofly.watermeter.custom.dto.*;
import com.tofly.watermeter.custom.entity.dto.SyncCommonDto;
import com.tofly.watermeter.custom.mapper.DmaCodeMapper;
import com.tofly.watermeter.custom.mapper.SynchronousAboutMapper;
import com.tofly.watermeter.custom.service.ReadDataCheckThreeService;
import com.tofly.watermeter.custom.service.sxj.SynchronousAboutService;
import com.tofly.watermeter.em.ApiCallEnum;
import com.tofly.watermeter.entity.*;
import com.tofly.watermeter.service.*;
import com.tofly.watermeter.util.service.CallAPIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bubble
 */
@Service
@Slf4j
public class SynchronousAboutServiceImpl implements SynchronousAboutService {

  @Autowired private DmaCodeMapper dmaCodeMapper;
  @Autowired private QfmidysxzbmEService qfmidysxzbmService;
  @Autowired private CallAPIService callApiService;
  @Autowired private QfkhjbxxService qfkhjbxxService;
  @Autowired private SynchronousAboutMapper synchronousAboutMapper;
  @Autowired private CbqybmService cbqybmService;
  @Autowired private CbqydbmService cbqydbmService;
  @Autowired private QfcbqfmxlsService qfcbqfmxlsService;
  @Autowired private ReadmeterhisService readmehisService;
  @Autowired private ReadDataCheckThreeService checkThreeService;
  @Autowired private YhbingqyService yhbingqyService;
  @Autowired private QfcbplanService qfcbplanService;
  @Autowired private QfcbplandetailsService qfcbplandetailsService;

  private static final String AREA_TABLENAME = "TF_YWPN_DMACISCBPQ_W";

  private static final String VENDOR_TABLENAME = "TF_YWPN_DMACISSBCJ_W";

  private static final String CLIENT_TABLENAME = "TF_YWPN_QFKHJBXX_W";

  private static final String READ_BOOK_TABLENAME = "TF_YWPN_DMACISCBB_W";

  /** 同步抄表区域 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void syncArea() {
    Map apiResult = callApiService.getApiResult(null, "/api/Business/MeterReadingAreas");
    if (verifyThatItWasSuccessful(apiResult)) {
      String data = String.valueOf(apiResult.get("data"));
      if (StringUtils.isNotBlank(data)) {
        List<AreaCodeDto> areaCodeDtos = JSONObject.parseArray(data, AreaCodeDto.class);
        dmaCodeMapper.deleteData(AREA_TABLENAME);
        dmaCodeMapper.deleteData("TF_YWPN_QFCBCBPQ_W");
        dmaCodeMapper.insertAreaCode(areaCodeDtos);
        dmaCodeMapper.insertAreaCodeQfcb(areaCodeDtos);
      }
    }
  }

  /** 同步水表厂家 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void syncFactory() {
    Map apiResult =
        callApiService.getApiResult(new SyncCommonDto(1, 200), "/api/Business/WaterMaker");
    if (verifyThatItWasSuccessful(apiResult)) {
      List<VendorCodeDto> data =
          JSONObject.parseArray(String.valueOf(apiResult.get("data")), VendorCodeDto.class);
      if (!CollectionUtils.isEmpty(data)) {
        dmaCodeMapper.deleteData(VENDOR_TABLENAME);
        dmaCodeMapper.insertVendorCode(data);
        // 操作字典表
        Long maxId = synchronousAboutMapper.getMaxId("TF_YWPN_SYSCHILDCODE_D");
        for (VendorCodeDto dto : data) {
          dto.setId(maxId);
          maxId++;
        }
        synchronousAboutMapper.deleteDictionaryByPcid(2L);
        synchronousAboutMapper.insertDictionaryVendor(data);
      }
    }
  }

  /** 同步用水性质 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void synUseNatures() {
    Map apiResult =
        callApiService.getApiResult(new SyncCommonDto(1, 200), "/api/Business/UseNatures");
    if (verifyThatItWasSuccessful(apiResult)) {
      List<NatureOfWaterUseDto> data =
          JSONObject.parseArray(String.valueOf(apiResult.get("data")), NatureOfWaterUseDto.class);
      if (CollectionUtil.isNotEmpty(data)) {
        // 清除用水性质编码表
        qfmidysxzbmService.remove(
            Wrappers.<QfmidysxzbmE>lambdaQuery().isNotNull(QfmidysxzbmE::getYsxzBm));
        qfmidysxzbmService.insertNatureOfWaterUse(data);
      }
    }
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void synCustomerInfo() {
    Map<String, Integer> params;
    // 默认获取第一页,每页获取1000条数据
    Integer pageNum = 1;
    Integer pageSize = 1000;
    List<Qfkhjbxx> clientList = new ArrayList<>();

    // 循环获取用户信息
    while (true) {
      params = new HashMap<>(2);
      params.put("PAGE_NUM", pageNum);
      params.put("PAGE_SIZE", pageSize);
      Map apiResult = callApiService.getApiResult(params, "/api/Business/CustomerAddorUpdate");
      // 接口获取数据为空或成功但无数据则跳出
      if (!verifyThatItWasSuccessful(apiResult)) {
        break;
      }
      String data = String.valueOf(apiResult.get("data"));
      if (StringUtils.isBlank(data)) {
        break;
      }
      SyncPageDto syncPageDto = JSONObject.parseObject(data, SyncPageDto.class);
      if (syncPageDto != null) {
        String dataList = syncPageDto.getList();
        if (StringUtils.isNotBlank(dataList)) {
          List<Qfkhjbxx> client =
              JSONObject.parseArray(dataList.replace("id", "userId"), Qfkhjbxx.class);
          if (CollectionUtils.isEmpty(client)) {
            break;
          }
          // 添加数据
          clientList.addAll(client);
        } else {
          break;
        }
      } else {
        break;
      }
      pageNum++;
    }
    // 获取数据不为空的话则删除表且重新添加数据
    if (CollectionUtils.isNotEmpty(clientList)) {
      log.info("获取用户档案成功,共{}条", clientList.size());
      dmaCodeMapper.deleteData(CLIENT_TABLENAME);
      qfkhjbxxService.saveBatch(clientList, 1000);
      // 同步完成后更新抄表序号
      synchronousAboutMapper.updateMeterNum();
    }
  }

  /** 获取抄表本 */
  @Override
  public void synMeterReading() {
    Map<String, Integer> params;
    // 默认获取第一页,每页获取1000条数据
    Integer pageNum = 1;
    Integer pageSize = 1000;
    List<ReadBookDto> readBookList = new ArrayList<>();

    // 循环获取用户信息
    while (true) {
      params = new HashMap<>(2);
      params.put("pageNum", pageNum);
      params.put("pageSize", pageSize);
      Map apiResult = callApiService.getApiResult(params, "/api/v1/fish/read/book/find/page");
      // 接口获取数据为空或成功但无数据则跳出
      if (!verifyThatItWasSuccessful(apiResult)) {
        break;
      }
      String data = String.valueOf(apiResult.get("data"));
      if (StringUtils.isBlank(data)) {
        break;
      }
      SyncPageDto syncPageDto = JSONObject.parseObject(data, SyncPageDto.class);
      if (syncPageDto != null) {
        String dataList = syncPageDto.getList();
        if (StringUtils.isNotBlank(dataList)) {
          List<ReadBookDto> readBook = JSONObject.parseArray(dataList, ReadBookDto.class);
          if (CollectionUtils.isEmpty(readBook)) {
            break;
          }
          // 添加数据
          readBookList.addAll(readBook);
          log.info("第{}页抄表本数据添加成功,共{}条", pageNum, readBookList.size());
        } else {
          break;
        }
      } else {
        break;
      }
      pageNum++;
    }
    // 获取数据不为空的话则删除表且重新添加数据
    if (CollectionUtils.isNotEmpty(readBookList)) {
      // 删除抄表本数据
      dmaCodeMapper.deleteData(READ_BOOK_TABLENAME);
      // 添加抄表本信息
      dmaCodeMapper.insertReadBookCode(readBookList);
    }
  }

  /** 获取水表口径 */
  @Override
  public void synTableCaliber() {
    Map<String, Object> map = new HashMap<>(1);
    map.put("dictionaryId", "991770150275431424");
    Map apiResult = callApiService.getApiResult(map, "/api/v1/rabbit/data/option/get");
    if (verifyThatItWasSuccessful(apiResult)) {
      List<DictionaryDto> data =
          JSONObject.parseArray(String.valueOf(apiResult.get("data")), DictionaryDto.class);
      if (CollectionUtil.isNotEmpty(data)) {
        Long maxId = synchronousAboutMapper.getMaxId("TF_YWPN_SYSCHILDCODE_D");
        for (DictionaryDto dto : data) {
          dto.setId(maxId);
          dto.setPcid("1");
          dto.setPcname("水表口径");
          maxId++;
        }
        if (CollectionUtil.isNotEmpty(data)) {
          // 清空字典表水表口径再次添加
          synchronousAboutMapper.deleteDictionaryByPcid(1L);
          synchronousAboutMapper.insertDictionary(data);
        }
      }
    }
  }

  /** 获取水表类型 */
  @Override
  public void synTableType() {
    Map apiResult =
        callApiService.getApiResult(new SyncCommonDto(1, 50), "/api/v1/fish/meter/type/find/all");
    if (verifyThatItWasSuccessful(apiResult)) {
      List<DictionaryDto> data =
          JSONObject.parseArray(String.valueOf(apiResult.get("data")), DictionaryDto.class);
      if (CollectionUtil.isNotEmpty(data)) {
        Long maxId = synchronousAboutMapper.getMaxId("TF_YWPN_SYSCHILDCODE_D");
        for (DictionaryDto dto : data) {
          dto.setId(maxId);
          dto.setPcid("3");
          dto.setPcname("水表类型");
          maxId++;
        }
        if (CollectionUtil.isNotEmpty(data)) {
          // 清空字典表类型口径再次添加
          synchronousAboutMapper.deleteDictionaryByPcid(3L);
          synchronousAboutMapper.insertDictionary(data);
        }
      }
    }
  }

  /**
   * 初始化区域区段
   *
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean initRegionSection() {
    Map<String, Object> params = new HashMap<>(1);
    params.put("type", 1);
    // 获取抄表区域与抄表册
    Map apiResult =
        callApiService.getApiResult(params, "/api/v1/koi/reading/sequence/book/census/find");
    if (verifyThatItWasSuccessful(apiResult)) {
      String data = String.valueOf(apiResult.get("data"));
      if (StringUtils.isNotBlank(data)) {
        List<Map> dataList = JSONObject.parseArray(data, Map.class);
        Cbqybm cbqybm;
        Cbqydbm cbqydbm;
        for (Map map : dataList) {
          // 保存前查询区域编码是否有重复情况
          String name = String.valueOf(map.get("name"));
          Cbqybm qy =
              cbqybmService.getOne(Wrappers.<Cbqybm>lambdaQuery().eq(Cbqybm::getQymc, name));
          String responses = String.valueOf(map.get("responses"));

          List<Map> responsesList = JSONObject.parseArray(responses, Map.class);

          if (StringUtil.isNotNull(qy)) {
            if (CollectionUtils.isNotEmpty(responsesList)) {
              String param = qy.getQybm();
              // 查询所属区段
              cbqydbmService.remove(Wrappers.<Cbqydbm>lambdaQuery().eq(Cbqydbm::getQybm, param));
              // 当前区域如果没有区段，则添加
              for (Map m : responsesList) {
                cbqydbm = new Cbqydbm();
                cbqydbm.setQybm(param);
                cbqydbm.setQydbm(String.valueOf(m.get("readBookCode")));
                cbqydbm.setQydmc(String.valueOf(m.get("readBookName")));
                cbqydbm.setCreateUser(0L);
                cbqydbm.setCreateDate(new Date());
                cbqydbm.setYxbz("0");
                cbqydbm.setUpdateFlag("1");
                cbqydbmService.save(cbqydbm);
              }
            }
          } else {
            cbqybm = new Cbqybm();
            cbqybm.setYxbz("0");
            cbqybm.setQybm(synchronousAboutMapper.getQybm());
            cbqybm.setQymc(name);
            cbqybm.setCreateUser(0L);
            cbqybm.setCreateDate(new Date());
            cbqybm.setUpdateFlag("1");
            cbqybmService.save(cbqybm);
            if (CollectionUtils.isNotEmpty(responsesList)) {
              for (Map m : responsesList) {
                cbqydbm = new Cbqydbm();
                cbqydbm.setQybm(cbqybm.getQybm());
                cbqydbm.setQydbm(String.valueOf(m.get("readBookCode")));
                cbqydbm.setQydmc(String.valueOf(m.get("readBookName")));
                cbqydbm.setYxbz("0");
                cbqydbm.setCreateUser(0L);
                cbqydbm.setCreateDate(new Date());
                cbqydbm.setUpdateFlag("1");
                cbqydbmService.save(cbqydbm);
              }
            }
          }
        }
      }
    }
    return true;
  }

  /**
   * 同步森鑫炬抄表历史记录
   *
   * <p>101 立山线路 201 金城线路 301 新政线路 401 马鞍线路
   *
   * @return boolean
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean syncReadHisRecord(Integer flag,String yearMonth) {
    //是否清除数据
    if (flag != null && flag == 1){
      qfcbqfmxlsService.truncateQfcbqfmxlsTable();
    }
    //同步数据开始时间
    Date date;
    if (StringUtils.isNotBlank(yearMonth)){
      date = DateUtil.parse(yearMonth + "01");
    }else {
      date = DateUtil.parse("2024-01-01");
    }
    Map<String, Object> params = new HashMap<>(3);
    int size = 1000;
    int num = 1;
    DateTime dateTime = DateUtil.beginOfMonth(DateUtil.offsetMonth(new Date(), 1));
    while (date.getTime() <= dateTime.getTime()) {
      Date yearonmonth1 = DateUtil.offset(date, DateField.YEAR, -1);
      Date yearonmonth2 = DateUtil.offset(date, DateField.YEAR, -2);
      Date yearonmonth3 = DateUtil.offset(date, DateField.YEAR, -3);
      String currentDate = DateUtil.format(date, "yyyyMM");
      params.put("READ_MONTH",currentDate);
      //查询要同步月份抄表历史是否存在数据
      int currentNum = qfcbqfmxlsService.count(Wrappers.<Qfcbqfmxls>lambdaQuery().eq(Qfcbqfmxls::getCbyf, currentDate));
      //存放添加数据
      List<Qfcbqfmxls> insertData = new ArrayList<>();
      if (currentNum == 0){
        //上月抄表数据
        Map<String,List<Qfcbqfmxls>> lastMonthData = qfcbqfmxlsService.list(Wrappers.<Qfcbqfmxls>lambdaQuery()
                .eq(Qfcbqfmxls::getCbyf, DateUtil.format(DateUtil.offsetMonth(date, -1), "yyyyMM")))
                .stream().filter(Objects::nonNull).collect(Collectors.groupingBy(Qfcbqfmxls::getYhbh, Collectors.toList()));

       while (true) {
          params.put("PAGE_NUM", num);
          params.put("PAGE_SIZE", size);
          log.info("获取{}第{}页数据",currentDate, num);
          // 获取抄表记录
          Map apiResult = callApiService.getApiResult(params, "/api/Business/GetReadAndFees");
          if (verifyThatItWasSuccessful(apiResult)) {
            //森鑫炬获取数据
            Map dataMap = JSONObject.parseObject(String.valueOf(apiResult.get("data")), Map.class);
            List<Qfcbqfmxls> dataList = JSONObject.parseArray(String.valueOf(dataMap.get("list")), Qfcbqfmxls.class);
            if (CollectionUtils.isNotEmpty(dataList)) {
              insertData.addAll(dataList);
              num++;
            } else {
              num = 1;
              break;
            }
          } else {
            break;
          }
        }
        log.info("拉取数据开始时间{}，当前获取数据条数：{}", currentDate, insertData.size());
        if (CollectionUtil.isNotEmpty(insertData)){
          for (Qfcbqfmxls data : insertData) {
            data.setBcjjl(data.getCbsl());
            data.setYearonmonth1(yearonmonth1);
            data.setYearonmonth2(yearonmonth2);
            data.setYearonmonth3(yearonmonth3);
            int zero = 0;
            int down = 0;
            int up = 0;
            int equal = 0;
            if (CollectionUtil.isNotEmpty(lastMonthData) && CollectionUtil.isNotEmpty(lastMonthData.get(data.getYhbh()))){
              Qfcbqfmxls last = lastMonthData.get(data.getYhbh()).get(0);
              Integer zeroCount = last.getZeroCount();
              Integer continuityDown = last.getContinuityDown();
              Integer continuityUp = last.getContinuityUp();
              Integer continuityEqual = last.getContinuityEqual();
              zero = data.getCbsl() == 0 ? zeroCount + 1 : 0;
              down = data.getCbsl() < last.getCbsl() ? continuityDown + 1 : 0;
              up = data.getCbsl() > last.getCbsl() ? continuityUp + 1 : 0;
              equal = data.getCbsl().equals(last.getCbsl()) ? continuityEqual + 1 : 0;
            }
            data.setZeroCount(zero);
            data.setContinuityDown(down);
            data.setContinuityEqual(equal);
            data.setContinuityUp(up);
          }
          qfcbqfmxlsService.saveBatch(insertData,1000);
          log.info("添加{}月份数据成功",currentDate);
        }
      }
      date = DateUtil.offsetMonth(date, 1);
    }
    log.info("拉取结束时间" + DateUtil.now());
    return true;
  }

  /**
   * 处理未同步抄表数据
   *
   * @return boolean
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean handleNotSyncReadWater() {
    // 获取当前月份
    String month = DateUtil.format(new Date(), "yyyyMM");
    List<Readmeterhis> readList =
        readmehisService.list(
            Wrappers.<Readmeterhis>lambdaQuery()
                .eq(Readmeterhis::getMonthPlan, month)
                .eq(Readmeterhis::getCbbz, 1)
                .eq(Readmeterhis::getSxjmessage, "请不要频繁重复请求！")
                .eq(Readmeterhis::getIssyn, 0));

    if (CollectionUtil.isNotEmpty(readList)) {
      for (Readmeterhis read : readList) {
        checkThreeService.synCbsl(read.getYhbh(), month, "0");
        // 避免出现 "请不要频繁重复请求！" 返回信息，休息一秒后继续请求
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
    return true;
  }

  /**
   * 同步抄表数据
   *
   * @return true
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean synchronousReadMeter() {
    // 获取抄表册信息
    List<Cbqydbm> sectionList = cbqydbmService.list();
    if (CollectionUtil.isNotEmpty(sectionList)) {
      List<Yhbingqy> resultData;
      Yhbingqy bind;
      // 首先清除绑定关系
      yhbingqyService.remove(Wrappers.<Yhbingqy>lambdaQuery().isNotNull(Yhbingqy::getYhbh));
      for (Cbqydbm section : sectionList) {
        resultData = new ArrayList<>();
        // 抄表册编码信息
        String code = section.getQydbm();
        // 区域编码
        String region = section.getQybm();
        if (StringUtil.isNotEmpty(code)) {
          Map<String, Object> param = new HashMap<>(1);
          param.put("readerBookCode", code);
          Map apiResult =
              callApiService.getApiResult(param, "/api/v1/koi/reading/sequence/find/user");
          if (verifyThatItWasSuccessful(apiResult)) {
            List<Map> dataList =
                JSONObject.parseArray(String.valueOf(apiResult.get("data")), Map.class);

            for (Map map : dataList) {
              bind = new Yhbingqy();
              bind.setYhbh(String.valueOf(map.get("code")));
              bind.setQybm(region);
              bind.setQydbm(code);
              bind.setCbxh(Integer.valueOf(String.valueOf(map.get("readSortNo"))));
              resultData.add(bind);
            }
            yhbingqyService.saveBatch(resultData);
          }
        }
      }
      // 获取绑定关系中未同步过来的客户编号
      List<String> clientCodeList = synchronousAboutMapper.doesNotExistClient();
      String clientCode = String.join(",", clientCodeList);
      // 未同步客户信息同步
      if (StringUtil.isNotEmpty(clientCode)) {

        Map<String, Object> params;
        params = new HashMap<>(2);
        params.put("PAGE_NUM", 1);
        params.put("PAGE_SIZE", 1000);
        params.put("USER_CODES", clientCode);
        Map apiResult = callApiService.getApiResult(params, "/api/Business/CustomerAddorUpdate");
        if (verifyThatItWasSuccessful(apiResult)) {
          String data = String.valueOf(apiResult.get("data"));
          SyncPageDto syncPageDto = JSONObject.parseObject(data, SyncPageDto.class);
          if (syncPageDto != null) {
            String dataList = syncPageDto.getList();
            if (StringUtils.isNotBlank(dataList)) {
              List<Qfkhjbxx> client =
                  JSONObject.parseArray(dataList.replace("id", "userId"), Qfkhjbxx.class);
              if (CollectionUtil.isNotEmpty(client)) {
                qfkhjbxxService.saveBatch(client);
              }
            }
          }
        }
      }

      /* ------------ 抄表计划生成 ---------------*/
      // 获取抄表人员
      Map<String, Object> queryUser = new HashMap<>(2);
      queryUser.put("name","");
      queryUser.put("type","2");
      Map readUserMap = callApiService.getApiResult(queryUser, "/api/v1/koi/reading/sequence/book/census/find");
      if (verifyThatItWasSuccessful(readUserMap)) {
        List<Map> readUserDataList = JSONObject.parseArray(String.valueOf(readUserMap.get("data")), Map.class);
        if (CollectionUtil.isNotEmpty(readUserDataList)){
          //获取本年抄表计划
          Qfcbplan plan = qfcbplanService.getOne(Wrappers.<Qfcbplan>lambdaQuery().eq(Qfcbplan::getIsGeneral,0)
                  .eq(Qfcbplan::getYear, DateUtil.format(new Date(), "yyyy")));
          if (plan != null){
            Long planId = plan.getId();
            //获取有分配抄表区与用户的抄表人员
            List<Map> filterData = readUserDataList.stream().filter(m -> Integer.parseInt(String.valueOf(m.get("readBookNum"))) != 0 && Integer.parseInt(String.valueOf(m.get("userNum"))) != 0)
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filterData)){
              //获取森鑫炬抄表在系统中对应的人员姓名id
              List<Map<String, Object>> nameList = synchronousAboutMapper.queryUserByName(filterData.stream()
                      .map(m -> String.valueOf(m.get("name"))).collect(Collectors.toList()));
              if (CollectionUtil.isNotEmpty(nameList)){
                //过滤在系统中存在的人员
                List<String> existUserName = nameList.stream().map(m -> String.valueOf(m.get("name"))).collect(Collectors.toList());
                List<Map> existFilterData = filterData.stream().filter(m -> existUserName.contains(String.valueOf(m.get("name")))).collect(Collectors.toList());
                Qfcbplandetails details;
                for (Map filter : existFilterData) {
                  String userName = String.valueOf(filter.get("name"));
                  List<Map<String, Object>> userList = nameList.stream().filter(Objects::nonNull).filter(m -> m.get("name").equals(userName)).collect(Collectors.toList());
                  if (CollectionUtil.isNotEmpty(userList)){
                    Map<String, Object> userMap = userList.get(0);
                    //系统用户id
                    Long sysId = Long.valueOf(String.valueOf(userMap.get("id")));
                    List<String> responsesList = JSONObject.parseArray(String.valueOf(filter.get("responses")), Map.class).stream()
                            .map(m -> String.valueOf(m.get("readBookCode"))).collect(Collectors.toList());
                    List<Qfcbplandetails> detailsList = qfcbplandetailsService.list(Wrappers.<Qfcbplandetails>lambdaQuery().eq(Qfcbplandetails::getPlanId, planId)
                            .isNotNull(Qfcbplandetails::getCbry).eq(Qfcbplandetails::getIsGeneral, 0).in(Qfcbplandetails::getCbqydBm, responsesList));
                    //抄表人员抄表本与森鑫炬匹配数据
                    List<Qfcbplandetails> matchList = detailsList.stream().filter(Objects::nonNull).filter(m -> m.getCbry().equals(sysId)).collect(Collectors.toList());
                    //抄表人员抄表本与森鑫炬不匹配数据
                    List<Qfcbplandetails> notMatchList = detailsList.stream().filter(Objects::nonNull).filter(m -> !m.getCbry().equals(sysId)).collect(Collectors.toList());

                    //与森鑫炬不匹配的本地计划更改计划的人员
                    if (CollectionUtil.isNotEmpty(notMatchList)){
                      for (Qfcbplandetails detail : notMatchList) {
                        detail.setCbry(sysId);
                        qfcbplandetailsService.update(Wrappers.<Qfcbplandetails>lambdaUpdate()
                                .set(Qfcbplandetails::getCbry, sysId)
                                .eq(Qfcbplandetails::getId, detail.getId()));
                      }
                    }
                    //当森鑫炬抄表人员分配片区与本地计划分配片区不一致
                    if (matchList.size() != responsesList.size()){
                      List<String> regionList = detailsList.stream().filter(Objects::nonNull).map(Qfcbplandetails::getCbqydBm).collect(Collectors.toList());
                      responsesList.removeAll(regionList);
                      for (String region : responsesList) {
                        List<Cbqydbm> cbqydbmList = sectionList.stream().filter(q -> q.getQydbm().equals(region)).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(cbqydbmList)){
                          Cbqydbm cbqydbm = cbqydbmList.get(0);
                          details = new Qfcbplandetails();
                          details.setPlanId(planId);
                          details.setCbqyBm(cbqydbm.getQybm());
                          details.setCbqyMc(cbqydbm.getQymc());
                          details.setCbqydBm(region);
                          details.setQydmc(cbqydbm.getQydmc());
                          details.setCbry(sysId);
                          details.setSinDouMonth("1");
                          details.setCreateUser(294L);
                          details.setCreateTime(new Date());
                          details.setIsGeneral("0");
                          details.setIsState("1");
                          details.setStartDay((short) 1);
                          details.setEndDay((short) 22);
                          qfcbplandetailsService.save(details);
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    return true;
  }

  /**
   * 查询当天是否有开户用户并新增
   *
   * @return boolean
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean queryAccountUser() {
    Map<String,Object> param = new HashMap<>(9);
    param.put("exportType",1);
    param.put("id","964978231113427968");
    param.put("needSummary",0);
    param.put("pageNum",1);
    param.put("pageSize",1000);
    param.put("queryName","按用户");
    param.put("sortFields",new ArrayList<>());
    List<Map<String,Object>> parameters = new ArrayList<>();
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("code", "CREATE_TIME");
    paramMap.put("value", Arrays.asList((DateUtil.beginOfDay(new Date()).getTime() + "," + DateUtil.endOfDay(new Date()).getTime()).split(",")));
    parameters.add(paramMap);
    param.put("parameters",parameters);

    Map apiResult = callApiService.getApiResult(param, "/api/v1/seagull/query/execute");
    if (verifyThatItWasSuccessful(apiResult)){
      Map data = JSONObject.parseObject(String.valueOf(apiResult.get("data")), Map.class);
      Map resultData = JSONObject.parseObject(String.valueOf(data.get("resultData")), Map.class);
      List<Map> list = JSONObject.parseArray(String.valueOf(resultData.get("list")), Map.class);
      if (CollectionUtil.isNotEmpty(list)){
        String code = list.stream().map(m -> String.valueOf(m.get("CODE"))).collect(Collectors.joining(","));
        synchronousAboutMapper.deleteClientInfo(code);
        Map<String, Object> params;
        params = new HashMap<>(2);
        params.put("PAGE_NUM", 1);
        params.put("PAGE_SIZE", 1000);
        params.put("USER_CODES", code);
        Map clientInfo = callApiService.getApiResult(params, "/api/Business/CustomerAddorUpdate");
        if (verifyThatItWasSuccessful(clientInfo)) {
          String clientDate = String.valueOf(clientInfo.get("data"));
          SyncPageDto syncPageDto = JSONObject.parseObject(clientDate, SyncPageDto.class);
          if (syncPageDto != null) {
            String dataList = syncPageDto.getList();
            if (StringUtils.isNotBlank(dataList)) {
              List<Qfkhjbxx> client =
                      JSONObject.parseArray(dataList.replace("id", "userId"), Qfkhjbxx.class);
              if (CollectionUtil.isNotEmpty(client)) {
                qfkhjbxxService.saveBatch(client);
              }
            }
          }
        }
      }
    }
    return true;
  }


  /**
   * 验证接口是否调用成功
   *
   * @param apiResult 接口返回结果
   * @return boolean
   */
  private boolean verifyThatItWasSuccessful(Map apiResult) {
    if (CollectionUtils.isNotEmpty(apiResult)) {
      String statusCode = String.valueOf(apiResult.get("statusCode"));
      return ApiCallEnum.STATUS_CODE_OK.getCode().equals(statusCode);
    }
    return false;
  }
}
