package system

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"github.com/silenceper/wechat/v2/officialaccount/message"
	"go.uber.org/zap"
	"net/http"
	"net/url"
)

type WechatApi struct {
}

func (b *WechatApi) Auth(c *gin.Context) {
	code := c.Query("code")
	state := c.Query("state")
	global.GVA_LOG.Info("用户授权", zap.Any("code", code), zap.Any("state", state))
	if acc, err := global.GVA_WECHAT.GetOauth().GetUserAccessToken(code); err != nil {
		global.GVA_LOG.Error("用户授权异常", zap.Any("err", err))
		c.String(http.StatusOK, "用户授权异常,请尝试重新点击授权链接")
	} else {
		if userInfo, err := global.GVA_WECHAT.GetOauth().GetUserInfo(acc.AccessToken, acc.OpenID, "zh_CN"); err != nil {
			global.GVA_LOG.Error("用户获取用户信息异常", zap.Any("err", err))
			c.String(http.StatusOK, "获取用户信息异常,请尝试重新点击授权链接")
		} else {
			global.GVA_LOG.Info("用户获取授权信息", zap.Any("res", userInfo))
			if err, userSys := userService.GetUserInfoByUnionId(userInfo.Unionid); err != nil {
				authorityId := "100"
				user := &system.SysUser{NickName: userInfo.Nickname, HeaderImg: userInfo.HeadImgURL, WechatId: userInfo.OpenID, UnionId: userInfo.Unionid, Password: utils.RandomString(10), AuthorityId: authorityId, Authorities: nil}
				userService.Register(*user)
			} else {
				//已有用户,更新信息
				userSys.NickName = userInfo.Nickname
				userSys.HeaderImg = userInfo.HeadImgURL
				userSys.WechatId = userInfo.OpenID
				userService.SetUserInfo(userSys)
			}
			c.String(http.StatusOK, "您已成功授权《"+global.GVA_CONFIG.Wxxcx.Name+"创城进行时》!")
		}
	}
}

func (b *WechatApi) Req(c *gin.Context) {
	// 传入request和responseWriter
	server := global.GVA_WECHAT.GetServer(c.Request, c.Writer)
	server.SkipValidate(true)
	//设置接收消息的处理方法
	server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
		//回复消息：演示回复用户发送的消息
		if msg.Event == message.EventSubscribe {
			global.GVA_LOG.Info("用户关注", zap.Any("openId", msg.FromUserName), zap.Any("msg", msg))
			if err, sysUser := userService.GetUserInfoByWechatId(string(msg.FromUserName)); err != nil {
				if user, err := global.GVA_WECHAT.GetUser().GetUserInfo(string(msg.FromUserName)); err == nil {
					global.GVA_LOG.Info("用户信息", zap.Any("user", user))
					if err, sysUser := userService.GetUserInfoByUnionId(user.UnionID); err != nil {
						//不存在则新增用户
						authorityId := "100"
						user := &system.SysUser{WechatId: user.OpenID, UnionId: user.UnionID, Password: utils.RandomString(10), AuthorityId: authorityId, Authorities: nil}
						userService.Register(*user)
					} else {
						//已存在小程序用户更新user 微信id到表
						sysUser.WechatId = user.OpenID
						userService.SetUserInfo(sysUser)
					}
				} else {
					global.GVA_LOG.Info("用户信息拉取失败", zap.Any("err", err))
				}
			} else {
				global.GVA_LOG.Info("用户已存在", zap.Any("err", err), zap.Any("sysUser", sysUser))
			}
			text := message.NewText("【" + global.GVA_CONFIG.Wxxcx.Name + "创城进行时】感谢您的关注！")
			//text := message.NewText("【经开创城进行时】感谢您的关注！ \r\n <a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx66e0fbb5a735bcc4&redirect_uri=" + url.QueryEscape(
			//	global.GVA_CONFIG.Wxxcx.AuthUrl) + "/wechat/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>点我授权</a>")
			return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
		}
		if msg.Content == "授权" {
			text := message.NewText("<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx66e0fbb5a735bcc4&redirect_uri=" + url.QueryEscape(
				global.GVA_CONFIG.Wxxcx.AuthUrl) + "/wechat/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'>点我授权</a>")
			return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
		}
		global.GVA_LOG.Info("用户消息", zap.Any("openId", msg.FromUserName), zap.Any("msg", msg))
		text := message.NewText(msg.Content)
		return &message.Reply{MsgType: message.MsgTypeImage, MsgData: text}

		//article1 := message.NewArticle("测试图文1", "图文描述", "", "")
		//articles := []*message.Article{article1}
		//news := message.NewNews(articles)
		//return &message.Reply{MsgType: message.MsgTypeNews, MsgData: news}

		//voice := message.NewVoice(mediaID)
		//return &message.Reply{MsgType: message.MsgTypeVoice, MsgData: voice}

		//
		//video := message.NewVideo(mediaID, "标题", "描述")
		//return &message.Reply{MsgType: message.MsgTypeVideo, MsgData: video}

		//music := message.NewMusic("标题", "描述", "音乐链接", "HQMusicUrl", "缩略图的媒体id")
		//return &message.Reply{MsgType: message.MsgTypeMusic, MsgData: music}

		//多客服消息转发
		//transferCustomer := message.NewTransferCustomer("")
		//return &message.Reply{MsgType: message.MsgTypeTransfer, MsgData: transferCustomer}
	})

	//处理消息接收以及回复
	err := server.Serve()
	if err != nil {
		global.GVA_LOG.Error("Serve Error, err=%+v", zap.Any("err", err))
		return
	}
	//发送回复的消息
	err = server.Send()
	if err != nil {
		global.GVA_LOG.Error("Send Error, err=%+v", zap.Any("err", err))
		return
	}
}
