package jdshop

import (
	"encoding/base64"
	"encoding/hex"
	"encoding/json"

	"git.rosy.net.cn/jx-callback/globals"

	"git.rosy.net.cn/jx-callback/globals/api"
)

var (
	KeyList []*Key
	// KeyList2 []*Key
)

type Key struct {
	ID           string `json:"id"`
	KeyExp       int64  `json:"key_exp"`
	KeyStatus    int    `json:"key_status"`
	KeyDigest    string `json:"key_digest"`
	KeyType      string `json:"key_type"`
	KeyString    string `json:"key_string"`
	KeyEffective int64  `json:"key_effective"`
	Version      int    `json:"version"`
}

func InitKey() {
	keyResult, err := api.JdShopAPI.KeyGet()
	if err != nil {
		return
	}
	for _, v := range keyResult.Response.ServiceKeyList[0].Keys {
		data, _ := json.Marshal(v)
		vv := &Key{}
		err = json.Unmarshal(data, &vv)
		KeyList = append(KeyList, vv)
	}
	// keyResult2, err := api.JdShop2API.KeyGet()
	// if err != nil {
	// 	return
	// }
	// for _, v := range keyResult2.Response.ServiceKeyList[0].Keys {
	// 	data, _ := json.Marshal(v)
	// 	vv := &Key{}
	// 	err = json.Unmarshal(data, &vv)
	// 	KeyList2 = append(KeyList2, vv)
	// }
	globals.SugarLogger.Debugf("jdshop key refreshed..")
}

func GetKey(keySign, vendorOrgCode string) (key string) {
	// if vendorOrgCode == "1" {
	for _, v := range KeyList {
		data, _ := base64.StdEncoding.DecodeString(v.ID)
		if keySign == hex.EncodeToString(data) {
			return v.KeyString
		}
	}
	// } else {
	// 	for _, v := range KeyList2 {
	// 		data, _ := base64.StdEncoding.DecodeString(v.ID)
	// 		if keySign == hex.EncodeToString(data) {
	// 			return v.KeyString
	// 		}
	// 	}
	// }
	globals.SugarLogger.Debugf("no key can equal..")
	return key
}
