package services

import (
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/roadshow"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

func GetRoleTypeCode(roleType string) string {
	var roleTypeCode string
	switch roleType {
	case utils.ROLE_TYPE_ADMIN:
		roleTypeCode = utils.ROLE_TYPE_CODE_ADMIN
	case utils.ROLE_TYPE_FICC_ADMIN:
		roleTypeCode = utils.ROLE_TYPE_CODE_FICC_ADMIN
	case utils.ROLE_TYPE_FICC_SELLER:
		roleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
	case utils.ROLE_TYPE_RAI_ADMIN:
		roleTypeCode = utils.ROLE_TYPE_CODE_RAI_ADMIN
	case utils.ROLE_TYPE_FICC_GROUP, utils.ROLE_TYPE_FICC_MANAGER:
		roleTypeCode = utils.ROLE_TYPE_CODE_FICC_GROUP
	case utils.ROLE_TYPE_RAI_GROUP:
		roleTypeCode = utils.ROLE_TYPE_CODE_RAI_GROUP
	case utils.ROLE_TYPE_FICC_DEPARTMENT:
		roleTypeCode = utils.ROLE_TYPE_CODE_FICC_DEPARTMENT
	case utils.ROLE_TYPE_RAI_DEPARTMENT:
		roleTypeCode = utils.ROLE_TYPE_CODE_RAI_DEPARTMENT
	case utils.ROLE_TYPE_FICC_RESEARCHR:
		roleTypeCode = utils.ROLE_TYPE_CODE_FICC_RESEARCHR
	case utils.ROLE_TYPE_RAI_RESEARCHR:
		roleTypeCode = utils.ROLE_TYPE_CODE_RAI_RESEARCHR
	case utils.ROLE_TYPE_RAI_SELLER:
		roleTypeCode = utils.ROLE_TYPE_CODE_RAI_SELLER
	default:
		roleTypeCode = utils.ROLE_TYPE_ADMIN
	}
	return roleTypeCode
}

type AdminGroup struct {
	GroupId        int    `description:"分组id"`
	GroupName      string `description:"分组名称"`
	ResearcherList []*roadshow.Researcher
}

// GetFiccSystemGroup 获取ficc的大分组
func GetFiccSystemGroup() (adminGroupList []AdminGroup, groupMap map[int]int, err error) {
	list, err := system.GetSysGroupListByDepartmentId(2)
	if err != nil {
		return
	}

	groupMap = make(map[int]int)
	adminGroupList = make([]AdminGroup, 0)
	for _, v := range list {
		if v.ParentId == 0 {
			researcherList := make([]*roadshow.Researcher, 0)
			adminGroup := AdminGroup{
				GroupId:        v.GroupId,
				GroupName:      v.GroupName,
				ResearcherList: researcherList,
			}
			adminGroupList = append(adminGroupList, adminGroup)
			groupMap[v.GroupId] = v.GroupId
		} else {
			groupMap[v.GroupId] = v.ParentId
		}
	}
	return
}

// GetFiccSystemGroupIdsByGroupId 获取groupIp相关的分组ID
func GetFiccSystemGroupIdsByGroupId(groupId int) (groupIds []int, err error) {
	list, err := system.GetSysGroupListByDepartmentId(2)
	if err != nil {
		return
	}
	groupMap := make(map[int]int) //整理三级分组对应的二级分组
	for _, v := range list {
		if v.ParentId == 0 {
			groupMap[v.GroupId] = v.GroupId
		} else {
			groupMap[v.GroupId] = v.ParentId
		}
	}
	parentId := 0
	for k, v := range groupMap {
		if k == groupId {
			parentId = v //找到当前相关的二级分组
			break
		}
	}

	if parentId > 0 { //根据二级分组，查三级和二级的组
		for k, v := range groupMap {
			if v == parentId {
				groupIds = append(groupIds, k)
			}
		}
	}
	return
}

// GetFiccSeller 获取ficc的销售（需要吧小分组的group_id给处理成大分组group_id）
func GetFiccSeller(firstDate time.Time, groupMap map[int]int) (researcherList []*roadshow.Researcher, err error) {
	roleTypeCode := "('ficc_seller','ficc_group','ficc_team')"
	researcherList, err = roadshow.GetSellerList(roleTypeCode, "")
	if err != nil {
		return
	}

	for index, v := range researcherList {
		tmpGroupId, ok := groupMap[v.GroupId]
		if !ok {
			tmpGroupId = v.GroupId
		}
		researcherList[index].GroupId = tmpGroupId
	}

	return
}

// GetRaiSystemGroup 获取权益的大分组
func GetRaiSystemGroup() (adminGroupList []AdminGroup, groupMap map[int]int, err error) {
	list, err := system.GetSysGroupListByDepartmentId(5)
	if err != nil {
		return
	}

	groupMap = make(map[int]int)
	adminGroupList = make([]AdminGroup, 0)
	for _, v := range list {
		if v.ParentId == 0 {
			researcherList := make([]*roadshow.Researcher, 0)
			adminGroup := AdminGroup{
				GroupId:        v.GroupId,
				GroupName:      v.GroupName,
				ResearcherList: researcherList,
			}
			adminGroupList = append(adminGroupList, adminGroup)
			groupMap[v.GroupId] = v.GroupId
		} else {
			groupMap[v.GroupId] = v.ParentId
		}
	}
	return
}

// GetRaiSeller 获取权益的销售（需要吧小分组的group_id给处理成大分组group_id）
func GetRaiSeller(groupMap map[int]int) (researcherList []*roadshow.Researcher, err error) {
	roleTypeCode := "('rai_seller','rai_group')"
	researcherList, err = roadshow.GetRaiSellerList(roleTypeCode, "")
	if err != nil {
		return
	}

	for index, v := range researcherList {
		tmpGroupId, ok := groupMap[v.GroupId]
		if !ok {
			tmpGroupId = v.GroupId
		}
		researcherList[index].GroupId = tmpGroupId
	}

	return
}

// CheckAdminIsSameBigGroup 判断是否两个系统用户是否同一个大组内
func CheckAdminIsSameBigGroup(adminInfo1, adminInfo2 *system.Admin) (isSame bool, err error) {
	// 如果销售和创建人是同一个小组
	if adminInfo1.GroupId == adminInfo2.GroupId {
		isSame = true
		return
	}
	var admin1BigGroupId, admin2BigGroupId int

	//获取第一个系统用户的大组id
	{
		//获取该账号的大组id
		pid, tmpErr := company.GetParentIdFromGroup(adminInfo1.GroupId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if pid != nil && *pid > 0 {
			//该账号放在了三级分组下
			admin1BigGroupId = *pid
		} else {
			//该账号放在了二级分组下
			admin1BigGroupId = adminInfo1.GroupId
		}
	}

	//获取第二个系统用户的大组id
	{
		//获取该账号的大组id
		pid, tmpErr := company.GetParentIdFromGroup(adminInfo2.GroupId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if pid != nil && *pid > 0 {
			//该账号放在了三级分组下
			admin2BigGroupId = *pid
		} else {
			//该账号放在了二级分组下
			admin2BigGroupId = adminInfo2.GroupId
		}
	}

	if admin1BigGroupId == admin2BigGroupId {
		isSame = true
		return
	}
	return
}

// GetBigGroupAllGroupInfo 根据分组id 获取该分组下所有关联的分组（包含上级分组和自己的分组）
func GetBigGroupAllGroupInfo(groupId int) (groupMap map[int]*system.SysGroup, err error) {
	groupInfo, err := system.GetSysGroupById(groupId)
	if err != nil {
		return
	}

	groupMap = make(map[int]*system.SysGroup)
	if groupInfo.ParentId == 0 { //当前就是处于大分组下的第一级分组
		groupMap[groupInfo.GroupId] = groupInfo
		childSysGroupList, tmpErr := system.GetChildSysGroupByGroupId(groupInfo.GroupId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range childSysGroupList {
			groupMap[v.GroupId] = v
		}
	} else { //当前处于二级分组
		childSysGroupList, tmpErr := system.GetChildSysGroupByGroupId(groupInfo.ParentId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range childSysGroupList {
			groupMap[v.GroupId] = v
		}

		//父级分组信息
		parentGroupInfo, tmpErr := system.GetSysGroupById(groupInfo.ParentId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		groupMap[groupInfo.GroupId] = parentGroupInfo
	}

	return
}

// GetBigGroupByFiccGroupId 根据主管分组id获取用户的大组
func GetBigGroupByFiccGroupId(groupId int) (groupMap map[int]*system.SysGroup, err error) {
	bigGroupId := 0
	//获取该账号的大组id
	pid, err := company.GetParentIdFromGroup(groupId)
	if err != nil {
		return
	}
	if pid != nil && *pid > 0 {
		//该账号放在了三级分组下
		bigGroupId = *pid
	} else {
		//该账号放在了二级分组下
		bigGroupId = groupId
	}
	groupMap, err = GetBigGroupAllGroupInfo(bigGroupId)
	return
}

// CheckRaiAdmin 判断是否为权益内部人员
func CheckRaiAdmin(adminId int) (isRai bool, err error) {
	raiAdmins, e := system.GetRaiAdmin()
	if e != nil {
		err = fmt.Errorf("获取权益内部人员失败, GetRaiAdmin Err: %s", e.Error())
		return
	}
	for _, r := range raiAdmins {
		if adminId == r.AdminId {
			isRai = true
			break
		}
	}
	return
}

func GetFiccChildGroupIdsByGroupIds(groupId int) (sid string, sellerIds string, err error) {
	pid, err := company.GetParentIdFromGroup(groupId)
	if err != nil {
		return
	}
	var ids []*string
	if pid != nil {
		if *pid != 0 {
			//销售主管放在三级列表中
			ids, err = company.GetGroupIdsByParentId(*pid)
			if err != nil {
				fmt.Println(err.Error())
				return
			}
		} else {
			//销售主管放在二级列表中
			ids, err = company.GetGroupIdsByParentId(groupId)
			if err != nil {
				fmt.Println(err.Error())
				return
			}
		}
	}
	var idSlice []string
	for _, id := range ids {
		idSlice = append(idSlice, *id)
	}
	//加入父级groupId
	if *pid > 0 {
		idSlice = append(idSlice, strconv.Itoa(*pid))
	} else {
		idSlice = append(idSlice, strconv.Itoa(groupId))
	}
	sid = strings.Join(idSlice, ",")

	//查询这些组内的所有seller_ids
	if len(idSlice) > 0 {
		admins, tErr := system.GetTeamSysUserListByIds(sid)
		if tErr != nil {
			err = tErr
			fmt.Println(tErr.Error())
			return
		}
		var sellerIdSlice []string
		for _, v := range admins {
			sellerIdSlice = append(sellerIdSlice, strconv.Itoa(v.AdminId))
		}
		sellerIds = strings.Join(sellerIdSlice, ",")
	}

	return
}

func GetFiccSellerIdsByGroupId(groupId int) (sellerIds string, err error) {
	//查询这些组内的所有seller_ids
	if groupId > 0 {
		admins, tErr := system.GetAdminByGroupId(groupId)
		if tErr != nil {
			err = tErr
			fmt.Println(tErr.Error())
			return
		}
		var sellerIdSlice []string
		for _, v := range admins {
			sellerIdSlice = append(sellerIdSlice, strconv.Itoa(v.AdminId))
		}
		sellerIds = strings.Join(sellerIdSlice, ",")
	}

	return
}
