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

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.trade.common.constant.ThirdpartyConstants;
import com.trade.common.utils.http.HttpClientUtils;
import com.trade.common.utils.http.HttpConfig;
import com.trade.common.utils.http.HttpHeader;
import com.trade.common.utils.http.StitchingUrlUtil;
import com.trade.service.thirdparty.qichacha.configuration.QichachaConfiguration;
import com.trade.service.thirdparty.qichacha.dto.ECIResult;
import com.trade.service.thirdparty.qichacha.dto.EcBasicDetailDto;
import com.trade.service.thirdparty.qichacha.dto.EcBasicInfoDto;
import com.trade.service.thirdparty.qichacha.service.QichachaService;
import liquibase.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

@Service
public class QichachaServiceImpl implements QichachaService {

    private static final Logger logger = LoggerFactory.getLogger(QichachaServiceImpl.class);
    @Resource
    private QichachaConfiguration qichachaConfiguration;
    // 企业关键字模糊查询接口
    private static final String ECIV4_SEARCH_URL = "http://api.qichacha.com/ECIV4/Search";
    // 410 企业工商照面
    private static final String GET_BASIC_DETAILS_BY_NAME_URL = "https://api.qichacha.com/ECIV4/GetBasicDetailsByName";

    @Override
    public List<EcBasicInfoDto> findBusinessName(String keyword) {
        Map<String, String> params = new HashMap<String, String>();
        params.put(ThirdpartyConstants.QCC_KEY, qichachaConfiguration.getApiKey());
        params.put("keyWord", keyword.replaceAll(" ", ""));
        // 企查查权限验证参数
        String rspStr = HttpClientUtils.get(HttpConfig.custom().url(StitchingUrlUtil.getUrl(ECIV4_SEARCH_URL, params))
                .headers(HttpHeader.custom().other("Token", getToken()).other("Timespan", getTimespan()).build()));
        ECIResult<List<EcBasicInfoDto>> result = JSONObject.parseObject(rspStr,
                new TypeReference<ECIResult<List<EcBasicInfoDto>>>() {
                });
        if (null != result && result.getStatus().equals("200")) {
            return result.getResult();
        }
        return Collections.emptyList();
    }

    @Override
    public EcBasicDetailDto getBasicDetailsByName(String keyword) {
        Map<String, String> params = new HashMap<String, String>();
        params.put(ThirdpartyConstants.QCC_KEY, qichachaConfiguration.getApiKey());
        params.put("keyword", keyword);
        // 企查查权限验证参数
        String rspStr = HttpClientUtils
                .get(HttpConfig.custom().url(StitchingUrlUtil.getUrl(GET_BASIC_DETAILS_BY_NAME_URL, params)).headers(
                        HttpHeader.custom().other("Token", getToken()).other("Timespan", getTimespan()).build()));
        ECIResult<EcBasicDetailDto> result = JSONObject.parseObject(rspStr,
                new TypeReference<ECIResult<EcBasicDetailDto>>() {
                });
        if (null != result && result.getStatus().equals("200")) {
            return result.getResult();
        }
        return null;
    }

    /**
     * 获取当前时间戳，精确到时分秒. <br/>
     */
    private String getTimespan() {
        return Long.toString(Instant.now().getEpochSecond());
    }

    /**
     * 获取企查查权限验证加密值. <br/>
     */
    private String getToken() {
        // token验证加密值（key+Timespan+SecretKey组成的32位md5加密的大写字符串）
        String token = qichachaConfiguration.getApiKey() + getTimespan() + qichachaConfiguration.getApiSecret();
        token = MD5Util.computeMD5(token);
        return token.toUpperCase();
    }
}
