package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
)

//func init() {
//	wxUser, userErr := models.GetWxUserByUserId(52994)
//	if userErr != nil {
//		fmt.Println(userErr)
//	}
//	activityInfo, err := cygx.GetAddActivityInfoById(2104)
//	if err != nil {
//		fmt.Println(err)
//	}
//	havePower, err := GetActivityDetailUserPower(wxUser, activityInfo)
//	fmt.Println(havePower)
//	fmt.Println(err)
//}

// GetSpecialDetailUserPower 处理用户查看详情的权限 作废 2023-06-26
func GetActivityDetailUserPowerold(user *models.WxUser, adminInfo *system.Admin, activityInfo *cygx.ActivityDetail) (havePower bool, err error) {
	var companyDetailStatus string
	var userTypeStr string
	if user.CompanyId == utils.HZ_COMPANY_ID {
		havePower = true
		return
	}

	//需求707： 不限制人数的活动，销售后台给客户报名时（包括预约外呼、预约纪要、会议提醒），可以不做是否有权限的校验，限制人数的仍需判断是否有权限。2023-06-14
	if activityInfo.IsLimitPeople == 0 {
		havePower = true
		return
	}

	////高毅资产的联系人，销售在后台添加报名时，不受行业权限的限制  高毅资产属于其他行业正式客户
	////Ps: 现在就这一家单独的公司需要先写死 2023-03-20 高毅资产 公司ID：5285
	//if user.CompanyId == 5285 {
	//	havePower = true
	//	return
	//}
	userType, permissionStr, permissionStrZhengShi, companyStatus, e := GetUserTypeZhengShi(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanyPermissionUpgrade, Err: " + e.Error())
		return
	}

	//何伯仪给用户报名不做权限的限制,给他的用户添加所有权限 需求：2023-06-13
	//if adminInfo.Mobile == "15216703664" {
	//	permissionStr = "医药(客观),医药(主观),消费(客观),消费(主观),科技(客观),科技(主观),智造(客观),智造(主观),策略,专家,路演服务,买方研选"
	//	permissionStrZhengShi = "医药(客观),医药(主观),消费(客观),消费(主观),科技(客观),科技(主观),智造(客观),智造(主观),策略,专家,路演服务,买方研选"
	//}

	//如果是 公司调研电话会：3，或 专家线下沙龙:5  而且  除易董同步过来的以外的研选类型活动，必须要有研选的正式权限
	if (activityInfo.ActivityTypeId == 3 || activityInfo.ActivityTypeId == 5) && activityInfo.YidongActivityId == "" && strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
		if !strings.Contains(permissionStrZhengShi, activityInfo.ChartPermissionName) {
			havePower = false
			return
		}
	}
	//如果是易董的活动且属于研选类型，只要开通任何权限就可以查看详情
	if activityInfo.YidongActivityId != "" && permissionStr != "" && strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
		havePower = true
		return
	}

	//处理决策人可见权限
	if user.IsMaker == 0 && activityInfo.IsMakerShow == 1 {
		havePower = false
		return
	}

	//if activityInfo.ActivityTypeId == 2 || activityInfo.ActivityTypeId == 6 || activityInfo.ActivityTypeId == 7 {
	//	if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(主观)") {
	//		havePower = true
	//	} else {
	//		havePower = false
	//	}
	//} else {
	//	if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(客观)") {
	//		havePower = true
	//	} else {
	//		havePower = false
	//	}
	//}
	////如果主客观校验不通过，那么直接返回
	//if !havePower {
	//	return
	//}
	if activityInfo.IsLimitPeople > 0 {
		mapUserType, e := GetActivityCcustomerTypeList()
		if e != nil {
			err = e
			return
		}
		userTypeStr = mapUserType[userType]
		// 永续客户、大套餐客户、30W套餐客户可以查看行业升级套餐客户 权限
		if userTypeStr == "1" || userTypeStr == "2" || userTypeStr == "AA" {
			if strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
				havePower = true
				//return
			}
		}
	} else {
		if strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
			havePower = true
			return
		}
	}

	//判断管理规模是否满足
	companyProduct, e := company.GetCompanyProductDetail(user.CompanyId, 2)
	if e != nil {
		err = e
		return
	}
	if companyProduct != nil && activityInfo.Scale != "" {
		if strings.Contains(activityInfo.Scale, companyProduct.Scale) {
			havePower = true
		}
	}

	if user.CompanyId <= 1 {
		return
	} else {
		if permissionStr == "" {
			return
		} else {
			//companyDetail, e := models.GetCompanyDetailById(user.CompanyId)
			//if e != nil {
			//	err = errors.New("GetCompanyPermissionUpgrade, Err: " + e.Error())
			//	return
			//}
			//if companyDetail == nil {
			//	err = errors.New("客户不存在，uid:" + strconv.Itoa(user.UserId) + "CompanyId：" + strconv.Itoa(user.CompanyId))
			//	return
			//}
			companyDetailStatus = companyStatus
		}
	}
	if activityInfo.ChartPermissionId == 1 {
		havePower = true
		return
	}
	if (activityInfo.ActivityTypeId == 1 || activityInfo.ActivityTypeId == 3) && strings.Contains(permissionStr, "专家") && activityInfo.IsLimitPeople == 0 {
		havePower = true
	} else if activityInfo.ActivityTypeId == 3 && strings.Contains(permissionStr, "专家") && companyDetailStatus == "正式" && strings.Contains(activityInfo.CustomerTypeIds, "4") {
		havePower = true
	} else if activityInfo.ActivityTypeId == 3 && strings.Contains(permissionStr, "专家") && companyDetailStatus == "试用" && strings.Contains(activityInfo.CustomerTypeIds, "5") {
		havePower = true
	} else if (activityInfo.ActivityTypeId == 1 || activityInfo.ActivityTypeId == 3 || activityInfo.ActivityTypeId == 4 || activityInfo.ActivityTypeId == 5) && strings.Contains(permissionStr, "专家") {
		havePower = true
	}
	//if (strings.Contains(activityInfo.ChartPermissionName, "研选") || activityInfo.ChartPermissionName == "策略") && strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
	//	havePower = true
	//	return
	//}
	fmt.Println(havePower)
	if strings.Contains(activityInfo.ChartPermissionName, "研选") || activityInfo.ChartPermissionName == "策略" {
		if strings.Contains(activityInfo.CustomerTypeIds, "5") {
			if strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
				havePower = true
				return
			}
		} else {
			if strings.Contains(permissionStrZhengShi, activityInfo.ChartPermissionName) {
				havePower = true
				return
			}
		}
	}

	permissionShengji, errs := cygx.GetCompanyPermissionByUserZhengShiTrip(user.CompanyId)
	if errs != nil {
		err = errs
		return
	}
	//if strings.Contains(permissionShengji, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
	//	havePower = true
	//}

	//处理升级权限以及用户身份的 双重判断
	if activityInfo.CustomerTypeIds != "" {
		if !strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) && userTypeStr != "8" {
			havePower = false
			if strings.Contains(permissionShengji, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
				havePower = true
			}
		}
	}
	//if strings.Contains(permissionStr, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) {
	//	havePower = true
	//	return
	//}
	if havePower && activityInfo.IsLimitPeople > 0 {
		//对于一些特殊的活动，即使权限满足也不给产看
		noPower, e := GetShareNoPoweNew(activityInfo, permissionStr, userType, user)
		if e != nil {
			err = errors.New("GetShareNoPowe, Err: " + e.Error())
			return
		}
		if noPower {
			havePower = false
		}
	}
	return
}

// GetSpecialDetailUserPower 处理用户查看详情的权限
func GetActivityDetailUserPower(user *models.WxUser, adminInfo *system.Admin, activityInfo *cygx.ActivityDetail) (havePower bool, err error) {
	var companyDetailStatus string
	var userTypeStr string
	userId := int(user.UserId)
	//如果是弘则的用户或者宏观的权限不做校验
	//if user.CompanyId == utils.HZ_COMPANY_ID || activityInfo.ChartPermissionName == "宏观" {
	if user.CompanyId == utils.HZ_COMPANY_ID {
		havePower = true
		return
	}
	//需求707： 不限制人数的活动，销售后台给客户报名时（包括预约外呼、预约纪要、会议提醒），可以不做是否有权限的校验，限制人数的仍需判断是否有权限。2023-06-14
	if activityInfo.IsLimitPeople == 0 {
		havePower = true
		return
	}

	userType, permissionStr, permissionStrZhengShi, _, e := GetUserTypeZhengShi(user.CompanyId)
	if e != nil {
		err = errors.New("GetUserTypeZhengShi, Err: " + e.Error())
		return
	}

	//判断用户是否开通了个人研选权限，如果有权限后缀拼接权限名称
	// 查询用户是否开通过
	mfyxUserPermissionTotal, e := cygx.GetCygxUserYanxuanPermissionCountByUserId(userId)
	if e != nil {
		err = errors.New("GetCygxUserYanxuanPermissionCountByUserId, Err: " + e.Error())
		return
	}

	if mfyxUserPermissionTotal == 1 {
		permissionStr += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}

	//如果正式权限有开通 研选扣点包 ，那么就拼接一个 研选订阅的权限
	if strings.Contains(permissionStrZhengShi, utils.YAN_XUAN_KOU_DIAN_BAO_NAME) {
		permissionStr += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
		permissionStrZhengShi += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}

	//如果测试权限有开通 研选扣点包 ，那么就拼接一个 研选订阅的权限
	if strings.Contains(permissionStr, utils.YAN_XUAN_KOU_DIAN_BAO_NAME) {
		permissionStr += "," + utils.CHART_PERMISSION_NAME_MF_YANXUAN
	}

	//如果一个权限都没有就返回无权限
	if permissionStr == "" {
		return
	}
	permissionStr += "," + utils.HONG_GUAN_NAME // 添加一个宏观权限
	if permissionStrZhengShi == "" {
		permissionStrZhengShi = utils.HONG_GUAN_NAME // 添加一个宏观权限
	} else {
		permissionStrZhengShi += "," + utils.HONG_GUAN_NAME // 添加一个宏观权限
	}

	//如果是易董的活动，主、副权限有一个满足即可
	if activityInfo.YidongActivityId != "" {
		if strings.Contains(permissionStr, activityInfo.ChartPermissionName) || strings.Contains(permissionStr, activityInfo.ChartPermissionNameDeputy) {
			havePower = true
			return
		}
	}

	//如果权限不包含那么直接返回
	if !strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
		return
	} else {
		havePower = true
	}

	//处理决策人可见权限
	if user.IsMaker == 0 && activityInfo.IsMakerShow == 1 {
		havePower = false
		return
	}
	// 处理本组可见权限
	if activityInfo.VisibleRange == 1 {
		adminIds, e := cygx.GetSelleridWhichGroup(user.CompanyId, 2)
		if e != nil {
			err = errors.New("GetSelleridWhichGroup, Err: " + e.Error())
			return
		}
		haveVisibleRange := false
		adminIdSlice := strings.Split(adminIds, ",")

		for _, v := range adminIdSlice {
			if v == strconv.Itoa(activityInfo.AdminId) {
				haveVisibleRange = true
			}
		}
		if !haveVisibleRange {
			havePower = false
			return
		}
	}
	if permissionStr == "" {
		return
	}
	//如果是易董的活动且属于研选类型，只要开通任何权限就可以查看详情
	if activityInfo.YidongActivityId != "" && permissionStr != "" && strings.Contains(activityInfo.ChartPermissionName, utils.CHART_PERMISSION_NAME_YANXUAN) {
		havePower = true
		return
	}
	//医药消费，科技，智造四大行业，验证主客观。如果主客观校验不通过，那么直接返回
	if strings.Contains(utils.YI_YAO_NAME+utils.XIAO_FEI_NAME+utils.KE_JI_NAME+utils.ZHI_ZAO_NAME, activityInfo.ChartPermissionName) {
		if activityInfo.ActivityTypeId == 2 || activityInfo.ActivityTypeId == 6 || activityInfo.ActivityTypeId == 7 {
			if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(主观)") {
				havePower = true
			} else {
				havePower = false
			}
		} else {
			if strings.Contains(permissionStr, activityInfo.ChartPermissionName+"(客观)") {
				havePower = true
			} else {
				havePower = false
			}
		}
		if !havePower {
			return
		}
	}
	if activityInfo.IsLimitPeople > 0 {
		mapUserType, e := GetActivityCcustomerTypeList()
		if e != nil {
			err = errors.New("GetActivityCcustomerTypeList, Err: " + e.Error())
			return
		}
		userTypeStr = mapUserType[userType]
		// 永续客户、大套餐客户、30W套餐客户可以查看行业升级套餐客户 权限
		if userTypeStr == "1" || userTypeStr == "2" || userTypeStr == "AA" {
			if strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
				havePower = true
				//return
			}
		}
	} else {
		if strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
			havePower = true
			return
		}
	}
	//判断管理规模是否满足
	companyProduct, e := cygx.GetCompanyProductDetail(user.CompanyId, 2)
	if e != nil {
		err = e
		return
	}
	if companyProduct != nil && activityInfo.Scale != "" {
		if strings.Contains(activityInfo.Scale, companyProduct.Scale) {
			havePower = true
		}
	}

	if user.CompanyId <= 1 {
		return
	} else {
		if permissionStr == "" {
			return
		} else {
			companyDetail, e := cygx.GetCompanyDetailById(user.CompanyId)
			if e != nil {
				err = errors.New("GetCompanyPermissionUpgrade, Err: " + e.Error())
				return
			}
			if companyDetail == nil {
				err = errors.New("客户不存在，uid:" + strconv.Itoa(int(user.UserId)) + "CompanyId：" + strconv.Itoa(user.CompanyId))
				return
			}
			companyDetailStatus = companyDetail.Status
		}
	}
	//宏观满足用户可见身份验证权限既满足  2023-9-18
	if activityInfo.ChartPermissionId == 1 {
		if activityInfo.IsLimitPeople > 0 {
			if strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) {
				havePower = true
				return
			}
		} else {
			havePower = true
			return
		}
	}
	if (activityInfo.ActivityTypeId == 1 || activityInfo.ActivityTypeId == 3) && strings.Contains(permissionStr, "专家") && activityInfo.IsLimitPeople == 0 {
		havePower = true
	} else if activityInfo.ActivityTypeId == 3 && strings.Contains(permissionStr, "专家") && companyDetailStatus == "正式" && strings.Contains(activityInfo.CustomerTypeIds, "4") {
		havePower = true
	} else if activityInfo.ActivityTypeId == 3 && strings.Contains(permissionStr, "专家") && companyDetailStatus == "试用" && strings.Contains(activityInfo.CustomerTypeIds, "5") {
		havePower = true
	} else if (activityInfo.ActivityTypeId == 1 || activityInfo.ActivityTypeId == 3 || activityInfo.ActivityTypeId == 4 || activityInfo.ActivityTypeId == 5) && strings.Contains(permissionStr, "专家") {
		havePower = true
	}
	if strings.Contains(activityInfo.ChartPermissionName, "研选") || activityInfo.ChartPermissionName == "策略" {
		if strings.Contains(activityInfo.CustomerTypeIds, "5") {
			if strings.Contains(permissionStr, activityInfo.ChartPermissionName) {
				havePower = true
				return
			}
		} else {
			if strings.Contains(permissionStrZhengShi, activityInfo.ChartPermissionName) {
				havePower = true
				return
			}
		}
	}

	permissionShengji, errs := cygx.GetCompanyPermissionByUserTrip(user.CompanyId)
	if errs != nil {
		err = errs
		return
	}

	//fmt.Println("主客观2", havePower)
	//if strings.Contains(permissionStr, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) {
	//	havePower = true
	//}
	//fmt.Println("主客观3", havePower)
	//处理升级权限以及用户身份的 双重判断
	if activityInfo.CustomerTypeIds != "" {
		if !strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) && userTypeStr != "8" {
			havePower = false
			if strings.Contains(permissionShengji, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
				havePower = true
			}
		}
	}
	if havePower && activityInfo.IsLimitPeople > 0 {
		//对于一些特殊的活动，即使权限满足也不给产看
		noPower, e := GetShareNoPowe(activityInfo, permissionStr, userType)
		if e != nil {
			err = errors.New("GetShareNoPowe, Err: " + e.Error())
			return
		}
		if noPower {
			havePower = false
		}
	}
	return
}

// 校验被分享的用户是否有查看详情的权限
func GetShareNoPoweNew(activityInfo *cygx.ActivityDetail, permissionStr string, userType int, user *models.WxUser) (noPower bool, err error) {
	//如果是弘则的就不进行可见权限校验
	if user.CompanyId == utils.HZ_COMPANY_ID {
		return
	}
	//var noPower bool
	//if !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(userType)) {
	//	noPower = true
	//}
	//1、永续客户 //2、大套餐客户（4个行业全开通的正式客户） //3、分行业套餐客户（开通对应行业的正式客户） //4、仅开通专家套餐的正式客户 //5、开通对应行业套餐或专家套餐的试用客户
	//if userType == 2 && strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(2)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(4)) {
	//	noPower = true
	//}
	//if userType == 2 && !strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(2)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) {
	//	noPower = true
	//}
	//if userType == 3 && strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(4)) {
	//	noPower = true
	//}
	//if userType == 3 && !strings.Contains(permissionStr, "专家") && !strings.Contains(activityInfo.CustomerTypeIds, strconv.Itoa(3)) {
	//	noPower = true
	//}
	if userType == 8 {
		permissionShengji, errs := cygx.GetCompanyPermissionByUserZhengShiTrip(user.CompanyId)
		if errs != nil {
			err = errs
			return
		}
		if !strings.Contains(permissionShengji, activityInfo.ChartPermissionName) {
			noPower = true
			return
		}
	}
	if !noPower {
		noPower, err = CheckUserPowerByActivityChoose(user, activityInfo)
	}
	return
}

// 处理活动本组们是否决策人权限
func CheckUserPowerByActivityChoose(user *models.WxUser, activityInfo *cygx.ActivityDetail) (noPower bool, err error) {
	//处理 见范围 1，仅本组可见 、2，全部客户可见
	if activityInfo.VisibleRange == 1 {
		adminIds, errAdmin := system.GetSelleridWhichGroup(user.CompanyId, 2)
		if errAdmin != nil {
			err = errAdmin
			return
		}
		sliceAdminIds := strings.Split(adminIds, ",")
		var haveAdminId bool
		for _, v := range sliceAdminIds {
			if v == strconv.Itoa(activityInfo.AdminId) {
				haveAdminId = true
			}
		}
		if !haveAdminId {
			noPower = true
		}
	}
	//处理 是否仅决策人可见 0，否 、1，是
	if activityInfo.IsMakerShow == 1 {
		if user.IsMaker == 0 {
			noPower = true
		}
	}
	return
}

// GetSpecialDetailUserPower 处理用户查看专项调研详情的权限
func GetSpecialDetailUserPower(user *models.WxUser, activityInfo *cygx.ActivitySpecialDetail) (havePower bool, err error) {
	if user.CompanyId == utils.HZ_COMPANY_ID {
		havePower = true
		return
	}
	userType, _, permissionStr, _, e := GetUserType(user.CompanyId)
	if e != nil {
		err = errors.New("GetCompanyPermissionUpgrade, Err: " + e.Error())
		return
	}
	if userType == 0 {
		return
	}
	mapUserType, e := GetActivityCcustomerTypeList()
	if e != nil {
		err = e
		return
	}
	var userTypeStr string
	userTypeStr = mapUserType[userType]
	// 永续客户、大套餐客户可以查看行业升级套餐客户 权限
	if userTypeStr == "1" || userTypeStr == "2" {
		if strings.Contains(activityInfo.CustomerTypeIds, userTypeStr) || strings.Contains(activityInfo.CustomerTypeIds, "8") {
			havePower = true
			return
		}
	}
	permissionShengji, errs := cygx.GetCompanyPermissionByUserTrip(user.CompanyId)
	if errs != nil {
		err = errs
		return
	}
	//如果有升级权限的自动添加策略、固收的升级权限
	if permissionStr != "" {
		if activityInfo.ChartPermissionName == utils.CE_LUE_NAME {
			permissionShengji += "," + utils.CE_LUE_NAME
		}
		if activityInfo.ChartPermissionName == utils.GU_SHOU_NAME {
			permissionShengji += "," + utils.GU_SHOU_NAME
		}
	}
	//如果没有对应的升级权限，则返回
	if !strings.Contains(permissionShengji, activityInfo.ChartPermissionName) {
		return
	}

	var pars []interface{}
	var condition string
	var userTypes string
	condition += `  AND art.publish_status = 1 AND art.is_offline = 0   `
	userTypes = "%" + userTypeStr + "%"
	condition += ` AND art.customer_type_ids LIKE ? `
	pars = append(pars, userTypes)
	condition += ` AND art.activity_id = ? `
	pars = append(pars, activityInfo.ActivityId)
	total, e := cygx.GetActivitySpecialCount(condition, pars)
	if e != nil {
		err = errors.New("GetSpecialUserType, Err: " + e.Error())
		return
	}
	if total == 1 {
		havePower = true
		return
	}

	if strings.Contains(permissionShengji, activityInfo.ChartPermissionName) && strings.Contains(activityInfo.CustomerTypeIds, "8") {
		havePower = true
		return
	}
	return
}
