package com.trade.service.thirdparty.sop.service.impl;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.service.thirdparty.sop.domain.SOPRequestLogPO;
import com.trade.service.thirdparty.sop.dto.*;
import com.trade.service.thirdparty.sop.service.SOPRequestLogService;
import com.trade.service.thirdparty.sop.service.SOPService;
import com.trade.service.thirdparty.sop.util.ResponseJson;
import com.trade.service.thirdparty.sop.util.SOPConstantUtil;
import com.trade.service.thirdparty.sop.util.SOPRestUtil;
import com.yomahub.liteflow.util.JsonUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SOPServiceImpl implements SOPService {

    @Resource
    private SOPRequestLogService sOPRequestLogService;

    @Override
    public ResponseJson sendPost2SOP(String url, SOPBasicRequest request) {
        ResponseJson json = SOPRestUtil.sendPost2SOP(url, request);
        saveLogAsync(request, json);
        if (null == json) {
            throw new ServiceException("请求SOP失败", HttpStatus.ERROR);
        }
        return json;
    }

    private void saveLogAsync(SOPBasicRequest request, ResponseJson json) {
        CompletableFuture.runAsync(() -> {
            SOPRequestLogPO logPO = new SOPRequestLogPO();
            logPO.setCustomerUserId(request.getUserId());
            logPO.setTransCode(request.getTransCode());
            logPO.setRequestPayload(JSON.toJSONString(request));
            if (null == json) {
                logPO.setSuccess(false);
            } else {
                logPO.setSuccess(json.isSuccess());
            }
            logPO.setResponse(JSON.toJSONString(json));
            sOPRequestLogService.add(logPO);
        }).exceptionally(r -> {
            r.printStackTrace();
            log.error("保存SOP请求日志异常");
            return null;
        });
    }

    @Override
    public SOPEnterpriseDetail getEnterpriseDetail(SOPEnterpriseDtlSearch sOPEnterpriseDtlSearch) {
        ResponseJson json = sendPost2SOP(SOPConstantUtil.SOP_API_ENTERPRISE_DETAIL, sOPEnterpriseDtlSearch);
        if (!json.isSuccess()) {
            log.error("调用SOP查询企业详细信息接口返回失败,错误信息：" + json.getMsg());
        }
        return JsonUtil.parseObject(json.getData().toString(), SOPEnterpriseDetail.class);
    }

    @Override
    public SOPRiskInvestigation getRiskInvestigation(Long userId, String socialCreditCode) {
        SOPBasicRequest request = new SOPBasicRequest();
        request.setUserId(userId);
        request.setEnterpriseIdentity(socialCreditCode);
        request.setTransCode(SOPConstantUtil.SOP_TRANS_CODE_ENTERPRISE_RISK_INVESTIGATION);
        ResponseJson json = SOPRestUtil.sendGet2SOP(
                SOPConstantUtil.SOP_API_ENTERPRISE_RISK_INVESTIGATION + "?socialCreditCode=" + socialCreditCode);
        saveLogAsync(request, json);
        if (null == json) {
            throw new ServiceException("获取企业风险调查信息失败", HttpStatus.ERROR);
        }
        return JsonUtil.parseObject(json.getData().toString(), SOPRiskInvestigation.class);
    }

    @Override
    public List<CDongjiangaoSxCheck> getManagementCreditExecution(Long userId, String socialCreditCode,
            String personName) {
        SOPBasicRequest request = new SOPBasicRequest();
        request.setUserId(userId);
        request.setEnterpriseIdentity(socialCreditCode);
        request.setTransCode(SOPConstantUtil.SOP_TRANS_CODE_MANAGEMENT_CREDIT_EXECUTION);
        ResponseJson json = SOPRestUtil.sendGet2SOP(SOPConstantUtil.SOP_API_MANAGEMENT_CREDIT_EXECUTION
                + "?socialCreditCode=" + socialCreditCode + "&personName=" + personName);
        saveLogAsync(request, json);
        if (null == json) {
            log.error("企业高管失信被执行信息查询接口调用失败");
            throw new ServiceException("获取企业风险调查信息失败", HttpStatus.ERROR);
        }
        return JSON.parseArray(json.getData().toString(), CDongjiangaoSxCheck.class);
    }

    @Override
    public List<CDongjiangaoSumptuaryCheck> getManagementConsumptionLimit(Long userId, String socialCreditCode,
            String personName) {
        SOPBasicRequest request = new SOPBasicRequest();
        request.setUserId(userId);
        request.setEnterpriseIdentity(socialCreditCode);
        request.setTransCode(SOPConstantUtil.SOP_TRANS_CODE_MANAGEMENT_CONSUMPTION_LIMIT);
        ResponseJson json = SOPRestUtil.sendGet2SOP(SOPConstantUtil.SOP_API_MANAGEMENT_CONSUMPTION_LIMIT
                + "?socialCreditCode=" + socialCreditCode + "&personName=" + personName);
        saveLogAsync(request, json);
        if (null == json) {
            log.error("企业高管限制高消费查询接口调用失败");
            throw new ServiceException("获取企业风险调查信息失败", HttpStatus.ERROR);
        }
        return JSON.parseArray(json.getData().toString(), CDongjiangaoSumptuaryCheck.class);
    }

    @Override
    public Boolean getExistFinancialOrPrivateLending(Long userId, String socialCreditCode,
            Long comprehensiveRiskInvestigationId) {
        SOPBasicRequest request = new SOPBasicRequest();
        request.setUserId(userId);
        request.setEnterpriseIdentity(socialCreditCode);
        request.setTransCode(SOPConstantUtil.SOP_TRANS_CODE_QUERY_JUDGMENT_DOCUMENTS);
        ResponseJson json = SOPRestUtil
                .sendGet2SOP(SOPConstantUtil.SOP_API_QUERY_JUDGMENT_DOCUMENTS + "?socialCreditCode=" + socialCreditCode
                        + "&comprehensiveRiskInvestigationId=" + comprehensiveRiskInvestigationId);
        saveLogAsync(request, json);
        if (null == json) {
            log.error("是否存在金融纠纷或民间借贷纠纷接口调用失败");
            throw new ServiceException("获取企业风险调查信息失败", HttpStatus.ERROR);
        }
        return JSON.parseObject(json.getData().toString(), Boolean.class);
    }
}
