package mtwmapi

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

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

func (a *API) AccessActPage(subURL string, params map[string]interface{}, isPost bool) (retVal map[string]interface{}, err error) {
	if a.GetCookieCount() == 0 {
		return nil, fmt.Errorf("需要设置User Cookie才能使用此方法")
	}
	rootURL := getRootURL(subURL)
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			if isPost {
				data, _ := json.Marshal(params)
				fullURL := utils.GenerateGetURL(rootURL, subURL, nil)
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
				request.Header.Set("Content-Type", "application/json")
			} else {
				request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(rootURL, subURL, params), 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")
			}
			retVal = jsonResult1
			if jsonResult1["code"] == nil {
				return platformapi.ErrLevelGeneralFail, fmt.Errorf("返回结果格式不正常")
			}
			code := int(utils.MustInterface2Int64(jsonResult1["code"]))
			if code == ResponseCodeSuccess {
				retVal, _ = jsonResult1["data"].(map[string]interface{})
				return platformapi.ErrLevelSuccess, nil
			}
			newErr := utils.NewErrorIntCode(jsonResult1["msg"].(string), code)
			return platformapi.ErrLevelCodeIsNotOK, newErr
		})
	return retVal, err
}

func (a *API) AccessActPage2(subURL string, params map[string]interface{}, isPost bool) (retVal map[string]interface{}, err error) {
	if a.GetCookieCount() == 0 {
		return nil, fmt.Errorf("需要设置User Cookie才能使用此方法")
	}
	rootURL := getRootURL(subURL)
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			var request *http.Request
			if isPost {
				fullURL := utils.GenerateGetURL(rootURL, subURL, nil)
				request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
				request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			} else {
				request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(rootURL, subURL, params), 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")
			}
			retVal = jsonResult1
			if jsonResult1["code"] == nil {
				return platformapi.ErrLevelGeneralFail, fmt.Errorf("返回结果格式不正常")
			}
			code := int(utils.MustInterface2Int64(jsonResult1["code"]))
			if code == ResponseCodeSuccess {
				retVal, _ = jsonResult1["data"].(map[string]interface{})
				return platformapi.ErrLevelSuccess, nil
			}
			newErr := utils.NewErrorIntCode(jsonResult1["msg"].(string), code)
			return platformapi.ErrLevelCodeIsNotOK, newErr
		})
	return retVal, err
}

type GetCenterListResult struct {
	ActivityStartTime      int           `json:"activityStartTime"`
	ActivityEndTime        int           `json:"activityEndTime"`
	ID                     int           `json:"id"`
	InviteID               int           `json:"inviteId"`
	PoiID                  int           `json:"poiId"`
	SegmentID              int           `json:"segmentId"`
	Name                   string        `json:"name"`
	BriefIntroduction      string        `json:"briefIntroduction"`
	EndTime                int           `json:"endTime"`
	Status                 int           `json:"status"`
	ActivityType           string        `json:"activityType"`
	RegistrationForm       string        `json:"registrationForm"`
	ActivityRule           string        `json:"activityRule"`
	ActivityIntroduction   string        `json:"activityIntroduction"`
	OperationAdvice        string        `json:"operationAdvice"`
	SegmentType            int           `json:"segmentType"`
	Faq                    string        `json:"faq"`
	IsEntered              int           `json:"isEntered"`
	EnterTime              int           `json:"enterTime"`
	ApproveStatus          int           `json:"approveStatus"`
	EnterID                int           `json:"enterId"`
	MatchPoiBaseFilter     int           `json:"matchPoiBaseFilter"`
	WeekTimes              string        `json:"weekTimes"`
	PoiApplyStatus         int           `json:"poiApplyStatus"`
	Period                 string        `json:"period"`
	PoiInviteType          int           `json:"poiInviteType"`
	PoiCurrentPolicy       interface{}   `json:"poiCurrentPolicy"`
	PoiPolicyType          int           `json:"poiPolicyType"`
	EnteredDataUnionStatus int           `json:"enteredDataUnionStatus"`
	ActivityDateList       []interface{} `json:"activityDateList"`
	RejectComment          interface{}   `json:"rejectComment"`
	PoiCouponVoListJSON    interface{}   `json:"poiCouponVoListJson"`
	PoiRedPackageVoJSON    interface{}   `json:"poiRedPackageVoJson"`
	CanEnter               int           `json:"canEnter"`
	CreateTime             int           `json:"createTime"`
	IsCanModify            int           `json:"isCanModify"`
	EnteredDataJSON        interface{}   `json:"enteredDataJson"`
}

func (a *API) GetCenterList(vendorStoreID string) (getCenterListResult []*GetCenterListResult, err error) {
	result, err := a.AccessActPage("api/sg/promotion/invite/centerList", map[string]interface{}{
		"wmPoiId": vendorStoreID,
	}, true)
	if err == nil {
		utils.Map2StructByJson(result["items"], &getCenterListResult, false)
	}
	return getCenterListResult, err
}

type GetInviteDetailResult struct {
	ID                     int           `json:"id"`
	InviteID               int           `json:"inviteId"`
	PoiID                  int           `json:"poiId"`
	SegmentID              int           `json:"segmentId"`
	Name                   string        `json:"name"`
	BriefIntroduction      string        `json:"briefIntroduction"`
	EndTime                int           `json:"endTime"`
	CreateTime             int           `json:"createTime"`
	Status                 int           `json:"status"`
	ActivityStartTime      int           `json:"activityStartTime"`
	ActivityEndTime        int           `json:"activityEndTime"`
	ActivityType           string        `json:"activityType"`
	RegistrationForm       string        `json:"registrationForm"`
	ActivityRule           string        `json:"activityRule"`
	ActivityIntroduction   string        `json:"activityIntroduction"`
	OperationAdvice        string        `json:"operationAdvice"`
	SegmentType            int           `json:"segmentType"`
	Faq                    string        `json:"faq"`
	IsEntered              int           `json:"isEntered"`
	EnterTime              int           `json:"enterTime"`
	ApproveStatus          int           `json:"approveStatus"`
	EnterID                int           `json:"enterId"`
	MatchPoiBaseFilter     int           `json:"matchPoiBaseFilter"`
	WeekTimes              string        `json:"weekTimes"`
	PoiApplyStatus         int           `json:"poiApplyStatus"`
	Period                 string        `json:"period"`
	PoiInviteType          int           `json:"poiInviteType"`
	PoiPolicyType          int           `json:"poiPolicyType"`
	MtCostAdd              int           `json:"mtCostAdd"`
	MtCostAddon            int           `json:"mtCostAddon"`
	EnteredDataUnionStatus int           `json:"enteredDataUnionStatus"`
	ActivityDateList       []interface{} `json:"activityDateList"`
	CanEnter               int           `json:"canEnter"`
	IsCanCancel            int           `json:"isCanCancel"`
	IsCanModify            int           `json:"isCanModify"`
	StatisticsData         struct {
		TotalOrderNum     int     `json:"totalOrderNum"`
		TotalIncome       float64 `json:"totalIncome"`
		AveragePrice      float64 `json:"averagePrice"`
		Cost              float64 `json:"cost"`
		InOutRatio        float64 `json:"inOutRatio"`
		TotalGoodsSoldNum int     `json:"totalGoodsSoldNum"`
		TotalObtainNum    int     `json:"totalObtainNum"`
		TotalUsedNum      int     `json:"totalUsedNum"`
		UseRate           float64 `json:"useRate"`
		Stock             int     `json:"stock"`
		CouponNum         int     `json:"couponNum"`
		DayCount          int     `json:"dayCount"`
		IsShow            int     `json:"isShow"`
	} `json:"statisticsData"`
	NeedApprove        int `json:"needApprove"`
	IsCollectorUpdated int `json:"isCollectorUpdated"`
	IsPoiCanModify     int `json:"isPoiCanModify"`
	IsPoiCanCancel     int `json:"isPoiCanCancel"`
}

func (a *API) GetInviteDetail(actID int, vendorStoreID string) (getCenterListResult *GetInviteDetailResult, err error) {
	result, err := a.AccessActPage2("api/invite/detail", map[string]interface{}{
		"wmPoiId":      vendorStoreID,
		"id":           actID,
		"usedForBatch": false,
	}, true)
	if err == nil {
		utils.Map2StructByJson(result, &getCenterListResult, false)
	}
	return getCenterListResult, err
}
