import { Config, Provide, InjectClient } from '@midwayjs/core';
import * as CryptoJS from 'crypto-js';
import dayjs = require('dayjs');
import { HttpServiceFactory, HttpService } from '@midwayjs/axios';
import { get } from 'lodash';
import { ServiceError } from '../../error/service.error';
/**
 * 企查查服务
 */
@Provide()
export class QichachaService {
  @Config('qichacha')
  qichacha: any;

  @InjectClient(HttpServiceFactory, 'default')
  axios: HttpService;

  getToken() {
    const { key, secretKey } = this.qichacha;
    const Timespan = dayjs().unix();
    const str = `${key}${Timespan}${secretKey}`;
    const token = CryptoJS.MD5(str).toString().toUpperCase();
    return { token, key, secretKey, Timespan, str };
  }

  /**
   * 通过企业名称模糊搜索匹配企业
   * https://openapi.qcc.com/dataApi/1027
   * @param {String} searchName 企业名称
   */
  async searchByName(searchName: string) {
    const info = this.getToken();
    const uri = ' https://api.qichacha.com/NameSearch/GetList';
    const url = `${uri}?key=${get(info, 'key')}&searchName=${searchName}`;
    const result = await this.axios.get(url, {
      headers: {
        Token: get(info, 'token'),
        Timespan: get(info, 'Timespan'),
      },
    });
    if (!result) return;
    const list = get(result, 'Data')
    return list;
  }

  analysisResponse(response) {
    const status = get(response, 'status');
    if (status !== 200) return;
    const result = get(response, 'data');
    const apiStatus = get(result, 'Status');
    if (status !== '200') return;
    return get(result, 'Result');
  }
}
