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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.friday.base.common.response.DubboResult;
import com.friday.custody.entity.*;
import com.friday.custody.service.basicService.impl.*;
import com.friday.custody.service.trustService.anxin.common.AnxinContants;
import com.friday.custody.common.CustodyContants;
import com.friday.custody.dto.TenantEscrowAuthorizationInfoDto;
import com.friday.custody.enums.DataDictionaryTypeEnum;
import com.friday.custody.service.basicService.DataDictionaryBusinessNameDetailsService;
import com.friday.custody.service.logicService.DataDictionaryBasicService;
import com.friday.custody.service.logicService.impl.DataDictionaryBasicServiceImpl;
import com.friday.custody.service.trustService.OutsourceService;
import com.friday.custody.service.trustService.anxin.utils.AnXinUtils;
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.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class OutSourceAnXinServiceImpl implements OutsourceService {
    @Autowired
    private AnXinUtils anXinUtils;
    @Autowired
    private FundInfoServiceImpl fundInfoService;
    @Autowired
    private DataDictionaryBasicServiceImpl basicService;
    @Autowired
    private MjAccountSeqInfoServiceImpl mjAccountSeqInfoService;
    @Autowired
    private FundNetValueInfoServiceImpl fundNetValueInfoService;
    @Autowired
    private FundTempFareInfoServiceImpl fundTempFareInfoService;
    @Autowired
    private FundFeeDataInfoServiceImpl fundFeeDataInfoService;
    @Autowired
    private TgAccountSeqInfoServiceImpl tgAccountSeqInfoService;
    @Autowired
    private AccountInfoServiceImpl accountInfoService;
    @Autowired
    private FundValueTableDataInfoServiceImpl fundValueTableDataInfoService;
    @Autowired
    private ChargeFeeDetailInfoServiceImpl chargeFeeDetailInfoService;
    @Autowired
    private TgAccountBalanceInfoServiceImpl tgAccountBalanceInfoService;
    @Autowired
    private DataDictionaryTypeCertificateCsdcServiceImpl certificateCsdcService;
    @Autowired
    private FundTradeInfoServiceImpl fundTradeInfoService;
    @Autowired
    private DataDictionaryBasicService dataDictionaryBasicService;
    @Autowired
    private CustShareInfoServiceImpl custShareInfoService;
    @Autowired
    private CustShareDetailInfoServiceImpl custShareDetailInfoService;

    @Autowired
    @Lazy
    private OutSourceAnXinServiceImpl outSourceAnXinService;

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

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

    private void getDataFromAnXin(TenantEscrowAuthorizationInfoDto tenant, int loopTime) {
        String trustNo = tenant.getTrustNo();
        try {
            //1.基金产品信息表 (fund_info)
            processFundInfoData(tenant, trustNo);
            //2.基金产品信息表 (fund_info) - 子基金
            processChildFundInfoData(tenant, trustNo);
            //3.募集户流水表 (MJAccount_seq_info)
            processMJAccountSeqInfoData(tenant, trustNo, loopTime);
            //4.基金净值信息表 (fund_net_value_info)
            processFundNetValueInfoData(tenant, trustNo, loopTime);
            //5.基金估值表费用信息表 (fund_temp_fare_info) + 基金费用数据表 (fund_fee_data_info)
            processFundTempAndFundFeeInfoData(tenant, trustNo, loopTime);
            //6.托管户流水表 (TGAccount_seq_info) 历史
            processTgHistoryAccountSeqInfoData(tenant, trustNo, loopTime);
            //7.托管户流水表 (TGAccount_seq_info) 当日
            processTgCurrentAccountSeqInfoData(tenant, trustNo);
            //8.资金账户基本信息表 (account_info)
            processAccountInfoData(tenant, trustNo);
            //9.基金估值报表数据表(fund_value_table_data_info)，安信接口废弃
//            processFundValueTableDataInfoData(tenant, trustNo, loopTime);
            //10.费用计提明细表 (charge_fee_detail_info)
            processChargeFeeDetailInfoData(tenant, trustNo, loopTime);
            //11.托管户银行账户余额信息表 (TGAccount_balance_info)
            processTgAccountBalanceInfoData(tenant, trustNo);
            //12.基金出资人信息表-investor_info   （基金出资人银行账户信息表-investor_bank_info）
            processInvestorAndInvestorBankInfoData(tenant, trustNo);
            //13.基⾦交易确认信息表（fund_trade_info）
            processFundTradeInfoData(tenant,trustNo,loopTime);
            //14.基金持有信息表（cust_share_info）
            processCustShareInfoData(tenant,trustNo);
            //15.基金持有份额明细表（cust_share_detail_info）
            processCustShareDetailInfoData(tenant, trustNo, loopTime);

        } catch (Exception e) {
            log.error("初始化安信托管数据失败！");
        }
    }
    private void processCustShareDetailInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo,int loopTime) {
        for (int i = 0; i < loopTime; i++) {
            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());

                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("c_amacfundcode",fundCode);
                        paramsMap.put("pageNo",pageNo);

                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&c_amacfundcode=" + fundCode;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.CUST_SHARE_DETAIL_INFO, paramStr, paramsMap);
                        log.info("anxin: processCustShareDetailInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processCustShareDetailInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<CustShareDetailInfoEntity> custShareDetailInfoEntities = getCustShareDetailInfo(tenant, returnObject, trustNo);
                                custShareDetailInfoService.saveData(null, custShareDetailInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("anxin：processCustShareDetailInfoData保存数据异常！", e);
            }
        }
    }
    private List<CustShareDetailInfoEntity> getCustShareDetailInfo(TenantEscrowAuthorizationInfoDto tenant, List<JSONObject> remoteDatas, String trustNo) {
        //1、获取字典表数据

        Map<String, String> sellerServiceDir = dataDictionaryBasicService.queryWithDetail(DataDictionaryTypeEnum.SELLER_SERVICE, "安信证券");

        //2、封装数据
        List<CustShareDetailInfoEntity> result = new ArrayList<>();
        Map<String, String> remoteDataMap;
        Date now = new Date();
        for (JSONObject remoteData : remoteDatas) {
            remoteDataMap = JSONObject.toJavaObject(remoteData, Map.class);
            String agencyNo = remoteDataMap.get("c_agency_no");
            String agencyNo1 = MatchDataDictionaryKeyUtil.getKey(sellerServiceDir, agencyNo);
            log.info("getCustShareDetailInfo_agencyNo原值={},映射值={}",agencyNo,agencyNo1);

            result.add(CustShareDetailInfoEntity.builder()
                            .fundCode(remoteDataMap.get("c_fund_acco"))
                            .fundName(remoteDataMap.get("c_trade_acco"))
                            .agencyNo(agencyNo1)
                            .agencyName(remoteDataMap.get("c_agency_name"))
                            .fundCode(remoteDataMap.get("c_amacfundcode"))
                            .oriBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_ori_balance")))
                            .oriShares(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_ori_shares")))
                            .remainShares(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_remai_shares")))
                            .registDate(remoteDataMap.get("d_regist_date"))
                            .seqNo(RandomStringUtils.randomAlphanumeric(32))
                            .trustNo(trustNo)
                            .admin(tenant.getTenantName())
                            .createTime(now)
                            .updateTime(now)
                            .build());
        }
        return result;
    }


    //14.基金持有信息表（cust_share_info）
    private void processCustShareInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        try {
            List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
            List<CustShareInfoEntity> allList = new ArrayList<>();
            for (String fundCode : fundCodeList) {
                int pageNo = 0;
                int totalPages = 0;
                List<CustShareInfoEntity> entityList = new ArrayList<>();
                for (; ; ) {
                    pageNo++;
                    //拼装请求参数
                    Map<String, Object> paramsMap = new HashMap<>();
                    paramsMap.put("c_amacfundcode", fundCode);
                    paramsMap.put("pageNo", pageNo);
                    paramsMap.put("c_conf_status", "1");
                    //拼装参数字符串
                    String paramStr = "&pageNo=" + pageNo + "&c_amacfundcode=" + fundCode + "&c_conf_status=" + "1";
                    Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.CUST_SHARE_INFO, paramStr, paramsMap);
                    log.info("anxin: processCustShareInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                    if (ObjectUtils.isNotEmpty(result)) {
                        if (JSONPath.contains(result, "$.returnObject")) {
                            totalPages = Integer.parseInt(result.get("totalPages").toString());
                            int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                            log.info("anxin: processCustShareInfoData : totalCount = {} ", totalCount);
                            List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                            List<CustShareInfoEntity> custShareInfoEntities = getCustShareInfo(tenant, trustNo, returnObject);
                            entityList.addAll(custShareInfoEntities);
                        }
                    }
                    if (pageNo >= totalPages) {
                        break;
                    }
                }
                allList.addAll(entityList);
            }
            custShareInfoService.saveData(null, allList);
        } catch (Exception e) {
            log.error("anxin：processMJAccountSeqInfoData保存数据异常！", e);
        }
    }
    private List<CustShareInfoEntity> getCustShareInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> dataList) {
        //获取数据字典
        Map<String, String> sellerServiceDir = dataDictionaryBasicService.queryWithDetail(DataDictionaryTypeEnum.SELLER_SERVICE, "安信证券");
        Map<String, String> dividendDir = dataDictionaryBasicService.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);
            String bonusType = dataMap.get("c_bonus_type_name");
            String bonusMethod = MatchDataDictionaryKeyUtil.getKey(dividendDir, bonusType);
            log.info("getCustShareInfo_bonusType原值={},映射值={}", bonusType, bonusMethod);
            String agencyNo = dataMap.get("c_agency_no");
            String agencyNo1 = MatchDataDictionaryKeyUtil.getKey(sellerServiceDir, agencyNo);
            log.info("getCustShareInfo_agencyNo原值={},映射值={}", agencyNo, agencyNo1);
            entityList.add(CustShareInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .fundAcco(dataMap.get("c_fund_acco"))
                    .agencyNo(agencyNo1)
                    .agencyName(dataMap.get("c_agency_name"))
                    .frozenShares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_frozen_shares")))
                    .lastHoldShares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_last_shares")))
                    .netValueDate(dataMap.get("d_market_date"))
                    .bonusMethod(bonusMethod)
                    .updateDate(dataMap.get("d_last_modify"))
                    .tradeAcco(dataMap.get("c_trade_acco"))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());


        }
        return entityList;
    }
    //13.基⾦交易确认信息表（fund_trade_info）
    @Autowired
    public DataDictionaryBusinessNameDetailsService dataDictionaryBusinessNameDetailsService;


    private void processFundTradeInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo,int loopTime) {
        Map<String, String> map = dataDictionaryBasicService.queryWithDetail(DataDictionaryTypeEnum.BUSINESS_NAME_SERVICE, trustNo);
        // 抽象成工具类方法 计算后的时间（startTime , 距离天数）
        //TimeUtil.getYesterday();获取昨天
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        localDate=localDate.plusDays(-1);
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusDays(59);
            startDate = dateTimeFormatter.format(lastMonth);

            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    Map<String, Object> paramsMap = new HashMap<>();
                    paramsMap.put("pageNo", pageNo);
                    paramsMap.put("d_conf_date_begin", startDate);
                    paramsMap.put("d_conf_date_end", endDate);
                    paramsMap.put("c_conf_status", "1");
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        paramsMap.put("c_amacfundcode", fundCode);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&d_conf_date_begin=" + startDate + "&d_conf_date_end=" + endDate + "&c_amacfundcode=" + fundCode + "&c_conf_status=" + "1";
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.FUND_TRADE_INFO, paramStr, paramsMap);
                        log.info("anxin: processFundTradeInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processFundTradeInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<FundTradeInfoEntity> fundTradeInfoEntities = getFundTradeInfo(tenant, trustNo, returnObject);
                                fundTradeInfoService.saveData(null, fundTradeInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }

            } catch (Exception e) {
                log.error("anxin：processFundTradeInfoData保存数据异常！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }
    //13.基⾦交易确认信息表（fund_trade_info）

    private List<FundTradeInfoEntity> getFundTradeInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo,List<JSONObject> remoteDatas) {
        //1、获取字典表数据
        //销售商
        Map<String, String> sellerServiceDir = dataDictionaryBasicService.queryWithDetail(DataDictionaryTypeEnum.SELLER_SERVICE, "安信证券");

        //业务类型
        Map<String, String> businessDir = dataDictionaryBasicService.queryWithDetail(DataDictionaryTypeEnum.BUSINESS_NAME_SERVICE, trustNo);
        //确认状态
        //Map<String, String> confirmDir = dataDictionaryBasicService.queryWithDetail(DataDictionaryTypeEnum.CONFIRM_STATUS_SERVICE, trustNo);

        //2、封装数据
        List<FundTradeInfoEntity> result = new ArrayList<>();
        Map<String, String> remoteDataMap;
        Date now = new Date();
        for (JSONObject remoteData : remoteDatas) {
            remoteDataMap = JSONObject.toJavaObject(remoteData, Map.class);

            String agencyNo = remoteDataMap.get("c_agency_no");
            //MatchDataDictionaryKeyUtil.getKey(sellerDic, item.getAgencyNo())
            String agencyNo1 = MatchDataDictionaryKeyUtil.getKey(sellerServiceDir, agencyNo);
            log.info("getFundTradeInfo_agencyNo原值={},映射值={}",agencyNo,agencyNo1);

            String busiFlag = remoteDataMap.get("c_business_name");
            String businessName = MatchDataDictionaryKeyUtil.getKey(businessDir, busiFlag);
            log.info("getFundTradeInfo_businessName原值={},映射值={}",busiFlag,businessName);

            result.add(FundTradeInfoEntity.builder()
                            .fundCode(remoteDataMap.get("c_amacfundcode"))
                            .fundName((String) remoteDataMap.get("c_fundname"))
                            .fundAcco(remoteDataMap.get("c_fund_acco"))
                            .tradeAcco(remoteDataMap.get("c_trade_acco"))
                            .agencyNo(agencyNo1)
                            .agencyName(remoteDataMap.get("c_agency_name"))
                            .businessName(businessName)
                            .requestDate(remoteDataMap.get("d_request_date"))
                            .applyBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_request_balance")))
                            .applyShares(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_request_shares")))
                            .confirmDate(remoteDataMap.get("d_confirm_date"))
                            .confirmBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_confirm_balance")))
                            .confirmShares(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_confirm_shares")))
                            .confirmStatus(remoteDataMap.get("c_confirm_status_name"))
                            .tradeFare(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_trade_fare")))
                            .profitBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_profit_yj")))
                            .agencyFare(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_agency_fare")))
                            .fundFare(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_fund_fare")))
                            .registFare(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_regist_fare")))
                            .interest(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_interest_balance")))
                            .interestShare(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_interest_shares")))
                            .netValue(BigDecimalUtil.obj2BigDecimalTrunToZero(remoteDataMap.get("f_net_value"),4))
                            .cserialNo(RandomStringUtils.randomAlphanumeric(32))
                            .trustNo(trustNo)
                            .admin(tenant.getTenantName())
                            .createTime(now)
                            .updateTime(now)
                            .build());
        }
        return result;
    }


    @Autowired
    InvestorInfoServiceImpl investorInfoService;
    @Autowired
    InvestorBankInfoServiceImpl investorBankInfoService;
    //12.基金出资人信息表-investor_info   （基金出资人银行账户信息表-investor_bank_info）

    private void processInvestorAndInvestorBankInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        int totalPages = 0;
        int pageNo = 0;
        try {
            for (; ; ) {
                pageNo++;
                //拼装请求参数
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("pageNo", pageNo);
                //拼装参数字符串
                String paramStr = "&pageNo=" + pageNo;
                Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.INVESTOR_INFO_AND_INVESTOR_BANK_INFO, paramStr, paramsMap);
                log.info("anxin: processInvestorAndInvestorBankInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                if (ObjectUtils.isNotEmpty(result)) {
                    if (JSONPath.contains(result, "$.returnObject")) {
                        totalPages = Integer.parseInt(result.get("totalPages").toString());
                        int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                        log.info("anxin: processInvestorAndInvestorBankInfoData : totalCount = {} ", totalCount);
                        List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                        //封装成标准表的对象
                        List<InvestorInfoEntity> investorInfo = getInvestorInfo(tenant, trustNo, returnObject);
                        List<InvestorBankInfoEntity> investorBankInfo = getInvestorBankInfo(tenant, trustNo, returnObject);
                        //调用保存数据接口
                        investorBankInfoService.saveData(null,investorBankInfo);
                        investorInfoService.saveData(null,investorInfo);
                    }
                }
                if (pageNo >= totalPages) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("anxin:processInvestorAndInvestorBankInfoData获取失败！", e);
        }
    }

    private List<InvestorInfoEntity> getInvestorInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //获取数据字典
        //中登-客户类型
        Map<String, String> custTypeCsdcDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CUST_TYPE_CSDC_SERVICE, trustNo);
        //中登-证件类型
        Map<String, Map<String, String>> identityTypeCsdnDic = certificateCsdcService.queryCertificateWithDetail(trustNo);
        //封装数据
        List<InvestorInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            String custType = MatchDataDictionaryKeyUtil.getKey(custTypeCsdcDic, dataMap.get("c_cust_type"));
            log.info("Anxin:getInvestorInfoData_custType原值为{},映射值为{}",dataMap.get("c_cust_type"), custType);
            String identityType = MatchDataDictionaryKeyUtil.getKey(custType, identityTypeCsdnDic, dataMap.get("c_certi_type"));
            log.info("Anxin:getInvestorInfoData_identityType原值为{},映射值为{}",dataMap.get("c_certi_type"), identityType);
            entityList.add(InvestorInfoEntity.builder()
                    .custName(dataMap.get("c_cust_name"))
                    .fundAcco(dataMap.get("c_fund_acco"))
                    .custType(custType)
                    .identityType(identityType)
                    .identityNo(dataMap.get("c_certi_no"))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());

        }
        return entityList;
    }

    private List<InvestorBankInfoEntity> getInvestorBankInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //封装数据
        List<InvestorBankInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        //HashMap<String, String> dataMap;
        for (JSONObject data : returnObject){
            dataMap = JSONObject.toJavaObject(data, Map.class);
            //dataMap = JSONObject.toJavaObject(data, HashMap.class);
            entityList.add(InvestorBankInfoEntity.builder()
                                    .bankNo(dataMap.get("c_bank_account"))
                                    .nameInBank(dataMap.get("c_bank_open_name"))
                                    .tradeAcco(dataMap.get("c_trade_acco"))
                                    .trustNo(trustNo)
                                    .admin(tenant.getTenantName())
                                    .createTime(new Date())
                                    .updateTime(new Date())
                                    .build());
        }
        return entityList;
    }


    public void processTgAccountBalanceInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        try {
            List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
            //acco_type_code应等于ZJ001（ZJ001-托管户）
            List<AccountInfoEntity> accountInfoEntityList = accountInfoService.getListByAccTypeCodeAndAdmin(trustNo, "ZJ001", tenant.getTenantName());
            for (String fundCode : fundCodeList) {
                for (AccountInfoEntity accountInfoEntity : accountInfoEntityList) {
                    if (StringUtils.isBlank(accountInfoEntity.getBankAcco())) {
                        continue;
                    }
                    int pageNo = 0;
                    int totalPages = 0;
                    String account = accountInfoEntity.getBankAcco();
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("pageNo", pageNo);
                        paramsMap.put("c_amacfundcode", fundCode);
                        paramsMap.put("c_account", account);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&c_amacfundcode=" + fundCode + "&c_account=" + account;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.TGACCOUNT_BALANCE_INFO, paramStr, paramsMap);
                        log.info("anxin: processTgAccountBalanceInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processTgAccountBalanceInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<TgAccountBalanceInfoEntity> tgAccountBalanceInfoEntities = getTgAccountBalanceInfo(tenant, trustNo, returnObject);
                                log.info("anxin: processTgAccountBalanceInfoData : 转义TgAccountBalanceInfoEntity dataSize = {} ", tgAccountBalanceInfoEntities);
                                tgAccountBalanceInfoService.saveData(null, tgAccountBalanceInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("anxin：processChargeFeeDetailInfoData！", e);
        }
    }

    private List<TgAccountBalanceInfoEntity> getTgAccountBalanceInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        Map<String, String> currencyDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CURRENCY_SERVICE, trustNo);
        List<TgAccountBalanceInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String updateTime = null;
            try {
                updateTime = sdf1.format(sdf.parse(dataMap.get("d_updatetime")));
            } catch (ParseException e) {
                log.error("TgAccountBalanceInfo updateTime转化失败！", e);
            }
            entityList.add(TgAccountBalanceInfoEntity.builder()
                    .bankAcco(dataMap.get("c_account"))
                    .accoBalance(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("c_accountbalance")))
                    .currency(MatchDataDictionaryKeyUtil.getKey(currencyDic, dataMap.get("c_currency")))
                    .updateDate(updateTime)
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }

    private void processChargeFeeDetailInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusDays(30);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("pageNo", pageNo);
                        paramsMap.put("d_sdate", finalStartDate);
                        paramsMap.put("d_edate", finalEndDate);
                        paramsMap.put("c_amacfundcode", fundCode);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&d_sdate=" + finalStartDate + "&d_edate=" + finalEndDate + "&c_amacfundcode=" + fundCode;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.CHARGE_FEE_DETAIL_INFO, paramStr, paramsMap);
                        log.info("anxin: processChargeFeeDetailInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processChargeFeeDetailInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<ChargeFeeDetailInfoEntity> chargeFeeDetailInfoEntities = getChargeFeeDetailInfo(tenant, trustNo, returnObject);
                                log.info("anxin: processChargeFeeDetailInfoData : 转义之后chargeFeeDetailInfo dataSize = {} ", chargeFeeDetailInfoEntities);
                                chargeFeeDetailInfoService.saveData(null, chargeFeeDetailInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("anxin：processChargeFeeDetailInfoData！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<ChargeFeeDetailInfoEntity> getChargeFeeDetailInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        List<ChargeFeeDetailInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            //管理费
            entityList.add(ChargeFeeDetailInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .feeDate(dataMap.get("d_rq"))
                    .feeType("GLF")
                    .chargeFee(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_managementFee")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            entityList.add(ChargeFeeDetailInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .feeDate(dataMap.get("d_rq"))
                    .feeType("TGF2")
                    .chargeFee(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_investmentFee")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            entityList.add(ChargeFeeDetailInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .feeDate(dataMap.get("d_rq"))
                    .feeType("XSF")
                    .chargeFee(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_salesFee")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            entityList.add(ChargeFeeDetailInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .feeDate(dataMap.get("d_rq"))
                    .feeType("TGF")
                    .chargeFee(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_custodianFee")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            entityList.add(ChargeFeeDetailInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .feeDate(dataMap.get("d_rq"))
                    .feeType("WBF")
                    .chargeFee(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_outsourcingFee")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            entityList.add(ChargeFeeDetailInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .feeDate(dataMap.get("d_rq"))
                    .feeType("ZZS")
                    .chargeFee(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_increFee")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            entityList.add(ChargeFeeDetailInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .feeDate(dataMap.get("d_rq"))
                    .feeType("FJS")
                    .chargeFee(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_addFee")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());

        }
        return entityList;
    }


    public void processFundValueTableDataInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusDays(30);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("pageNo", pageNo);
                        paramsMap.put("d_sdate", finalStartDate);
                        paramsMap.put("d_edate", finalEndDate);
                        paramsMap.put("c_amacfundcode", fundCode);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&d_sdate=" + finalStartDate + "&d_edate=" + finalEndDate + "&c_amacfundcode=" + fundCode;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.FUND_VALUE_TABLE_DATA_INFO, paramStr, paramsMap);
                        log.info("anxin: processFundValueTableDataInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processFundValueTableDataInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<FundValueTableDataInfoEntity> fundValueTableDataInfoEntities = getFundValueTableInfo(trustNo, tenant, returnObject, fundCode);
                                fundValueTableDataInfoService.saveData(null, fundValueTableDataInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("anxin：processFundTempAndFundFeeInfoData！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<FundValueTableDataInfoEntity> getFundValueTableInfo(String trustNo, TenantEscrowAuthorizationInfoDto tenant, List<JSONObject> returnObject, String fundCode) {
        //获取数据字典
        //封装数据
        List<FundValueTableDataInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(FundValueTableDataInfoEntity.builder()
                    .fundName(dataMap.get("c_fundname"))
                    .netValue(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_dwjz"), 4))
                    .valueDate(dataMap.get("d_rq"))
                    .kmCode(dataMap.get("c_kmdm"))
                    .kmName(dataMap.get("c_kmmc"))
                    .amount(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_sl")))
                    .perCost(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_dwcb")))
                    .portCost(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_cb")))
                    .costBi(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_cbzjz"), 4))
                    .vapPrice(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_hqjz")))
                    .portMv(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_sz")))
                    .mvBl(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_szzjz"), 4))
                    .portIv(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_gzzz")))
                    .suspension(dataMap.get("c_tpxx"))
                    .fundCode(fundCode)
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }

        return entityList;
    }


    public void processAccountInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        try {
            List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
            for (String fundCode : fundCodeList) {
                int pageNo = 0;
                int totalPages = 0;
                for (; ; ) {
                    pageNo++;
                    //拼装请求参数
                    String accoType = "122,102";
                    Map<String, Object> paramsMap = new HashMap<>();
                    paramsMap.put("pageNo", pageNo);
                    paramsMap.put("c_amacfundcode", fundCode);
                    //可多填，用逗号分隔 122:募集账户 102:托管账户
                    paramsMap.put("c_accotype", accoType);
                    //拼装参数字符串
                    String paramStr = "&pageNo=" + pageNo + "&c_amacfundcode=" + fundCode + "&c_accotype=" + accoType;
                    Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.ACCOUNT_INFO, paramStr, paramsMap);
                    log.info("anxin: processAccountInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                    if (ObjectUtils.isNotEmpty(result)) {
                        if (JSONPath.contains(result, "$.returnObject")) {
                            totalPages = Integer.parseInt(result.get("totalPages").toString());
                            int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                            log.info("anxin: processAccountInfoData : totalCount = {} ", totalCount);
                            List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                            List<AccountInfoEntity> accountInfoEntities = getAccountInfo(tenant, trustNo, returnObject);
                            log.info("anxin: processAccountInfoData : 转义accountInfo dataSize = {} ", accountInfoEntities.size());
                            accountInfoService.saveData(null, accountInfoEntities);
                        }
                    }
                    if (pageNo >= totalPages) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("anxin：processAccountInfoData！", e);
        }
    }

    private List<AccountInfoEntity> getAccountInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //获取数据字典
        Map<String, String> accountTypeDic = basicService.queryWithDetail(DataDictionaryTypeEnum.ACCOUNT_TYPE_SERVICE, trustNo);//账户类型
        Map<String, String> currencyDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CURRENCY_SERVICE, trustNo);//币种
        Map<String, String> accountStatusDic = basicService.queryWithDetail(DataDictionaryTypeEnum.ACCOUNT_STATUS_SERVICE, trustNo);
        //封装数据
        List<AccountInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(AccountInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundName"))
                    .accoTypeCode(MatchDataDictionaryKeyUtil.getKey(accountTypeDic, dataMap.get("c_accotype")))
                    .bankAcco(dataMap.get("c_account"))
                    .nameInBank(dataMap.get("c_accountname"))
                    .branchBankName(dataMap.get("c_bankname"))
                    .largePayAcco(dataMap.get("c_largepayacco"))
                    .currency(MatchDataDictionaryKeyUtil.getKey(currencyDic, dataMap.get("c_currency")))
                    .acctStatus(MatchDataDictionaryKeyUtil.getKey(accountStatusDic, dataMap.get("c_accstat")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }


    public void processTgCurrentAccountSeqInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        try {
            List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
            for (String fundCode : fundCodeList) {
                int pageNo = 0;
                int totalPages = 0;
                for (; ; ) {
                    pageNo++;
                    //拼装请求参数
                    Map<String, Object> paramsMap = new HashMap<>();
                    paramsMap.put("pageNo", pageNo);
                    paramsMap.put("c_amacfundcode", fundCode);
                    //拼装参数字符串
                    String paramStr = "&pageNo=" + pageNo + "&c_amacfundcode=" + fundCode;
                    Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.TGACCOUNT_CURRENT_SEQ_INFO, paramStr, paramsMap);
                    log.info("anxin: processTgCurrentAccountSeqInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                    if (ObjectUtils.isNotEmpty(result)) {
                        if (JSONPath.contains(result, "$.returnObject")) {
                            totalPages = Integer.parseInt(result.get("totalPages").toString());
                            int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                            log.info("anxin: processTgCurrentAccountSeqInfoData : totalCount = {} ", totalCount);
                            List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                            List<TgAccountSeqInfoEntity> tgAccountSeqInfoEntities = getTgCurrentAccountSeqInfo(tenant, trustNo, returnObject);
                            log.info("anxin: processTgCurrentAccountSeqInfoData : 转义TgAccountSeqInfo dataSize = {} ", tgAccountSeqInfoEntities);
                            tgAccountSeqInfoService.saveData(null, tgAccountSeqInfoEntities);
                        }
                    }
                    if (pageNo >= totalPages) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("anxin：processFundTempAndFundFeeInfoData！", e);
        }
    }

    private List<TgAccountSeqInfoEntity> getTgCurrentAccountSeqInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //获取数据字典
        Map<String, String> payMentDirDic = basicService.queryWithDetail(DataDictionaryTypeEnum.PAYMENT_DIRECTION_SERVICE, trustNo);//收付方向
        Map<String, String> currencyDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CURRENCY_SERVICE, trustNo);//币种
        //封装数据
        List<TgAccountSeqInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(TgAccountSeqInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .transferInOut(MatchDataDictionaryKeyUtil.getKey(payMentDirDic, String.valueOf(dataMap.get("c_way"))))
                    .seqNo(dataMap.get("c_seqno").length() > 32 ? dataMap.get("c_seqNo").substring(0, 32) : dataMap.get("c_seqNo"))
                    .account(dataMap.get("c_account"))
                    .accountName(dataMap.get("c_accountname"))
                    .opAccount(dataMap.get("c_opAccount"))
                    .opAccountName(dataMap.get("c_opAccountname"))
                    .amount(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_amount")))
                    .transferDate(dataMap.get("d_transferdate").split(" ")[0].replaceAll("-", ""))
                    .transferTime(dataMap.get("d_transferdate").split(" ")[1])
                    .summary(dataMap.get("c_summary"))
                    .currency(MatchDataDictionaryKeyUtil.getKey(currencyDic, dataMap.get("c_currency")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }


    public void processTgHistoryAccountSeqInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusDays(30);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("pageNo", pageNo);
                        paramsMap.put("d_sdate", finalStartDate);
                        paramsMap.put("d_edate", finalEndDate);
                        paramsMap.put("c_amacfundcode", fundCode);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&d_sdate=" + finalStartDate + "&d_edate=" + finalEndDate + "&c_amacfundcode=" + fundCode;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.TGACCOUNT_HISTORY_SEQ_INFO, paramStr, paramsMap);
                        log.info("anxin: processTGHistoryAccountSeqInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processTGHistoryAccountSeqInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<TgAccountSeqInfoEntity> tgAccountSeqInfoEntities = getTgHistoryAccountSeqInfo(tenant, trustNo, returnObject);
                                log.info("anxin: processTGHistoryAccountSeqInfoData : 转义TgAccountSeqInfo dataSize = {} ", tgAccountSeqInfoEntities);
                                tgAccountSeqInfoService.saveData(null, tgAccountSeqInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("anxin：processFundTempAndFundFeeInfoData！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<TgAccountSeqInfoEntity> getTgHistoryAccountSeqInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //获取数据字典
        Map<String, String> currencyDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CURRENCY_SERVICE, trustNo);
        //封装数据
        List<TgAccountSeqInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(TgAccountSeqInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .transferInOut(String.valueOf(dataMap.get("c_way")))
                    .seqNo(dataMap.get("c_seqno").length() > 32 ? dataMap.get("c_seqno").substring(0, 32) : dataMap.get("c_seqno"))
                    .account(dataMap.get("c_account"))
                    .accountName(dataMap.get("c_accountname"))
                    .opAccount(dataMap.get("c_opAccount"))
                    .opAccountName(dataMap.get("c_opAccountname"))
                    .amount(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_amount")))
                    .transferDate(dataMap.get("d_transferdate").split(" ")[0].replaceAll("-", ""))
                    .transferTime(dataMap.get("d_transferdate").split(" ")[1])
                    .summary(dataMap.get("c_summary"))
                    .currency(MatchDataDictionaryKeyUtil.getKey(currencyDic, dataMap.get("c_currency")))
                    .updateDate(dataMap.get("d_updatetime"))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());

        }
        return entityList;
    }


    public void processFundTempAndFundFeeInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusDays(30);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("pageNo", pageNo);
                        paramsMap.put("d_sdate", finalStartDate);
                        paramsMap.put("d_edate", finalEndDate);
                        paramsMap.put("c_amacfundcode", fundCode);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&d_sdate=" + finalStartDate + "&d_edate=" + finalEndDate + "&c_amacfundcode=" + fundCode;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.FUND_TEMP_FARE_AND_FUND_FEE_INFO, paramStr, paramsMap);
                        log.info("anxin: processFundTempAndFundFeeInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processFundTempAndFundFeeInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<FundTempFareInfoEntity> fundTempFareInfoEntities = getFundTempFareInfo(tenant, trustNo, returnObject);
                                log.info("anxin: processFundTempAndFundFeeInfoData : 转义fundTempFareInfo dataSzie = {} ", fundTempFareInfoEntities.size());
                                fundTempFareInfoService.saveData(null, fundTempFareInfoEntities);
                                List<FundFeeDataInfoEntity> fundFeeDataInfoEntities = getFundFeeInfo(tenant, trustNo, returnObject);
                                log.info("anxin: processFundTempAndFundFeeInfoData : 转义fundFeeDataInfoEntities dataSzie = {} ", fundFeeDataInfoEntities.size());
                                fundFeeDataInfoService.saveData(null, fundFeeDataInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("anxin：processFundTempAndFundFeeInfoData！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<FundFeeDataInfoEntity> getFundFeeInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        List<FundFeeDataInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            //增值税
            entityList.add(FundFeeDataInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .confirmDate(dataMap.get("d_confirmDate"))
                    .fareDebit(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_vat")))
                    .subjectCode("ZZS")
                    .subjectName("增值税")
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            //附加税
            entityList.add(FundFeeDataInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .confirmDate(dataMap.get("d_confirmDate"))
                    .fareDebit(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_surtax")))
                    .subjectCode("FJS")
                    .subjectName("附加税")
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            //管理费
            entityList.add(FundFeeDataInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .confirmDate(dataMap.get("d_confirmDate"))
                    .fareDebit(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_management")))
                    .subjectCode("GLF")
                    .subjectName("管理费")
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            //托管费
            entityList.add(FundFeeDataInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .confirmDate(dataMap.get("d_confirmDate"))
                    .fareDebit(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_hosting")))
                    .subjectCode("TGF")
                    .subjectName("托管费")
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            //业绩报酬
            entityList.add(FundFeeDataInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .confirmDate(dataMap.get("d_confirmDate"))
                    .fareDebit(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_businessCompensation")))
                    .subjectCode("YJBC")
                    .subjectName("业绩报酬")
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
            //运营服务费
            entityList.add(FundFeeDataInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .confirmDate(dataMap.get("d_confirmDate"))
                    .fareDebit(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_operationService")))
                    .subjectCode("YYFWF")
                    .subjectName("运营服务费")
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }

    private List<FundTempFareInfoEntity> getFundTempFareInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //获取数据字典
        //封装请求参数
        List<FundTempFareInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(FundTempFareInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .confirmDate(dataMap.get("d_confirmDate"))
                    .fareVat(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_vat")))
                    .fareSurtax(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_surtax")))
                    .fareManagement(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_management")))
                    .fareHosting(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_hosting")))
                    .fareBusiness(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_businessCompensation")))
                    .fareOperationService(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_operationService")))
                    .fareVatTemp(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_zg_vat")))
                    .fareSurtaxTemp(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_zg_surtax")))
                    .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("yyyyMMdd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusDays(30);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("pageNo", pageNo);
                        paramsMap.put("d_sdate", finalStartDate);
                        paramsMap.put("d_edate", finalEndDate);
                        paramsMap.put("c_amacfundcode", fundCode);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&d_sdate=" + finalStartDate + "&d_edate=" + finalEndDate + "&c_amacfundcode=" + fundCode;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.FUND_NET_VALUE_INFO, paramStr, paramsMap);
                        log.info("anxin: processFundNetValueInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processFundNetValueInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<FundNetValueInfoEntity> fundNetValueInfoEntities = getFundNetValueInfo(tenant, trustNo, returnObject);
                                log.info("anxin: processFundNetValueInfoData : 转义之后 dataSize= {} ", fundNetValueInfoEntities.size());
                                fundNetValueInfoService.saveData(null, fundNetValueInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("anxin：processFundNetValueInfoData获取数据异常！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<FundNetValueInfoEntity> getFundNetValueInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //获取数据字典
        Map<String, String> fundCLassificationLogoDic = basicService.queryWithDetail(DataDictionaryTypeEnum.FUND_CLASSIFICATION_LOGO_SERVICE, trustNo);
        //封装数据
        List<FundNetValueInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(FundNetValueInfoEntity.builder()
                    .netValueDate(dataMap.get("d_rq"))
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .netValue(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_dwjz"), 4))
                    .totalNetValue(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_ljdwjz"), 4))
                    .shares(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_zcfe")))
                    .assetValue(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_zcjz")))
                    .totalAsset(BigDecimalUtil.obj2BigDecimalTrunToZero(dataMap.get("f_zchj")))
                    .innerFundCode(dataMap.get("f_fjjjdm"))
                    .fundLevel(MatchDataDictionaryKeyUtil.getKey(fundCLassificationLogoDic, dataMap.get("c_fjjb")))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }
        return entityList;
    }


    public void processMJAccountSeqInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, int loopTime) {
        String startDate;
        String endDate;
        LocalDate localDate = LocalDate.now();
        LocalDate lastMonth;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        endDate = dateTimeFormatter.format(localDate);
        for (int i = 0; i < loopTime; i++) {
            lastMonth = localDate.minusDays(30);
            startDate = dateTimeFormatter.format(lastMonth);
            String finalStartDate = startDate;
            String finalEndDate = endDate;
            try {
                List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());

                for (String fundCode : fundCodeList) {
                    int pageNo = 0;
                    int totalPages = 0;
                    for (; ; ) {
                        pageNo++;
                        //拼装请求参数
                        Map<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("pageNo", pageNo);
                        paramsMap.put("d_sdate", finalStartDate);
                        paramsMap.put("d_edate", finalEndDate);
                        paramsMap.put("c_amacfundcode", fundCode);
                        //拼装参数字符串
                        String paramStr = "&pageNo=" + pageNo + "&d_sdate=" + finalStartDate + "&d_edate=" + finalEndDate + "&c_amacfundcode=" + fundCode;
                        Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.MJACCOUNT_SEQ_INFO, paramStr, paramsMap);
                        log.info("anxin: processMJAccountSeqInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                        if (ObjectUtils.isNotEmpty(result)) {
                            if (JSONPath.contains(result, "$.returnObject")) {
                                totalPages = Integer.parseInt(result.get("totalPages").toString());
                                int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                                log.info("anxin: processMJAccountSeqInfoData : totalCount = {} ", totalCount);
                                List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                                List<MjAccountSeqInfoEntity> mjAccountSeqInfoEntities = getMJAccountSeqInfo(tenant, trustNo, returnObject);
                                mjAccountSeqInfoService.saveData(null, mjAccountSeqInfoEntities);
                            }
                        }
                        if (pageNo >= totalPages) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("anxin：processMJAccountSeqInfoData保存数据异常！", e);
            }
            localDate = lastMonth;
            endDate = startDate;
        }
    }

    private List<MjAccountSeqInfoEntity> getMJAccountSeqInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        //获取数据字典
        Map<String, String> paymentDirectionDic = basicService.queryWithDetail(DataDictionaryTypeEnum.PAYMENT_DIRECTION_SERVICE, trustNo);//收付方向
        Map<String, String> currencyDic = basicService.queryWithDetail(DataDictionaryTypeEnum.CURRENCY_SERVICE, trustNo);
        //封装数据
        List<MjAccountSeqInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(MjAccountSeqInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .transferInOut(MatchDataDictionaryKeyUtil.getKey(paymentDirectionDic, dataMap.get("c_tranflag")))
                    .seqNo(dataMap.get("c_tradingno").length() > 32 ? dataMap.get("c_tradingno").substring(0, 32) : dataMap.get("c_tradingno"))
                    .account(dataMap.get("c_recipientacco"))
                    .opBankName(dataMap.get("c_paybankname"))
                    .opAccount(dataMap.get("c_payacco"))
                    .opAccountName(dataMap.get("c_payacconame"))
                    .amount(BigDecimalUtil.str2BigDecimalDefaultZero(dataMap.get("f_amount")))
                    .balance(BigDecimalUtil.str2BigDecimalDefaultZero(dataMap.get("f_balance")))
                    .transferDate(dataMap.get("d_occurtime").split(" ")[0].replaceAll("-", ""))
                    .transferTime(dataMap.get("d_occurtime").split(" ")[1])
                    .summary(dataMap.get("c_abstract"))
                    .currency(MatchDataDictionaryKeyUtil.getKey(currencyDic, dataMap.get("c_currency")))
                    .updateDate(dataMap.get("d_updatetime"))
                    .trustNo(trustNo)
                    .admin(tenant.getTenantName())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build());
        }

        return entityList;
    }

    public void processChildFundInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        try {
            List<String> fundCodeList = fundInfoService.getFundCodeList(trustNo, tenant.getTenantName());
            for (String fundCode : fundCodeList) {
                int pageNo = 0;
                int totalPages = 0;
                for (; ; ) {
                    pageNo++;
                    //拼装请求参数
                    Map<String, Object> paramsMap = new HashMap<>();
                    paramsMap.put("c_amacfundcode", fundCode);
                    paramsMap.put("pageNo", pageNo);
                    //拼装参数字符串
                    String paramStr = "&pageNo=" + pageNo + "&c_amacfundcode=" + fundCode;
                    Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.CHILD_FUND_INFO, paramStr, paramsMap);
                    log.info("anxin: processChildFundInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                    if (ObjectUtils.isNotEmpty(result)) {
                        if (JSONPath.contains(result, "$.returnObject")) {
                            totalPages = Integer.parseInt(result.get("totalPages").toString());
                            int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                            log.info("anxin: processChildFundInfoData : totalCount = {} ", totalCount);
                            List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                            List<FundInfoEntity> fundInfoEntities = getChildFundInfo(tenant, trustNo, returnObject);
                            log.info("anxin: processChildFundInfoData : 转义后fundChildInfo dataSize = {}", fundInfoEntities.size());
                            fundInfoService.saveData(null, fundInfoEntities);
                        }
                    }
                    if (pageNo >= totalPages) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("anxin:processChildFundInfoData获取失败！", e);
        }
    }

    private List<FundInfoEntity> getChildFundInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {
        List<FundInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            if (Objects.equals(dataMap.get("c_amacfundcode"), dataMap.get("c_subfundcode"))) {
                entityList.add(FundInfoEntity.builder()
                        .fundCode(dataMap.get("c_amacfundcode"))
                        .innerFundCode(dataMap.get("c_subfundcode"))
                        .fundName(dataMap.get("c_subfundname"))
                        .fundLevel("2")
                        .trustNo(trustNo)
                        .admin(tenant.getTenantName())
                        .createTime(new Date())
                        .updateTime(new Date())
                        .build());
            }
        }
        return entityList;
    }

    public void processFundInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo) {
        int totalPages = 0;
        int pageNo = 0;
        try {
            for (; ; ) {
                pageNo++;
                //拼装请求参数
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("pageNo", pageNo);
                //拼装参数字符串
                String paramStr = "&pageNo=" + pageNo;
                Map<String, Object> result = anXinUtils.sendMessage(tenant, AnxinContants.FUND_INFO, paramStr, paramsMap);
                log.info("anxin: processFundInfoData : params = {} ,result = {}", paramsMap, JSONObject.toJSONString(result));
                if (ObjectUtils.isNotEmpty(result)) {
                    if (JSONPath.contains(result, "$.returnObject")) {
                        totalPages = Integer.parseInt(result.get("totalPages").toString());
                        int totalCount = Integer.parseInt(result.get("totalRecords").toString());
                        log.info("anxin: processFundInfoData : totalCount = {} ", totalCount);
                        List<JSONObject> returnObject = JSONObject.parseArray(JSONObject.toJSONString(result.get("returnObject")), JSONObject.class);
                        List<FundInfoEntity> fundInfoEntities = getFundInfo(tenant, trustNo, returnObject);
                        log.info("anxin: processFundInfoData : 转义后fundInfo dataSize = {}", fundInfoEntities.size());
                        fundInfoService.saveData(null, fundInfoEntities);
                    }
                }
                if (pageNo >= totalPages) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("anxin:processFundInfoData获取失败！", e);
        }
    }

    private List<FundInfoEntity> getFundInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, List<JSONObject> returnObject) {

        //获取字典
        Map<String, String> fundOrganizationDic = basicService.queryWithDetail(DataDictionaryTypeEnum.FUND_ORGANIZATION_SERVICE, trustNo);//基金组织形式
        Map<String, String> fundTypeDic = basicService.queryWithDetail(DataDictionaryTypeEnum.FUND_TYPE_SERVICE, trustNo);//基金类型
        Map<String, String> privateFundTypeDic = basicService.queryWithDetail(DataDictionaryTypeEnum.PRIVATE_FUND_TYPE_SERVICE, trustNo);
        Map<String, String> fundOperationFormDic = basicService.queryWithDetail(DataDictionaryTypeEnum.FUND_OPERATION_FORM_SERVICE, trustNo);//基金运作方式
        Map<String, String> settlementModeDic = basicService.queryWithDetail(DataDictionaryTypeEnum.SETTLEMENT_MODE_SERVICE, trustNo);//场内结算模式
        Map<String, String> fundClassificationLogoDic = basicService.queryWithDetail(DataDictionaryTypeEnum.FUND_CLASSIFICATION_LOGO_SERVICE, trustNo);
        //封装数据
        List<FundInfoEntity> entityList = new ArrayList<>();
        Map<String, String> dataMap;
        for (JSONObject data : returnObject) {
            dataMap = JSONObject.toJavaObject(data, Map.class);
            entityList.add(FundInfoEntity.builder()
                    .fundCode(dataMap.get("c_amacfundcode"))
                    .innerFundCode(dataMap.get("c_amacfundcode"))
                    .fundName(dataMap.get("c_fundname"))
                    .orgForm(MatchDataDictionaryKeyUtil.getKey(fundOrganizationDic, dataMap.get("c_zzxs")))
                    .fundType(MatchDataDictionaryKeyUtil.getKey(fundTypeDic, dataMap.get("c_cplx")))
                    .peType(MatchDataDictionaryKeyUtil.getKey(privateFundTypeDic, dataMap.get("c_cplx")))
                    .operationMethod(MatchDataDictionaryKeyUtil.getKey(fundOperationFormDic, dataMap.get("c_yzfs")))
                    .settlementType(MatchDataDictionaryKeyUtil.getKey(settlementModeDic, String.valueOf(dataMap.get("c_settlement_type"))))
                    .createDate(dataMap.get("d_createdate"))
                    .fundLevel(MatchDataDictionaryKeyUtil.getKey(fundClassificationLogoDic, dataMap.get("c_fundstructure")))
                    .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("更新安信证券托管数据开始......");
        int loopTime = CustodyContants.UPDATE_BY_MONTH_DAILY_LOOP_TIME;
        getUpdateDataFromAnXin(tenant, loopTime);
        log.info("更新安信证券托管数据完成......");
        return R.ok("更新安信证券托管成功！");
    }

    private void getUpdateDataFromAnXin(TenantEscrowAuthorizationInfoDto tenant, int loopTime) {
        String trustNo = tenant.getTrustNo();
        try {
            //基金产品信息表 (fund_info)
            processFundInfoData(tenant, trustNo);
            //基金产品信息表 (fund_info) - 子基金
            processChildFundInfoData(tenant, trustNo);
            //基金估值表费用信息表 (fund_temp_fare_info) + 基金费用数据表 (fund_fee_data_info)
            processFundTempAndFundFeeInfoData(tenant, trustNo, loopTime);
            //托管户流水表 (TGAccount_seq_info) 历史
            processTgHistoryAccountSeqInfoData(tenant, trustNo, loopTime);
            //资金账户基本信息表 (account_info)
            processAccountInfoData(tenant, trustNo);
            //基金估值报表数据表(fund_value_table_data_info)，安信接口废弃
//            processFundValueTableDataInfoData(tenant, trustNo, loopTime);
            // 费用计提明细表 (charge_fee_detail_info)
            processChargeFeeDetailInfoData(tenant, trustNo, loopTime);
            //12.基金出资人信息表-investor_info   （基金出资人银行账户信息表-investor_bank_info）
            processInvestorAndInvestorBankInfoData(tenant, trustNo);
            //13.基⾦交易确认信息表（fund_trade_info）
            processFundTradeInfoData(tenant,trustNo,loopTime);
            //14.基金持有信息表（cust_share_info）
            processCustShareInfoData(tenant,trustNo);
            //15.基金持有份额明细表（cust_share_detail_info）
            processCustShareDetailInfoData(tenant, trustNo, loopTime);

        } catch (Exception e) {
            log.error("更新安信托管数据失败！");
        }
    }

    @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) {
        log.info("initLaterSingleTenantData is begin... the versionStr is {} ,the tenant is {}", versionStr, JSON.toJSONString(tenant));
        String trustNo = tenant.getTrustNo();
        Integer loopNum = CustodyContants.INIT_BY_MONTH_LOOP_TIME;
        switch (versionStr) {
            case CustodyContants.R_PT_S_CUSTODY_3_2_6:
                //募集户流水表
                processMJAccountSeqInfoData(tenant, trustNo, loopNum);
                log.info("管理人{}安信募集户流水表更新完成!", tenant.getTenantName());
                //托管户流水表 (TGAccount_seq_info) 历史
                processTgHistoryAccountSeqInfoData(tenant, trustNo, loopNum);
                log.info("管理人{}安信托管历史流水表更新完成!", tenant.getTenantName());
                break;
        }
    return null;
}
    public void initTenantDataBy305Patch02(TenantEscrowAuthorizationInfoDto tenant,String trustNo,Integer loopNum){
        log.info("安信更新fundOpenInfo开始");
        //12.基金出资人信息表-investor_info   （基金出资人银行账户信息表-investor_bank_info）
        processInvestorAndInvestorBankInfoData(tenant, trustNo);
        //13.基⾦交易确认信息表（fund_trade_info）
        processFundTradeInfoData(tenant,trustNo,loopNum);
        //14.基金持有信息表（cust_share_info）
        processCustShareInfoData(tenant,trustNo);
        //15.基金持有份额明细表（cust_share_detail_info）
        processCustShareDetailInfoData(tenant, trustNo, loopNum);
        log.info("安信更新fundOpenInfo结束");
    }

    @Override
    public R initByAppointedTrustNoAndMouth(TenantEscrowAuthorizationInfoDto tenant, int mouth) {
        String trustNo = tenant.getTrustNo();
        try {
            getDataFromAnXin(tenant, mouth);
        } catch (Exception e) {
            log.error("初始化安信托管数据失败！");
            return R.error("初始化安信托管数据失败！");
        }
        return R.ok("初始化安信托管数据成功！");
    }

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

    @Override
    public R updateSingleData20min(TenantEscrowAuthorizationInfoDto tenant) {
        try {
            log.info("*****************安信证券托管数据每半小时更新开始************************");
            String trustNo = tenant.getTrustNo();//42
            Integer loopTime = CustodyContants.UPDATE_BY_MONTH_DAILY_LOOP_TIME;
            //募集户流水表 (MJAccount_seq_info)
            outSourceAnXinService.processMJAccountSeqInfoData(tenant, trustNo, loopTime);
            //托管户流水表 (TGAccount_seq_info) 当日
            outSourceAnXinService.processTgCurrentAccountSeqInfoData(tenant, trustNo);
            //托管户银行账户余额信息表 (TGAccount_balance_info)
            outSourceAnXinService.processTgAccountBalanceInfoData(tenant, trustNo);
            log.info("******************安信证券托管数据每半小时更新结束***********************");
            return R.ok("安信证券托管数据每半小时更新完成！");
        } catch (Exception e) {
            log.error("安信证券托管数据每半小时更新异常！", e);
            return R.ok("安信证券托管数据每半小时更新失败！");
        }
    }


    @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
            outSourceAnXinService.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 {
            processMJAccountSeqInfoData(tenant, tenant.getTrustNo(), CustodyContants.UPDATE_BY_MONTH_DAILY_LOOP_TIME);
            return DubboResult.newSuccess();
        } catch (Exception e) {
            log.error("手动更新募集户流水失败", e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "手动更新募集户流水失败" + e.getMessage());
        }
    }

    @Override
    public DubboResult updateTGBalanceData(TenantEscrowAuthorizationInfoDto tenant) {
        try {
            //7.托管户流水表 (TGAccount_seq_info) 当日
            processTgCurrentAccountSeqInfoData(tenant, tenant.getTrustNo());
            return DubboResult.newSuccess();
        } catch (Exception e) {
            log.error("手动更新托管户余额失败", e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "手动更新托管户余额失败" + e.getMessage());
        }
    }

    @Override
    public DubboResult updateTGSeqData(TenantEscrowAuthorizationInfoDto tenant) {
        try {
            processTgHistoryAccountSeqInfoData(tenant, tenant.getTrustNo(), CustodyContants.UPDATE_BY_MONTH_DAILY_LOOP_TIME);
            return DubboResult.newSuccess();
        } catch (Exception e) {
            log.error("手动更新托管户流水失败", e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, "手动更新托管户流水失败" + e.getMessage());
        }
    }
}
