package idnum

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/fonchain_enterprise/micro-account/pkg/cache"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var param = map[string]string{
	"grant_type":    "client_credentials",
	"client_id":     "AlbWwhnZINIy1YqWP3agQA42",
	"client_secret": "NL2nT4rnGHIcpopBI93a7G85WscluOEH",
}

type IDCheckRes struct {
	ErrorCode int         `json:"error_code"`
	ErrorMsg  string      `json:"error_msg"`
	LogID     int         `json:"log_id"`
	Timestamp int         `json:"timestamp"`
	Cached    int         `json:"cached"`
	Result    interface{} `json:"result"`
}
type TokenInfo struct {
	RefreshToken  string `json:"refresh_token"`
	ExpiresIn     int    `json:"expires_in"`
	Scope         string `json:"scope"`
	SessionKey    string `json:"session_key"`
	AccessToken   string `json:"access_token"`
	SessionSecret string `json:"session_secret"`
}

/*
Tru89O1zosjSCIN2uUlEctbE
rLgGU2gwNvEQAo0UooTwArtvqBTaL3Y3
25346530
*/

func CheckIDNumFromNet(idNum string, name string) error {
	var host = "https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch"
	accessToken, err := getAccessToken()
	fmt.Println("1百度生成token---", accessToken, err)
	if err != nil {
		return err
	}

	uri, err := url.Parse(host)
	if err != nil {
		fmt.Println(err)
		return err
	}
	query := uri.Query()
	query.Set("access_token", accessToken)
	uri.RawQuery = query.Encode()

	var params = map[string]string{}
	params["id_card_number"] = idNum
	params["name"] = name
	sendBody, err := json.Marshal(params)
	if err != nil {
		fmt.Println(err)
		return err
	}
	sendData := string(sendBody)
	client := &http.Client{}
	request, err := http.NewRequest("POST", uri.String(), strings.NewReader(sendData))
	if err != nil {
		fmt.Println(err)
		return err
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println(string(result))
	var res IDCheckRes

	err = json.Unmarshal(result, &res)

	fmt.Println(string(result))
	if err != nil {
		fmt.Println(err)
		return err
	}

	if res.ErrorCode != 0 {
		if res.ErrorCode == 222351 {
			return errors.New("不匹配或者身份证不存在")
		}
		return errors.New("实名认证未通过")
	}

	return nil
}

func getAccessToken() (string, error) {

	var tokenInfo TokenInfo
	var err error
	key := "baidu:Id:access_token" + param["client_id"]
	strCmd := cache.RedisClient.Get(key)

	accessToken := strCmd.Val()
	if accessToken != "" {
		err := json.Unmarshal([]byte(accessToken), &tokenInfo)
		if err != nil {
			return "", err
		}
		return tokenInfo.AccessToken, nil
	}

	accessToken, err = getNewAccessToken()

	if err != nil {
		return "", err
	}

	if merr := cache.RedisClient.Set(key, accessToken, 5*60*1000*time.Millisecond).Err(); merr != nil {
		return "", merr
	}

	err = json.Unmarshal([]byte(accessToken), &tokenInfo)

	if err != nil {
		return "", err
	}

	return tokenInfo.AccessToken, nil
}

func getNewAccessToken() (string, error) {
	accessToken := ""

	var host = "https://aip.baidubce.com/oauth/2.0/token"

	uri, err := url.Parse(host)
	fmt.Println(uri)
	if err != nil {
		fmt.Println(err)
		return accessToken, err
	}
	query := uri.Query()
	for k, v := range param {
		query.Set(k, v)
	}
	uri.RawQuery = query.Encode()

	response, err := http.Get(uri.String())

	fmt.Println(response)
	if err != nil {
		fmt.Println(err)
		return accessToken, err
	}
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
		return accessToken, err
	}
	fmt.Println(string(result))

	return string(result), err
}
