package staff

import (
	"context"
	"errors"
	"regexp"
	"time"

	"bsm/full/module/ec/mall/internal/excode"
	"bsm/full/module/ec/mall/internal/impl"
	"bsm/full/module/ec/mall/internal/models"
	pb "bsm/full/module/ec/mall/pb"
	"git.apinb.com/bsm-sdk/core/crypto/encipher"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/utils"
	"git.apinb.com/bsm-sdk/core/vars"
	"gorm.io/gorm"
)

// Login 员工登录验证
func Login(ctx context.Context, in *pb.LoginRequest) (reply *pb.LoginReply, err error) {
	var record models.MallStaff

	// 根据登录类型进行不同的验证
	switch in.LoginGenre {
	case 1: // 账号密码登录
		if in.Account == "" || in.Password == "" {
			return nil, errcode.ErrInvalidArgument
		}
		err := impl.DBService.Where("account = ?", in.Account).First(&record).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return nil, errcode.ErrAccountNotFound
			}
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}
		// 密码校验 - 使用MD5加盐验证
		if record.Password != utils.Md5(in.Password+record.Salt) {
			return nil, errcode.ErrPassword
		}

	case 2: // 手机验证码登录
		if in.Phone == "" || in.VerifyCode == "" || ValidatePhone(in.Phone) != nil {
			return nil, errcode.ErrInvalidArgument
		}

		err := impl.DBService.Where("phone = ?", in.Phone).First(&record).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return nil, errcode.ErrAccountNotFound
			}
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}
		// TODO: 添加验证码校验逻辑

	default:
		return nil, errcode.ErrUnimplemented
	}

	// 账号状态校验
	if record.Status == models.DisabledStatus {
		return nil, errcode.ErrAccountDisabled
	}

	// 检查店铺是否正常运营
	var storeData = models.MallStore{}
	err = impl.DBService.Model(&models.MallStore{}).Where("id = ? AND status = 1", record.Store_ID).First(&storeData).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, excode.ErrStoreNotFound
		}
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	if storeData.Status == 0 {
		return nil, excode.ErrStoreDisabled
	}

	store := models.Std_Store{
		Store_ID:       record.Store_ID,
		Store_Identity: record.Store_Identity,
	}

	token, err := encipher.GenerateTokenAes(record.ID, record.Identity, "", record.Role, store, map[string]string{"role": record.Role})
	if err != nil {
		printer.Error(err.Error())
		return nil, err
	}

	// 更新登录时间
	record.LastLoginAt = time.Now()
	err = impl.DBService.Where("id = ?", record.ID).Select("last_login_at").Updates(record).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, err
	}

	return &pb.LoginReply{
		Token:         token,
		Identity:      record.Identity,
		Name:          record.Name,
		Account:       record.Account,
		Role:          record.Role,
		StoreName:     storeData.Title,
		StoreIdentity: storeData.Identity,
		Status:        int32(record.Status),
		CreatedAt:     record.CreatedAt.Format(vars.YYYY_MM_DD_HH_MM_SS),
	}, nil
}

// ValidatePhone 验证手机号格式
func ValidatePhone(phone string) error {
	// 中国大陆手机号验证：1开头，第二位为3-9，总共11位数字
	matched, err := regexp.MatchString("^1[3-9]\\d{9}$", phone)
	if err != nil || !matched {
		return errcode.ErrInvalidArgument
	}
	return nil
}
