package service

import (
	"encoding/json"
	"errors"
	"net/url"

	"gitee.com/yansen_zh/wechat-oplatform-sdk/api"
	"gitee.com/yansen_zh/wechat-oplatform-sdk/entity"
	"gitee.com/yansen_zh/wechat-oplatform-sdk/utils"
	"gitee.com/yansen_zh/wechat-oplatform-sdk/utils/request"
)

// AuthorizerListParam 拉取所有已授权的帐号信息参数
type AuthorizerListParam struct {
	ComponentAppId string `json:"component_appid"`
	Offset         int    `json:"offset"`
	Count          int    `json:"count"`
}

// AuthorizerListResult 拉取所有已授权的帐号信息结果
type AuthorizerListResult struct {
	entity.Error
	TotalCount float64                      `json:"total_count"`
	List       []entity.AuthorizerBasicInfo `json:"list"`
}

// AuthorizerList 拉取所有已授权的帐号信息
func AuthorizerList(componentAccessToken string, param AuthorizerListParam) (*AuthorizerListResult, error) {
	if componentAccessToken == "" {
		return nil, errors.New("拉取所有已授权的帐号信息 第三方平台的 component_access_token 不能为空")
	}

	if param.ComponentAppId == "" {
		return nil, errors.New("拉取所有已授权的帐号信息 第三方平台的 appid 不能为空")
	}

	if param.Offset < 0 {
		param.Offset = 0
	}

	if param.Count < 0 {
		param.Count = 100
	}

	if param.Count > 500 {
		param.Count = 500
	}

	data, e1 := json.Marshal(param)
	if e1 != nil {
		return nil, e1
	}

	queryParam := url.Values{}
	queryParam.Set("component_access_token", componentAccessToken)

	apiUrl, _ := utils.ParseURL(api.GetAuthorizerList, &queryParam)
	resp, e2 := request.PostJSON(apiUrl.String(), data)
	if e2 != nil {
		return nil, e2
	}

	result := AuthorizerListResult{}
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, err
	}

	if result.Code != 0 {
		return &result, result.Error
	}

	return &result, nil
}