package middleware

import (
	"dubbo.apache.org/dubbo-go/v3/common/logger"
	"errors"
	"fmt"
	"fonchain-fiee/api/account"
	api "fonchain-fiee/api/accountFiee"
	jwt2 "fonchain-fiee/pkg/common/jwt"
	"fonchain-fiee/pkg/common/m"
	"fonchain-fiee/pkg/e"
	"fonchain-fiee/pkg/logic"
	"fonchain-fiee/pkg/model"
	"fonchain-fiee/pkg/model/login"
	"fonchain-fiee/pkg/service"
	"fonchain-fiee/pkg/utils/secret"
	"github.com/gin-gonic/gin"
	"time"
)

// CheckLogin 检测登陆
func CheckLogin(provider *api.AccountFieeClientImpl) gin.HandlerFunc {

	return func(ctx *gin.Context) {

		//如果没有登录
		authorization := ctx.GetHeader(e.BoxAuthorization)
		if authorization == "" {
			service.NotLoginError(ctx, errors.New(e.ErrNotLogin))
			return
		}

		jwt, err := jwt2.ParseToken(authorization, m.JWTSecret)
		fmt.Println(jwt)

		if err != nil {
			service.NotLoginError(ctx, errors.New(e.ErrNotLogin))
			return
		}

		//1 获取用户的账号信息
		infoReq := &api.UserByTelRequest{
			Tel:    jwt.Phone,
			Domain: jwt.Domain,
		}

		infoRes, err := service.AccountFieeProvider.UserByTel(ctx, infoReq)
		if err != nil {
			service.Error(ctx, err)
			return
		}

		//info := infoRes.Info/
		loginInfo := login.Info{
			ID:                 infoRes.Id,
			Status:             infoRes.Status,
			Name:               infoRes.Name,
			Sex:                infoRes.Sex,
			Nationality:        infoRes.Nationality,
			DocumentType:       infoRes.DocumentType,
			CertificatePicture: infoRes.CertificatePicture,
			Validity:           infoRes.Validity,
			PlaceOfResidence:   infoRes.PlaceOfResidence,
			GroupPhoto:         infoRes.GroupPhoto,
			Attachment:         infoRes.Attachment,
			SubNum:             infoRes.SubNum,
			NotPassRemarks:     infoRes.NotPassRemarks,
			Domain:             infoRes.Domain,
			TelNum:             jwt.Phone,
			SubscriberNumber:   infoRes.SubscriberNumber,
		}

		ctx.Set("jwtInfo", loginInfo)

		ctx.Next()
	}
}
func CheckWebLogin(provider *account.AccountClientImpl) gin.HandlerFunc {

	return func(ctx *gin.Context) {
		startTime := time.Now()
		//如果没有登录
		authorization := ctx.GetHeader(e.Authorization)
		if authorization == "" {
			service.NotLoginRes(ctx, logic.ConvertLoginMsg(ctx, e.ErrNotLogin))
			return
		}

		jwt, err := secret.GetJwtFromStr(authorization)

		logger.Info("---------end帐号转jwt:时间:", time.Now().Sub(startTime))
		if err != nil {
			service.NotLoginRes(ctx, err.Error())
			return
		}

		//0 解密
		req := account.DecryptJwtRequest{
			Token:  jwt,
			Domain: "fontree",
		}

		info, err := service.AccountProvider.DecryptJwt(ctx, &req)
		logger.Info("---------end帐号微服务解密:时间:", time.Now().Sub(startTime))

		if err != nil {
			service.NotLoginRes(ctx, err.Error())
			return
		}

		//if info.OfflineCode == e.OfflineSqueeze {
		//	service.Error(ctx, e.NotLoginSqueeze, errors.New(e.ErrOfflineSqueeze))
		//	return
		//}

		if info.IsOffline == true {
			service.ErrorWeb(ctx, e.NotLogin, errors.New(logic.ConvertOfflineMsg(ctx, e.ErrOffline)))
			return
		}

		//1 获取用户的账号信息
		infoReq := &account.InfoRequest{
			ID:     info.ID,
			Scene:  "base",
			Domain: "fontree",
		}

		infoRes, err := service.AccountProvider.Info(ctx, infoReq)

		logger.Info("---------end帐号info时间:", time.Now().Sub(startTime))

		if err != nil {
			service.ErrorWeb(ctx, e.Error, err)
			return
		}

		//3 获取用户的岗位信息
		//uReq := rule.RulesRequest{
		//	AccountID: info.ID,
		//}
		//
		//qres, err1 := service.RuleProvider.UserInfo(ctx, &uReq)
		//
		//logger.Info("---------end帐号,rule的userInfo:时间:", time.Now().Sub(startTime))
		//if err1 != nil {
		//	service.Error(ctx, e.Error, err)
		//	return
		//}

		loginInfo := login.Info{
			Domain: info.Domain,
			ID:     info.ID,
			//Account:        info.Account,
			//NickName:       info.NickName,
			//PositionUsers:  qres.PositionUsers,
			//Extend:         infoRes.Info.Extend,
			TelNum: infoRes.Info.TelNum,
			//Avatar:         infoRes.Info.Avatar,
			//JumpTo:         "",
			//DepartmentName: "",
		}

		//if infoRes.Info.Extend != nil {
		//	loginInfo.JumpTo = infoRes.Info.Extend.JumpTo
		//}
		//
		//if len(qres.PositionUsers) >= 1 {
		//	loginInfo.DepartmentName = qres.PositionUsers[0].DepartmentName
		//}

		ctx.Set("jwtInfo", loginInfo)
		var mLoginInfo model.LoginInfo
		mLoginInfo.ID = loginInfo.ID
		mLoginInfo.NickName = loginInfo.Name
		mLoginInfo.Phone = loginInfo.TelNum
		//mLoginInfo.PositionUsers = qres.PositionUsers
		ctx.Set("mLoginInfo", mLoginInfo)
		logger.Info("---------check_login:总时间", time.Now().Sub(startTime))
		ctx.Next()

	}
}