package com.friday.custody.service.trustService.cmsc.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.friday.custody.service.trustService.cmsc.dto.*;
import com.friday.custody.service.trustService.htsc.common.HtscConstants;
import com.friday.custody.service.trustService.htsc.dto.ChildPrdtInfoDto;
import com.friday.custody.service.trustService.htsc.dto.CustSharesDto;
import com.friday.custody.service.trustService.htsc.dto.FundValueDto;
import com.friday.custody.service.trustService.htsc.dto.InvestmentSubjectsDto;
import com.friday.custody.service.trustService.htsc.utils.HTSCGetDataUtil;
import com.friday.custody.service.trustService.htsc.utils.HTSCRemoteUtil;
import com.friday.custody.service.trustService.htsc.utils.HTSCSignGenerator;
import com.google.gson.Gson;
import com.friday.custody.dto.CmscAppSecretDTO;
import com.friday.custody.dto.TenantEscrowAuthorizationInfoDto;
import com.friday.custody.service.trustService.cmsc.common.CmscConstants;
import com.friday.custody.utils.PullDataFailureUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static java.time.LocalDateTime.now;

@Slf4j
@Service("cMSCGetDataUtil")
public class CMSCGetDataUtil {

    @Autowired
    HTSCGetDataUtil htscGetDataUtil;

    @Autowired
    HttpUtil httpUtil;

    public  Map<String, Object> processChildPrdtInfo(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix, String today) {
        Map<String, String> headerParamsMap = new HashMap<>();
        headerParamsMap.put("appid", tenant.getAppKey());
        headerParamsMap.put("fundLevel", "2");
        headerParamsMap.put("Timestamp", today);
        headerParamsMap.put("url", HtscConstants.CHILD_PRDT_INFO_API);
        String appSecret = tenant.getAppSecret();
        String sign = HTSCSignGenerator.genSign(appSecret, headerParamsMap);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Timestamp", today);
        headers.set("Sign", sign);
        HashMap remoteResp = HTSCRemoteUtil.getDataFromRemote(htscUrlPrefix + HtscConstants.CHILD_PRDT_INFO_API + "?appId=" + tenant.getAppKey()
                + "&fundLevel=2", headers);
        // 2.1 调用失败 将错误记录到错误记录表中
        if ((Integer) remoteResp.get("code") == 200) {
            Object remoteData = remoteResp.get("data");
            if (!Objects.isNull(remoteData) && remoteData instanceof List) {
                return processChildPrdtInfoData((List<Object>) remoteData);
            }
        }
        return PullDataFailureUtil.createErrorMap(trustNo, HtscConstants.CHILD_PRDT_INFO_API, headers, "appId=" + tenant.getAppKey(), remoteResp);
    }

//    public String getEnvByTenant(TenantEscrowAuthorizationInfoDto tenant){
//        log.info("getEnvByTenant入参"+JSON.toJSONString(tenant));
//        String appKey = tenant.getAppKey();
//        String appSecret = tenant.getAppSecret();
//        String cmscEnv = new String();
//        if(CmscConstants.TY_UAP_USER_NO.equals(appKey) && CmscConstants.TY_UNZIP_CODE.equals(appSecret)){
//            cmscEnv = "TY";
//        }else if(CmscConstants.YC_UAP_USER_NO.equals(appKey) && CmscConstants.YC_UNZIP_CODE.equals(appSecret)){
//            cmscEnv = "YC";
//        }else if(CmscConstants.TEST_UAP_USER_NO.equals(appKey) && CmscConstants.TEST_UNZIP_CODE.equals(appSecret)){
//            cmscEnv = "TEST";
//        }
//        if(StringUtils.isBlank(cmscEnv)){
//            log.error("招商的租户信息不正确！");
//            return null;
//        }
//        log.info("getEnvByTenant出参"+cmscEnv);
//        return cmscEnv;
//    }

    private  Map<String, Object> processChildPrdtInfoData(List<Object> childPrdtInfo) {
        ArrayList<ChildPrdtInfoDto> result = new ArrayList<>();
        ChildPrdtInfoDto po;
        for (Object item : childPrdtInfo) {
            if (item == null) continue;
            po = JSON.parseObject(JSON.toJSONString(item), ChildPrdtInfoDto.class);
            result.add(po);
        }
        Map<String, List<ChildPrdtInfoDto>> collect = result.stream().collect(Collectors.groupingBy(ChildPrdtInfoDto::getParentPrdtConvertCode));
        return collect.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));


    }

    //第二张表
    public  Map<String, Object> processInvestorInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                        String today, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount = 0;
        int pageNum = 1;
        int pageSize = 300;
        do {
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);

                String filePath = tenant.getFilePath();
                String requestNo = "1008";

                //1008
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMInvestorInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap,  stringObjectMap, CMInvestorInfoDto.class,tenant,requestNo,businessparam);
            } catch (Exception e) {
                log.error("processInvestorInfoData_招商查询失败" + e.getMessage());
            }
        } while (pageCount >= pageNum-1);

        log.info("第二张表查询{}页数据 数据量为{}", pageNum - 1, returnMap.size());
        return returnMap;
    }
    private ObjectMapper objectMapper = new ObjectMapper();
    public CmscAppSecretDTO getAppSecretDTO(TenantEscrowAuthorizationInfoDto tenant){
        String tenantAppSecret = tenant.getAppSecret();
        if (ObjectUtil.isEmpty(tenantAppSecret)){
            return null;
        }
        CmscAppSecretDTO cmscAppSecretDTO = new CmscAppSecretDTO();
        try {
            cmscAppSecretDTO = objectMapper.readValue(tenantAppSecret, CmscAppSecretDTO.class);
            String date = DateUtil.format(now(), "yyyyMMddHHmmss");
            String random = String.valueOf(RandomUtil.randomInt(10, 99));
            String uapRequestId = date + random;
            cmscAppSecretDTO.setUapRequestId(uapRequestId);
        } catch (IOException e) {
            log.error("获取token时, 解析账密失败{}!", e, cmscAppSecretDTO);
        }
        return cmscAppSecretDTO;
    }

    //第十一张表 (1)
    public  Map<String, Object> processAccountInfoData1(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                        String today, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount = 0;
        int pageNum = 1;
        int pageSize = 300;
        do {
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);

                String filePath = tenant.getFilePath();

                String requestNo = "1001";

                //1001
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMMJAccountInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap,  stringObjectMap, CMMJAccountInfoDto.class,tenant,requestNo,businessparam);
            } catch (Exception e) {
                log.error("招商查询失败" + e.getMessage());
            }
        } while (pageCount >= pageNum-1);

        log.info("第十一张表查询{}页数据 数据量为{}", pageNum - 1, returnMap.size());
        log.info("processAccountInfoData1_"+JSON.toJSONString(returnMap));
        return returnMap;
    }


    //第十一张表 (1)
    public  Map<String, Object> processAccountInfoData2(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                        String today, String companyId,String fundCode) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount = 0;
        int pageNum = 1;
        int pageSize = 300;
        do {
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                map.put("fundCode", fundCode);
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);

                String requestNo = "1010";
                String filePath = tenant.getFilePath();

                //1001
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMTGHAccountInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap,  stringObjectMap, CMTGHAccountInfoDto.class,tenant,requestNo,businessparam);
            } catch (Exception e) {
                log.error("processAccountInfoData2_招商查询失败" + e.getMessage());
            }
        } while (pageCount >= pageNum-1);

        log.info("第十一张表查询{}页数据 数据量为{}", pageNum - 1, returnMap.size());
        return returnMap;
    }

    /**
     * 第七张表
     * @param tenant
     * @param trustNo
     * @param htscUrlPrefix
     * @param today
     * @param companyId
     * @return
     */
    public  Map<String, Object> processMJAccountBalanceInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                                String today, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 300;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);

                String filePath = tenant.getFilePath();

                String requestNo = "1001";

                //1011
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMMJAccountBalanceInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMMJAccountBalanceInfoDto.class,tenant,requestNo,businessparam);
            } catch (Exception e) {
                log.error("招商查询失败" + e.getMessage());
            }
        } while (pageCount >= pageNum-1);

        log.info("第七张表查询{}页数据 数据量为{}", pageNum - 1, returnMap.size());
        return returnMap;
    }


    /**
     * 第二张表（2）
     * @param tenant
     * @param fundCode
     * @param beginDate
     * @param endDate
     * @return
     */
    public  Map<String, Object> processTGAccountSeqInfoDataData2(TenantEscrowAuthorizationInfoDto tenant,
                                                                 String fundCode,String beginDate,String endDate,String today) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 100;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("fundCode", fundCode);
                map.put("beginDate", beginDate);
                map.put("endDate", endDate);
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);

                String filePath = tenant.getFilePath();

                String requestNo = "1012";

                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMTgAccountSeqInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMTgAccountSeqInfoDto.class, tenant, requestNo, businessparam);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } while (pageCount >= pageNum - 1);


        log.info("从{}到{}查询到{} 入库{}", beginDate, endDate, returnMap.size());
        return returnMap;
    }

    /**
     * 第六张表(1)
     *
     * @param tenant
     * @param trustNo
     * @param htscUrlPrefix
     * @param today
     * @param companyId
     * @return
     */
    public Map<String, Object> processTGAccountSeqInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                           String today, String companyId, String fundCode) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 300;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                map.put("fundCode", fundCode);
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);

                String filePath = tenant.getFilePath();

                String requestNo = "1011";
                //1011
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMTgAccountSeqInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMTgAccountSeqInfoDto.class, tenant, requestNo, businessparam);
            } catch (Exception e) {
                log.error("processTGAccountSeqInfoData_招商查询失败" + e.getMessage());
            }
        } while (pageCount >= pageNum - 1);

        log.info("第六张表查询{}页数据 数据量为{}", pageNum - 1, returnMap.size());
        return returnMap;
    }

    // 根据fundname获取fundCode
    public String getFundCodeByFundName(TenantEscrowAuthorizationInfoDto tenant,
                                        String today,
                                        String beginDate,
                                        String endDate,
                                        String fundName) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        int pageNum = 1;
        int pageSize = 10;

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("beginDate", beginDate);
            map.put("endDate", endDate);
            map.put("pageNumber", String.valueOf(pageNum));
            map.put("pageSize", String.valueOf(pageSize));
            map.put("fundName", fundName);
            Gson gson = new Gson();
            String businessparam = gson.toJson(map);
            log.info("businessparam" + businessparam);

            String filePath = tenant.getFilePath();

            String requestNo = "1009";

            Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                    requestNo,
                    filePath,
                    today,
                    businessparam,
                    CMPrdInfoDto.class,
                    tenant);

            String fundCode = getFundCode(stringObjectMap);
            log.info("getFundCodeByFundName查询上游1009接口参数为{}，上游返回为为{}，返回fundCode为{}",businessparam,JSON.toJSONString(stringObjectMap),fundCode);

            return fundCode;


        } catch (Exception e) {
            log.error(e.getMessage());
        }


        return null;
    }

    // 第一张表
    public Map<String, Object> processFundInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                   String today, String beginDate, String endDate, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 100;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("beginDate", beginDate);
                map.put("endDate", endDate);
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);

                String filePath = tenant.getFilePath();

                String requestNo = "1009";

                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMPrdInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMPrdInfoDto.class, tenant, requestNo, businessparam);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } while (pageCount >= pageNum - 1);


        log.info("从{}到{}查询到{} 入库", beginDate, endDate, returnMap.size());
        return returnMap;
    }

    public <T extends CMBaseDto> int getResultSize(Map<String, Object> returnMap, Map<String, Object> stringObjectMap, Class<T> classT, TenantEscrowAuthorizationInfoDto tenant, String requestNo, String businessparam) {

        int pageCount = 0;
        if ((Boolean) stringObjectMap.get("result")) {
            List<T> data = (List<T>) stringObjectMap.get("data");

            HashMap<String, String> map = new HashMap<>();
            for (Map.Entry<String, Object> stringObjectEntry : stringObjectMap.entrySet()) {
                Object value = stringObjectEntry.getValue();
                String key = stringObjectEntry.getKey();
                map.put(key, value == null ? "" : value.toString());
            }

            CMPageDto page = (CMPageDto) stringObjectMap.get("page");

            if (page != null && page.getPageCount() != null) {
                pageCount = page.getPageCount();
            }

            if (classT == CMTGHAccountInfoDto.class && "1010".equals(requestNo)){
                Map<String, CMTGHAccountInfoDto> collect = data.stream()
                        .map(t -> (CMTGHAccountInfoDto) t)
                        .collect(Collectors.toMap(t -> t.getAccountNo(), t -> t, (t1, t2) -> t1));
                returnMap.putAll(collect);

            }else {
                Map<String, T> collect = data.stream().collect(Collectors.toMap(item -> item.getLogicUniqueKey(), item -> item, (item1, item2) -> item1));
                returnMap.putAll(collect);
            }


        } else {
            HashMap<String, Object> data = (HashMap<String, Object>) stringObjectMap.get("data");

            log.info("getResultSize_招商查询失败时参数情况" + data);
            returnMap.putAll(data);
        }
        return pageCount;
    }

    public String getFundCode(Map<String, Object> stringObjectMap) {

        String fundCode = "";
        try {
            if ((Boolean) stringObjectMap.get("result")) {
                List<CMPrdInfoDto> data = (List<CMPrdInfoDto>) stringObjectMap.get("data");

                HashMap<String, String> map = new HashMap<>();
                for (Map.Entry<String, Object> stringObjectEntry : stringObjectMap.entrySet()) {
                    Object value = stringObjectEntry.getValue();
                    String key = stringObjectEntry.getKey();
                    map.put(key, value == null ? "" : value.toString());
                }


                Map<String, CMPrdInfoDto> collect = data.stream().collect(Collectors.toMap(item -> item.getLogicUniqueKey(), item -> item, (item1, item2) -> item1));

                for (String s : collect.keySet()) {
                    CMPrdInfoDto dto = collect.get(s);
                    fundCode = dto.getFundCode();
                    if (StringUtils.isNotBlank(fundCode)) {
                        return fundCode;
                    }
                }
            } else {
                log.error("招商getFundName发生问题：(Boolean) stringObjectMap.get(\"result\")为false_stringObjectMap为：", JSON.toJSONString(stringObjectMap));
            }
        } catch (Exception e) {
            log.error("招商getFundName发生问题：", e);
        }
        return null;
    }

    public <T extends CMBaseDto> long getCount(Map<String, Object> returnMap, Map<String, Object> stringObjectMap, Class<T> classT, TenantEscrowAuthorizationInfoDto tenant, String requestNo, String businessparam) {

        long pageCount = 0;
        if ((Boolean) stringObjectMap.get("result")) {
            List<T> data = (List<T>) stringObjectMap.get("data");

            HashMap<String, String> map = new HashMap<>();
            for (Map.Entry<String, Object> stringObjectEntry : stringObjectMap.entrySet()) {
                Object value = stringObjectEntry.getValue();
                String key = stringObjectEntry.getKey();
                map.put(key, value == null ? "" : value.toString());
            }

            CMPageDto page = (CMPageDto) stringObjectMap.get("page");

            if (page != null && page.getPageCount() != null) {
                pageCount = page.getCount();
            }


            Map<String, T> collect = data.stream().collect(Collectors.toMap(item -> item.getLogicUniqueKey(), item -> item, (item1, item2) -> item1));

            returnMap.putAll(collect);
        } else {
            HashMap<String, Object> data = (HashMap<String, Object>) stringObjectMap.get("data");
            log.info("getCount招商查询失败时参数情况" + data);
            returnMap.putAll(data);
        }
        return pageCount;
    }


    // 第八张表
    public Map<String, Object> processMJAccountSeqInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                           String today, String beginDate, String endDate, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 100;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("ksrq", beginDate);
                map.put("jsrq", endDate);
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);
                String filePath = tenant.getFilePath();
                //1002
                String requestNo = "1002";
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMMJAccountSeqInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMMJAccountSeqInfoDto.class, tenant, requestNo, businessparam);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } while (pageCount >= pageNum - 1);

        log.info("从{}到{}查询到{} 入库", beginDate, endDate, returnMap.size());
        return returnMap;
    }

    //第五张表
    public Map<String, Object> processTGAccountBalanceInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                               String today, String companyId, String fundCode) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 300;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                map.put("fundCode", fundCode);
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);
                String filePath = tenant.getFilePath();

                String requestNo = "1010";
                //1010
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMTgAccountBalanceInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMTgAccountBalanceInfoDto.class, tenant, requestNo, businessparam);
            } catch (Exception e) {
                log.error("招商查询失败processTGAccountBalanceInfoData" + e.getMessage());
            }
        } while (pageCount >= pageNum - 1);

        log.info("第五张表查询{}页数据 数据量为{}", pageNum - 1, returnMap.size());
        return returnMap;
    }

    // 第九张表
    public Map<String, Object> processFundTradeInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                        String today, String beginDate, String endDate, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 100;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("beginDate", beginDate);
                map.put("endDate", endDate);
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);
                String filePath = tenant.getFilePath();

                String requestNo = "1006";
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMFundTradeInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMFundTradeInfoDto.class, tenant, requestNo, businessparam);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } while (pageCount >= pageNum - 1);

        log.info("从{}到{}查询到{} 入库", beginDate, endDate, returnMap.size());
        return returnMap;
    }

    // 第三张表
    public Map<String, Object> processFundNetValueInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                           String today, String beginDate, String endDate, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 100;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("beginDate", beginDate);
                map.put("endDate", endDate);
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);
                String filePath = tenant.getFilePath();


                String requestNo = "1005";

                //1005
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMFundNetValueInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMFundNetValueInfoDto.class, tenant, requestNo, businessparam);

            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } while (pageCount >= pageNum - 1);

        log.info("从{}到{}查询到{} 入库", beginDate, endDate, returnMap.size());
        return returnMap;
    }

    // 第四张表
    public Map<String, Object> processCustShareInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                                        String today, String beginDate, String endDate, String companyId) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);
        Map<String, Object> returnMap = new HashMap<>();
        int pageCount;
        int pageNum = 1;
        int pageSize = 100;
        do {
            pageCount = 0;
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("beginDate", beginDate);
                map.put("endDate", endDate);
                map.put("pageNumber", String.valueOf(pageNum++));
                map.put("pageSize", String.valueOf(pageSize));
                Gson gson = new Gson();
                String businessparam = gson.toJson(map);
                log.info("businessparam" + businessparam);
                String filePath = tenant.getFilePath();
                //1004
                String requestNo = "1004";
                Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                        requestNo,
                        filePath,
                        today,
                        businessparam,
                        CMCustShareInfoDto.class,
                        tenant);

                pageCount = getResultSize(returnMap, stringObjectMap, CMCustShareInfoDto.class, tenant, requestNo, businessparam);

            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } while (pageCount >= pageNum - 1);

        log.info("从{}到{}查询到{} 入库{}", beginDate, endDate, returnMap.size());
        return returnMap;
    }

    public boolean getFundStatus(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix,
                                 String today, String companyId, String fundCode) {
        CmscAppSecretDTO appSecretDTO = getAppSecretDTO(tenant);

        if (StringUtils.isBlank(fundCode)) {
            return false;
        }
        Map<String, Object> returnMap = new HashMap<>();
        boolean returnBool = false;
        long pageCount;
        int pageNum = 1;
        int pageSize = 100;

        LocalDate now = LocalDate.now();
        LocalDate lastMonth = now.minusMonths(1L);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        String nowStr = dtf.format(now);
        String lastMonthStr = dtf.format(lastMonth);

        pageCount = 0;
        String businessparam = new String();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("pageNumber", String.valueOf(pageNum++));
            map.put("beginDate", lastMonthStr);
            map.put("endDate", nowStr);
            map.put("pageSize", String.valueOf(pageSize));
            map.put("fundCode", fundCode);
            Gson gson = new Gson();
            businessparam = gson.toJson(map);
            String filePath = tenant.getFilePath();

            String requestNo = "1004";

            //1004
            Map<String, Object> stringObjectMap = httpUtil.sendMessage(appSecretDTO,
                    requestNo,
                    filePath,
                    today,
                    businessparam,
                    CMCustShareInfoDto.class,
                    tenant);

            pageCount = getCount(returnMap, stringObjectMap, CMCustShareInfoDto.class, tenant, requestNo, businessparam);

        } catch (Exception e) {
            log.error(e.getMessage());
        }
        if (pageCount > 0) {
            returnBool = true;
        }


        log.info("fundCode为{}时,查询到持仓信息--{}", fundCode, returnBool);
        return returnBool;
    }

    private Map<String, Object> processFundValueData(List<Object> fundValue) {
        ArrayList<FundValueDto> result = new ArrayList<>();
        FundValueDto po;
        for (Object item : fundValue) {
            if (item == null) continue;
            po = JSON.parseObject(JSON.toJSONString(item), FundValueDto.class);
            result.add(po);
        }
//        return result.stream().collect(Collectors.groupingBy(FundValueDto::getC_fundcode));
        Map<String, List<FundValueDto>> collect = result.stream().collect(Collectors.groupingBy(FundValueDto::getC_fundcode));
        return collect.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    public Map<String, Object> processInvestmentSubjects(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String htscUrlPrefix, String today) {

        Map<String, String> headerParamsMap = new HashMap<>();
        headerParamsMap.put("appid", tenant.getAppKey());
        headerParamsMap.put("Timestamp", today);
        headerParamsMap.put("url", HtscConstants.INVESTMENT_SUBJECTS_API);
        String appSecret = tenant.getAppSecret();
        String sign = HTSCSignGenerator.genSign(appSecret, headerParamsMap);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Timestamp", today);
        headers.set("Sign", sign);
        HashMap remoteResp = HTSCRemoteUtil.getDataFromRemote(htscUrlPrefix + HtscConstants.INVESTMENT_SUBJECTS_API + "?appId=" + tenant.getAppKey(), headers);
        // 2.1 调用失败 将错误记录到错误记录表中
        if ((Integer) remoteResp.get("code") == 200) {
            Object remoteData = remoteResp.get("data");
            if (!Objects.isNull(remoteData) && remoteData instanceof List) {
                return processInvestmentSubjectsData((List<Object>) remoteData);
            }
        }
        return PullDataFailureUtil.createErrorMap(trustNo, HtscConstants.INVESTMENT_SUBJECTS_API, headers, "appId=" + tenant.getAppKey(), remoteResp);

    }

    private Map<String, Object> processInvestmentSubjectsData(List<Object> investmentSubjects) {

        ArrayList<InvestmentSubjectsDto> result = new ArrayList<>();
        InvestmentSubjectsDto po;
        for (Object item : investmentSubjects) {
            if (item == null) continue;
            log.info("processInvestmentSubjectsData is {}", JSON.toJSONString(item));
            po = JSON.parseObject(JSON.toJSONString(item), InvestmentSubjectsDto.class);
            result.add(po);
        }
        return result.stream().collect(Collectors.toMap(InvestmentSubjectsDto::getC_fundacco, x -> x));
    }

    /**
     * 第四 张表
     *
     * @param remoteData
     * @return
     */
    private Map<String, Object> processCustSharesData(List<Object> remoteData) {
        ArrayList<CustSharesDto> result = new ArrayList<>();
        CustSharesDto po;
        for (Object item : remoteData) {
            if (item == null) continue;
            po = JSON.parseObject(JSON.toJSONString(item), CustSharesDto.class);
            result.add(po);
        }
        Map<String, List<CustSharesDto>> collect = result.stream().collect(Collectors.groupingBy(CustSharesDto::getC_fundcode));
        return collect.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    public CmscConstants getCmscConstantsFromTenant(TenantEscrowAuthorizationInfoDto tenant) {
        CmscConstants cmscConstants = new CmscConstants();
        String appSecret = tenant.getAppSecret();
        cmscConstants.setPropertyFromJson(appSecret);
        String appKey = tenant.getAppKey();
        if (StringUtils.isNotBlank(appKey) && appKey.equals(cmscConstants.UAP_USER_NO)) {
            log.info("getCmscConstantsFromTenant 返回内容{}", JSON.toJSONString(cmscConstants));
            return cmscConstants;
        }
        log.error("appkey与appSecret不匹配,appkey为{}，appSecret为{}", appKey, appSecret);
        throw new IllegalArgumentException("appkey与appSecret不匹配");
    }

/*    public Map<String, Object> processFundFeeDataInfoData(TenantEscrowAuthorizationInfoDto tenant, String trustNo, String cmscUrlPrefix, String today, int pageNum, int pageSize, String finalStartDate, String finalEndDate, String companyId) {
        CmscConstants cmscConstants = getCmscConstantsFromTenant(tenant);
        Map<String, Object> returnMap = new HashMap<>();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("beginDate", finalStartDate);
            map.put("endDate", finalEndDate);
            map.put("pageNumber", String.valueOf(pageNum++));
            map.put("pageSize", String.valueOf(pageSize));
            Gson gson = new Gson();
            String businessparam = gson.toJson(map);
            log.info("businessparam" + businessparam);
            String filePath = tenant.getFilePath();

            String requestNo = "1020";
            Map<String, Object> stringObjectMap = httpUtil.sendMessage(cmscConstants,
                    requestNo,
                    filePath,
                    today,
                    businessparam,
                    CMFundFeeDataInfoDto.class,
                    tenant);

            getResultSize(returnMap, stringObjectMap, CMFundTradeInfoDto.class, tenant, requestNo, businessparam);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.info("fundFeeDataInfo 从{}到{}查询到{} 入库", finalStartDate, finalEndDate, returnMap.size());
        return returnMap;
    }*/
}
