package jdunionapi

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
	"net/http"
	"strings"
	"time"
)

type API struct {
	platformapi.APICookie

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

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

func (a *API) AccessStorePage(fullURL string, bizParams map[string]interface{}, isPost bool) (retVal map[string]interface{}, err error) {
	if a.GetCookieCount() == 0 {
		return nil, fmt.Errorf("需要设置Store Cookie才能使用此方法")
	}
	data, _ := json.Marshal(bizParams)
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			if isPost {
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
			} else {
				request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(fullURL, "", bizParams), nil)
				request.Header.Set("accept", "application/json, text/plain, */*")
				//request.Header.Set("accept-encoding", "gzip, deflate, br")
				request.Header.Set("accept-language", "zh-CN,zh;q=0.9")
				request.Header.Set("origin", "https://union.jd.com")
				request.Header.Set("referer", "https://union.jd.com")
				request.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36")
			}
			a.FillRequestCookies(request)
			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 strings.Contains(bodyStr, "登录") || strings.Contains(bodyStr, "访问的内容") {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("cookie可能过期了！")
			}
			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
}

type ListActivitysResult struct {
	Activityenddate   string `json:"activityEndDate"`
	Activityid        int    `json:"activityId"`
	Activityname      string `json:"activityName"`
	Activitystartdate string `json:"activityStartDate"`
	Activitystatus    int    `json:"activityStatus"`
	Activitystatusstr string `json:"activityStatusStr"`
	Activitytypeid    int    `json:"activityTypeId"`
	Activitytypename  string `json:"activityTypeName"`
	Bonusstatement    int    `json:"bonusStatement"`
	Businesstype      int    `json:"businessType"`
	Imageurl          string `json:"imageUrl"`
	Paystatus         int    `json:"payStatus"`
	Pcdescurl         string `json:"pcDescUrl"`
	Plantype          int    `json:"planType"`
	Remark            string `json:"remark"`
	Reporttype        int    `json:"reportType"`
}

func (a *API) ListActivitys() (listActivitysResult []*ListActivitysResult, err error) {
	result, err := a.AccessStorePage("https://api.m.jd.com/api", map[string]interface{}{
		"functionId": "listActivitys",
		"appid":      "unionpc",
		"_":          time.Now().UnixNano(),
		"loginType":  3,
		"body":       "{\"funName\":\"listActivitys\",\"param\":{\"activityStatus\":\"3\"},\"page\":{\"pageNo\":1,\"pageSize\":20}}",
	}, false)
	if err == nil {
		utils.Map2StructByJson(result["result"], &listActivitysResult, false)
	}
	return listActivitysResult, err
}

func (a *API) UnionPromotion(PID string) (err error) {
	_, err = a.AccessStorePage("https://api.m.jd.com/api", map[string]interface{}{
		"functionId": "unionPromotion",
		"appid":      "u",
		"_":          time.Now().UnixNano(),
		"loginType":  3,
		"body":       "{\"funName\":\"savePromotionSite\",\"param\":{\"siteId\":4100279071,\"spaceName\":" + PID + ",\"type\":3,\"unionType\":1}}",
	}, false)
	return err
}
