package controllers

import (
	"encoding/json"
	"fmt"
	"hongze/hongze_api/models"
	"hongze/hongze_api/services"
	"hongze/hongze_api/utils"
	"strconv"
	"time"
)

type WechatController struct {
	BaseAuthController
}

type WechatCommonController struct {
	BaseCommonController
}

// @Title 微信登录接口
// @Description 微信登录接口
// @Param   Code   query   string  true       "微信唯一编码code"
// @Success 200 {object} models.WxLoginResp
// @router /login [get]
func (this *WechatCommonController) WechatLogin() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	code := this.GetString("Code")
	fmt.Println("code:", code)
	item, err := services.WxGetUserOpenIdByCode(code)
	if err != nil {
		br.Msg = "获取用户信息失败"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	if item.Errcode != 0 {
		br.Msg = "获取用户信息失败"
		br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
		return
	}
	openId := item.Openid
	accessToken, err := services.WxGetAccessToken()
	if err != nil {
		br.Msg = "获取用户信息失败"
		br.ErrMsg = "获取access_token失败,err:" + err.Error()
		return
	}
	//获取用户信息
	wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
	if err != nil {
		br.Msg = "获取用户信息失败"
		br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
		return
	}
	if wxUserInfo.Errcode != 0 {
		userInfoJson, _ := json.Marshal(wxUserInfo)
		br.Msg = "登录失败"
		br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
		return
	}

	unionid := item.Unionid
	if unionid == "" {
		unionid = wxUserInfo.Unionid
	}
	firstLogin := 1
	userId := 0
	utils.FileLog.Info("openId:%s", openId)
	utils.FileLog.Info("unionid:%s", unionid)
	//获取成功
	if unionid != "" {
		wxUser, err := models.GetWxUserItemByUnionid(unionid)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取用户信息失败"
			br.ErrMsg = "根据openid获取用户信息失败,Eerr:" + err.Error()
			return
		}
		if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
			user := new(models.WxUser)
			user.OpenId = openId
			user.CompanyId = 1
			user.CreatedTime = time.Now()
			user.UnionId = unionid
			user.Unionid = unionid
			user.NickName = wxUserInfo.Nickname
			user.Sex = wxUserInfo.Sex
			user.City = wxUserInfo.City
			user.Province = wxUserInfo.Province
			user.Country = wxUserInfo.Country
			user.Headimgurl = wxUserInfo.Headimgurl
			user.FirstLogin = 1
			user.Enabled = 1
			user.RegisterPlatform = 1
			user.RegisterTime = time.Now()
			_, err = models.AddWxUser(user)
			wxUser, err = models.GetWxUserItemByUnionid(unionid)
			if err != nil {
				br.Msg = "获取用户信息失败"
				br.ErrMsg = "unionid登录,获取微信用户信息失败,Err:" + err.Error()
				return
			}
			userId = wxUser.UserId
		} else {
			firstLogin = wxUser.FirstLogin
			userId = wxUser.UserId
		}
	} else {
		if openId != "" {
			wxUser, err := models.GetWxUserItemByOpenId(openId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取用户信息失败"
				br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
				return
			}
			if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
				user := new(models.WxUser)
				user.OpenId = openId
				user.CompanyId = 1
				user.CreatedTime = time.Now()
				user.UnionId = unionid
				user.Unionid = unionid
				user.NickName = wxUserInfo.Nickname
				user.Sex = wxUserInfo.Sex
				user.City = wxUserInfo.City
				user.Province = wxUserInfo.Province
				user.Country = wxUserInfo.Country
				user.Headimgurl = wxUserInfo.Headimgurl
				user.FirstLogin = 1
				user.Enabled = 1
				user.RegisterPlatform = 1
				user.RegisterTime = time.Now()
				_, err = models.AddWxUser(user)

				wxUser, err = models.GetWxUserItemByOpenId(openId)
				if err != nil {
					br.Msg = "获取用户信息失败"
					br.ErrMsg = "unionid登录,获取微信用户信息失败,Err:" + err.Error()
					return
				}
				userId = wxUser.UserId
			} else {
				userId = wxUser.UserId
			}
		}
	}
	permission, err := services.CheckUserPermission(userId)
	if err != nil {
		utils.FileLog.Info("userId:%s,err:%s", strconv.Itoa(userId), err)
	}
	//if err != nil {
	//	br.Msg = "登录失败"
	//	br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
	//	return
	//}
	var token string
	tokenItem, err := models.GetTokenByUid(userId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "登录失败"
		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
		return
	}

	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
		timeUnix := time.Now().Unix()
		timeUnixStr := strconv.FormatInt(timeUnix, 10)
		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
		//新增session
		{
			session := new(models.Session)
			session.OpenId = openId
			session.UserId = userId
			session.CreatedTime = time.Now()
			session.LastUpdatedTime = time.Now()
			session.ExpireTime = time.Now().AddDate(0, 1, 0)
			session.AccessToken = token
			err = models.AddSession(session)
			if err != nil {
				br.Msg = "登录失败"
				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
				return
			}
		}
	} else {
		token = tokenItem.AccessToken
	}

	if wxUserInfo != nil {
		go models.ModifyWxUserInfo(wxUserInfo.Nickname, wxUserInfo.Headimgurl, wxUserInfo.City, wxUserInfo.Province, wxUserInfo.Country, wxUserInfo.Sex, userId)
	}

	resp := new(models.WxLoginResp)
	resp.UserId = userId
	resp.Code = 0
	resp.FirstLogin = firstLogin
	resp.Authorization = token
	resp.UserPermission = permission
	br.Ret = 200
	br.Success = true
	br.Msg = "登录成功"
	br.Data = resp
}

// @Title 微信获取签名接口
// @Description 微信获取签名接口
// @Param   Url   query   string  true       "url地址"
// @Success 200 {object} models.WechatSign
// @router /getWxSign [get]
func (this *WechatController) GetWxSign() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	getUrl := this.GetString("Url")
	fmt.Println("getUrl:", getUrl)
	accessToken, err := services.WxGetAccessToken()
	if err != nil {
		br.Msg = "获取用户信息失败"
		br.ErrMsg = "获取access_token失败,err:" + err.Error()
		return
	}

	ticket, err := services.GetWxTicket(accessToken)
	if err != nil {
		br.Msg = "获取Ticket失败,请联系客服"
		br.ErrMsg = "获取Ticket失败,Err" + err.Error()
		return
	}
	if ticket == "" {
		br.Msg = "获取Ticket失败,请联系客服"
		br.ErrMsg = "ticket为空" + ticket
		return
	}
	nonceStr := utils.GetRandStringNoSpecialChar(16)
	signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr)

	resp := new(models.WechatSign)
	resp.AppId = utils.WxAppId
	resp.NonceStr = nonceString
	resp.Timestamp = timestamp
	resp.Url = getUrl
	resp.Signature = signature
	br.Ret = 200
	br.Success = true
	br.Msg = "获取签名成功"
	br.Data = resp
}