package com.friday.custody.service.trustService.zhongtai.service;

import com.alibaba.fastjson.JSONObject;
import com.friday.base.common.response.DubboResult;
import com.friday.custody.common.CustodyContants;
import com.friday.custody.dto.TenantEscrowAuthorizationInfoDto;
import com.friday.custody.entity.*;
import com.friday.custody.service.basicService.impl.*;
import com.friday.custody.enums.DataDictionaryTypeEnum;
import com.friday.custody.service.basicService.DataDictionaryTypeCertificateCsdcService;
import com.friday.custody.service.logicService.impl.DataDictionaryBasicServiceImpl;
import com.friday.custody.service.trustService.OutsourceService;
import com.friday.custody.service.trustService.gtja.utils.RandomStrUtil;
import com.friday.custody.service.trustService.zhongtai.common.ZhongTaiContants;
import com.friday.custody.service.trustService.zhongtai.utils.ZhongTaiUtils;
import com.friday.custody.utils.BigDecimalUtil;
import com.friday.custody.utils.MatchDataDictionaryKeyUtil;
import com.friday.custody.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class OutSourceZhongTaiServiceImpl implements OutsourceService {

    @Autowired
    private InvestorInfoServiceImpl investorInfoService;
    @Autowired
    private DataDictionaryBasicServiceImpl basicService;
    @Autowired
    private ZhongTaiUtils zhongTaiUtils;
    @Autowired
    private FundNetValueInfoServiceImpl fundNetValueInfoService;
    @Autowired
    private FundInfoServiceImpl fundInfoService;
    @Autowired
    private CustShareInfoServiceImpl custShareInfoService;
    @Autowired
    private DataDictionaryTypeCertificateCsdcService certificateCsdcService;
    @Autowired
    private FundTradeInfoServiceImpl fundTradeInfoService;
    @Autowired
    private FundProfitInfoServiceImpl fundProfitInfoService;
    @Autowired
    private DataDictionarySellerServiceImpl sellerService;
    @Override
    public R initTenantData(List<TenantEscrowAuthorizationInfoDto> tenants) {
        return null;
    }

    @Autowired
    @Lazy
    OutSourceZhongTaiServiceImpl outSourceZhongTaiService;

    @Override
    public R initTenantDataSingle(TenantEscrowAuthorizationInfoDto tenant) {
        log.info("***************初始化中泰托管数据开始****************");
        int loopTime = CustodyContants.INIT_BY_MONTH_LOOP_TIME;
        getDataFromZhongTai(tenant, loopTime);
        return R.ok("初始化中泰托管数据成功！");
    }

    private void getDataFromZhongTai(TenantEscrowAuthorizationInfoDto tenant, int loopTime) {
        String trustNo = tenant.getTrustNo();
        processFundNetValueInfoData(tenant, trustNo, loopTime);
        processInvestorInfoData(tenant, trustNo);
        processCustShareInfoData(tenant, trustNo, loopTime);
        processFundTradeInfoData(tenant, trustNo, loopTime);
        processFundProfitInfoData(tenant, trustNo, loopTime);
    }

    public void processFundProfitInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusMonths(1);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                int pageNo = 0;
                int pageSize = 500;
                int totalCount = 0;
                for (; ; ) {
                    pageNo++;
                    //封装请求参数
                    Map<String, Object> paramMap = new HashMap<>();
                    //分页参数
                    paramMap.put("currentpage",pageNo);
                    paramMap.put("rows", pageSize);
                    paramMap.put("scdate",finalStartDate);
                    paramMap.put("ecdate", finalEndDate);
                    String paramStr = "?currentpage=" + pageNo + "&rows=" + pageSize + "&scdate=" + finalStartDate + "&ecdate=" + finalEndDate;
                    JSONObject remoteData = zhongTaiUtils.sendMessage(tenant, ZhongTaiContants.FUND_PROFIT_INFO, paramStr, paramMap);
                    log.info("zhongtai : processFundProfitInfoData : 请求参数params = {}, 返回结果 = {}", paramMap, remoteData);
                    if (!ObjectUtils.isEmpty(remoteData) && remoteData.getBoolean("success")) {
                        JSONObject data = remoteData.getJSONObject("data");
                        List<JSONObject> records = JSONObject.parseArray(data.getString("records"), JSONObject.class);
                        if (!ObjectUtils.isEmpty(records)) {
                            totalCount = data.getIntValue("total");
                            log.info("zhongtai : processFundProfitInfoData : 转义之前数据dataSize=", totalCount);
                            List<FundProfitInfoEntity> fundProfitInfoEntities = getFundProfitInfo(tenant, trustNo, records);
                            log.info("zhongtai : processFundProfitInfoData : 转义之后fundProfitInfo数据dataSize=", fundProfitInfoEntities.size());
                            fundProfitInfoService.saveData(null, fundProfitInfoEntities);
                        }
                    }
                    if (pageSize * pageNo >= totalCount){
                        break;
                    }
                }
            } catch (Exception e) {
                log.error("zhongtai : processFundProfitInfoData获取数据失败！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<FundProfitInfoEntity> getFundProfitInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> records) {
        //获取数据字典
        Map<String, String> businessNameDic = basicService.queryWithDetail(DataDictionaryTypeEnum.BUSINESS_NAME_SERVICE, trustNo);
        //封装数据
        List<FundProfitInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : records){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            String agencyName = dataMap.get("agencyname");
            String agencyNo = sellerService.queryAgencyNo("中泰证券", agencyName);
            entityList.add(FundProfitInfoEntity.builder()
                    .fundAcco(dataMap.get("fundacco"))
                    .agencyName(agencyName)
                    .agencyNo(agencyNo)
                    .fundCode(dataMap.get("fundcode"))
                    .fundName(dataMap.get("fundname"))
                    .businessName(MatchDataDictionaryKeyUtil.getKey(businessNameDic, dataMap.get("businname")))
                    .requestDate(dataMap.get("xdate"))
                    .confirmDate(dataMap.get("cdate"))
                    .registDate(dataMap.get("registdate"))
                    .holdDay(String.valueOf(dataMap.get("holddays")))
                    .shares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("confshares")))
                    .oriNav(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("beginnetvalue"), 4))
                    .oriTotalNav(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("begintotalnetvalue"),4))
                    .nav(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("netvalue"),4))
                    .totalNav(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("totalnetvalue"), 4))
                    .currRatio(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("curratio"), 4))
                    .yearRatio(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("yearratio"), 4))
                    .oriBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("deductbalance"), 4))
                    .factBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("factdeductbalance")))
                    .factShares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("factdeductshares")))
                    .oriDate(dataMap.get("begindate"))
                    .bonusBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("bonusbalance")))
                    .tradeAcco(dataMap.get("tradeacco"))
                    .cserialNo(RandomStrUtil.getRandomStr(32))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }

    public void processFundTradeInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusMonths(1);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                int pageNo = 0;
                int pageSize = 500;
                int totalCount = 0;
                for (; ; ) {
                    pageNo++;
                    //封装请求参数
                    Map<String, Object> paramMap = new HashMap<>();
                    //分页参数
                    paramMap.put("currentpage",pageNo);
                    paramMap.put("rows", pageSize);
                    paramMap.put("slastmodify",finalStartDate);
                    paramMap.put("elastmodify", finalEndDate);
                    String paramStr = "?currentpage=" + pageNo + "&rows=" + pageSize + "&slastmodify=" + finalStartDate + "&elastmodify=" + finalEndDate;
                    JSONObject remoteData = zhongTaiUtils.sendMessage(tenant, ZhongTaiContants.FUND_TRADE_INFO, paramStr, paramMap);
                    log.info("zhongtai : processFundTradeInfoData : 请求参数params = {}, 返回结果 = {}", paramMap, remoteData);
                    if (!ObjectUtils.isEmpty(remoteData) && remoteData.getBoolean("success")) {
                        JSONObject data = remoteData.getJSONObject("data");
                        List<JSONObject> records = JSONObject.parseArray(data.getString("records"), JSONObject.class);
                        if (!ObjectUtils.isEmpty(records)) {
                            totalCount = data.getIntValue("total");
                            log.info("zhongtai : processFundTradeInfoData : 转义之前数据dataSize=", totalCount);
                            List<FundTradeInfoEntity> fundTradeInfoEntities = getFundTradeInfo(tenant, trustNo, records);
                            log.info("zhongtai : processFundTradeInfoData : 转义之后fundtradeInfo数据dataSize=", fundTradeInfoEntities.size());
                            fundTradeInfoService.saveData(null, fundTradeInfoEntities);
                        }
                    }
                    if (pageSize * pageNo >= totalCount){
                        break;
                    }
                }
            } catch (Exception e) {
                log.error("zhongtai : processFundTradeInfoData获取数据失败！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<FundTradeInfoEntity> getFundTradeInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> records) {
        //获取数据字典
        Map<String, String> confirmStatusDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CONFIRM_STATUS_SERVICE, trustNo);
        Map<String, String> businessNameDic = basicService.queryWithDetail(DataDictionaryTypeEnum.BUSINESS_NAME_SERVICE, trustNo);
        //封装数据
        List<FundTradeInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : records){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            String agencyName = dataMap.get("agencyname");
            String agencyNo = sellerService.queryAgencyNo("中泰证券", agencyName);
            entityList.add(FundTradeInfoEntity.builder()
                    .fundAcco(dataMap.get("fundacco"))
                    .agencyName(agencyName)
                    .agencyNo(agencyNo)
                    .businessName(MatchDataDictionaryKeyUtil.getKey(businessNameDic, dataMap.get("businname")))
                    .requestDate(dataMap.get("xdate"))
                    .confirmDate(dataMap.get("cdate"))
                    .fundCode(dataMap.get("fundcode"))
                    .fundName(dataMap.get("fundname"))
                    .applyBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("balance")))
                    .applyShares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("shares")))
                    .confirmBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("confirmbalance")))
                    .confirmShares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("confirmshares")))
                    .tradeFare(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("tradefare")))
                    .registFare(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("registfare")))
                    .fundFare(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("fundfare")))
                    .profitBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("factdeductbalance")))
                    .netValue(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("netvalue"), 4))
                    .confirmStatus(MatchDataDictionaryKeyUtil.getKey(confirmStatusDic, dataMap.get("statusname")))
                    .tradeAcco(dataMap.get("tradeacco"))
                    .totalFare(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("totalfare")))
                    .agencyFare(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("agencyfare")))
                    .cserialNo(RandomStrUtil.getRandomStr(32))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }

    public void processCustShareInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastDate = localDate.minusMonths(loopTime);
        LocalDate nextMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        startDate = dateTimeFormatter.format(lastDate);
        for (int i = 0; i < loopTime; i++) {
            nextMonth = lastDate.plusMonths(1);
            endDate = dateTimeFormatter.format(nextMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                int pageNo = 0;
                int pageSize = 500;
                int totalCount = 0;
                List<CustShareInfoEntity> entityList = new ArrayList<>();
                for (; ; ) {
                    pageNo++;
                    //封装请求参数
                    Map<String, Object> paramMap = new HashMap<>();
                    //分页参数
                    paramMap.put("currentpage",pageNo);
                    paramMap.put("rows", pageSize);
                    paramMap.put("slastmodify",finalStartDate);
                    paramMap.put("elastmodify", finalEndDate);
                    String paramStr = "?currentpage=" + pageNo + "&rows=" + pageSize + "&slastmodify=" + finalStartDate + "&elastmodify=" + finalEndDate;
                    JSONObject remoteData = zhongTaiUtils.sendMessage(tenant, ZhongTaiContants.CUST_SHARE_INFO, paramStr, paramMap);
                    log.info("zhongtai : processCustShareInfoData : 请求参数params = {}, 返回结果 = {}", paramMap, remoteData);
                    if (!ObjectUtils.isEmpty(remoteData) && remoteData.getBoolean("success")) {
                        JSONObject data = remoteData.getJSONObject("data");
                        List<JSONObject> records = JSONObject.parseArray(data.getString("records"), JSONObject.class);
                        if (!ObjectUtils.isEmpty(records)) {
                            totalCount = data.getIntValue("total");
                            log.info("zhongtai : processCustShareInfoData : 转义之前数据dataSize=", totalCount);
                            List<CustShareInfoEntity> custShareInfoEntities = getCustShareInfo(tenant, trustNo, records);
                            log.info("zhongtai : processCustShareInfoData : 转义之后custShareInfo数据dataSize=", custShareInfoEntities.size());
                            entityList.addAll(custShareInfoEntities);
                        }
                    }
                    if (pageSize * pageNo >= totalCount){
                        break;
                    }
                }
                custShareInfoService.saveData(null, entityList);
            } catch (Exception e) {
                log.error("zhongtai : processCustShareInfoData！", e);
            }
            lastDate = nextMonth;
            startDate = endDate;
        }
    }

    private List<CustShareInfoEntity> getCustShareInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> dataList) {
        //获取数据字典
        Map<String, String> dividedWayDic = basicService.queryWithDetail(DataDictionaryTypeEnum.DIVIDEND_WAY_SERVICE, trustNo);
        //封装数据
        List<CustShareInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : dataList){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 =  new SimpleDateFormat("yyyyMMdd");
            String lastmodify = null;
            if (!ObjectUtils.isEmpty(dataMap.get("lastmodify"))) {
                try {
                    lastmodify = sdf.format(sdf1.parse(dataMap.get("lastmodify")));
                } catch (ParseException e) {
                    log.error("格式化时间异常！", e);
                }
            }
            String agencyName = dataMap.get("agencyname");
            String agencyNo = sellerService.queryAgencyNo("中泰证券", agencyName);
            entityList.add(CustShareInfoEntity.builder()
                    .fundAcco(dataMap.get("fundacco"))
                    .agencyName(agencyName)
                    .agencyNo(agencyNo)
                    .fundCode(dataMap.get("fundcode"))
                    .fundName(dataMap.get("fundname"))
                    .updateDate(lastmodify)
                    .lastHoldShares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("realshares")))
                    .tradeAcco(dataMap.get("tradeacco"))
                    .frozenShares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("frozenshares")))
                    .bonusMethod(MatchDataDictionaryKeyUtil.getKey(dividedWayDic, dataMap.get("bonustype")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }

    public void processFundNetValueInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusMonths(1);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                int pageNo = 0;
                int pageSize = 500;
                int totalCount = 0;
                for (; ; ) {
                    pageNo++;
                    //封装请求参数
                    Map<String, Object> paramMap = new HashMap<>();
                    //分页参数
                    paramMap.put("currentpage", pageNo);
                    paramMap.put("rows", pageSize);
                    paramMap.put("sdate", finalStartDate);
                    paramMap.put("edate", finalEndDate);
                    String paramStr = "?currentpage=" + pageNo + "&rows=" + pageSize + "&sdate=" + finalStartDate + "&edate=" + finalEndDate;
                    JSONObject remoteData = zhongTaiUtils.sendMessage(tenant, ZhongTaiContants.FUND_NET_VALUE_INFO_AND_FUND_INFO, paramStr, paramMap);
                    log.info("zhongtai : processFundNetValueInfoData : 请求参数params = {}, 返回结果 = {}", paramMap, remoteData);
                    if (!ObjectUtils.isEmpty(remoteData) && remoteData.getBoolean("success")) {
                        JSONObject data = remoteData.getJSONObject("data");
                        List<JSONObject> records = JSONObject.parseArray(data.getString("records"), JSONObject.class);
                        if (!ObjectUtils.isEmpty(records)) {
                            totalCount = data.getIntValue("total");
                            log.info("zhongtai : processFundNetValueInfoData : 转义之前数据dataSize=", totalCount);
                            List<FundNetValueInfoEntity> fundNetValueInfoEntities = getFundNetValueInfo(tenant, trustNo, records);
                            log.info("zhongtai : processFundNetValueInfoData : 转义之后fundNetValueInfo数据dataSize=", fundNetValueInfoEntities.size());
                            fundNetValueInfoService.saveData(null, fundNetValueInfoEntities);
                            List<FundInfoEntity> fundInfoEntities = getFundInfo(tenant, trustNo, records);
                            log.info("zhongtai : processFundNetValueInfoData : 转义之后fundInfo数据dataSize=", fundInfoEntities.size());
                            fundInfoService.saveData(null, fundInfoEntities);
                        }
                    }
                    if (pageSize * pageNo >= totalCount){
                        break;
                    }
                }
            } catch (Exception e) {
                log.error("zhongtai : processFundNetValueInfoData获取数据失败！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<FundInfoEntity> getFundInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> dataList) {
        List<FundInfoEntity> entityList = new ArrayList<>();
        Map<String,String> dataMap;
        for (JSONObject data : dataList){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(FundInfoEntity.builder()
                    .fundCode(dataMap.get("fundcode"))
                    .fundName(dataMap.get("fundname"))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }

    private List<FundNetValueInfoEntity> getFundNetValueInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> dataList) {
        //获取数据字典
        Map<String, String> confrimStatusDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CONFIRM_STATUS_SERVICE, trustNo);//确认状态
        //封装数据
        List<FundNetValueInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : dataList){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(FundNetValueInfoEntity.builder()
                    .fundCode(dataMap.get("fundcode"))
                    .fundName(dataMap.get("fundname"))
                    .netValue(BigDecimalUtil.str2BigDecimalDefaultZero(dataMap.get("dwjz"), 4))
                    .totalNetValue(BigDecimalUtil.str2BigDecimalDefaultZero(dataMap.get("ljdwjz"), 4))
                    .assetValue(BigDecimalUtil.str2BigDecimalDefaultZero(dataMap.get("zcjz"), 4))
                    .shares(BigDecimalUtil.str2BigDecimalDefaultZero(dataMap.get("zcfe")))
                    .totalAsset(BigDecimalUtil.str2BigDecimalDefaultZero(dataMap.get("zchj")))
                    .checkStatus(MatchDataDictionaryKeyUtil.getKey(confrimStatusDic, dataMap.get("sfqr")))
                    .netValueDate(dataMap.get("rq"))
                    .currency("156")
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }

    public void processInvestorInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        int totalCount = 0;
        int pageNo = 0;
        int pageSize = 500;
        try{
            for (; ; ){
                pageNo++;
                //封装请求参数
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("currentpage", pageNo);
                paramsMap.put("rows",pageSize);
                String paramStr = "?currentpage=" + pageNo + "&rows=" + pageSize;
                JSONObject remoteData = zhongTaiUtils.sendMessage(tenant, ZhongTaiContants.INVESTOR_INFO, paramStr, paramsMap);
                log.info("zhongtai : processInvestorInfoData : 请求参数params = {}, 返回结果 = {}", paramsMap, remoteData);
                if (!ObjectUtils.isEmpty(remoteData) && remoteData.getBoolean("success")){
                    JSONObject data = remoteData.getJSONObject("data");
                    List<JSONObject> records = JSONObject.parseArray(data.getString("records"), JSONObject.class);
                    if (!ObjectUtils.isEmpty(records)){
                        totalCount = data.getIntValue("total");
                        log.info("zhongtai : processInvestorInfoData : 转义之前数据dataSize=", totalCount);
                        List<InvestorInfoEntity> investorInfoEntities = getInvestorInfo(tenant, trustNo, records);
                        log.info("zhongtai : processInvestorInfoData : 转义之后数据dataSize=", investorInfoEntities.size());
                        investorInfoService.saveData(null, investorInfoEntities);
                    }
                }
                if (pageNo * 500 >= totalCount){
                    break;
                }
            }
        } catch (Exception e){
            log.error("zhongtai ：processInvestorInfoData获取数据失败！", e);
        }
    }

    private List<InvestorInfoEntity> getInvestorInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> dataList) {
        //获取数据字典
        Map<String, String> custTypeCsdcDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CUST_TYPE_CSDC_SERVICE, trustNo);//客户类型
        Map<String, Map<String, String>> identityTypeCsDcDic = certificateCsdcService.queryCertificateWithDetail(trustNo);//证件类型
        //封装请求参数
        List<InvestorInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : dataList){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 =  new SimpleDateFormat("yyyyMMdd");
            String lastmodify = null;
            if (!ObjectUtils.isEmpty(dataMap.get("lastmodify"))) {
                try {
                    lastmodify = sdf.format(sdf1.parse(dataMap.get("lastmodify")));
                } catch (ParseException e) {
                    log.error("格式化时间异常！", e);
                }
            }
            String custType = MatchDataDictionaryKeyUtil.getKey(custTypeCsdcDic, dataMap.get("custtype"));
            entityList.add(InvestorInfoEntity.builder()
                    .fundAcco(dataMap.get("fundacco"))
                    .custName(dataMap.get("custname"))
                    .custType(custType)
                    .identityType(MatchDataDictionaryKeyUtil.getKey(custType, identityTypeCsDcDic, dataMap.get("identitytype")))
                    .identityNo(dataMap.get("identityno"))
                    .accoOpenDate(dataMap.get("opendate"))
                    .mobileNo(dataMap.get("mobileno"))
                    .email(dataMap.get("email"))
                    .address(dataMap.get("address"))
                    .updateDate(lastmodify)
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }

        return  entityList;
    }

    @Override
    public R updateDataDaily(List<TenantEscrowAuthorizationInfoDto> tenants) {
        return null;
    }

    @Override
    public R updateSingleDataDaily(TenantEscrowAuthorizationInfoDto tenant) {
        log.info("***************更新中泰证券托管数据开始********************");
        try {
            int loopTime = CustodyContants.UPDATE_BY_MONTH_DAILY_LOOP_TIME;
            getUpdateDataFromZhongTai(tenant, loopTime);
            log.info("更新中泰证券托管数据完成......");
        }catch (Exception e){
            log.error("更新中泰证券托管数据失败！", e);
            return R.error("更新中泰证券托管失败！");
        }
        return R.ok("更新中泰证券托管成功！");
    }

    private void getUpdateDataFromZhongTai(TenantEscrowAuthorizationInfoDto tenant, int loopTime) {
        String trustNo = tenant.getTrustNo();
        processInvestorInfoData(tenant, trustNo);
        processCustShareInfoData(tenant, trustNo, loopTime);
        processFundTradeInfoData(tenant, trustNo, loopTime);
        processFundProfitInfoData(tenant, trustNo, loopTime);
    }

    @Override
    public R PullRemoteDataFirstQueueJob() {
        return null;
    }

    @Override
    public R initLaterTenantData(String versionStr, List<TenantEscrowAuthorizationInfoDto> tenants) {
        return null;
    }

    @Override
    public R initLaterSingleTenantData(String versionStr, TenantEscrowAuthorizationInfoDto tenant) {
        return null;
    }

    @Override
    public R initByAppointedTrustNoAndMouth(TenantEscrowAuthorizationInfoDto tenant, int month) {
        log.info("***************initByAppointedTrustNoAndMouth：初始化中泰托管数据开始****************");
        getDataFromZhongTai(tenant, month);
        return R.ok("初始化中泰托管数据成功！");
    }

    @Override
    public R updateData20min(List<TenantEscrowAuthorizationInfoDto> data) {
        return null;
    }

    @Override
    public R updateSingleData20min(TenantEscrowAuthorizationInfoDto tenant) {
        return null;
    }

    @Override
    public R updateData1h(List<TenantEscrowAuthorizationInfoDto> data) {
        return null;
    }

    @Override
    public R updateSingleData1h(TenantEscrowAuthorizationInfoDto tenant) {
        return null;
    }

    @Override
    public R updateDataCJ(String date, String flag, TenantEscrowAuthorizationInfoDto tenant) {
        return null;
    }

    @Override
    public R updateNetValueData(List<TenantEscrowAuthorizationInfoDto> tenants) {
        return null;
    }

    @Override
    public R updateSingleNetValueData(TenantEscrowAuthorizationInfoDto tenant) {
        log.info("******************中泰托管数据每8点、12点、20点更新开始******************");
        try {
            String trustNo = tenant.getTrustNo();
            Integer loopTime = CustodyContants.UPDATE_BY_MONTH_DAILY_LOOP_TIME;
            //3.基金净值信息表 fund_net_value_info
            outSourceZhongTaiService.processFundNetValueInfoData(tenant,trustNo,loopTime);
            log.info("******************中泰托管数据每8点、12点、20点更新结束****************** ");
        }catch (Exception e){
            log.error("中泰托管数据每8点、12点、20点更新异常！", e);
        }
        return R.ok("中泰托管数据每8点、12点、20点更新完成!");
    }

    @Override
    public DubboResult updateMJBalanceData(TenantEscrowAuthorizationInfoDto tenant) {
        try {

            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "暂不支持");
        } catch (Exception e) {
            log.error("手动更新募集户余额失败", e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "手动更新募集户余额失败" + e.getMessage());
        }
    }

    @Override
    public DubboResult updateMJSeqData(TenantEscrowAuthorizationInfoDto tenant) {
        try {

            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "暂不支持");
        } catch (Exception e) {
            log.error("手动更新募集户流水失败", e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "手动更新募集户流水失败" + e.getMessage());
        }
    }

    @Override
    public DubboResult updateTGBalanceData(TenantEscrowAuthorizationInfoDto tenant) {
        try {

            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "暂不支持");
        } catch (Exception e) {
            log.error("手动更新托管户余额失败", e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "手动更新托管户余额失败" + e.getMessage());
        }
    }

    @Override
    public DubboResult updateTGSeqData(TenantEscrowAuthorizationInfoDto tenant) {
        try {

            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "暂不支持");
        } catch (Exception e) {
            log.error("手动更新托管户流水失败", e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "手动更新托管户流水失败" + e.getMessage());
        }
    }
}
