package service

import (
	"fmt"
	"strings"
	"time"

	sysRoleModel "nms_nbi/features/sys_role/model"
	sysUserModel "nms_nbi/features/sys_user/model"
	"nms_nbi/lib/core/datasource"
	"nms_nbi/lib/core/utils/date"
	"nms_nbi/lib/core/utils/parse"
	"nms_nbi/lib/log"
	"nms_nbi/src/framework/utils/crypto"
)

// 实例化数据层 RepoSysUser 结构体
var NewRepoSysUser = &RepoSysUser{
	selectSql: `select u.id,
	u.account_id, u.name, u.sn, u.gender, u.description, u.telephone_number, u.mobile, u.email, 
	u.start_time, u.end_time, u.id_card_number, u.employee_number, 
	u.organize, u.employee_type, u.supporter_corp_name, u.real_name, u.password, u.password_sha512, 
	u.change_password_flag,u.password_expiration, u.status, u.user_expiration, u.group_name,
	u.profile, u.phone, u.create_time, u.update_time, u.unit,
	r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.status as role_status
	from user u 
	left join sys_user_role ur on u.id = ur.user_id
	left join sys_role r on r.role_id = ur.role_id`,

	sysUserMap: map[string]string{
		"id":                   "Id",
		"account_id":           "AccountId",
		"name":                 "Name",
		"sn":                   "Sn",
		"gender":               "Gender",
		"description":          "Description",
		"telephone_number":     "TelephoneNumber",
		"mobile":               "Mobile",
		"email":                "Email",
		"start_time":           "StartTime",
		"end_time":             "EndTime",
		"id_card_number":       "IdCardNumber",
		"employee_number":      "EmployeeNumber",
		"organize":             "Organize",
		"employee_type":        "EmployeeType",
		"supporter_corp_name":  "SupporterCorpName",
		"real_name":            "RealName",
		"password":             "Password",
		"password_sha512":      "PasswordSha512",
		"change_password_flag": "ChangePasswordFlag",
		"password_expiration":  "PasswordExpiration",
		"status":               "Status",
		"user_expiration":      "UserExpiration",
		"group_name":           "GroupName",
		"profile":              "Profile",
		"phone":                "Phone",
		"create_time":          "CreateTime",
		"update_time":          "UpdateTime",
		"unit":                 "Unit",
	},

	sysRoleMap: map[string]string{
		"role_id":     "RoleID",
		"role_name":   "RoleName",
		"role_key":    "RoleKey",
		"role_sort":   "RoleSort",
		"data_scope":  "DataScope",
		"role_status": "Status",
	},
}

// RepoSysUser 用户表 数据层处理
type RepoSysUser struct {
	// 查询视图对象SQL
	selectSql string
	// 用户信息实体映射
	sysUserMap map[string]string
	// 用户角色实体映射 一对多
	sysRoleMap map[string]string
}

// convertResultRows 将结果记录转实体结果组
func (r *RepoSysUser) convertResultRows(rows []map[string]any) []sysUserModel.SysUser {
	arr := make([]sysUserModel.SysUser, 0)

	for _, row := range rows {
		sysUser := sysUserModel.SysUser{}
		sysRole := sysRoleModel.SysRole{}
		sysUser.Roles = []sysRoleModel.SysRole{}

		for key, value := range row {
			if keyMapper, ok := r.sysUserMap[key]; ok {
				datasource.SetFieldValue(&sysUser, keyMapper, value)
			}
			if keyMapper, ok := r.sysRoleMap[key]; ok {
				datasource.SetFieldValue(&sysRole, keyMapper, value)
			}
		}

		if sysRole.RoleKey != "" {
			sysUser.Roles = append(sysUser.Roles, sysRole)
		}

		one := true
		for i, a := range arr {
			if a.Id == sysUser.Id {
				arrUser := &arr[i]
				arrUser.Roles = append(arrUser.Roles, sysUser.Roles...)
				one = false
				break
			}
		}
		if one {
			arr = append(arr, sysUser)
		}
	}

	return arr
}

// SelectUserPage 根据条件分页查询用户列表
func (r *RepoSysUser) SelectUserPage(query map[string]any) map[string]any {
	selectUserSql := `select u.id,
	u.account_id, u.name, u.sn, u.gender, u.description, u.telephone_number, u.mobile, u.email, 
	u.start_time, u.end_time, u.id_card_number, u.employee_number, 
	u.organize, u.employee_type, u.supporter_corp_name, u.real_name, 
	u.change_password_flag,u.password_expiration, u.status, u.user_expiration, u.group_name,
	u.profile, u.phone, u.create_time, u.update_time, u.unit
	from user u`
	selectUserTotalSql := `select count(distinct u.id) as 'total' from user u`

	// 查询条件拼接
	var conditions []string
	var params []any
	if v, ok := query["accountId"]; ok && v != "" {
		conditions = append(conditions, "u.account_id = ?")
		params = append(params, v)
	}
	if v, ok := query["name"]; ok && v != "" {
		conditions = append(conditions, "u.name concat('%', concat(?, '%'))")
		params = append(params, v)
	}
	if v, ok := query["status"]; ok && v != "" {
		conditions = append(conditions, "u.status = ?")
		params = append(params, v)
	}
	if v, ok := query["phonenumber"]; ok && v != "" {
		conditions = append(conditions, "u.phonenumber like concat('%', concat(?, '%'))")
		params = append(params, v)
	}
	beginTime, ok := query["beginTime"]
	if !ok {
		beginTime, ok = query["params[beginTime]"]
	}
	if ok && beginTime != "" {
		conditions = append(conditions, "u.login_date >= ?")
		beginDate := date.ParseStrToDate(beginTime.(string), date.YYYY_MM_DD)
		params = append(params, beginDate.UnixMilli())
	}
	endTime, ok := query["endTime"]
	if !ok {
		endTime, ok = query["params[endTime]"]
	}
	if ok && endTime != "" {
		conditions = append(conditions, "u.login_date <= ?")
		endDate := date.ParseStrToDate(endTime.(string), date.YYYY_MM_DD)
		params = append(params, endDate.UnixMilli())
	}
	if v, ok := query["deptId"]; ok && v != "" {
		conditions = append(conditions, "(u.dept_id = ? or u.dept_id in ( select t.dept_id from sys_dept t where find_in_set(?, ancestors) ))")
		params = append(params, v)
		params = append(params, v)
	}

	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}

	// 查询数量 长度为0直接返回
	totalSql := selectUserTotalSql + whereSql
	totalRows, err := datasource.RawDB("", totalSql, params)
	if err != nil {
		log.Errorf("total err => %v", err)
	}
	total := parse.Number(totalRows[0]["total"])
	if total == 0 {
		return map[string]any{
			"total": total,
			"rows":  []sysUserModel.SysUser{},
		}
	}

	// 分页
	pageNum, pageSize := datasource.PageNumSize(query["pageNum"], query["pageSize"])
	pageSql := " limit ?,? "
	params = append(params, pageNum*pageSize)
	params = append(params, pageSize)

	// 查询数据
	querySql := selectUserSql + whereSql + pageSql
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		log.Errorf("query err => %v", err)
	}

	// 转换实体
	rows := r.convertResultRows(results)
	return map[string]any{
		"total": total,
		"rows":  rows,
	}
}

// SelectAllocatedPage 根据条件分页查询分配用户角色列表
func (r *RepoSysUser) SelectAllocatedPage(query map[string]any) map[string]any {
	// 查询条件拼接
	var conditions []string
	var params []any
	if v, ok := query["name"]; ok && v != "" {
		conditions = append(conditions, "u.name like concat('%', concat(?, '%'))")
		params = append(params, v)
	}
	if v, ok := query["phone"]; ok && v != "" {
		conditions = append(conditions, "u.phone like concat('%', concat(?, '%'))")
		params = append(params, v)
	}
	if v, ok := query["status"]; ok && v != "" {
		conditions = append(conditions, "u.status = ?")
		params = append(params, v)
	}
	// 分配角色用户
	if allocated, ok := query["allocated"]; ok && allocated != "" {
		if roleId, ok := query["roleId"]; ok && roleId != "" {
			if parse.Boolean(allocated) {
				conditions = append(conditions, "r.role_id = ?")
				params = append(params, roleId)
			} else {
				conditions = append(conditions, `(r.role_id != ? or r.role_id IS NULL) 
				and u.id not in (
					select u.id from user u 
					inner join sys_user_role ur on u.id = ur.user_id 
					and ur.role_id = ?
				)`)
				params = append(params, roleId)
				params = append(params, roleId)
			}

		}
	}

	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}

	// 查询数量 长度为0直接返回
	totalSql := `select count(distinct u.id) as 'total' from user u
    left join sys_user_role ur on u.id = ur.user_id
    left join sys_role r on r.role_id = ur.role_id`
	totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
	if err != nil {
		log.Errorf("total err => %v", err)
	}
	total := parse.Number(totalRows[0]["total"])
	if total == 0 {
		return map[string]any{
			"total": total,
			"rows":  []sysUserModel.SysUser{},
		}
	}

	// 分页
	pageNum, pageSize := datasource.PageNumSize(query["pageNum"], query["pageSize"])
	pageSql := " limit ?,? "
	params = append(params, pageNum*pageSize)
	params = append(params, pageSize)

	// 查询数据
	querySql := `select distinct 
    u.id, u.account_id, u.name, u.gender, u.email, 
    u.phone, u.status, u.create_time, u.real_name
    from user u
    left join sys_user_role ur on u.id = ur.user_id
    left join sys_role r on r.role_id = ur.role_id`
	querySql = querySql + whereSql + pageSql
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		log.Errorf("query err => %v", err)
	}

	// 转换实体
	rows := r.convertResultRows(results)
	return map[string]any{
		"total": total,
		"rows":  rows,
	}
}

// SelectUserList 根据条件查询用户列表
func (r *RepoSysUser) SelectUserList(sysUser sysUserModel.SysUser, dataScopeSQL string) []sysUserModel.SysUser {
	selectUserSql := `select 
    u.id, u.account_id, u.name, u.real_name, u.email, u.gender, u.phone, u.create_time, u.status, u.description 
    from user u`

	// 查询条件拼接
	var conditions []string
	var params []any
	if sysUser.AccountId != "" {
		conditions = append(conditions, "u.account_id = ?")
		params = append(params, sysUser.AccountId)
	}
	if sysUser.Name != "" {
		conditions = append(conditions, "u.name like concat('%', concat(?, '%'))")
		params = append(params, sysUser.Name)
	}
	if sysUser.Status != "" {
		conditions = append(conditions, "u.status = ?")
		params = append(params, sysUser.Status)
	}
	if sysUser.Phone != "" {
		conditions = append(conditions, "u.phone like concat('%', concat(?, '%'))")
		params = append(params, sysUser.Phone)
	}

	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	}

	// 查询数据
	querySql := selectUserSql + whereSql + dataScopeSQL
	rows, err := datasource.RawDB("", querySql, params)
	if err != nil {
		log.Errorf("query err => %v", err)
		return []sysUserModel.SysUser{}
	}
	return r.convertResultRows(rows)
}

// SelectUserByIds 通过用户ID查询用户
func (r *RepoSysUser) SelectUserByIds(userIds []string) []sysUserModel.SysUser {
	placeholder := datasource.KeyPlaceholderByQuery(len(userIds))
	querySql := r.selectSql + " where u.id in (" + placeholder + ")"
	parameters := datasource.ConvertIdsSlice(userIds)
	results, err := datasource.RawDB("", querySql, parameters)
	if err != nil {
		log.Errorf("query err => %v", err)
		return []sysUserModel.SysUser{}
	}
	// 转换实体
	return r.convertResultRows(results)
}

// SelectUserByUserName 通过用户登录账号查询用户
func (r *RepoSysUser) SelectUserByUserName(userName string) sysUserModel.SysUser {
	querySql := r.selectSql + " where u.name = ?"
	results, err := datasource.RawDB("", querySql, []any{userName})
	if err != nil {
		log.Errorf("query err => %v", err)
		return sysUserModel.SysUser{}
	}
	// 转换实体
	rows := r.convertResultRows(results)
	if len(rows) > 0 {
		return rows[0]
	}
	return sysUserModel.SysUser{}
}

// InsertUser 新增用户信息
func (r *RepoSysUser) InsertUser(sysUser sysUserModel.SysUser) string {
	// 参数拼接
	params := make(map[string]any)
	if sysUser.AccountId != "" {
		params["account_id"] = sysUser.AccountId
	}
	if sysUser.Name != "" {
		params["name"] = sysUser.Name
	}
	if sysUser.Sn != "" {
		params["sn"] = sysUser.Sn
	} else {
		params["sn"] = ""
	}
	if sysUser.RealName != "" {
		params["real_name"] = sysUser.RealName
	} else {
		params["real_name"] = ""
	}
	if sysUser.Gender != "" {
		params["gender"] = sysUser.Gender
	}
	if sysUser.Email != "" {
		params["email"] = sysUser.Email
	} else {
		params["email"] = ""
	}
	if sysUser.Phone != "" {
		params["phone"] = sysUser.Phone
	} else {
		params["phone"] = ""
	}
	if sysUser.Unit != "" {
		params["unit"] = sysUser.Unit
	} else {
		params["unit"] = ""
	}

	if sysUser.Organize != "" {
		params["organize"] = sysUser.Organize
	}
	if sysUser.Password != "" {
		password := crypto.BcryptHash(sysUser.Password)
		params["password"] = password
	}
	if sysUser.Status != "" {
		params["status"] = sysUser.Status
	}
	if sysUser.PasswordExpiration != "" {
		params["password_expiration"] = sysUser.PasswordExpiration
	}
	if sysUser.UserExpiration != "" {
		params["user_expiration"] = sysUser.UserExpiration
	}
	if sysUser.GroupName != "" {
		params["group_name"] = sysUser.GroupName
	}
	params["create_time"] = time.Now()

	// 构建执行语句
	keys, placeholder, values := datasource.KeyPlaceholderValueByInsert(params)
	sql := "insert into user (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"

	// 执行插入
	results, err := datasource.ExecDB("", sql, values)
	if err != nil {
		log.Errorf("insert row : %v", err.Error())
		return ""
	}
	insertId, err := results.LastInsertId()
	if err != nil {
		log.Errorf("insert row : %v", err.Error())
		return ""
	}
	return fmt.Sprint(insertId)
}

// UpdateUser 修改用户信息
func (r *RepoSysUser) UpdateUser(sysUser sysUserModel.SysUser) int64 {
	// 参数拼接
	params := make(map[string]any)
	if sysUser.Name != "" {
		params["name"] = sysUser.Name
	}
	if sysUser.Sn != "" {
		params["sn"] = sysUser.Sn
	} else {
		params["sn"] = ""
	}
	if sysUser.RealName != "" {
		params["real_name"] = sysUser.RealName
	} else {
		params["real_name"] = ""
	}
	if sysUser.Gender != "" {
		params["gender"] = sysUser.Gender
	}
	if sysUser.Email != "" {
		params["email"] = sysUser.Email
	} else {
		params["email"] = ""
	}
	if sysUser.Phone != "" {
		params["phone"] = sysUser.Phone
	} else {
		params["phone"] = ""
	}
	if sysUser.Unit != "" {
		params["unit"] = sysUser.Unit
	} else {
		params["unit"] = ""
	}

	if sysUser.Organize != "" {
		params["organize"] = sysUser.Organize
	}
	if sysUser.Password != "" {
		password := crypto.BcryptHash(sysUser.Password)
		params["password"] = password
	}
	if sysUser.Status != "" {
		params["status"] = sysUser.Status
	}
	if sysUser.PasswordExpiration != "" {
		params["password_expiration"] = sysUser.PasswordExpiration
	}
	if sysUser.UserExpiration != "" {
		params["user_expiration"] = sysUser.UserExpiration
	}
	if sysUser.GroupName != "" {
		params["group_name"] = sysUser.GroupName
	}
	params["update_time"] = time.Now()

	// 构建执行语句
	keys, values := datasource.KeyValueByUpdate(params)
	sql := "update user set " + strings.Join(keys, ",") + " where id = ?"

	// 执行更新
	values = append(values, sysUser.Id)
	results, err := datasource.ExecDB("", sql, values)
	if err != nil {
		log.Errorf("update row : %v", err.Error())
		return 0
	}
	affected, err := results.RowsAffected()
	if err != nil {
		log.Errorf("update err => %v", err)
		return 0
	}
	return affected
}

// DeleteUserByIds 批量删除用户信息
func (r *RepoSysUser) DeleteUserByIds(userIds []string) int64 {
	placeholder := datasource.KeyPlaceholderByQuery(len(userIds))
	sql := "delete from user where id in (" + placeholder + ")"
	parameters := datasource.ConvertIdsSlice(userIds)
	results, err := datasource.ExecDB("", sql, parameters)
	if err != nil {
		log.Errorf("delete err => %v", err)
		return 0
	}
	affected, err := results.RowsAffected()
	if err != nil {
		log.Errorf("delete err => %v", err)
		return 0
	}
	return affected
}

// CheckUniqueUser 校验用户信息是否唯一
func (r *RepoSysUser) CheckUniqueUser(sysUser sysUserModel.SysUser) string {
	// 查询条件拼接
	var conditions []string
	var params []any
	if sysUser.Name != "" {
		conditions = append(conditions, "name = ?")
		params = append(params, sysUser.Name)
	}
	if sysUser.AccountId != "" {
		conditions = append(conditions, "account_id = ?")
		params = append(params, sysUser.AccountId)
	}

	// 构建查询条件语句
	whereSql := ""
	if len(conditions) > 0 {
		whereSql += " where " + strings.Join(conditions, " and ")
	} else {
		return ""
	}

	// 查询数据
	querySql := "select id as 'str' from user " + whereSql + " limit 1"
	results, err := datasource.RawDB("", querySql, params)
	if err != nil {
		log.Errorf("query err %v", err)
	}
	if len(results) > 0 {
		return fmt.Sprint(results[0]["str"])
	}
	return ""
}
