package handler

import (
	"cold-delivery/conf"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/alibaba/sentinel-golang/util"
	log "gogs.baozhida.cn/zoie/OAuth-core/logger"
	coreModel "gogs.baozhida.cn/zoie/OAuth-core/model"
	"gogs.baozhida.cn/zoie/OAuth-core/pkg"
	"gogs.baozhida.cn/zoie/OAuth-core/sdk"
	"gorm.io/gorm"
	"net/http"
)

type Login struct {
	Username          string `form:"UserName" json:"username"`                   // 用户名
	Password          string `form:"Password" json:"password"`                   // 密码
	Phone             string `form:"Phone" json:"phone"`                         // 手机号
	VerifyCode        string `form:"VerifyCode" json:"verifyCode"`               // 验证码
	Type              int    `form:"Type" json:"type"`                           // 1-密码  2-短信验证码 3-微信登录
	Mobile            bool   `form:"Mobile" json:"mobile"`                       // 是否手机登录
	AuthorizationCode string `form:"authorizationCode" json:"authorizationCode"` // 微信登录code
}

//Code     string `form:"Code" json:"code" binding:"required"`
//UUID     string `form:"UUID" json:"uuid" binding:"required"`

type SmsLogin struct {
}

func (u *Login) GetUser(tx *gorm.DB) (user SysUser, role SysRole, dept SysDept, err error) {
	err = tx.Table("sys_user").Where("username = ? and status = 2", u.Username).First(&user).Error
	if err != nil {
		log.Errorf("get user error, %s", err.Error())
		return
	}
	_, err = pkg.CompareHashAndPassword(user.Password, u.Password)
	if err != nil {
		log.Errorf("user login error, %s", err.Error())
		return
	}
	if user.RoleId > 0 {
		err = tx.Table("sys_role").Where("id = ? ", user.RoleId).First(&role).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			log.Errorf("get role error, %s", err.Error())
		}
	}
	if user.DeptId > 0 {
		err = tx.Table("sys_dept").Where("id = ? ", user.DeptId).First(&dept).Error
		if err != nil {
			log.Errorf("get dept error, %s", err.Error())
			return
		}
	}

	return
}

func (u *Login) GetUserByCode(tx *gorm.DB) (user SysUser, role SysRole, dept SysDept, err error) {
	err = tx.Table("sys_user").Where("phone = ? and status = 2", u.Phone).First(&user).Error
	if err != nil {
		log.Errorf("get user error, %s", err.Error())
		return
	}
	code, err := sdk.Runtime.GetCacheAdapter().Get(GetVerifyCodeCacheKey(u.Phone))
	if err != nil {
		log.Errorf("user login error, %s", err.Error())
		err = errors.New("验证码已过期")
		return
	}
	if code != u.VerifyCode {
		log.Errorf("user login error, %s", "验证码错误")
		err = errors.New("验证码错误")
		return
	}

	err = tx.Table("sys_role").Where("id = ? ", user.RoleId).First(&role).Error
	if err != nil {
		log.Errorf("get role error, %s", err.Error())
		return
	}
	if user.DeptId > 0 {
		err = tx.Table("sys_dept").Where("id = ? ", user.DeptId).First(&dept).Error
		if err != nil {
			log.Errorf("get dept error, %s", err.Error())
			return
		}
	}

	return
}

func GetUserByID(tx *gorm.DB, id int64) (user SysUser, role SysRole, err error) {
	err = tx.Table("sys_user").Where("id = ? ", id).First(&user).Error
	if err != nil {
		log.Errorf("get user error, %s", err.Error())
		return
	}
	err = tx.Table("sys_role").Where("id = ? ", user.RoleId).First(&role).Error
	if err != nil {
		log.Errorf("get role error, %s", err.Error())
		return
	}
	return
}

type AppletCustomerRegisterReq struct {
	Type       int    `json:"type"`       // 类型  0-商户 1-私人
	Phone      string `json:"phone"`      // 手机号
	Password   string `json:"password"`   // 密码
	VerifyCode string `json:"verifyCode"` // 验证码

}

type AppletCustomerLoginResp struct {
	Openid      string `json:"openid"`      //用户唯一标识
	Session_key string `json:"session_key"` // 会话密钥 session_key 是对用户数据进行 加密签名 的密钥
	Unionid     string `json:"unionid"`     // 用户在开放平台的唯一标识符，若当前小程序已绑定到微信开放平台帐号下会返回
	Errcode     int    `json:"errcode"`     //错误码： -1、0、40029、 45011、 40226  （具体说明，请阅读 接口文档）
	Errmsg      string `json:"errmsg"`      //错误信息
}

func (u *Login) GetUserByWX(tx *gorm.DB) (user SysUser, role SysRole, dept SysDept, err error) {

	url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	appid := conf.ExtConfig.Applet.Appid
	appSecret := conf.ExtConfig.Applet.AppSecret
	url = fmt.Sprintf(url, appid, appSecret, u.AuthorizationCode)
	// 发起请求
	res, _ := http.Get(url)

	// 成功后获取openId
	wxRes := AppletCustomerLoginResp{}
	err = json.NewDecoder(res.Body).Decode(&wxRes)

	if err != nil || wxRes.Openid == "" {
		err = errors.New("获取openid失败")
		return
	}

	err = tx.Where("username = ? and user_type = 'customer' and status = '2' and dept_id = 0", u.Phone).First(&user).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 添加客户
			user = SysUser{
				User: coreModel.User{
					Uuid:     util.NewUuid(),
					Username: u.Phone,
					Phone:    u.Phone,
				},
				UserType: "customer",
				Openid:   wxRes.Openid,
			}
			err = tx.Create(&user).Error
			if err != nil {
				err = errors.New("添加个人信息失败")
			}
		} else {
			err = errors.New("获取个人信息失败")
			return
		}
	}

	if user.Openid != wxRes.Openid {
		user.Openid = wxRes.Openid
		err = tx.Save(&user).Error
		if err != nil {
			err = errors.New("同步个人信息失败")
			return
		}
	}

	return
}
