package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hz_crm_api/utils"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func GetCompanyInfo() {
	qccKey := `efd43bfceaa74cf1811079dbcec25c33`
	qccSecretKey := `2985D128630B085C1BFE8F88630B5DA8`
	getUrl := `http://api.qichacha.com/ECIV4/Search?key=` + qccKey + `&keyword=913300007125582210`

	timespan := time.Now().Unix()
	timespanStr := strconv.FormatInt(timespan, 10)
	token := utils.MD5(qccKey + timespanStr + qccSecretKey)
	client := &http.Client{}
	//提交请求
	reqest, err := http.NewRequest("GET", getUrl, nil)
	//增加header选项
	reqest.Header.Add("Token", token)
	reqest.Header.Add("Timespan", timespanStr)

	if err != nil {
		panic(err)
	}
	//处理返回结果
	response, _ := client.Do(reqest)
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	fmt.Println("body:", string(body))
	utils.FileLog.Info("%s", string(body))
}

type QCCResp struct {
	Paging      Paging   `json:"Paging"`
	Result      []Result `json:"Result"`
	Status      string   `json:"Status"`
	Message     string   `json:"Message"`
	OrderNumber string   `json:"OrderNumber"`
}
type Paging struct {
	PageSize     int `json:"PageSize"`
	PageIndex    int `json:"PageIndex"`
	TotalRecords int `json:"TotalRecords"`
}

type Result struct {
	KeyNo      string `json:"KeyNo"`
	Name       string `json:"Name"`
	CreditCode string `json:"CreditCode"`
	StartDate  string `json:"StartDate"`
	OperName   string `json:"OperName"`
	Status     string `json:"Status"`
	No         string `json:"No"`
}

func QCCFuzzySearch(keyWord string) (results []Result, err error) {
	qccKey := `49464d73ae1c46e99ad4eff1efe943c1`
	qccSecretKey := `9DE7E83FFE26789815004C5172503290`
	getUrl := `http://api.qichacha.com/FuzzySearch/GetList?pageSize=20&key=%s&searchKey=%s `
	utils.StrFilterNonChinese(&keyWord)
	finalUrl := fmt.Sprintf(getUrl, qccKey, keyWord)
	timespan := time.Now().Unix()
	timespanStr := strconv.FormatInt(timespan, 10)
	token := utils.MD5(qccKey + timespanStr + qccSecretKey)
	client := &http.Client{}
	//提交请求
	reqest, err := http.NewRequest("GET", finalUrl, nil)
	if err != nil {
		utils.FileLog.Info("NewRequest err:" + err.Error())
		err = errors.New("NewRequest err:" + err.Error())
		return
	}
	//增加header选项
	reqest.Header.Add("Token", strings.ToUpper(token))
	reqest.Header.Add("Timespan", timespanStr)

	if err != nil {
		return
	}
	//处理返回结果
	response, _ := client.Do(reqest)
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	var qccResp QCCResp
	err = json.Unmarshal(body, &qccResp)
	if err != nil {
		utils.FileLog.Info("Json Unmarshal err:" + err.Error())
		err = errors.New("Json Unmarshal err:" + err.Error())
		return
	}
	if qccResp.Status != "200" {
		utils.FileLog.Info("QCCFuzzySearch err:" + qccResp.Message)
		err = errors.New("QCCFuzzySearch err:" + qccResp.Message)
		return
	} else {
		results = qccResp.Result
		return
	}
}
