package company

import (
	"fmt"
	"hongze/hongze_open_api/models/response/report"
	"hongze/hongze_open_api/models/tables/admin"
	"hongze/hongze_open_api/models/tables/company"
	"hongze/hongze_open_api/models/tables/company_product"
	"hongze/hongze_open_api/models/tables/company_report_permission"
	"hongze/hongze_open_api/models/tables/wx_user"
	"hongze/hongze_open_api/utils"
)

var (
	CheckTypeApply   = "apply"
	CheckTypeContact = "contact"
	CheckTypeExpire  = "expired"
)

// PermissionCheckInfo 权限校验完成后的结果
type PermissionCheckInfo struct {
	Name         string       `json:"name" description:"销售名称"`
	Mobile       string       `json:"mobile" description:"手机号"`
	Type         string       `json:"type" description:"校验失败，没有权限，需要让前端处理的类型，枚举值：apply,contact"`
	CustomerInfo CustomerInfo `json:"customer_info" description:"客户信息"`
}

// CustomerInfo 客户信息
type CustomerInfo struct {
	CompanyName string `json:"company_name" description:"客户（公司）名称"`
	Name        string `json:"name" description:"联系人名称"`
	Mobile      string `json:"mobile" description:"手机号"`
	Status      string `json:"status" description:"状态"`
	IsSuspend   int    `json:"is_suspend" description:"启用与否字段：1:暂停,0:启用"`
	HasApply    bool   `json:"has_apply" description:"是否有申请过"`
}

// CheckPermissionByPermissionIdList2Ficc 根据权限id集合权限校验（ficc）
func CheckPermissionByPermissionIdList2Ficc(companyId int, userId int, permissionIdList []int) (ok bool, permissionCheckInfo PermissionCheckInfo, err error) {
	defer func() {
		//// 如果无权限，那么就去查询是否申请过
		//if ok == false {
		//	ok, _ = checkPermissionByPermissionIdList2Rai(companyId, userId, permissionIdList)
		//}
		//if ok == false && permissionCheckInfo.Type == CheckTypeApply {
		//	_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId) // 从来源我的/活动申请的记录
		//	if err != nil && err != utils.ErrNoRow {
		//		return
		//	}
		//	//查询是否有申请过，如果有申请过的话，那么err是nil
		//	if err == nil {
		//		permissionCheckInfo.CustomerInfo.HasApply = true
		//	}
		//}
	}()
	//非潜在客户
	if len(permissionIdList) <= 0 {
		err = fmt.Errorf("权限异常，请传入需要校验的权限")
		return
	}

	permissionMap := make(map[int]bool)
	for _, permissionId := range permissionIdList {
		permissionMap[permissionId] = true
	}
	productId := 1
	if companyId > 1 {
		//查询是否 开通ficc的客户
		companyProductInfo, tmpErr := company_product.GetCompanyProductByCompanyIdAndProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr.Error() == utils.NotEmpty() {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}

		wxUser, tmpErr := wx_user.GetByUserId(userId)
		if tmpErr != nil {
			permissionCheckInfo.Type = CheckTypeApply
			err = tmpErr
			return
		}

		// 查询用户是否为弘则研究已禁用的联系人
		if companyId == 16 {
			if wxUser.Enabled != 1 {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
		}

		//客户信息
		companyInfo, tmpErr := company.GetCompanyById(companyId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr.Error() == utils.ErrNoRow() {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}
		customerInfo := CustomerInfo{
			CompanyName: companyInfo.CompanyName,
			Status:      companyProductInfo.Status,
			Name:        wxUser.RealName,
			IsSuspend:   companyProductInfo.IsSuspend,
			Mobile:      wxUser.Mobile,
		}
		permissionCheckInfo.CustomerInfo = customerInfo

		// 如果客户ficc产品的状态是流失，那么也是让去申请
		if companyProductInfo.Status == "流失" {
			permissionCheckInfo.Type = CheckTypeApply
			return
		}

		//查找对应客户的销售信息
		adminInfo, tmpErr := admin.GetByAdminId(companyProductInfo.SellerId)
		if tmpErr != nil {
			//if tmpErr ==
			err = tmpErr
			return
		}

		permissionCheckInfo.Name = adminInfo.RealName
		permissionCheckInfo.Mobile = adminInfo.Mobile
		if companyProductInfo.Status == "冻结" {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		//客户状态是：试用暂停状态（联系销售）
		if companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1 {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		// 获取有效的权限id列表
		validPermissionIdList, tmpErr := GetValidPermissionIdListByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 校验在有效的权限id列表中是否存在该权限
		for _, validPermissionId := range validPermissionIdList {
			//如果有该权限id，那么直接返回校验通过
			if _, validOk := permissionMap[validPermissionId]; validOk {
				ok = true
				return
			}
		}
		permissionCheckInfo.Type = CheckTypeContact
	} else {
		permissionCheckInfo.Type = CheckTypeApply
	}

	return
}

// checkPermissionByPermissionIdList2Rai 根据权限id集合权限校验（权益）
func checkPermissionByPermissionIdList2Rai(companyId int, userId int, permissionIdList []int) (ok bool, err error) {
	//非潜在客户
	if len(permissionIdList) <= 0 {
		err = fmt.Errorf("权限异常，请传入需要校验的权限")
		return
	}

	// 查询用户是否为弘则研究已禁用的联系人
	wxUser, tmpErr := wx_user.GetByUserId(userId)
	if tmpErr != nil {
		err = fmt.Errorf("用户信息异常")
		return
	}
	if companyId == 16 {
		if wxUser.Enabled != 1 {
			return
		}
	}

	//市场策略（ficc权限id）：33
	ficcPermissionId := 33
	//市场策略（权益权限id）：23
	raiPermissionId := 23

	//是否往下校验
	var permissionOk bool
	for _, permissionId := range permissionIdList {
		if permissionId == ficcPermissionId {
			permissionOk = true
		}
	}
	productId := 2
	if companyId > 1 && permissionOk {
		// 获取有效的权限id列表
		validPermissionIdList, tmpErr := GetValidPermissionIdListByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 校验在有效的权限id列表中是否存在该权限
		for _, validPermissionId := range validPermissionIdList {
			if validPermissionId == raiPermissionId {
				ok = true
				return
			}
		}
	}

	return
}

func GetCheckPermission(companyId int, userId int, permissionIdList []int) (ok bool, permissionCheckInfo report.PermissionCheckInfo, finalValidPermissionIds []int, err error) {
	defer func() {
		// 如果无权限，那么就去查询是否申请过
		//if ok == false {
		//	ok, _ = checkPermissionByPermissionIdList2Rai(companyId, userId, permissionIdList)
		//}
		//if ok == false && permissionCheckInfo.Type == CheckTypeApply {
		//	_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId) // 从来源我的/活动申请的记录
		//	if err != nil {
		//		if err == utils.ErrNoRow {
		//			err = nil
		//		}
		//		return
		//	}
		//	//查询是否有申请过，如果有申请过的话，那么err是nil
		//	if err == nil {
		//		permissionCheckInfo.CustomerInfo.HasApply = true
		//	}
		//}
	}()
	permissionCheckInfo.HzPhone = utils.HZPHONE
	//非潜在客户
	permissionMap := make(map[int]bool)
	if len(permissionIdList) > 0 {
		for _, permissionId := range permissionIdList {
			permissionMap[permissionId] = true
		}
	}

	productId := 1
	if companyId > 1 {
		//查询是否 开通ficc的客户
		companyProductInfo, tmpErr := company_product.GetCompanyProductByCompanyIdAndProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr.Error() == utils.ErrNoRow() {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}

		wxUser, tmpErr := wx_user.GetByUserId(userId)
		if tmpErr != nil {
			permissionCheckInfo.Type = CheckTypeApply
			err = tmpErr
			return
		}

		//客户信息
		companyInfo, tmpErr := company.GetCompanyById(companyId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr.Error() == utils.ErrNoRow() {
				permissionCheckInfo.Type = CheckTypeApply
				return
			}
			err = tmpErr
			return
		}
		customerInfo := report.CustomerInfo{
			CompanyName: companyInfo.CompanyName,
			Status:      companyProductInfo.Status,
			Name:        wxUser.RealName,
			IsSuspend:   companyProductInfo.IsSuspend,
			Mobile:      wxUser.Mobile,
		}
		permissionCheckInfo.CustomerInfo = customerInfo

		// 如果客户ficc产品的状态是流失，那么也是让去申请
		if companyProductInfo.Status == "流失" {
			permissionCheckInfo.Type = CheckTypeApply
			return
		}

		//查找对应客户的销售信息
		adminInfo, tmpErr := admin.GetByAdminId(companyProductInfo.SellerId)
		if tmpErr != nil {
			//if tmpErr ==
			err = tmpErr
			return
		}

		permissionCheckInfo.Name = adminInfo.RealName
		permissionCheckInfo.Mobile = adminInfo.Mobile
		if companyProductInfo.Status == "冻结" {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		//客户状态是：试用暂停状态（联系销售）
		if companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1 {
			permissionCheckInfo.Type = CheckTypeContact
			return
		}

		// 获取有效的权限id列表
		validPermissionIdList, tmpErr := GetValidPermissionIdListByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 校验在有效的权限id列表中是否存在该权限
		if len(permissionIdList) > 0 {
			for _, validPermissionId := range validPermissionIdList {
				//如果有该权限id，那么直接返回校验通过
				if _, validOk := permissionMap[validPermissionId]; validOk {
					finalValidPermissionIds = append(finalValidPermissionIds, validPermissionId)
					ok = true
				}
			}
			return
		}

		permissionCheckInfo.Type = CheckTypeContact
	} else {
		permissionCheckInfo.Type = CheckTypeApply
	}
	return
}

// GetValidPermissionIdListByCompany2ProductId 根据客户id和产品id获取有效的权限id列表
func GetValidPermissionIdListByCompany2ProductId(companyId, productId int) (list []int, err error) {
	companyReportPermissionList, err := GetValidPermissionByCompany2ProductId(companyId, productId)
	if err != nil {
		return
	}
	for _, v := range companyReportPermissionList {
		list = append(list, v.ChartPermissionId)
	}
	return
}

// GetValidPermissionByCompany2ProductId 根据客户id和产品id获取有效的权限列表
func GetValidPermissionByCompany2ProductId(companyId, productId int) (list []*company_report_permission.CompanyReportPermission, err error) {
	return company_report_permission.GetPermissionListByCompanyIdAndProductId(companyId, productId)
}
