package system

import (
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
)

type LoginReq struct {
	Username   string `description:"账号"`
	Password   string `description:"密码"`
	IsRemember bool   `description:"是否属于受信设备"`
}

type LoginResp struct {
	Authorization   string
	AdminName       string `description:"系统用户名称"`
	RealName        string `description:"系统用户姓名"`
	RoleName        string `description:"角色名称"`
	RoleTypeCode    string `description:"角色类型编码"`
	SysRoleTypeCode string `description:"角色类型编码"`
	AdminId         int    `description:"系统用户id"`
	ProductName     string `description:"产品名称：admin,ficc,权益"`
	Authority       int    `description:"管理权限，0：无，1：部门负责人，2：小组负责人,或者ficc销售主管，4:ficc销售组长"`
	DepartmentName  string `description:"部门名称"`
	GroupName       string `description:"分组名称"`
}

type Admin struct {
	AdminId                   int    `orm:"column(admin_id);pk" description:"系统用户id"`
	AdminName                 string `description:"系统用户名称"`
	AdminAvatar               string `description:"用户头像"`
	RealName                  string `description:"系统用户姓名"`
	Password                  string `json:"-"`
	LastUpdatedPasswordTime   string `json:"-"`
	Enabled                   int
	Email                     string `description:"系统用户邮箱"`
	LastLoginTime             string
	CreatedTime               time.Time
	LastUpdatedTime           string
	Role                      string    `description:"系统用户角色"`
	Mobile                    string    `description:"手机号"`
	RoleType                  int       `description:"角色类型:1需要录入指标,0:不需要"`
	RoleId                    int       `description:"角色ID"`
	RoleName                  string    `description:"角色名称"`
	RoleTypeCode              string    `description:"角色类型编码"`
	DepartmentId              int       `description:"部门id"`
	DepartmentName            string    `description:"部门名称"`
	GroupId                   int       `description:"分组id"`
	GroupName                 string    `description:"分组名称"`
	Authority                 int       `description:"管理权限，0：无，1：部门负责人，2：小组负责人,或者ficc销售主管，3：超级管理员，4:ficc销售组长"`
	Position                  string    `description:"职位"`
	DisableTime               time.Time `description:"禁用时间"`
	ChartPermission           int8      `description:"图表权限id"`
	OpenId                    string    `description:"弘则部门公众号的openid"`
	UnionId                   string    `description:"微信公众平台唯一标识"`
	EdbPermission             int8      `description:"指标库操作权限，0：只能操作 自己的，1：所有指标可操作"`
	MysteelChemicalPermission int8      `description:"上海钢联指标操作权限，0：只能操作 自己的，1：所有指标可操作"`
	PredictEdbPermission      int8      `description:"预测指标库操作权限，0：只能操作 自己的，1：所有预测指标可操作"`
	Province                  string    `description:"省"`
	ProvinceCode              string    `description:"省编码"`
	City                      string    `description:"市"`
	CityCode                  string    `description:"市编码"`
	EmployeeId                string    `description:"员工工号(钉钉/每刻报销)"`
	TelAreaCode               string    `description:"手机区号"`
	IsLdap                    int       `description:"是否为域用户：0-系统账户；1-域用户"`
}

// Update 更新用户基础信息
func (item *Admin) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(item, cols...)
	return
}

func CheckSysUser(userName, password string) (item *Admin, err error) {
	sql := ` SELECT a.*,b.role_type_code FROM admin AS a
			 INNER JOIN sys_role AS b ON a.role_id=b.role_id WHERE a.admin_name=? AND a.password=? LIMIT 1`
	o := orm.NewOrm()
	err = o.Raw(sql, userName, password).QueryRow(&item)
	return
}

func GetSysUserById(sysUserId int) (item *Admin, err error) {
	sql := `SELECT * FROM admin WHERE admin_id=? LIMIT 1`
	o := orm.NewOrm()
	err = o.Raw(sql, sysUserId).QueryRow(&item)
	return
}

func ModifyPwd(sysUserId int, newPwd string) (err error) {
	sql := `UPDATE admin SET password=?,last_updated_time=NOW() WHERE admin_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, newPwd, sysUserId).Exec()
	return
}

type ModifyPwdReq struct {
	OldPwd string `description:"旧密码"`
	NewPwd string `description:"新密码"`
}

// AdminWxUserRelation 管理员-微信用户关联
type AdminWxUserRelation struct {
	AdminId   int    `json:"admin_id"`
	AdminName string `json:"admin_name"`
	RealName  string `json:"real_name"`
	UserId    int    `json:"user_id"`
}

// GetAdminListByIdList 根据用户id列表获取系统用户列表
func GetAdminListByIdList(idList []int) (items []*Admin, err error) {
	lenNum := len(idList)
	if lenNum <= 0 {
		return
	}
	sql := `SELECT * FROM admin WHERE admin_id in (` + utils.GetOrmInReplace(lenNum) + `) and enabled=1 `
	o := orm.NewOrm()
	_, err = o.Raw(sql, idList).QueryRows(&items)
	return
}

// GetAdminListByIdList 根据用户id列表获取系统用户列表
func GetAdminListByIdListWithoutEnable(idList []int) (items []*Admin, err error) {
	lenNum := len(idList)
	if lenNum <= 0 {
		return
	}
	sql := `SELECT * FROM admin WHERE admin_id in (` + utils.GetOrmInReplace(lenNum) + `) `
	o := orm.NewOrm()
	_, err = o.Raw(sql, idList).QueryRows(&items)
	return
}

func (item *Admin) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM admin WHERE 1=1 %s`, condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (item *Admin) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*Admin, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY created_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM admin WHERE 1=1 %s %s`, fields, condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

// GetSysUserByMobile 手机号获取用户
func GetSysUserByMobile(mobile string) (item *Admin, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				a.*, b.role_type_code
			FROM
				admin AS a
			INNER JOIN sys_role AS b ON a.role_id = b.role_id
			WHERE
				a.mobile = ?
			LIMIT 1`
	err = o.Raw(sql, mobile).QueryRow(&item)
	return
}

// GetSysUserByEmail 邮箱获取用户
func GetSysUserByEmail(email string) (item *Admin, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				a.*, b.role_type_code
			FROM
				admin AS a
			INNER JOIN sys_role AS b ON a.role_id = b.role_id
			WHERE
				a.email = ?
			LIMIT 1`
	err = o.Raw(sql, email).QueryRow(&item)
	return
}

// GetSysUserByAdminName 账号获取用户
func GetSysUserByAdminName(adminName string) (item *Admin, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				a.*, b.role_type_code
			FROM
				admin AS a
			INNER JOIN sys_role AS b ON a.role_id = b.role_id
			WHERE
				a.admin_name = ?
			LIMIT 1`
	err = o.Raw(sql, adminName).QueryRow(&item)
	return
}
