package sdk

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/beego/beego/v2/adapter/httplib"

	"tower_api/pkg/util"
)

const eightUDomain = "https://h5.8uyx.com" //8u的接口地址

// EightU 8U对接部分
type EightU struct {
}

func New8U() EightU {
	return EightU{}
}

func (e EightU) CheckOpenId(appid, uid, appKey string) (bool, error) {
	req := httplib.Post(eightUDomain+"/cp/api_get_user_fcm_info").
		SetTimeout(3*time.Second, 3*time.Second)
	curUnix := time.Now().Unix()
	sign := genUserInfoSign(appid, uid, appKey, curUnix)
	req.Param("uid", uid)
	req.Param("appid", appid)
	req.Param("time", fmt.Sprintf("%d", curUnix))
	req.Param("sign", sign)

	retByte, err := req.Bytes()
	if err != nil {
		return false, err //网络请求失败
	}
	//判断返回是否正确
	var res EightURet
	err = json.Unmarshal(retByte, &res)
	if err != nil {
		return false, err
	}
	if res.Code != 0 {
		return false, errors.New("账户信息不正确")
	}
	return true, nil
}

type Data struct {
	Pi string `json:"pi"`
}

type EightURet struct {
	Code int    `json:"code"`
	Msg  string `json:"msg,omitempty"`
	Data struct {
		Pi string `json:"pi"`
	} `json:"data,omitempty"`
}

func genUserInfoSign(appid, uid, appKey string, nowUnix int64) string {
	str := fmt.Sprintf(
		"uid=%s&appid=%s&time=%d&appkey=%s",
		uid,
		appid,
		nowUnix,
		appKey,
	)
	return util.EncodeMD5(str)
}
