package model

import (
	model2 "cold-delivery/common/model"
	"errors"
	"fmt"
	coreModel "gogs.baozhida.cn/zoie/OAuth-core/model"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

var (
	UserTypeSys         = "sys"
	UserTypeCustomer    = "customer"
	SysUserTypeSys      = 1
	SysUserTypeStoreSys = 2
	SysUserTypeDriver   = 3
	SysUserTypeSalesman = 4
)

type SysUser struct {
	model2.Model
	coreModel.User
	Type       int         `json:"type" gorm:"size:128;comment:类型"` // 管理员1 门店管理员2 配送员3  4销售人员
	UserType   string      `json:"userType" gorm:"size:128;comment:用户类型"`
	Openid     string      `json:"openid" gorm:"size:128;comment:微信openid"`                // 微信openid
	Dept       SysDept     `json:"dept" gorm:"->"`                                         // 部门
	Role       SysRole     `json:"-" gorm:"-"`                                             // 角色
	CreateUser SysUserOmit `json:"createUser" gorm:"->;foreignkey:CreateBy;references:Id"` // 角色
	model2.ControlBy
	model2.ModelTime
}

func (SysUser) TableName() string {
	return "sys_user"
}
func (e *SysUser) Generate() model2.ActiveRecord {
	o := *e
	return &o
}

func (e *SysUser) GetId() interface{} {
	return e.Id
}

// 加密
func (e *SysUser) Encrypt() (err error) {
	if e.Password == "" {
		return
	}

	var hash []byte
	if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
		return
	} else {
		e.Password = string(hash)
		return
	}
}

var (
	ErrForbidUpdateSysUser = errors.New("禁止修改系统用户")
	ErrForbidDeleteSysUser = errors.New("禁止删除系统用户")
)

// HasPost 是否有岗位权限（替代旧 type 判断）
func (e *SysUser) HasPost() bool {
	return e.PostId > 0
}

func (e *SysUser) BeforeCreate(_ *gorm.DB) error {
	return e.Encrypt()
}

func (e *SysUser) BeforeUpdate(_ *gorm.DB) error {
	if e.Username == "admin" {
		return ErrForbidUpdateSysUser
	}
	var err error
	if e.Password != "" {
		err = e.Encrypt()
	}
	return err
}

func (e *SysUser) BeforeDelete(_ *gorm.DB) error {
	if e.Username == "admin" {
		return ErrForbidDeleteSysUser
	}
	return nil
}

func GetUserCacheKey(id int) string {
	return fmt.Sprintf("oauth:user:%d", id)
}

type SysUserOmit struct {
	Id       int    `json:"id,omitempty"`       // 主键编码
	NickName string `json:"nickName,omitempty"` // 昵称
	Phone    string `json:"phone,omitempty"`    // 昵称
}

func (SysUserOmit) TableName() string {
	return "sys_user"
}

type SysUserForBind struct {
	model2.Model
	coreModel.User
	Type     int    `json:"type" gorm:"size:128;comment:类型"`         // 管理员1 仓管2 司机3
	UserType string `json:"userType" gorm:"size:128;comment:用户类型"`   // 系统用户-sys 客户-customer
	Openid   string `json:"openid" gorm:"size:128;comment:微信openid"` // 微信openid
	IsBind   bool
	model2.ControlBy
	model2.ModelTime
}

func (SysUserForBind) TableName() string {
	return "sys_user"
}
