/**
 * Copyright (c) 2022 Yansen Zhang
 * wxcomponent is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
**/

package webpage

import (
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"net/url"
	"strconv"
	"time"

	"gitee.com/yansen_zh/wxcomponent/errors"
	"gitee.com/yansen_zh/wxcomponent/utils"
	"gitee.com/yansen_zh/wxcomponent/utils/request"
)

// JsapiTicketResult 通过 access_token 获取 jsapi_ticket 结果
type JsapiTicketResult struct {
	errors.Error
	Ticket    string `json:"ticket"`
	ExpiresIn int    `json:"expires_in"`
}

// JsapiSignature 可以用来初始化 JS SDK
type JsapiSignature struct {
	Timestamp int64  `json:"timestamp"`
	NonceStr  string `json:"nonceStr"`
	Signature string `json:"signature"`
}

const (
	apiGetJSTicket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"
)

// GetJSTicket 通过 access_token 获取 jsapi_ticket
func GetJSTicket(authorizerToken string) (*JsapiTicketResult, error) {
	if authorizerToken == "" {
		return nil, errors.New("获取 jsapi_ticket authorizerToken 不能为空")
	}

	param := url.Values{}
	param.Set("access_token", authorizerToken)
	param.Set("type", "jsapi")

	resp, e2 := request.GetJSON(apiGetJSTicket, &param)
	if e2 != nil {
		return nil, e2
	}

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

	return &result, nil
}

// GetJSAPISignature 获取 JsapiSignature
func GetJSAPISignature(ticket, url string) *JsapiSignature {
	timestamp := time.Now().Unix()
	timestampStr := strconv.FormatInt(timestamp, 10)
	nonceStr := utils.RandStr(16)

	s1 := "jsapi_ticket=" + ticket
	s2 := "&noncestr=" + nonceStr
	s3 := "&timestamp=" + timestampStr
	s4 := "&url=" + url

	plain := s1 + s2 + s3 + s4
	signature := fmt.Sprintf("%x", sha1.Sum([]byte(plain)))

	return &JsapiSignature{
		Timestamp: timestamp,
		NonceStr:  nonceStr,
		Signature: signature,
	}
}