package english_report

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/company"
	"eta/eta_api/models/system"
	"eta/eta_api/models/system/request"
	"eta/eta_api/models/system/response"
	"eta/eta_api/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

// EnglishAuthController 英文销售权限
type EnglishAuthController struct {
	controllers.BaseAuthController
}

// List
// @Title 权限列表
// @Description 权限列表
// @Success 200 {object}  response.RoleAdminItemResp
// @router /auth/list [get]
func (this *EnglishAuthController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	// 获取英文角色配置
	confRoles := make([]company.ConfEnAuthRole, 0)
	authKey := company.ConfEnAuthRoleKey
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文权限角色配置失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &confRoles); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置有误"
		return
	}
	roleCodes := make([]string, 0)
	for _, v := range confRoles {
		roleCodes = append(roleCodes, v.RoleCode)
	}

	// 获取权限列表
	var cond string
	var pars []interface{}
	cond += ` AND r.role_type_code IN (` + utils.GetOrmInReplace(len(roleCodes)) + `)`
	pars = append(pars, roleCodes)
	total, adminList, err := system.GetEnglishAuthRoleAdminList(cond, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取管理账号列表失败！"
		br.ErrMsg = "获取管理账号列表失败，Err:" + err.Error()
		return
	}

	// 查询分组信息
	departmentGroupNameMap := make(map[int]string)
	departmentNameMap := make(map[int]string)
	groupList, err := system.GetFullGroup()
	if err != nil {
		br.Msg = "查询分组信息失败！"
		br.ErrMsg = "查询分组信息失败，Err:" + err.Error()
		return
	}
	departmentList, err := system.GetDepartmentList()
	if err != nil {
		br.Msg = "查询部门信息失败！"
		br.ErrMsg = "查询部门信息失败，Err:" + err.Error()
		return
	}
	for _, d := range departmentList {
		departmentNameMap[d.DepartmentId] = d.DepartmentName
	}
	for _, g := range groupList {
		if g.ParentGroupName != "" {
			departmentGroupNameMap[g.GroupId] = g.DepartmentName + "/" + g.ParentGroupName + "/" + g.GroupName
		} else {
			departmentGroupNameMap[g.GroupId] = g.DepartmentName + "/" + g.GroupName
		}
	}

	// 查询角色信息
	roles, err := system.GetSysRoleAll(false)
	if err != nil {
		br.Msg = "查询角色信息失败！"
		br.ErrMsg = "查询角色信息失败，Err:" + err.Error()
		return
	}
	rolesNameMap := make(map[int]string)
	for _, v := range roles {
		rolesNameMap[v.RoleId] = v.RoleName
	}
	var list []*response.RoleAdminItemResp
	for _, v := range adminList {
		item := new(response.RoleAdminItemResp)
		item.SysRoleAdminId = v.SysRoleAdminId
		item.AdminId = v.AdminId
		item.Mobile = v.Mobile
		item.RealName = v.RealName
		item.Enabled = v.Enabled
		if v.GroupId > 0 {
			if departmentGroup, ok := departmentGroupNameMap[v.GroupId]; ok {
				item.DepartmentGroup = departmentGroup
			}
		} else {
			if departmentName, ok := departmentNameMap[v.DepartmentId]; ok {
				item.DepartmentGroup = departmentName
			}
		}

		// 整理角色名称
		item.RoleId = v.RoleId
		if rolesName, ok := rolesNameMap[v.RoleId]; ok {
			item.RoleName = rolesName
		}
		// 整理标签
		if v.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
			item.LabelVal = 1
		} else if v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN ||
			v.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
			item.LabelVal = 2
		} else {
			if v.Authority == 1 {
				item.LabelVal = 3
			} else if v.Authority == 2 && v.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
				item.LabelVal = 4
			} else if v.Authority == 2 && v.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
				item.LabelVal = 5
			} else if v.Authority == 4 {
				item.LabelVal = 4
			}
		}

		list = append(list, item)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := response.RoleAdminListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// BatchAdd
// @Title 批量新增权限
// @Description 批量新增权限
// @Param	request  body  request.AddEnglishAuthRoleAdminReq  true  "type json string"
// @Success Ret=200 操作成功
// @router /auth/batch_add [post]
func (this *EnglishAuthController) BatchAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 request.AddEnglishAuthRoleAdminReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.AdminIds == "" {
		br.Msg = "请选择用户"
		return
	}

	// 校验参数
	adminIdArr := strings.Split(req.AdminIds, ",")
	if len(adminIdArr) == 0 {
		br.Msg = "请选择用户"
		return
	}
	adminIds := make([]int, 0)
	for i := range adminIdArr {
		v, e := strconv.Atoi(adminIdArr[i])
		if e != nil {
			br.Msg = "请选择用户"
			br.ErrMsg = "参数解析异常, Err:" + e.Error()
			return
		}
		adminIds = append(adminIds, v)
	}
	if len(adminIds) == 0 {
		br.Msg = "请选择有效用户"
		return
	}

	// 获取英文角色配置
	confRoles := make([]company.ConfEnAuthRole, 0)
	authKey := company.ConfEnAuthRoleKey
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文权限角色配置失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &confRoles); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置有误"
		return
	}
	roleCodes := make([]string, 0)
	for _, v := range confRoles {
		roleCodes = append(roleCodes, v.RoleCode)
	}

	// 获取英文权限角色
	roleItems, e := system.GetEnglishAuthRoleItems(roleCodes)
	if e != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "获取英文权限角色IDs失败, Err: " + e.Error()
		return
	}
	if len(roleItems) == 0 || len(roleItems) != len(roleCodes) {
		br.Msg = "英文权限角色信息有误"
		return
	}

	// 查询已绑定的管理员账号
	var noBindIds []int
	bindMap := make(map[int]bool)
	hasBindList, e := system.CheckEnglishAuthRoleAdminByAdminIds(adminIds, roleCodes)
	if e != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "查询已绑定英文权限的账号失败, Err:" + e.Error()
		return
	}
	for i := range hasBindList {
		bindMap[hasBindList[i].AdminId] = true
	}
	for i := range adminIds {
		if !bindMap[adminIds[i]] {
			noBindIds = append(noBindIds, adminIds[i])
		}
	}
	if len(noBindIds) == 0 {
		br.Msg = "账号已绑定，无需重复绑定"
		br.ErrMsg = "账号已绑定，无需重复绑定"
		return
	}

	// 获取未绑定的用户列表
	unboundAdmins := make([]*system.Admin, 0)
	{
		cond := fmt.Sprintf(` AND admin_id IN (%s)`, utils.GetOrmInReplace(len(noBindIds)))
		pars := make([]interface{}, 0)
		pars = append(pars, noBindIds)
		admins, e := system.GetSysAdminList(cond, pars, []string{}, "")
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "获取未绑定的用户列表失败, Err: " + e.Error()
			return
		}
		unboundAdmins = admins
	}

	// 新增绑定关系
	var syncRoles []system.SyncAdminEnRole
	nowTime := time.Now().Local()
	newBounds := make([]*system.SysRoleAdmin, 0)
	for _, a := range unboundAdmins {
		var d system.SyncAdminEnRole
		d.AdminName = a.AdminName
		for r := range roleItems {
			v := &system.SysRoleAdmin{
				AdminId:    a.AdminId,
				RoleId:     roleItems[r].RoleId,
				CreateTime: nowTime,
			}
			newBounds = append(newBounds, v)
			d.RoleCodes = append(d.RoleCodes, roleItems[r].RoleTypeCode)
		}
		syncRoles = append(syncRoles, d)
	}
	if e = system.AddRoleAdminBatch(newBounds); e != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增英文权限绑定关系失败, Err:" + e.Error()
		return
	}

	// 写入同步缓存
	for _, v := range syncRoles {
		_ = utils.Rc.LPush(utils.CACHE_SYNC_USER_EN_ROLE, v)
	}

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

// Detail
// @Title 权限详情
// @Description 权限详情
// @Param   AdminId  query  string  int  "管理员ID"
// @Success 200 {object}  response.EnglishAuthRoleDetailResp
// @router /auth/detail [get]
func (this *EnglishAuthController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}
	adminId, _ := this.GetInt("AdminId", 0)
	if adminId <= 0 {
		br.Msg = "参数有误"
		return
	}

	// 获取英文角色配置
	confRoles := make([]company.ConfEnAuthRole, 0)
	authKey := company.ConfEnAuthRoleKey
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文权限角色配置失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &confRoles); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置有误"
		return
	}
	roleCodes := make([]string, 0)
	for _, v := range confRoles {
		roleCodes = append(roleCodes, v.RoleCode)
	}

	resp := make([]*response.EnglishAuthRoleDetailResp, 0)
	authList, e := system.GetAdminEnglishAuthRoleDetail(adminId, roleCodes)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取管理员英文权限详情失败, Err:" + e.Error()
		return
	}
	authMap := make(map[string]bool, 0)
	for i := range authList {
		authMap[authList[i].RoleTypeCode] = true
	}

	for _, v := range confRoles {
		resp = append(resp, &response.EnglishAuthRoleDetailResp{
			AdminId:      adminId,
			AuthName:     v.RoleName,
			RoleTypeCode: v.RoleCode,
			AuthOk:       authMap[v.RoleCode],
		})
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Edit
// @Title 编辑权限
// @Description 编辑权限
// @Param	request  body  request.EditEnglishAuthRoleAdminReq  true  "type json string"
// @Success Ret=200 操作成功
// @router /auth/edit [post]
func (this *EnglishAuthController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 request.EditEnglishAuthRoleAdminReq
	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 = "管理员ID有误"
		return
	}
	if req.RoleTypeCodes == "" {
		br.Msg = "请选择权限"
		return
	}
	roleArr := strings.Split(req.RoleTypeCodes, ",")
	if len(roleArr) == 0 {
		br.Msg = "请选择权限"
		return
	}

	// 若用户不存在, 则忽略
	admin, e := system.GetSysAdminById(req.AdminId)
	if e != nil {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	// 获取英文角色配置
	confRoles := make([]company.ConfEnAuthRole, 0)
	authKey := company.ConfEnAuthRoleKey
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文权限角色配置失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &confRoles); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置有误"
		return
	}
	roleCodes := make([]string, 0)
	for _, v := range confRoles {
		roleCodes = append(roleCodes, v.RoleCode)
	}

	for i := range roleArr {
		if !utils.InArrayByStr(roleCodes, roleArr[i]) {
			br.Msg = "权限信息有误"
			return
		}
	}

	// 获取英文权限角色IDs
	roleIds, e := system.GetEnglishAuthRoleIds(roleCodes)
	if e != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "获取英文权限角色IDs失败, Err: " + e.Error()
		return
	}
	if len(roleIds) == 0 {
		br.Msg = "英文权限角色信息有误"
		return
	}

	// 获取编辑的权限角色IDs
	editRoles, e := system.GetEnglishAuthRoleItems(roleArr)
	if e != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "获取编辑英文权限角色IDs失败, Err: " + e.Error()
		return
	}
	if len(editRoles) != len(roleArr) {
		br.Msg = "权限角色信息有误"
		return
	}

	// 同步缓存
	var syncData system.SyncAdminEnRole
	syncData.AdminName = admin.AdminName

	// 编辑权限
	nowTime := time.Now().Local()
	newBinds := make([]*system.SysRoleAdmin, 0)
	for _, r := range editRoles {
		v := &system.SysRoleAdmin{
			AdminId:    req.AdminId,
			RoleId:     r.RoleId,
			CreateTime: nowTime,
		}
		newBinds = append(newBinds, v)
		syncData.RoleCodes = append(syncData.RoleCodes, r.RoleTypeCode)
	}
	if e = system.EditEnglishAuthRoleAdmin(req.AdminId, roleIds, newBinds); e != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑管理员英文权限绑定关系失败, Err:" + e.Error()
		return
	}

	// 写入同步缓存
	_ = utils.Rc.LPush(utils.CACHE_SYNC_USER_EN_ROLE, syncData)

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

// Del
// @Title 删除权限
// @Description 删除权限
// @Param	request  body  request.DelEnglishAuthRoleAdminReq  true  "type json string"
// @Success Ret=200 操作成功
// @router /auth/del [post]
func (this *EnglishAuthController) Del() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 request.DelEnglishAuthRoleAdminReq
	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 = "参数有误"
		return
	}

	// 若用户不存在, 则忽略
	admin, e := system.GetSysAdminById(req.AdminId)
	if e != nil {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	// 获取英文角色配置
	confRoles := make([]company.ConfEnAuthRole, 0)
	authKey := company.ConfEnAuthRoleKey
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取英文权限角色配置失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &confRoles); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "英文权限角色配置有误"
		return
	}
	roleCodes := make([]string, 0)
	for _, v := range confRoles {
		roleCodes = append(roleCodes, v.RoleCode)
	}

	// 获取英文权限角色IDs
	roleIds, e := system.GetEnglishAuthRoleIds(roleCodes)
	if e != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "获取英文权限角色IDs失败, Err: " + e.Error()
		return
	}
	if len(roleIds) == 0 {
		br.Msg = "删除失败"
		br.ErrMsg = "解除英文权限角色绑定关系失败, 角色信息有误"
		return
	}

	// 解除绑定关系
	if e = system.DeleteRoleAdminByAdminIdAndRoleIds(req.AdminId, roleIds); e != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "解除英文权限角色绑定关系失败, Err:" + e.Error()
		return
	}

	// 写入同步缓存
	var syncData system.SyncAdminEnRole
	syncData.AdminName = admin.AdminName
	_ = utils.Rc.LPush(utils.CACHE_SYNC_USER_EN_ROLE, syncData)

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