package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// CompanyReceiveController 客户领取管理
type CompanyReceiveController struct {
	BaseAuthController
}

// SellerList
// @Title 获取组长/组员下所有销售不包括研究员等（根据部门、分组）
// @Description 获取组长/组员下销售不包括研究员等（根据部门、分组）接口
// @Success 200 {object} company.ReceiveGroupSellersResp
// @router /receive/seller/group [get]
func (this *CompanyReceiveController) SellerList() {
	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
	}

	productId := services.GetProductId(sysUser.RoleTypeCode)
	condition := " and enabled=1 "
	var pars []interface{}

	roleCodeTypeStr := ""
	switch productId {
	case 0:
		roleCodeTypeStr = `"` + utils.ROLE_TYPE_CODE_FICC_SELLER + `","` + utils.ROLE_TYPE_CODE_FICC_GROUP + `","` + utils.ROLE_TYPE_CODE_FICC_TEAM + `","` + utils.ROLE_TYPE_CODE_FICC_ADMIN + `","` + utils.ROLE_TYPE_CODE_RAI_SELLER + `","` + utils.ROLE_TYPE_CODE_RAI_GROUP + `","` + utils.ROLE_TYPE_CODE_RAI_ADMIN + `"`
	case 1:
		roleCodeTypeStr = `"` + utils.ROLE_TYPE_CODE_FICC_SELLER + `","` + utils.ROLE_TYPE_CODE_FICC_GROUP + `","` + utils.ROLE_TYPE_CODE_FICC_TEAM + `","` + utils.ROLE_TYPE_CODE_FICC_ADMIN + `"`
	case 2:
		roleCodeTypeStr = `"` + utils.ROLE_TYPE_CODE_RAI_SELLER + `","` + utils.ROLE_TYPE_CODE_RAI_GROUP + `","` + utils.ROLE_TYPE_CODE_RAI_ADMIN + `"`
	}
	if roleCodeTypeStr != "" {
		condition += " and role_type_code in (" + roleCodeTypeStr + ")"
	}
	//先查询出所有的销售，再根据当前用户权限进行区分

	//只有ficc/权益管理员以及超管才有访问该接口的权限
	fullGroups, err := system.GetFullGroup()
	if err != nil {
		br.Msg = "获取分组失败"
		br.ErrMsg = "获取分组失败,Err:" + err.Error()
		return
	}
	fullGroupMap := make(map[int]*system.SysFullGroup)
	for _, v := range fullGroups {
		fullGroupMap[v.GroupId] = v
	}
	var listGroup []company.ReceiveGroupSellers
	var listDepartment []company.ReceiveGroupSellers
	departmentListMap := make(map[int][]company.ReceiveGroupSellers)
	groupListMap := make(map[int][]company.ReceiveGroupSellers)
	teamListMap := make(map[int][]company.ReceiveGroupSellers)
	departmentHasMap := make(map[int]bool)
	groupHasMap := make(map[int]bool)
	teamHasMap := make(map[int]bool)

	sellerList, err := system.GetSysUserItemsOrderByCreated(condition, pars)
	if err != nil {
		br.Msg = "获取管理账号失败"
		br.ErrMsg = "获取管理账号失败,Err:" + err.Error()
		return
	}
	for _, v := range sellerList {
		tmp := company.ReceiveGroupSellers{
			AdminId:  strconv.Itoa(v.AdminId),
			RealName: v.RealName,
		}
		if v.GroupId > 0 {
			if groupInfo, ok := fullGroupMap[v.GroupId]; ok {
				if groupInfo.ParentId > 0 {
					teamListMap[v.GroupId] = append(teamListMap[v.GroupId], tmp)
				} else {
					groupListMap[groupInfo.GroupId] = append(groupListMap[groupInfo.GroupId], tmp)
				}
			} else {
				departmentListMap[v.DepartmentId] = append(departmentListMap[v.DepartmentId], tmp)
			}
		} else if v.DepartmentId > 0 {
			departmentListMap[v.DepartmentId] = append(departmentListMap[v.DepartmentId], tmp)
		}
	}
	for _, groupInfo := range fullGroups {
		var team1 company.ReceiveGroupSellers
		//处理小组
		if groupInfo.ParentId > 0 {
			if _, ok2 := teamHasMap[groupInfo.GroupId]; !ok2 {
				if len(teamListMap[groupInfo.GroupId]) > 0 {
					team1 = company.ReceiveGroupSellers{
						AdminId:      "team_" + strconv.Itoa(groupInfo.GroupId),
						RealName:     groupInfo.GroupName,
						ChildrenList: teamListMap[groupInfo.GroupId],
					}
					teamHasMap[groupInfo.GroupId] = true
					groupListMap[groupInfo.ParentId] = append(groupListMap[groupInfo.ParentId], team1)
				}
			}
		}
	}
	for _, groupInfo := range fullGroups {
		var group1 company.ReceiveGroupSellers
		//处理大组
		if groupInfo.ParentId == 0 {
			if _, ok2 := groupHasMap[groupInfo.GroupId]; !ok2 {
				if len(groupListMap[groupInfo.GroupId]) > 0 {
					group1 = company.ReceiveGroupSellers{
						AdminId:      "group_" + strconv.Itoa(groupInfo.GroupId),
						RealName:     groupInfo.GroupName,
						ChildrenList: groupListMap[groupInfo.GroupId],
					}
					groupHasMap[groupInfo.GroupId] = true
					departmentListMap[groupInfo.DepartmentId] = append(departmentListMap[groupInfo.DepartmentId], group1)
					listGroup = append(listGroup, group1)
				}
			}
		}
	}

	departmentList, err := system.GetDepartmentList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取部门失败,Err:" + err.Error()
		return
	}
	departmentMap := make(map[int]*system.SysDepartmentList)
	for _, v := range departmentList {
		departmentMap[v.DepartmentId] = v
	}
	for _, groupInfo := range departmentList {
		var department1 company.ReceiveGroupSellers
		//处理部门
		if len(departmentListMap[groupInfo.DepartmentId]) > 0 {
			if _, ok1 := departmentHasMap[groupInfo.DepartmentId]; !ok1 {
				department1 = company.ReceiveGroupSellers{
					AdminId:      "department_" + strconv.Itoa(groupInfo.DepartmentId),
					RealName:     groupInfo.DepartmentName,
					ChildrenList: departmentListMap[groupInfo.DepartmentId],
				}
				departmentHasMap[groupInfo.DepartmentId] = true
				listDepartment = append(listDepartment, department1)
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	if len(listDepartment) > 1 {
		br.Data = company.ReceiveGroupSellersResp{
			List: listDepartment,
		}
	} else {
		br.Data = company.ReceiveGroupSellersResp{
			List: listGroup,
		}
	}
	return
}

// List
// @Title 配置领取权限的销售列表
// @Description 获取组长/组员下销售不包括研究员等（根据部门、分组）接口
// @Success 200 {object} models.ReceiveSellerListResp
// @router /receive/seller [get]
func (this *CompanyReceiveController) List() {
	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
	}
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_FICC_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		br.Msg = "无权查看"
		return
	}
	pageSize, _ := this.GetInt("PageSize", utils.PageSize20)
	currentIndex, _ := this.GetInt("CurrentIndex", 1)
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize := paging.StartIndex(currentIndex, pageSize)
	condition := " and enabled=1 "
	var pars []interface{}

	adminIds := this.GetString("AdminIds")
	if adminIds != "" {
		condition += " and admin_id in (" + adminIds + ")"
	}
	realName := this.GetString("KeyWord")
	if realName != "" {
		condition += " and real_name like '%" + realName + "%'"
	}

	productId := services.GetProductId(sysUser.RoleTypeCode)
	roleCodeTypeStr := ""
	switch productId {
	case 0:
		roleCodeTypeStr = `"` + utils.ROLE_TYPE_CODE_FICC_SELLER + `","` + utils.ROLE_TYPE_CODE_FICC_GROUP + `","` + utils.ROLE_TYPE_CODE_FICC_TEAM + `","` + utils.ROLE_TYPE_CODE_FICC_ADMIN + `","` + utils.ROLE_TYPE_CODE_RAI_SELLER + `","` + utils.ROLE_TYPE_CODE_RAI_GROUP + `","` + utils.ROLE_TYPE_CODE_RAI_ADMIN + `"`
	case 1:
		roleCodeTypeStr = `"` + utils.ROLE_TYPE_CODE_FICC_SELLER + `","` + utils.ROLE_TYPE_CODE_FICC_GROUP + `","` + utils.ROLE_TYPE_CODE_FICC_TEAM + `","` + utils.ROLE_TYPE_CODE_FICC_ADMIN + `"`
	case 2:
		roleCodeTypeStr = `"` + utils.ROLE_TYPE_CODE_RAI_SELLER + `","` + utils.ROLE_TYPE_CODE_RAI_GROUP + `","` + utils.ROLE_TYPE_CODE_RAI_ADMIN + `"`
	}
	if roleCodeTypeStr != "" {
		condition += " and role_type_code in (" + roleCodeTypeStr + ")"
	}

	//查询所有部门
	departmentList, err := system.GetDepartmentList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取部门失败,Err:" + err.Error()
		return
	}
	departmentNameMap := make(map[int]string)
	for _, v := range departmentList {
		departmentNameMap[v.DepartmentId] = v.DepartmentName
	}

	//先查询出所有的销售，再根据当前用户权限进行区分
	fullGroups, err := system.GetFullGroup()
	if err != nil {
		br.Msg = "获取分组失败"
		br.ErrMsg = "获取分组失败,Err:" + err.Error()
		return
	}
	departmentGroupNameMap := make(map[int]string)
	for _, g := range fullGroups {
		if g.ParentGroupName != "" {
			departmentGroupNameMap[g.GroupId] = g.DepartmentName + "/" + g.ParentGroupName + "/" + g.GroupName
		} else {
			departmentGroupNameMap[g.GroupId] = g.DepartmentName + "/" + g.GroupName
		}
	}
	var list []*company.ReceiveSellerItemResp

	sellerList, err := system.GetSysUserItemsList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取管理账号失败"
		br.ErrMsg = "获取管理账号失败,Err:" + err.Error()
		return
	}
	permissionAminIds := ""
	for _, v := range sellerList {
		permissionAminIds += "," + strconv.Itoa(v.AdminId)
	}
	var adminPermissions []*company.SellerCompanyPermission
	permissionEnabledMap := make(map[int]int)
	if permissionAminIds != "" {
		//查询管理员ID对应的领取客户的权限
		permissionAminIds = strings.Trim(permissionAminIds, ",")
		adminPermissions, err = company.GetSellerCompanyPermissionByAdminIdsType(permissionAminIds, 1)
		if err != nil {
			br.Msg = "获取权限列表失败"
			br.ErrMsg = "获取权限列表失败,Err:" + err.Error()
			return
		}
		for _, v := range adminPermissions {
			permissionEnabledMap[v.AdminId] = v.Enabled
		}
	}

	for _, v := range sellerList {
		tmp := &company.ReceiveSellerItemResp{
			AdminId:  v.AdminId,
			RealName: v.RealName,
		}
		tmp.Enabled = 1 //默认是有权限的
		if p, ok := permissionEnabledMap[v.AdminId]; ok {
			tmp.Enabled = p
		}

		if v.GroupId > 0 {
			if name, ok := departmentGroupNameMap[v.GroupId]; ok {
				tmp.DepartmentGroup = name
			}
		} else {
			if name, ok := departmentNameMap[v.DepartmentId]; ok {
				tmp.DepartmentGroup = name
			}
		}
		list = append(list, tmp)
	}

	total, err := system.GetSysUserItemsTotal(condition, pars)
	if err != nil {
		br.Msg = "获取管理账号总数失败"
		br.ErrMsg = "获取管理账号总数失败,Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, int(total))
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = company.ReceiveSellerListResp{
		List:   list,
		Paging: page,
	}
	return
}

// ChangePermission
// @Title 修改用户添加客户的权限
// @Description 修改用户添加客户的权限
// @Param	request	body models.ChangeReceivePermissionReq true "type json string"
// @Success 200 操作成功
// @router /receive/permission/change [post]
func (this *CompanyReceiveController) ChangePermission() {
	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
	}
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_FICC_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		br.Msg = "无权操作"
		return
	}

	var req company.ChangeReceivePermissionReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Enabled != 0 && req.Enabled != 1 {
		br.Msg = "请输入正常的操作类型"
		return
	}
	sellerInfo, err := system.GetSysAdminById(req.AdminId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "销售不存在"
			return
		} else {
			br.Msg = "查询销售出错！"
			br.ErrMsg = "查询销售出错，Err:" + err.Error()
			return
		}
	}
	if sellerInfo.Enabled == 0 {
		br.Msg = "销售账号已无效"
		return
	}
	// 查询当前销售 添加客户权限状态
	sellerPermission, err := company.GetSellerCompanyPermissionByAdminIdType(req.AdminId, 1)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "查询权限状态出错！"
		br.ErrMsg = "查询权限状态出错，Err:" + err.Error()
		return
	}
	now := time.Now()
	if sellerPermission != nil {
		if sellerPermission.Enabled == req.Enabled {
			br.Ret = 200
			br.Success = true
			br.Msg = "操作成功"
			return
		} else {
			err = company.UpdateSellerCompanyPermissionEnabledById(sellerPermission.Id, req.Enabled)
			if err != nil {
				br.Msg = "更新权限状态失败！"
				br.ErrMsg = "更新权限状态失败，Err:" + err.Error()
				return
			}
		}
	} else {
		if req.Enabled == 1 {
			br.Ret = 200
			br.Success = true
			br.Msg = "操作成功"
			return
		} else {
			// 禁用权限
			sellerPermission = &company.SellerCompanyPermission{
				AdminId:        req.AdminId,
				Enabled:        req.Enabled,
				CreateTime:     now,
				ModifyTime:     now,
				PermissionType: 1,
			}
			err = company.AddSellerCompanyPermission(sellerPermission)
			if err != nil {
				br.Msg = "更新权限状态失败！"
				br.ErrMsg = "更新权限状态失败，Err:" + err.Error()
				return
			}
		}
	}

	// 权限变更给销售发送模版通知
	go services.SendCompanyReceivePermissionWxTemplateMsg(sellerInfo.Mobile, req.Enabled)
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	return
}
