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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.friday.base.common.response.DubboResult;
import com.friday.custody.dto.InterProviderResponseDto;
import com.friday.mystery.forwardapi.dto.DistributorGetDatePostResponseDto;
import com.friday.mystery.forwardapi.service.IHttpRequestService;
import com.google.common.collect.Lists;
import com.friday.custody.dto.TenantEscrowAuthorizationInfoDto;
import com.friday.custody.entity.InvokeRecordEntity;
import com.friday.custody.service.basicService.impl.InvokeRecordServiceImpl;
import com.friday.custody.service.basicService.impl.TenantEscrowAuthorizationInfoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class SearchReturnModifyClass {

    @Autowired
    private InvokeRecordServiceImpl invokeRecordService;

    @Autowired
    private TenantEscrowAuthorizationInfoServiceImpl tenantEscrowAuthorizationInfoService;

    @Resource
    private IHttpRequestService httpRequestService;

    public static Object getObject() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"dubboContext.xml"});
        context.start();

        // 获取远程服务代理
        IHttpRequestService httpRequestService = (IHttpRequestService) context.getBean("httpRequestService");
        return httpRequestService;
    }

    /**
     * 查询资讯中心数据接口DEMO 返回实体类
     *
     * @param param
     * @throws InterruptedException
     * @auther i@jiaxiaohei.com
     */
    public String getFundCode(String param) throws InterruptedException {
        log.info("咨询平台参数：" + param);
        // 使用参数
        // 资源名称
        String resource = "ZX_FNDBASICINFOCY";
        // 排序字段
        String orderBy = "";
        // 查询字段 為空则查询全部字段
        List<String> selectedFields = Lists.newArrayList("REGCODE");
        // 分页偏移
        int page = 0;
        // 每页条数
        int pageSize = 1000;
        // 查询条件
        Map<String, List<String>> paramMaps = new HashMap<>();
        paramMaps.put("FUNDFULLNAME", Lists.newArrayList(param));//一村睿华1号私募证券投资基金

        // 执行查询操作
        log.info("调用资讯中心接口入参：{}, {}", resource, JSON.toJSONString(paramMaps));
        DubboResult<DistributorGetDatePostResponseDto> resultData = httpRequestService.getInformationByDistributor(resource, paramMaps, page, pageSize, orderBy, selectedFields);
        InterProviderResponseDto responseDto = getInterProviderResponse(resultData);
        if (responseDto.isSuccess()) {
            List<Map<String, Object>> dataList = responseDto.getDataList();
            String fundCode = "";
            for (Map<String, Object> map : dataList) {
                fundCode = (String) map.get("REGCODE");
                log.info("咨询平台返回数据:" + fundCode);
                if (StringUtils.isNotBlank(fundCode)) {
                    return fundCode;
                }
            }
        }
        return null;

//        // 返回参数
//        // 状态码 成功1
//        System.out.println(resultData.getStatus());
//        // 状态 成功返回执行时间 是吧返回错误原因
//        System.out.println(resultData.getMsg());
//        // 符合条件总数
//        System.out.println(resultData.getTotalCount());
//        // 返回数据数
//        System.out.println(resultData.getDataCount());
//        // 数据List<Map<Sring,Object>>
//        System.out.println(resultData.getDataList());
//        // 查询列名
//        String[] selectedFields1 = resultData.getSelectedFields();
//        for (int i =0;i<selectedFields1.length-1;i++){
//            System.out.println(selectedFields1[i]);
//        }
//
//        System.exit(1);
    }

    /**
     * 查询资讯中心数据接口DEMO 返回实体类
     *
     * @throws InterruptedException
     * @auther i@jiaxiaohei.com
     */
    public Map<String, Object> getFundInfoFromZx(/*TenantEscrowAuthorizationInfoDto tenant,*/String tenantName, String trustNo, String key, int pageNo, int pageSize) throws InterruptedException {

//        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"dubboContext.xml"});
//        context.start();
//
//        // 获取远程服务代理
//        IInterProvider interProvider = (IInterProvider) context.getBean("interProvider");

        // 使用参数
        // 资源名称
        String resource = "ZX_FNDBASICINFOCY";
        // 排序字段
        String orderBy = "";
        // 查询字段 為空则查询全部字段
        List<String> selectedFields = Lists.newArrayList("REGCODE", "FUNDFULLNAME", "FUNDNAME", "ISLIQUIDATION");
        // 查询条件
        Map<String, List<String>> paramMaps = new HashMap<>();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("source", resource);
        jsonObject.put("paramMaps", paramMaps);
        jsonObject.put("startRow", pageNo);
        jsonObject.put("rowNum", pageSize);
        jsonObject.put("orderBy", orderBy);
        jsonObject.put("selectedFields", selectedFields);
        jsonObject.put("key", key);
        // 执行查询操作
        log.info("调用资讯中心接口入参：{}, {}", resource, JSON.toJSONString(jsonObject));
        DubboResult<DistributorGetDatePostResponseDto> resultData = httpRequestService.getInformationByDistributor(resource, paramMaps, pageNo, pageSize, orderBy, selectedFields);
        InterProviderResponseDto responseDto = getInterProviderResponse(resultData);
        //保存调用记录
        saveInvokeRecord(tenantName, trustNo, resource, jsonObject, responseDto);
        if (responseDto.isSuccess()) {
            Map<String, Object> result = new HashMap<>();
            result.put("totalCount", responseDto.getTotalCount());
            result.put("dataList", responseDto.getDataList());
            return result;
        }
        return null;

    }

    /**
     * @throws InterruptedException
     * @auther i@jiaxiaohei.com
     */
    public InterProviderResponseDto sendMessage(String tenantName, String key, String trustNo, String resource, Map<String, List<String>> paramMaps, Integer startRow, Integer rowNum, String orderBy, List<String> selectedFields) {
        try {
            Thread.sleep(30L);
        } catch (InterruptedException e) {
            log.error("调用资讯平台的睡眠被打断了。。。。");
            Thread.currentThread().interrupt();
        }
        // 查询条件
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("source", resource);
        jsonObject.put("paramMaps", paramMaps);
        jsonObject.put("startRow", startRow);
        jsonObject.put("rowNum", rowNum);
        jsonObject.put("orderBy", orderBy);
        jsonObject.put("selectedFields", selectedFields);
        jsonObject.put("key", key);
        log.info("调用资讯中心接口入参：{}, {}", resource, JSON.toJSONString(jsonObject));
        DubboResult<DistributorGetDatePostResponseDto> resultData = httpRequestService.getInformationByDistributor(resource, paramMaps, startRow, rowNum, orderBy, selectedFields);
        InterProviderResponseDto interProviderResponseDto = getInterProviderResponse(resultData);
        //保存调用记录
        saveInvokeRecord(tenantName, trustNo, resource, jsonObject, interProviderResponseDto);
        return interProviderResponseDto;
    }

    public String getFundIds(/*TenantEscrowAuthorizationInfoDto tenant*/String tenantName, String key, String trustNo, String admin) {
        // 使用参数
        // 资源名称
        String resource = "ZX_FNDORGCY";
        // 查询字段 為空则查询全部字段
        List<String> selectedFields = Lists.newArrayList("REGCODE", "MANAGEFUNDID");
        // 查询条件
        Map<String, List<String>> paramMaps = new HashMap<>();
        // 查询条件
        paramMaps.put("REGCODE", Lists.newArrayList(admin));
        InterProviderResponseDto resultData = InterProviderResponseDto.builder().build();
        try {
            resultData = sendMessage(tenantName,key,trustNo, resource, paramMaps, 0, 1000, null, selectedFields);
        } catch (Exception e) {
            log.error("查询咨询平台基金编号数据失败！", e);
        }
        List<Map<String, Object>> dataList = resultData.getDataList();
        if (!CollectionUtils.isEmpty(dataList)) {
            return (String) dataList.get(0).get("MANAGEFUNDID");
        }
        return null;
    }

    public List<Map<String, Object>> queryPrtInfo(String admin) {
        String trustNo = "99";
        TenantEscrowAuthorizationInfoDto tenant = tenantEscrowAuthorizationInfoService.queryAuthorizationByTrustNo(trustNo);
        //1.通过私募基金公司基本信息  ZX_FNDORGCY 查询出基金编号
        String fundIds = getFundIds(tenant.getTenantName(),tenant.getAppKey(),trustNo ,admin);
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (StringUtils.isNotBlank(fundIds)) {
            String[] fundIdArr = fundIds.split(",");
            //2.通过私募基金基本信息  ZX_FNDBASICINFOCY 查询出对应的基金基本信息
            String resource = "ZX_FNDBASICINFOCY";
            // 查询字段 為空则查询全部字段
            List<String> selectedFields1 = Lists.newArrayList("REGCODE", "FUNDNAME", "FUNDFULLNAME");
            // 查询条件
            Map<String, List<String>> paramMaps = new HashMap<>();
            // 查询条件
            paramMaps.put("FUNDID", Lists.newArrayList(fundIdArr));
            int startRow = 0;
            int pageNo = 0;
            int pageSize = 3000;
            int totalCount = 0;
            for (; ; ) {
                pageNo++;
                InterProviderResponseDto resultData = InterProviderResponseDto.builder().build();
                try {
                    resultData = sendMessage(tenant.getTenantName(),tenant.getAppKey(), trustNo, resource, paramMaps, startRow, pageSize, null, selectedFields1);
                } catch (Exception e) {
                    log.error("查询咨询平台数据失败！", e);
                }
                if (resultData.isSuccess()) {
                    totalCount = resultData.getTotalCount();
                    if (!ObjectUtils.isEmpty(resultData.getDataList())) {
                        dataList.addAll(resultData.getDataList());
                    }
                }
                if (pageNo * pageSize > totalCount) {
                    break;
                }
                startRow += pageSize;
            }
        }
        return dataList;
    }

    public void saveInvokeRecord(String tenantName, String trustNo, String invokeType, JSONObject jsonObject, InterProviderResponseDto responseDto) {
        Date now = new Date();
        InvokeRecordEntity invokeRecordEntity = InvokeRecordEntity.builder()
                .trustNo(trustNo)
                .admin(tenantName)
                .invokeType(invokeType)
                .reqParam(JSON.toJSONString(jsonObject))
                .invokeTime(now)
                .invokeResult(JSON.toJSONString(responseDto))
                .queryKey(tenantName + "::" + trustNo + "::" + invokeType)
                .createTime(now)
                .updateTime(now)
                .build();
        invokeRecordService.save(invokeRecordEntity);
    }

    private InterProviderResponseDto getInterProviderResponse(DubboResult<DistributorGetDatePostResponseDto> resultData){
        if (resultData == null) {
            return InterProviderResponseDto.builder().success(false).failMsg("资讯接口调用失败，返回结果为空！").build();
        }
        if (resultData.success()) {
            DistributorGetDatePostResponseDto responseDto = resultData.getObject();
            if (responseDto.getRetCode() == 0) {
                String value = JSON.toJSONString(responseDto.getValue());
                if (StringUtils.isNotEmpty(value)) {
                    return JSON.parseObject(value, InterProviderResponseDto.class);
                }
            } else {
                return InterProviderResponseDto.builder().success(false).failMsg(responseDto.getMessage()).build();
            }
        }
        return InterProviderResponseDto.builder().success(false).failMsg(resultData.getError() + resultData.getMessage()).build();
    }

}
