package jdshop

import (
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"git.rosy.net.cn/baseapi/platformapi/jdshopapi"
)

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() {
	newapi := jdshopapi.New("37d36b62c0d14bd4b872f948b335c95czinj", "E1D746D42474D5F1F1A10CECE75D99F6", "efa7e1d1a22640fa990e6cf164b28608")
	keyResult, err := newapi.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 := jdshopapi.New("f9c5ce9a5ce24218936924f7c4864cc9owe1", "E1D746D42474D5F1F1A10CECE75D99F6", "efa7e1d1a22640fa990e6cf164b28608").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)
	}
}

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
		}
	}
	// } else {
	// 	for _, v := range KeyList2 {
	// 		data, _ := base64.StdEncoding.DecodeString(v.ID)
	// 		if keySign == hex.EncodeToString(data) {
	// 			return v.KeyString
	// 		}
	// 	}
	// }
	return key
}
