package com.inkasso.factoring.common.util;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.inkasso.adapter.util.MD5Util;
import com.inkasso.factoring.common.constant.QichachaConstant;
import com.inkasso.factoring.common.domain.CompanyBasicInfo;
import com.inkasso.factoring.common.domain.QichachaQueryResult;
import com.inkasso.management.statistics.entity.InterfaceStatisticsDO;
import com.inkasso.management.statistics.enums.InterfaceTypeEnum;
import com.inkasso.management.statistics.service.InterfaceStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 企查查
 */
@Component
public class QichachaUtil {

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private InterfaceStatisticsService interfaceStatisticsService;

    /**
     *
     */
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String  REDIS_KEY_PREFIX = "qichacha";

    private static final String MARK=":";

    private static final Integer number = 100;


    /**
     * 企业工商照面
     */
    public QichachaQueryResult<CompanyBasicInfo> getBasicDetailsByName(String keyWord,Long userId) {
        //校验该用户使用企查查接口次数
        String redisKey = getRedisKey(userId);
        Long count = redisTemplate.opsForValue().increment(redisKey,1);
        if(count==1){
            redisTemplate.expire(redisKey,60*60*24, TimeUnit.SECONDS);
        }

        HttpEntity httpEntity = new HttpEntity(getHeader());
        String url = QichachaConstant.GET_COMPANY_INFO + "?key=" + QichachaConstant.QCC_KEY_VALUE
                + "&searchKey=" + keyWord;
        ResponseEntity<String> result = restTemplate
                .exchange(url, HttpMethod.GET, httpEntity, String.class);
        String body = result.getBody();
        Gson gson = new Gson();
        QichachaQueryResult<CompanyBasicInfo> s2  = gson.fromJson(body,new TypeToken<QichachaQueryResult<CompanyBasicInfo>>(){}.getType());
        if(!"200".equals(s2.getStatus())){
            //说明查询异常 需要 记录下来
            InterfaceStatisticsDO interfaceStatisticsDO = new InterfaceStatisticsDO();
            interfaceStatisticsDO.setName("企业高级搜索");
            interfaceStatisticsDO.setStatus(false);
            interfaceStatisticsDO.setUrl(url);
            interfaceStatisticsDO.setResult(body);
            interfaceStatisticsDO.setType(InterfaceTypeEnum.QCC.getCode());

            interfaceStatisticsService.save(interfaceStatisticsDO);
        }
        return s2;
    }


    private HttpHeaders getHeader() {
        HttpHeaders header = new HttpHeaders();
        String timeStr = Long.toString(System.currentTimeMillis() / 1000L);
        String s = MD5Util.EncodeByMD5(
                QichachaConstant.QCC_KEY_VALUE + timeStr + QichachaConstant.SECRET_KEY_VALUE);
        header.set("Token", s.toUpperCase());
        header.set("Timespan", timeStr);
        return header;
    }

    private String getRedisKey(Long userId){

        StringBuffer sb = new StringBuffer();
        sb.append(REDIS_KEY_PREFIX).append(MARK).append(userId);
        return sb.toString();
    }

}
