package controllers

import (
	"encoding/base64"
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/company"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/system"
	"eta/eta_api/services"
	etaTrialService "eta/eta_api/services/eta_trial"
	"eta/eta_api/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

// 系统用户
type SysAdminController struct {
	BaseAuthController
}

// @Title 根据分组或者部门获取系统用户列表
// @Description 根据分组或者部门获取系统用户列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   DepartmentId   query   int  true       "部门ID"
// @Param   GroupId   query   int  true       "分组ID"
// @Param   TeamId   query   int  true       "小组ID"
// @Param   RoleId   query   int  true       "角色ID"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} system.SysuserListResp
// @router /sysuser/list [get]
func (this *SysAdminController) ListSysuser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	departmentId, _ := this.GetInt("DepartmentId")
	groupId, _ := this.GetInt("GroupId")
	teamId, _ := this.GetInt("TeamId")
	roleId, _ := this.GetInt("RoleId")
	keyWord := this.GetString("KeyWord")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	if departmentId > 0 {
		condition += ` AND department_id=? `
		pars = append(pars, departmentId)
	}

	if roleId > 0 {
		condition += ` AND role_id=? `
		pars = append(pars, roleId)
	}

	if keyWord != "" {
		condition += ` AND (real_name LIKE '%` + keyWord + `%' OR admin_name LIKE '%` + keyWord + `%' OR mobile LIKE '%` + keyWord + `%' )  `
	}

	var total int
	var err error
	if teamId <= 0 {
		if groupId > 0 {
			ids, err := system.GetGroupIdByParentId(groupId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			sGroupId := strconv.Itoa(groupId)
			ids = append(ids, &sGroupId)
			var idList []string
			for _, id := range ids {
				idList = append(idList, *id)
			}
			sid := strings.Join(idList, ",")

			condition += ` AND group_id IN (` + sid + `) `
		}
		total, err = system.GetSysuserListCount(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	} else {
		nCondition := condition + ` AND group_id=? `
		nPars := append(pars, teamId)
		total, err = system.GetSysuserListCount(nCondition, nPars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	}

	var list []*system.AdminItem
	adminIdArr := make([]int, 0)
	if teamId <= 0 {
		//if groupId > 0 {
		//	ids, err := system.GetGroupIdByParentId(groupId, startSize, pageSize)
		//	if err != nil {
		//		br.Msg = "获取失败"
		//		br.ErrMsg = "获取失败，Err:" + err.Error()
		//		return
		//	}
		//	sGroupId := strconv.Itoa(groupId)
		//	ids = append(ids, &sGroupId)
		//	var idList []string
		//	for _, id := range ids {
		//		idList = append(idList, *id)
		//	}
		//	sid := strings.Join(idList,",")
		//
		//	condition += ` AND group_id IN (` + sid + `) `
		//}
		list, err = system.GetSysuserList(condition, pars, startSize, pageSize)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		lenList := len(list)
		for i := 0; i < lenList; i++ {

			item := list[i]
			//adminIdArr = append(adminIdArr, strconv.Itoa(item.AdminId))
			adminIdArr = append(adminIdArr, item.AdminId)
			var secondName *string
			if item.GroupId != 0 {
				pid, err := company.GetParentIdFromGroup(item.GroupId)
				if err != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "查询父级id异常" + err.Error()
					return
				}

				if pid != nil && *pid != 0 {
					secondName, err = company.GetGroupNamesById(*pid)
					if err != nil {
						br.Msg = "获取失败"
						br.ErrMsg = "查询二级组名异常" + err.Error()
						return
					}
				}

				if *pid > 0 {
					list[i].TeamId = list[i].GroupId
					list[i].GroupId = *pid
				}
			}

			if item.DepartmentName != "" {
				if item.GroupName == "" {
					list[i].DepartmentGroup = item.DepartmentName
				} else if secondName != nil {
					list[i].DepartmentGroup = item.DepartmentName + "/" + *secondName + "/" + item.GroupName
				} else {
					list[i].DepartmentGroup = item.DepartmentName + "/" + item.GroupName
				}
			}
			labelVal := 0
			fmt.Println("item.RoleTypeCode:", item.RoleTypeCode)
			fmt.Println("item.Authority:", item.Authority)
			if item.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
				labelVal = 1
			} else if item.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
				item.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
				labelVal = 2
			} else {
				if item.Authority == 1 {
					labelVal = 3
				} else if item.Authority == 2 && item.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
					labelVal = 4
				} else if item.Authority == 2 && item.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
					labelVal = 5
				} else if item.Authority == 4 {
					labelVal = 4
				}
			}
			list[i].LabelVal = labelVal
		}
	} else {
		condition += ` AND group_id=? `
		pars = append(pars, teamId)
		list, err = system.GetSysuserList(condition, pars, startSize, pageSize)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		groupItem, err := system.GetSysGroupById(groupId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		lenList := len(list)
		for i := 0; i < lenList; i++ {
			item := list[i]
			//adminIdArr = append(adminIdArr, strconv.Itoa(item.AdminId))
			adminIdArr = append(adminIdArr, item.AdminId)

			if item.DepartmentName != "" {
				if item.GroupName == "" {
					list[i].DepartmentGroup = item.DepartmentName
				} else if item.GroupName != "" {
					list[i].DepartmentGroup = item.DepartmentName + "/" + groupItem.GroupName + "/" + item.GroupName
				} else {
					list[i].DepartmentGroup = item.DepartmentName + "/" + item.GroupName
				}
			}
			labelVal := 0
			if item.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
				labelVal = 1
			} else if item.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
				item.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
				labelVal = 2
			} else {
				if item.Authority == 1 {
					labelVal = 3
				} else if item.Authority == 2 && item.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
					labelVal = 4
				} else if item.Authority == 2 && item.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
					labelVal = 5
				} else if item.Authority == 4 {
					labelVal = 4
				}
			}
			list[i].LabelVal = labelVal
		}
	}
	//if teamId > 0 {
	//	var groupIdSlice []string
	//	var groupIds string
	//	for _, item := range list {
	//		groupIdSlice = append(groupIdSlice, strconv.Itoa(groupId))
	//	}
	//	groupIds = strings.Join(groupIdSlice, ",")
	//	fmt.Println("groupIds:", groupIds)
	//}
	if teamId > 0 {
		for _, item := range list {
			item.TeamId = teamId
			item.GroupId = groupId
		}
	}
	// 研究方向分组
	if len(adminIdArr) > 0 && utils.BusinessCode == utils.BusinessCodeRelease {
		//adminIds := strings.Join(adminIdArr, ",")
		//researchGroupList, e := system.GetAdminResearchGroupListByAdminId(adminIds)
		researchGroupList, e := models.GetAdminVarietyTagRelationListByAdminId(adminIdArr)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取研究方向分组列表失败, Err:" + e.Error()
			return
		}
		researchGroupAdminIdName := make(map[int]string, 0)
		for _, g := range researchGroupList {
			researchGroupAdminIdName[g.AdminId] = g.GroupNameStr
		}
		for _, v := range list {
			v.ResearchGroupName = researchGroupAdminIdName[v.AdminId]
		}
	}

	fmt.Println("teamId:", teamId)
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(system.SysuserListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Add
// @Title 新增系统用户
// @Description 新增系统用户接口
// @Param	request	body system.SysuserAddReq true "type json string"
// @Success 200 新增成功
// @router /sysuser/add [post]
func (this *SysAdminController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysuserAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RoleId <= 0 {
		br.Msg = "请选择角色"
		br.ErrMsg = "角色ID小于等于0"
		return
	}

	count, err := system.GetSysAdminCount(req.AdminName)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败"
		return
	}
	if count > 0 {
		br.Msg = "账号已存在,请重新输入"
		br.IsSendEmail = false
		return
	}

	// 手机号和邮箱必填一个
	req.Mobile = strings.TrimSpace(req.Mobile)
	req.Email = strings.TrimSpace(req.Email)
	if req.Mobile == "" && req.Email == "" {
		br.Msg = "至少输入一个手机号或邮箱"
		return
	}
	if req.Mobile != "" {
		if req.TelAreaCode == "86" {
			if !utils.ValidateMobileFormatat(req.Mobile) {
				br.Msg = "手机号格式有误, 请检查"
				return
			}
		}

		mobileCount, err := system.GetSysAdminCountByMobile(req.Mobile, 0)
		if err != nil {
			br.Msg = "判断手机号是否存在失败"
			br.ErrMsg = "判断手机号是否存在失败，Err:" + err.Error()
			return
		}
		if mobileCount > 0 {
			br.Msg = "手机号已存在，请重新填写"
			br.IsSendEmail = false
			return
		}
	}
	if req.Email != "" {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "邮箱格式有误, 请检查"
			return
		}
		_, e := system.GetSysUserByEmail(req.Email)
		if e.Error() != utils.ErrNoRow() {
			br.Msg = "邮箱已存在, 请重新填写"
			return
		}
	}

	var roleName, departmentName, groupName, teamName string

	roleItem, err := system.GetSysRoleById(req.RoleId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "所选角色不存在"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取角色数据失败，Err:" + err.Error()
		return
	}
	if roleItem != nil {
		roleName = roleItem.RoleName
	}
	if req.DepartmentId > 0 {
		departmentItem, err := system.GetSysDepartmentById(req.DepartmentId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "所选部门不存在"
				return
			}
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取部门数据失败，Err:" + err.Error()
			return
		}
		if departmentItem != nil {
			departmentName = departmentItem.DepartmentName
		}
	}

	if req.GroupId > 0 {
		groupItem, err := system.GetSysGroupById(req.GroupId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "所选分组不存在"
				return
			}
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取分组数据失败，Err:" + err.Error()
			return
		}
		if groupItem != nil {
			groupName = groupItem.GroupName
		}
	}

	if req.TeamId > 0 {
		teamItem, err := system.GetSysGroupById(req.TeamId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "所选小组不存在"
				return
			}
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取小组数据失败，Err:" + err.Error()
			return
		}
		if teamItem != nil {
			teamName = teamItem.GroupName
		}
	}

	pwdByte, err := base64.StdEncoding.DecodeString(req.Password)
	if err != nil {
		br.Msg = "解析数据失败"
		br.ErrMsg = "解析数据失败，Err:" + err.Error()
		return
	}
	pwdStr := string(pwdByte)
	//pwdStr = strings.ToLower(pwdStr)
	if pwdStr == "" {
		br.Msg = "请输入密码"
		return
	}
	if !utils.CheckPwd(pwdStr) {
		br.Msg = "密码格式错误，请重新输入"
		return
	}

	// 员工工号
	req.EmployeeId = strings.TrimSpace(req.EmployeeId)

	admin := new(system.Admin)
	admin.AdminName = req.AdminName
	admin.RealName = req.RealName
	admin.Password = utils.MD5(pwdStr)
	admin.LastUpdatedPasswordTime = time.Now().Format(utils.FormatDateTime)
	admin.Enabled = 1
	admin.LastLoginTime = time.Now().Format(utils.FormatDateTime)
	admin.CreatedTime = time.Now()
	admin.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
	admin.Mobile = req.Mobile
	admin.RoleType = 0
	admin.RoleId = req.RoleId
	admin.RoleName = roleName
	admin.RoleTypeCode = roleItem.RoleTypeCode
	admin.DepartmentId = req.DepartmentId
	admin.DepartmentName = departmentName
	admin.AdminAvatar = req.AdminAvatar
	if req.TeamId <= 0 {
		admin.GroupId = req.GroupId
		admin.GroupName = groupName
	} else {
		admin.GroupId = req.TeamId
		admin.GroupName = teamName
	}
	if strings.Contains(admin.RoleTypeCode, "researcher") {
		admin.Role = "researcher"
	} else if strings.Contains(admin.RoleTypeCode, "seller") {
		admin.Role = "sales"
	} else {
		admin.Role = "admin"
	}
	admin.EmployeeId = req.EmployeeId
	admin.Email = req.Email

	var authority int
	if roleItem.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		authority = 3
	} else if roleItem.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
		authority = 4
	} else if roleItem.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		authority = 2
	} else {
		if strings.Contains(roleItem.RoleType, "销售主管") {
			authority = 2
		} else if strings.Contains(roleItem.RoleType, "部门经理") {
			authority = 1
		} else {
			authority = 0
		}
	}
	admin.Authority = authority
	admin.Position = req.Position
	admin.Province = req.Province
	admin.ProvinceCode = req.ProvinceCode
	admin.City = req.City
	admin.CityCode = req.CityCode
	admin.TelAreaCode = req.TelAreaCode
	err = system.AddAdmin(admin)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，Err:" + err.Error()
		return
	}

	// 同步用户缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncAdminData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.AdminName = admin.AdminName
		_ = utils.Rc.LPush(utils.CACHE_SYNC_ADMIN, syncData)
	}

	err = services.UpdateResearcherTagGroup(admin.AdminId, req.ResearchGroupIds)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败，Err:" + err.Error()
		return
	}

	// 清楚系统用户列表缓存key
	utils.Rc.Delete(utils.CACHE_KEY_ADMIN)
	utils.Rc.Delete(utils.CACHE_KEY_ADMIN_ID)

	//thirdGroupId := 0 //角色：2=研究员，3=机构销售
	if admin.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR ||
		admin.RoleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR ||
		admin.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR ||
		admin.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT ||
		admin.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
		//thirdGroupId = 2
	} else if admin.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
		admin.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP ||
		admin.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
		admin.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		//thirdGroupId = 3
	}

	//if thirdGroupId > 0 {
	//	go roadshow.CreateOaUser(admin.Mobile, admin.RealName, thirdGroupId)
	//}

	// 新增弘则联系人
	//go services.AddHzCompanyUser(admin.Mobile, admin.RealName, this.SysUser.AdminId, this.SysUser.RealName)

	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// Edit
// @Title 编辑系统用户
// @Description 编辑系统用户接口
// @Param	request	body system.SysuserEditReq true "type json string"
// @Success 200 编辑成功
// @router /sysuser/edit [post]
func (this *SysAdminController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysuserEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.RoleId <= 0 {
		br.Msg = "请选择角色"
		br.ErrMsg = "角色ID小于等于0"
		return
	}
	//根据用户id获取用户信息
	adminInfo, err := system.GetSysAdminById(req.AdminId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户已被删除, 请刷新页面"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error() + ";AdminId:" + fmt.Sprint(req.AdminId)
		return
	}

	// 根据用户登录用户名获取用户信息
	item, err := system.GetSysAdminByName(req.AdminName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error() + ";AdminName:" + req.AdminName
		return
	}
	if item != nil && item.AdminId != req.AdminId {
		br.Msg = "账号名称已存在,请重新输入"
		return
	}

	// 手机号和邮箱必填一个
	req.Mobile = strings.TrimSpace(req.Mobile)
	req.Email = strings.TrimSpace(req.Email)
	if req.Mobile == "" && req.Email == "" {
		br.Msg = "至少输入一个手机号或邮箱"
		return
	}
	if req.Mobile != "" {
		if req.TelAreaCode == "86" {
			if !utils.ValidateMobileFormatat(req.Mobile) {
				br.Msg = "手机号格式有误, 请检查"
				return
			}
		}

		mobileCount, e := system.GetSysAdminCountByMobile(req.Mobile, adminInfo.AdminId)
		if e != nil {
			br.Msg = "判断手机号是否存在失败"
			br.ErrMsg = "判断手机号是否存在失败，Err:" + e.Error()
			return
		}
		if mobileCount > 0 {
			br.Msg = "手机号已存在，请重新填写"
			br.IsSendEmail = false
			return
		}
	}
	if req.Email != "" {
		if !utils.ValidateEmailFormatat(req.Email) {
			br.Msg = "邮箱格式有误, 请检查"
			return
		}
		emailUser, e := system.GetSysUserByEmail(req.Email)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "邮箱获取用户信息失败, Err: " + e.Error()
			return
		}
		if emailUser != nil && emailUser.AdminId != adminInfo.AdminId {
			br.Msg = "邮箱已存在, 请检查"
			return
		}
	}

	// 角色
	var roleName string

	roleItem, err := system.GetSysRoleById(req.RoleId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "角色不存在，请重新选择"
			br.ErrMsg = "角色不存在"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取角色数据失败，Err:" + err.Error()
		return
	}
	if roleItem != nil {
		roleName = roleItem.RoleName
	}

	// 员工工号
	req.EmployeeId = strings.TrimSpace(req.EmployeeId)
	if req.EmployeeId != "" && utils.BusinessCode == utils.BusinessCodeRelease {
		// 去重
		countOB := new(system.Admin)
		countCond := ` AND employee_id = ? AND admin_id <> ?`
		countPars := make([]interface{}, 0)
		countPars = append(countPars, req.EmployeeId, req.AdminId)
		countEmployee, e := countOB.GetCountByCondition(countCond, countPars)
		if e != nil {
			br.Msg = "工号去重查询失败"
			br.ErrMsg = "工号去重查询失败, Err: " + e.Error()
			return
		}
		if countEmployee > 0 {
			br.Msg = "工号已存在"
			return
		}
	}

	// 管理权限
	var authority int
	if roleItem.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		authority = 3
	} else if roleItem.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
		authority = 4
	} else if roleItem.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		authority = 2
	} else {
		if strings.Contains(roleItem.RoleType, "销售主管") {
			authority = 2
		} else if strings.Contains(roleItem.RoleType, "部门经理") {
			authority = 1
		} else {
			authority = 0
		}
	}

	adminInfo.AdminName = req.AdminName
	adminInfo.RealName = req.RealName
	adminInfo.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
	adminInfo.Mobile = req.Mobile
	adminInfo.RoleId = req.RoleId
	adminInfo.RoleName = roleName
	adminInfo.Enabled = req.Enabled
	adminInfo.Authority = authority
	adminInfo.Position = req.Position
	adminInfo.RoleTypeCode = roleItem.RoleTypeCode
	adminInfo.Province = req.Province
	adminInfo.ProvinceCode = req.ProvinceCode
	adminInfo.City = req.City
	adminInfo.CityCode = req.CityCode
	adminInfo.EmployeeId = req.EmployeeId
	adminInfo.Email = req.Email
	adminInfo.TelAreaCode = req.TelAreaCode
	cols := []string{
		"AdminName", "RealName", "LastUpdatedTime", "Mobile", "RoleId", "RoleName", "Enabled", "Authority",
		"Position", "RoleTypeCode", "Province", "ProvinceCode", "City", "CityCode", "EmployeeId", "Email", "TelAreaCode",
	}
	if e := adminInfo.Update(cols); e != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "更新用户信息失败, Err:" + e.Error()
		return
	}

	// 同步用户缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncAdminData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.AdminName = adminInfo.AdminName
		_ = utils.Rc.LPush(utils.CACHE_SYNC_ADMIN, syncData)
	}

	// 用户登出
	logOutSystemUser(adminInfo.AdminId)

	// 研究方向分组
	if e := services.UpdateResearcherTagGroup(req.AdminId, req.ResearchGroupIds); e != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "更新用户研究方向失败, Err:" + e.Error()
		return
	}

	// 清楚系统用户列表缓存key
	utils.Rc.Delete(utils.CACHE_KEY_ADMIN)
	utils.Rc.Delete(utils.CACHE_KEY_ADMIN_ID)

	// 试用客户更新对应信息
	if utils.BusinessCode == utils.BusinessCodeSandbox && adminInfo.DepartmentName == "ETA试用客户" {
		go func() {
			var r etaTrialService.EtaTrialUserEditReq
			r.RealName = req.RealName
			r.Position = req.Position
			r.Mobile = adminInfo.Mobile
			r.Enabled = req.Enabled
			_, _ = etaTrialService.EditEtaTrialUser(r)
		}()
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "编辑成功"
}

// @Title 开启/禁用系统用户
// @Description 开启/禁用系统用户接口
// @Param	request	body system.SysuserEditReq true "type json string"
// @Success 200 操作成功
// @router /sysuser/editEnabled [post]
func (this *SysAdminController) EditEnabled() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysuserEditEnabledReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	adminItem, err := system.GetSysAdminById(req.AdminId)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error()
		return
	}

	if req.Enabled == 0 {
		//禁用
		err = system.DisableAdmin(req.AdminId)
		if err != nil {
			br.Msg = "修改失败"
			br.ErrMsg = "修改系统用户数据失败，Err:" + err.Error()
			return
		}

		// 更新试用平台客户
		if utils.BusinessCode == utils.BusinessCodeSandbox && adminItem.DepartmentName == "ETA试用客户" {
			go func() {
				var r etaTrialService.EtaTrialUserReq
				r.Mobile = adminItem.Mobile
				_, _ = etaTrialService.DisableEtaTrialUser(r)
			}()
		}
	} else {
		admin := new(system.Admin)
		admin.Enabled = req.Enabled
		admin.AdminId = req.AdminId
		err = system.EditAdminEnabled(admin)
		if err != nil {
			br.Msg = "修改失败"
			br.ErrMsg = "修改系统用户数据失败，Err:" + err.Error()
			return
		}
	}

	// 同步用户缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncAdminData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.AdminName = adminItem.AdminName
		_ = utils.Rc.LPush(utils.CACHE_SYNC_ADMIN, syncData)
	}

	//用户被禁用的情况下，需要将他对应的token给过期
	if adminItem.Enabled == 1 && req.Enabled == 0 {
		logOutSystemUser(adminItem.AdminId)
	}

	// 联动弘则研究公司下的联系人启禁用
	{
		go services.SwitchHzUserEnabledByMobile(req.Enabled, adminItem.Mobile)
	}

	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title 删除系统用户
// @Description 删除系统用户接口
// @Param	request	body system.SysuserDeleteReq true "type json string"
// @Success 200 删除成功
// @router /sysuser/delete [post]
func (this *SysAdminController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysuserDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.AdminId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,GroupId 小于等于0 "
		return
	}
	mobile := ""
	adminInfo, _ := system.GetSysUserById(req.AdminId)
	if adminInfo != nil {
		mobile = adminInfo.Mobile
	}
	err = system.DeleteSysuser(req.AdminId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败，Err:" + err.Error()
		return
	}

	// 同步用户缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncAdminData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.AdminName = adminInfo.AdminName
		_ = utils.Rc.LPush(utils.CACHE_SYNC_ADMIN, syncData)
	}

	// 删除手工数据关联用户
	{
		go data_manage.DeleteManualUser(req.AdminId)
	}
	// 删除弘则研究公司下的相同手机号联系人
	{
		go services.DeleteHzUserByMobile(mobile)
	}

	// 清楚系统用户列表缓存key
	utils.Rc.Delete(utils.CACHE_KEY_ADMIN)
	utils.Rc.Delete(utils.CACHE_KEY_ADMIN_ID)

	// 删除试用平台客户
	if utils.BusinessCode == utils.BusinessCodeSandbox && adminInfo.DepartmentName == "ETA试用客户" {
		go func() {
			var r etaTrialService.EtaTrialUserReq
			r.Mobile = mobile
			_, _ = etaTrialService.RemoveEtaTrialUser(r)
		}()
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

/*
func init() {
	fmt.Println("start")
	pwdStr:=`11111`
	//compile := `(\d+.*[^a-zA-Z]+){6,12}|([^a-zA-Z]+.*\d+){6,12}`
	compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
	///^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/
	///^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/
	reg := regexp.MustCompile(compile)
	flag := reg.MatchString(pwdStr)
	fmt.Println(flag)
	fmt.Println("end")
}*/

// SetConfig
// @Title 用户信息配置接口
// @Description 用户信息配置接口
// @Success 200 {object} system.SetAdminConfigReq
// @router /sysuser/config/set [post]
func (this *SysAdminController) SetConfig() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req system.SetAdminConfigReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	item, err := system.GetConfigDetailByCode(this.SysUser.AdminId, req.ConfigCode)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "设置失败"
			br.ErrMsg = "设置失败，Err:" + err.Error()
			return
		}

		// 获取默认配置
		defaultConfig, err := system.GetDefaultConfigDetailByCode(req.ConfigCode)
		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "获取默认配置失败，Err:" + err.Error()
			return
		}
		adminConfigItem := &system.AdminConfig{
			//ConfigId:    0,
			AdminId:     this.SysUser.AdminId,
			ConfigCode:  req.ConfigCode,
			ConfigValue: req.ConfigValue,
			Remark:      defaultConfig.Remark,
			CreateTime:  time.Now(),
		}
		err = adminConfigItem.Create()

		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置失败，Err:" + err.Error()
			return
		}
	} else {
		// 存在配置，那么就修改
		item.ConfigValue = req.ConfigValue
		err = item.Update([]string{"ConfigValue"})

		if err != nil {
			br.Msg = "设置失败"
			br.ErrMsg = "设置失败，Err:" + err.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "设置成功"
}

// logOutSystemUser 用户登出
func logOutSystemUser(adminId int) {
	// 退出管理后台
	_ = system.ExpiredSysSessionByAdminId(adminId)
	// 退出随手办公小程序
	_ = system.UnBindAdminRecordByUserId(adminId)
}

// Move
// @Title 移动分组
// @Description 移动分组
// @Param	request	body system.SysUserMoveReq true "type json string"
// @Success 200 编辑成功
// @router /sysuser/move [post]
func (this *SysAdminController) Move() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysUserMoveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.AdminId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, AdminId"
		return
	}
	if req.DepartmentId <= 0 {
		br.Msg = "请选择部门"
		return
	}

	adminInfo, err := system.GetSysAdminById(req.AdminId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error() + ";AdminId:" + fmt.Sprint(req.AdminId)
		return
	}

	var departmentName, groupName, teamName string
	if req.DepartmentId > 0 {
		departmentItem, err := system.GetSysDepartmentById(req.DepartmentId)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取部门数据失败，Err:" + err.Error()
			return
		}
		if departmentItem != nil {
			departmentName = departmentItem.DepartmentName
		}
	}
	if req.GroupId > 0 {
		groupItem, err := system.GetSysGroupById(req.GroupId)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取分组数据失败，Err:" + err.Error()
			return
		}
		if groupItem != nil {
			groupName = groupItem.GroupName
		}
	}
	if req.TeamId > 0 {
		teamItem, err := system.GetSysGroupById(req.TeamId)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取小组数据失败，Err:" + err.Error()
			return
		}
		if teamItem != nil {
			teamName = teamItem.GroupName
		}
	}

	adminInfo.DepartmentId = req.DepartmentId
	adminInfo.DepartmentName = departmentName
	if req.TeamId <= 0 {
		adminInfo.GroupId = req.GroupId
		adminInfo.GroupName = groupName
	} else {
		adminInfo.GroupId = req.TeamId
		adminInfo.GroupName = teamName
	}
	adminInfo.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
	if e := adminInfo.Update([]string{"DepartmentId", "DepartmentName", "GroupId", "GroupName", "LastUpdatedTime"}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新系统用户分组失败, Err: " + e.Error()
		return
	}

	// 修改客户关联的分组
	{
		if req.TeamId > 0 {
			if req.TeamId != adminInfo.GroupId {
				err = company.ModifyCompanyGroupId(req.AdminId, req.TeamId)
				if err != nil {
					br.Msg = "编辑失败"
					br.ErrMsg = "ModifyCompanyGroupId，Err:" + err.Error()
					return
				}
			}
		} else {
			if req.GroupId != adminInfo.GroupId {
				err = company.ModifyCompanyGroupId(req.AdminId, req.GroupId)
				if err != nil {
					br.Msg = "编辑失败"
					br.ErrMsg = "ModifyCompanyGroupId，Err:" + err.Error()
					return
				}
			}
		}

		if req.DepartmentId != adminInfo.DepartmentId {
			err = company.ModifyCompanyDepartmentId(req.AdminId, req.DepartmentId)
			if err != nil {
				br.Msg = "编辑失败"
				br.ErrMsg = "ModifyCompanyDepartmentId，Err:" + err.Error()
				return
			}
		}
	}

	// 同步用户缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncAdminData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.AdminName = adminInfo.AdminName
		_ = utils.Rc.LPush(utils.CACHE_SYNC_ADMIN, syncData)
	}

	// 清除系统用户列表缓存key
	_ = utils.Rc.Delete(utils.CACHE_KEY_ADMIN)
	_ = utils.Rc.Delete(utils.CACHE_KEY_ADMIN_ID)

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// ResetPass
// @Title 重置密码
// @Description 重置密码
// @Param	request	body system.SysUserResetPassReq true "type json string"
// @Success 200 编辑成功
// @router /sysuser/reset_pass [post]
func (this *SysAdminController) ResetPass() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysUserResetPassReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.AdminId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "参数有误, AdminId"
		return
	}
	req.Password = strings.TrimSpace(req.Password)
	if req.Password == "" {
		br.Msg = "新密码不能为空"
		return
	}
	req.RePassword = strings.TrimSpace(req.RePassword)
	if req.RePassword == "" {
		br.Msg = "确认密码不能为空"
		return
	}
	if req.Password != req.RePassword {
		br.Msg = "两次输入密码不一致，请重新填写"
		return
	}

	adminInfo, err := system.GetSysAdminById(req.AdminId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户已被删除, 请刷新页面"
			return
		}
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取系统用户数据失败，Err:" + err.Error() + ";AdminId:" + fmt.Sprint(req.AdminId)
		return
	}

	b, err := base64.StdEncoding.DecodeString(req.Password)
	if err != nil {
		br.Msg = "解析数据失败"
		br.ErrMsg = "解析数据失败，Err:" + err.Error()
		return
	}
	pwd := string(b)
	//pwd = strings.ToLower(pwd)
	pwd = utils.MD5(pwd)

	adminInfo.Password = pwd
	adminInfo.LastUpdatedPasswordTime = time.Now().Format(utils.FormatDateTime)
	adminInfo.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
	if e := adminInfo.Update([]string{"Password", "LastUpdatedPasswordTime", "LastUpdatedTime"}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新系统用户分组失败, Err: " + e.Error()
		return
	}

	// 同步用户缓存
	if utils.BusinessCode == utils.BusinessCodeRelease {
		var syncData system.SyncAdminData
		syncData.Source = utils.SOURCE_ETA_FLAG
		syncData.AdminName = adminInfo.AdminName
		_ = utils.Rc.LPush(utils.CACHE_SYNC_ADMIN, syncData)
	}

	// 清除系统用户列表缓存key
	_ = utils.Rc.Delete(utils.CACHE_KEY_ADMIN)
	_ = utils.Rc.Delete(utils.CACHE_KEY_ADMIN_ID)

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "重置密码成功"
}
