package wechat

import (
	"context"
	"dsbqj-admin/pkg/cache"
	"dsbqj-admin/pkg/logger"
	"dsbqj-admin/pkg/util"
	"github.com/goccy/go-json"
	"github.com/silenceper/wechat"
	"os"
	"sync/atomic"

	wechatCache "dsbqj-admin/pkg/cache/wechat"
)

var GOpenid OpenidMgr

type OpenidMgr struct {
	V    atomic.Value //值
	Over int64        //过期时间
}

type WechatHelper struct {
	ctx       context.Context
	Wechat    *wechat.Wechat
	AppId     string
	AppSecret string
}

const (
	subscribeUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
)

func NewWechatHelper() *WechatHelper {
	appID := os.Getenv("WECHAT_APPID")
	appSecret := os.Getenv("WECHAT_SECRET")
	wx := wechat.NewWechat(&wechat.Config{
		AppID:     appID,
		AppSecret: appSecret,
		Cache:     wechatCache.NewAccessToken(cache.RedisReport),
	})

	return &WechatHelper{
		ctx:       context.Background(),
		AppId:     appID,
		AppSecret: appSecret,
		Wechat:    wx,
	}
}

type errmsg struct {
	Errcode int    `json:"errcode"` //错误码
	Errmsg  string `json:"errmsg"`  //错误信息
	Result  struct {
		Suggest string `json:"suggest"` //建议，有risky、pass、review三种值
		Label   int    `json:"label"`   //命中标签枚举值，100 正常；10001 广告；20001 时政；20002 色情；20003 辱骂；20006 违法犯罪；20008 欺诈；20012 低俗；20013 版权；21000 其他
	} `json:"result"`
}

type Subscribe struct {
	ToUser           string      `json:"touser"`
	TemplateId       string      `json:"template_id"`
	MiniProgramState string      `json:"miniprogram_state"`
	Lang             string      `json:"lang"`
	Data             interface{} `json:"data"`
}

func (this *WechatHelper) SendWechatSubscribe(openid string, template string, msg interface{}) int {
	token, _ := this.Wechat.GetAccessToken()
	url := subscribeUrl + token
	reqData := Subscribe{ToUser: openid, TemplateId: template, Lang: "zh_CN"}
	reqData.Data = msg

	data, _ := json.Marshal(reqData)
	buf, err := util.HTTPPost(url, string(data))
	if err != nil {
		logger.Info("[ERROR] CheckWechatMsg post err!err:", err.Error())
		return 101
	}
	var re = new(errmsg)
	err = json.Unmarshal(buf, re)
	if err != nil {
		logger.Info("[ERROR] CheckWechatMsg Unmarshal err!err:", err)
		return 103
	}
	if re.Errcode != 0 {
		if re.Errcode == 40003 || re.Errcode == 43101 { //openid无效,appid与openid不匹配, 用户未订阅消息（用户未在近两小时访问小程序）
			logger.Info("CheckWechatMsg msg: %s ret: %d errmsg: %s", msg, re.Errcode, re.Errmsg)
			return 0
		}

	} else {
		if re.Result.Label != 100 && re.Result.Label != 0 {
			logger.Info("[ERROR]CheckWechatMsg msg:", msg, " ret:", re.Result.Label, " ,suggest:", re.Result.Suggest)
			return re.Result.Label
		}
	}
	return re.Errcode
}
