package wechat

import (
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	response2 "hongze/hongze_yb/models/response"
	userResp "hongze/hongze_yb/models/response/user"
	"hongze/hongze_yb/services/user"
	userService "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/services/wechat"
	"hongze/hongze_yb/services/wx_app"
	"hongze/hongze_yb/utils"
	"strconv"
)

func GetQrCode(c *gin.Context) {
	//wxApp := wx_app.GetWxApp()
	//response.OkData("获取成功", qrCode, c)
}

func GetUserInfo(c *gin.Context) {
	openid := `oN0jD1S3P-FVosLhq-YiVOXldtRo`
	userInfo, err := wechat.GetUserInfo(openid)
	if err != nil {
		response.Fail("获取失败，Err:"+err.Error(), c)
		return
	}
	response.OkData("获取成功", userInfo, c)
}

func GetUserSession(c *gin.Context) {
	code, _ := c.GetQuery("code")
	// 是否为备用小程序
	copyYb := c.Request.Header.Get("CopyYb")
	//c.Sho
	//fmt.Println(c.Request.)
	userInfo, err := wx_app.GetSession(code, copyYb)
	if err != nil {
		response.Fail("获取失败，Err:"+err.Error(), c)
		return
	}
	response.OkData("获取成功", userInfo, c)
}

// Login 微信登录
// @Tags 微信相关接口
// @Summary  微信登录
// @Description 微信登录
// @Accept  json
// @Product json
// @Param code query string true "微信code"
// @Success 200 {object} response.LoginResp
// @Router /wechat/login [get]
func Login(c *gin.Context) {
	//code, _ := c.GetQuery("code")
	code := c.DefaultQuery("code", "")
	// 是否为备用小程序
	copyYb := c.Request.Header.Get("CopyYb")

	wxUserInfo, err := wx_app.GetSession(code, copyYb)
	if err != nil {
		response.Fail("获取失败，Err:"+err.Error(), c)
		return
	}
	wxPlatform := utils.USER_RECORD_PLATFORM_YB
	if copyYb == "true" {
		wxPlatform = utils.USER_RECORD_PLATFORM_COPY_YB
	}

	token, userId, isBind, err := user.WxLogin(wxPlatform, wxUserInfo)
	if err != nil {
		response.Fail("登录失败，Err:"+err.Error(), c)
		return
	}

	response.OkData("获取成功", response2.LoginResp{
		UserId:        userId,
		IsBind:        isBind,
		Authorization: token,
	}, c)
}

// 消息解密请求参数
type EncryptReq struct {
	Code			string	`description:"手机号获取凭证"`
	EncryptedData 	string
	Iv            	string
	IsBind        	bool `json:"isBind" description:"是否需要去授权绑定"`
}

// GetEncryptInfo 消息解密
// @Tags 微信相关接口
// @Summary  消息解密
// @Description 消息解密
// @Accept  json
// @Product json
// @Param encryptedData query string true "加密数据"
// @Param iv query string true "加密算法初始向量"
// @Success 200 {string} string "获取成功"
// @Router /wechat/getEncryptInfo [post]
func GetEncryptInfo(c *gin.Context) {
	// 是否为备用小程序
	copyYb := c.Request.Header.Get("CopyYb")
	var req EncryptReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.Fail("参数异常", c)
		return
	}
	if req.EncryptedData == "" {
		response.Fail("参数异常:encryptedData", c)
		return
	}
	if req.Iv == "" {
		response.Fail("参数异常:iv", c)
		return
	}
	// 获取登录用户信息
	userInfo := user.GetInfoByClaims(c)
	if userInfo.RecordInfo.SessionKey == "" {
		response.Fail("请重新登录", c)
		return
	}
	decryptData, err := wx_app.GetDecryptInfo(userInfo.RecordInfo.SessionKey, req.EncryptedData, req.Iv, copyYb)
	if err != nil {
		response.Fail("获取失败，Err:"+err.Error(), c)
		return
	}

	if !req.IsBind {
		response.OkData("获取成功", decryptData, c)
		return
	}

	purePhoneNumber := ""
	if req.Code != "" {
		// 新版code获取手机号
		if phoneInfo, err := wx_app.GetPhoneNumber(req.Code, copyYb); err != nil {
			response.Fail("code获取手机号信息失败, Err:" + err.Error(), c)
			return
		} else {
			purePhoneNumber = phoneInfo.PhoneInfo.PurePhoneNumber
		}
	} else {
		purePhoneNumber = decryptData.PurePhoneNumber
	}

	//如果需要静默授权绑定，那么就去走静默绑定手机号流程
	openId := userInfo.OpenID
	//国际区号
	countryCode, _ := strconv.Atoi(decryptData.CountryCode)
	token, newUserInfo, err, errMsg := userService.BindWxUser(openId, purePhoneNumber, "", "", 3, countryCode, 1)
	if err != nil {
		if errMsg == "" {
			errMsg = "登录失败"
		}
		response.Fail(errMsg, c)
		return
	}

	response.OkData("登录成功", userResp.LoginResp{
		UserID: int(newUserInfo.UserID),
		Token:  token,
		Email:  newUserInfo.Email,
		Mobile: newUserInfo.Mobile,
	}, c)
}

// GetWxJsConf
// @Title 微信获取签名接口
// @Description 微信获取签名接口
// @Param   Url   query   string  true       "url地址"
// @Success 200 {string} string "获取成功"
// @router /getWxJsConf [get]
func GetWxJsConf(c *gin.Context) {
	getUrl := c.DefaultQuery("Url", "")
	jsConf, err := wechat.GetJsConfig(getUrl)
	if err != nil {
		response.Fail("获取失败，Err:"+err.Error(), c)
		return
	}
	//resp := new(models.WechatSign)
	//resp.AppId = utils.WxAppId
	//resp.NonceStr = nonceString
	//resp.Timestamp = timestamp
	//resp.Url = getUrl
	//resp.Signature = signature
	//jsConf.AppID
	response.OkData("获取成功", jsConf, c)
}
