package mtpsapi

import (
	"fmt"
	"net/http"
	"strings"

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

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才能使用此方法")
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			if isPost {
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(bizParams).Encode()))
				request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
				request.Header.Set("Referer", "https://page.peisong.meituan.com/open/admin/poilist")
			} else {
				request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(fullURL, "", bizParams), nil)
			}
			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
}

func (a *API) PagePoiUpdate(outerPoiID, contactName, contactPhone, contactEmail string) (err error) {
	// if outerPoiID == "" || contactName == "" || contactPhone == "" || contactEmail == "" {
	// 	return fmt.Errorf("所有参数必须都要有值")
	// }
	// params := map[string]interface{}{
	// 	"outerPoiId":   outerPoiID,
	// 	"contactName":  contactName,
	// 	"contactPhone": contactPhone,
	// 	"contactEmail": contactEmail,
	// }
	// _, err = a.AccessAPI2("https://page.peisong.meituan.com/api", "haikuiopen/haikui/open/partner/poi/update", params)
	return err
}

func (a *API) RefreshToken() (token string, err error) {
	result, err := a.AccessStorePage("https://peisong.meituan.com/api/haikuiopen/haikui/open/auth/csrf/token/refresh", nil, true)
	if err == nil {
		token = result["tokens"].(map[string]interface{})["csrfToken"].(string)
	}
	return token, err
}

func (a *API) GetAccountDetail() (err error) {
	params := map[string]interface{}{}
	_, err = a.AccessAPI2("https://peisong.meituan.com/api", "haikuiopen/haikui/open/partner/base/detail", params)
	return err
}

type GetStoreStatusResult struct {
	PoiID            int         `json:"poiId"`
	OuterPoiID       string      `json:"outerPoiId"`
	AppkeyID         int         `json:"appkeyId"`
	PoiName          string      `json:"poiName"`
	CityID           int         `json:"cityId"`
	CityName         string      `json:"cityName"`
	ContactPhone     string      `json:"contactPhone"`
	ContactName      interface{} `json:"contactName"`
	ContactEmail     interface{} `json:"contactEmail"`
	Address          string      `json:"address"`
	AddressDetail    interface{} `json:"addressDetail"`
	OpenType         int         `json:"openType"`
	CategoryID       int         `json:"categoryId"`
	SecondCategoryID int         `json:"secondCategoryId"`
	PoiLat           float64     `json:"poiLat"`
	PoiLng           float64     `json:"poiLng"`
	SubBrandID       int         `json:"subBrandId"`
	PoiType          int         `json:"poiType"`
}

type GetStoreStatusResultAll struct {
	TotalCount int                    `json:"totalCount"`
	PageNum    int                    `json:"pageNum"`
	PageSize   int                    `json:"pageSize"`
	DataList   []GetStoreStatusResult `json:"dataList"`
}

func (a *API) GetStoreStatus(poiName string) (getStoreStatusResult *GetStoreStatusResultAll, err error) {
	params := map[string]interface{}{
		"poiName":  poiName,
		"openType": -1,
		"cityId":   -1,
		"pageNum":  1,
		"pageSize": 20,
	}
	result, err := a.AccessAPI2("https://page.peisong.meituan.com/api", "haikuiopen/haikui/open/partner/poi/search", params)
	if err == nil {
		utils.Map2StructByJson(result.Data, &getStoreStatusResult, false)
	}
	return getStoreStatusResult, err
}

func (a *API) GetStoreStatusAll() (getStoreStatusResult []*GetStoreStatusResultAll, err error) {
	num := 1
	cookie := "_lxsdk_cuid=172c5ed322ac8-081f1f7ebdcbeb-f7d1d38-149c48-172c5ed322ac8; " +
		"_lxsdk=172c5ed322ac8-081f1f7ebdcbeb-f7d1d38-149c48-172c5ed322ac8; " +
		"uuid=fa1894be8819a84be4ef.1592458555.1.0.0; wm_order_channel=sjzxpc; " +
		"cssVersion=82f258e3; utm_source=60376; au_trace_key_net=default; " +
		"openh5_uuid=172c5ed322ac8-081f1f7ebdcbeb-f7d1d38-149c48-172c5ed322ac8; " +
		"bmm-uuid=dbdc11bf-fcfe-84a0-0586-97e3d7d23ec7; " +
		"token=-MfbU7noKEgDWuNA559DeG6LmYZ51CCiH8bYrH-eYuaugCOqJL7863lKoAWfx8HoydOzJE8r9gGM3QJ0IC3niA; " +
		"_lxsdk_s=172fa436aed-861-103-c9b%7C%7C7"
	a.SetCookieWithStr(cookie)
	for {
		params := map[string]interface{}{
			"pageNum":  num,
			"pageSize": 20,
		}
		var getStoreStatusResult1 *GetStoreStatusResultAll
		getStoreStatusResult1 = new(GetStoreStatusResultAll)
		result, err := a.AccessAPI2("https://page.peisong.meituan.com/api", "haikuiopen/haikui/open/partner/poi/search", params)
		if err == nil {
			utils.Map2StructByJson(result.Data, &getStoreStatusResult1, false)
		}
		if len(getStoreStatusResult1.DataList) == 0 || getStoreStatusResult1.DataList == nil {
			break
		}
		getStoreStatusResult = append(getStoreStatusResult, getStoreStatusResult1)
		num++
	}
	return getStoreStatusResult, err
}

type GetStoreInfoResult struct {
	OuterPoiID  string      `json:"outerPoiId"`
	PoiName     string      `json:"poiName"`
	AccountInfo interface{} `json:"accountInfo"`
}

func (a *API) GetStoreInfo(outerPoiId int) (getStoreInfoResult []*GetStoreInfoResult, err error) {
	params := map[string]interface{}{
		"outerPoiId": outerPoiId,
		"pageNum":    1,
		"pageSize":   20,
	}
	result, err := a.AccessAPI2("https://page.peisong.meituan.com/api", "haikuiopen/haikui/open/partner/poi/account/list", params)
	if err == nil {
		utils.Map2StructByJson(result.Data["dataList"], &getStoreInfoResult, false)
	}
	return getStoreInfoResult, err
}

func (a *API) GetStoreInfoByID(outerPoiId int) (getStoreInfoResult *GetStoreStatusResult, err error) {
	params := map[string]interface{}{
		"outerPoiId": outerPoiId,
		"pageNum":    1,
		"pageSize":   20,
		"cityId":     -1,
	}
	result, err := a.AccessAPI2("https://peisong.meituan.com/api", "haikuiopen/haikui/open/partner/poi/search", params)
	if err == nil {
		if result.Data["dataList"] != nil {
			utils.Map2StructByJson(result.Data["dataList"].([]interface{})[0], &getStoreInfoResult, false)
		}
	}
	return getStoreInfoResult, err
}
