package agency

import (
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"bsm/full/module/ec/market/internal/models"
	pb "bsm/full/module/ec/market/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 更新密码
func SetPassword(ctx context.Context, in *pb.SetPasswordRequest) (reply *pb.StatusReply, err error) {
	var (
		identity string
	)
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	identity = auth.Identity
	fmt.Println("identity:", auth.Identity)
	if in.GetIdentity() != "" {
		identity = in.GetIdentity()
	}
	if in.GetOldPassword() == "" || in.GetNewPassword() == "" {
		return nil, errcode.ErrInvalidArgument
	}
	// 获取当前角色数据
	mktModel := models.MarketAgency{}
	if err := models.DBService.Where("identity = ?", identity).First(&mktModel).Error; err != nil {
		log.Println("获取代理商数据失败：", err)
		return nil, err
	}

	// 判断旧密码是否匹配
	if utils.Md5(in.GetOldPassword()+mktModel.Salt) != mktModel.Password {
		return nil, errors.New("旧密码错误")
	}

	// 设置新密码
	newPwd := utils.Md5(in.GetNewPassword() + mktModel.Salt)
	if err := models.DBService.Model(&mktModel).Update("password", newPwd).Error; err != nil {
		log.Println("更新密码失败：", err)
		return nil, err
	}

	return &pb.StatusReply{
		Code:     0,
		Message:  "OK",
		Identity: identity,
		Timeseq:  time.Now().UnixMilli(),
	}, nil

}
