package user

import (
	"errors"

	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/libs"
	"bsm/full/module/base/mgt/internal/models"
	"bsm/full/module/base/mgt/internal/types"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/printer"
	coreTypes "git.apinb.com/bsm-sdk/core/types"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Midify(c *gin.Context) {
	var (
		request = types.UserRequest{}
		user    = models.MgtUser{}
	)

	err := c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}
	request.PassWord = ""

	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.ID == 0 {
		printer.Error("更新用户参数异常: ID不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.Account != "" {
		if err := impl.DBService.Model(&models.MgtUser{}).Where("account = ? and id <>?", request.Account, request.ID).First(&user).Error; err != nil {
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				infra.Response.Error(c, errcode.ErrDB)
				return
			}
		}
		if user.ID != 0 {
			printer.Info("账号已被使用: account=%s", request.Account)
			infra.Response.Error(c, errcode.ErrAlreadyExists)
			return
		}
	}

	var userModel = models.MgtUser{
		Name:       request.Name,
		Phone:      request.Phone,
		Email:      request.Email,
		Avatar:     request.Avatar,
		Std_IICUDS: coreTypes.Std_IICUDS{Status: request.Status},
	}
	updateFields := []string{"name", "phone", "email", "avatar", "status"}
	if request.Account != "" {
		userModel.Account = request.Account
		updateFields = append(updateFields, "account")
	}
	if err := impl.DBService.Model(&models.MgtUser{}).Where("id = ?", request.ID).Select(updateFields).Updates(&userModel).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	printer.Info("用户更新成功: ID=%d", request.ID)
	infra.Response.Success(c, types.IdResp{Id: request.ID, Identity: userModel.Identity})
}
