package middleware

import (
	"errors"
	"fmt"
	api "fonchain-fiee/api/account"
	jwt2 "fonchain-fiee/pkg/common/jwt"
	"fonchain-fiee/pkg/common/m"
	"fonchain-fiee/pkg/e"
	"fonchain-fiee/pkg/model/login"
	"fonchain-fiee/pkg/service"
	"github.com/gin-gonic/gin"
)

// CheckLogin 检测登陆
func CheckLogin(provider *api.AccountClientImpl) 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.AccountProvider.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()
	}
}
