package enterprise_wechat

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

// 通讯录
func New(corpId, corpSecret string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}

	return &API{
		corpId:     corpId,
		corpSecret: corpSecret,
		locker:     sync.RWMutex{},
		client:     &http.Client{Timeout: curConfig.ClientTimeout},
		config:     &curConfig,
	}
}

// 会话
func NewMin(corpId, corpSecret string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}

	return &API{
		corpId:     corpId,
		corpSecret: corpSecret,
		locker:     sync.RWMutex{},
		client:     &http.Client{Timeout: curConfig.ClientTimeout},
		config:     &curConfig,
	}
}

// 获取token
type EnterpriseToken struct {
	ErrCode     int    `json:"errcode"`      // 错误码
	ErrMsg      string `json:"errmsg"`       // 错误消息
	AccessToken string `json:"access_token"` // 权限说明
	ExpiresIn   int64  `json:"expires_in"`   // 过期时间
}

func (a *API) SetToken(token string) {
	a.locker.Lock()
	defer a.locker.Unlock()
	a.accessToken = token
}

func (a *API) SetExpiresInTime(int2 int64) {
	a.locker.Lock()
	defer a.locker.Unlock()
	a.expiresIn = time.Now().Unix() + int2
}

func (a *API) ReturnToken() string {
	a.locker.Lock()
	defer a.locker.Unlock()
	return a.accessToken
}

// 获取access_token
func (a *API) GetAccessToken() (tokenInfo *EnterpriseToken, err error) {
	parameter := make(map[string]interface{}, 2)
	parameter["corpid"] = a.corpId
	parameter["corpsecret"] = a.corpSecret

	result, err := a.AccessAPI(WeChatBaseApi, GetToken, http.MethodGet, parameter)
	if err != nil {
		return nil, err
	}

	accessToken := &EnterpriseToken{}
	if err := utils.Map2StructByJson(result, &accessToken, false); err != nil {
		return nil, err
	}
	if accessToken.ErrCode != 0 {
		return nil, errors.New(accessToken.ErrMsg)
	}
	a.SetToken(accessToken.AccessToken)
	a.SetExpiresInTime(accessToken.ExpiresIn)
	return accessToken, err
}

// 数据发送
func (a *API) AccessAPI(baseUrl, actionApi, method string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	data, err := json.Marshal(bizParams) // 序列化
	if err != nil {
		return nil, err
	}

	// 发送请求
	sendUrl := func() *http.Request {
		var request *http.Request
		if http.MethodPost == method {
			// 全路径请求参数
			fullURL := utils.GenerateGetURL(baseUrl, actionApi, map[string]interface{}{"access_token": a.accessToken})
			request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
		} else {
			getUrl := utils.GenerateGetURL(baseUrl, actionApi, bizParams)
			request, _ = http.NewRequest(http.MethodGet, getUrl, nil)
		}
		request.Header.Set("Content-Type", "application/json")
		return request
	}

	// 数据解析
	dataMarshal := 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 {
			return "", err
		}
		if utils.MustInterface2Int64(jsonResult1["errcode"]) != 0 {
			errLevel = platformapi.ErrLevelGeneralFail
			err = utils.NewErrorCode(jsonResult1["errmsg"].(string), utils.Int64ToStr(utils.MustInterface2Int64(jsonResult1["errcode"])))
		}
		retVal = jsonResult1
		return errLevel, err
	}

	err = platformapi.AccessPlatformAPIWithRetry(a.client, sendUrl, a.config, dataMarshal)
	return retVal, err
}

// 检查token是否应该更新
func (a *API) CheckAccessTokenExpiresIn() {
	if a.expiresIn == 0 || a.expiresIn <= time.Now().Unix() || a.accessToken == "" {
		a.GetAccessToken()
	}
	return
}
