package jdshopapi

import (
	"crypto/md5"
	"fmt"
	"net/http"
	"sort"
	"strings"
	"time"

	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
)

const (
	prodURL              = "https://api.jd.com/routerjson"
	prodURL2             = "http://114.67.73.174:8080/ask/routerjson"
	sigKey               = "sign"
	JdsImgURL            = "//img10.360buyimg.com/imgzone/"
	JdsImgDescURL        = `<img src=" //img10.360buyimg.com/imgzone/jfs/t1/111969/32/6692/171733/5ebbb9daE5bedb5b2/38350dca19e2b9d2.jpg" style="width: auto; height: auto; max-width: 100%;">`
	JdsStoreImg          = "http://image.jxc4.com/image/2659335b16e3880e367759b8fc675933.tem.png"
	JdsStoreCategoryName = "pop-mendian-Selfdelivery"
	JdsMobileKey         = "5a8f3244786ea9b8"
	JdsMobileToken       = `j9ma4js4tphmu2ajmlr1590716634146mdnd~NmZeSyVEbFNSdH58dlVdAH50AAlpRHpTBiUjb35DFm5vLUROOBEzLUF7G28iAAFBKBgVFA1EPwIVKDclGENXbm8iVlQiAwpTTx1lKSsTCG5vfmsaZlRiQVodZWEYQwtub35rGmgCY0laIiF+JlRcBX4lBFppUGcUVSBweHYEC1AudwFaZwUuEz9jaxFmCB5fEWYNZHMANx0QJBtvaD1PWj4waxprOnQfBjYoPyAEHxw+LFhIfwwyXwAuKhFmTTEQPSprGms6dF4MMyMoNk4CQCkhRXw0EjcYDx1lYRhDHUYRZg1kcw4iBRMyfRFmTTEQPS1rGms6dEBVbXRhdk1fAGFwGw1nOnQMQW1lKCAFHlVvfhVeIVMhU09jJD5mW08KPjROVjQPIRNQdj4oNwUaQj50BktpFiACCTE0fDAPAloqJgAafUQ1U1ljKnk9GAxePi1aSihWZgZWOHV7PFBYC31wBwhmX2BGWnN2dTxUTx5vIERWc1x0RQEqcHUrUBgQYWZeS3NcdEBBbWUnLQJPCG99DgFoRCs=|~1591240251425~1~20200318~eyJ2aXdlIjoiMCIsImJhaW4iOnsiaWMiOiIxIiwibGUiOiIxMDAiLCJjdCI6IjAiLCJkdCI6ImkifX0=~1~-776~giiz|1d3o-m7,ki,m7,ki;gw4;1df8l-m8,u5,m8,u5;1d9-lc,tr,gu,d;1d7-ke,tc,fw,1i;1de-i3,sb,dl,h;1d8-gw,ru,ce,0;1d8-fs,rb,bb,g;1dg-db,qi,db,py;1d8-c2,q2,ax,8c;1d8-av,pl,u,2c;1d8-9u,p6,8,76;1dg-7x,ok,6i,6k;1d8-74,oa,5p,6a;1d8-6g,nx,50,1f;1d8-5q,no,4a,16;1dg-4h,ms,31,a;1d8-3u,mb,2f,4b;1d8-3a,lw,3,h;1d8-2q,li,1b,3;1dg-1r,kw,c,p;1d8-1l,ku,6,n;1d8-1i,ks,3,l;1d1l-1i,kt,3,m;1d7-1i,kv,3,o;1d8-1l,kv,6,o;1d8-1q,kw,b,p;1d8-1x,kw,i,p;1dg-2t,kw,1e,p;1d8-38,kw,1,p;1d9-3q,kw,j,p;1d4f-7k,l5,4d,y;1d15-7p,ld,4i,16;1d2v-7t,ls,g,d;bd2j-7t,ls,g,d;doei:,1,1,0,0,1,1000,-1000,1000,-1000;dmei:,1,1,1,1000,-1000,1000,-1000,1000,-1000;emc:,d:62;emmm:,d:28-0;emcf:,d:62;ivli:;iivl:;ivcvj:;scvje:;ewhi:;1591240230712,1591240251421,0,0,35,35,0,32,0,0,0;1gxs`

	JdsStoreStatusRest    = 6
	JdsStoreStatusOnline  = 1
	JdsStoreStatusDisable = 2

	JdsOrderStatusPause          = 5
	JdsOrderStatusWaittingExport = 8
	JdsOrderStatusWaittingPay    = 2
	JdsOrderStatusWaittingPayDel = -2

	CreateCatType = "3"
	UpdateCatType = "1"

	VenderID    = 10374877
	VendorID2   = 10569615
	TransportID = 2158480

	JxBrandId             = 559853
	BrandIdNO             = 44259
	JdShopMaxStock        = 9999
	JdsPromiseID          = 13725637
	JdsDeliveryCompany3rd = "1274"
	JdsDeliveryCompanyJD  = "773574"

	JdsSkuStatus1    = 1    //从未上架
	JdsSkuStatus2    = 2    //自主下架
	JdsSkuStatus4    = 4    //系统下架
	JdsSkuStatus8    = 8    //在售
	JdsSkuStatus513  = 513  //从未上架 待审核
	JdsSkuStatus514  = 514  //自主下架 待审核
	JdsSkuStatus516  = 516  //系统下架 待审核
	JdsSkuStatus520  = 520  //在售 待审核
	JdsSkuStatus1025 = 1025 //从未上架 审核不通过 暂时没用
	JdsSkuStatus1026 = 1026 //自主下架 审核不通过 暂时没用
	JdsSkuStatus1028 = 1028 //系统下架 审核不通过
	JdsSkuStatus1032 = 1032 //在售 审核不通过

	PassReason = "审核通过"

	JdsOtherMeatCatID = 15245
	JdsBeefCatID      = 13582
	JdsBeefLastCatID  = 17902

	JdsPayPercentage float64 = 0.94

	JdsYdToken = "JxCaIsHiGetJsdOrderTmpToken_20200731" //云鼎token。。我自己随便整的一个。
)

var (
	SensitiveWordMap = []string{
		"[畅销]",
		"【畅销】",
		"包邮",
	}
)

type API struct {
	platformapi.APICookie

	accessToken string
	appKey      string
	appSecret   string
	client      *http.Client
	config      *platformapi.APIConfig
}

type UniteResp struct {
	Num        int    `json:"num"`
	IsSuccess  bool   `json:"is_success"`
	ErrorCode  string `json:"error_code"`
	ErrorMsgCn string `json:"error_msg_cn"`
	ErrorMsg   string `json:"error_msg"`
}

func New(accessToken, appKey, appSecret string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}
	return &API{
		accessToken: accessToken,
		appKey:      appKey,
		appSecret:   appSecret,
		client:      &http.Client{Timeout: curConfig.ClientTimeout},
		config:      &curConfig,
	}
}

func (a *API) signParam(params map[string]interface{}) (sig string) {
	var valueList []string
	for k, v := range params {
		if k != sigKey {
			if str := fmt.Sprint(v); str != "" {
				valueList = append(valueList, fmt.Sprintf("%s%s", k, str))
			}
		}
	}
	sort.Sort(sort.StringSlice(valueList))
	valueList = append(valueList, fmt.Sprintf("%s", a.appSecret))
	var valueList2 = make([]string, len(valueList)+1)
	at := copy(valueList2, valueList[:0])
	at += copy(valueList2[at:], []string{a.appSecret})
	copy(valueList2[at:], valueList[0:])
	sig = strings.Join(valueList2, "")
	binSig := md5.Sum([]byte(sig))
	sig = fmt.Sprintf("%X", binSig)
	return sig
}

func (a *API) AccessAPI(action string, url string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	params := make(map[string]interface{})
	params["access_token"] = a.accessToken
	params["app_key"] = a.appKey
	params["timestamp"] = utils.Time2Str(time.Now())
	params["method"] = action
	params["v"] = "2.0"
	params = utils.MergeMaps(params, bizParams)
	signStr := a.signParam(params)
	params["sign"] = signStr
	fullURL := utils.GenerateGetURL(url, "", nil)
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
			request.Header.Set("charset", "UTF-8")
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if err == nil {
				if jsonResult1["error_response"] != nil {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["zh_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}

func (a *API) AccessAPI2(action string, pURL string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	params := make(map[string]interface{})
	params["access_token"] = a.accessToken
	params["app_key"] = a.appKey
	params["timestamp"] = utils.Time2Str(time.Now())
	params["method"] = action
	params["v"] = "2.0"
	params = utils.MergeMaps(params, bizParams)
	signStr := a.signParam(params)
	params["sign"] = signStr
	fullURL := utils.GenerateGetURL(pURL, "", nil)
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
			request.Header.Set("charset", "UTF-8")
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			if err == nil {
				if jsonResult1["error_response"] != nil {
					errLevel = platformapi.ErrLevelGeneralFail
					err = utils.NewErrorCode(jsonResult1["error_response"].(map[string]interface{})["en_desc"].(string), jsonResult1["error_response"].(map[string]interface{})["code"].(string))
				}
				retVal = jsonResult1
			}
			return errLevel, err
		})
	return retVal, err
}
