package company

import (
	"fmt"
	"hongze/hongze_yb/models/tables/admin"
	"hongze/hongze_yb/models/tables/chart_permission"
	"hongze/hongze_yb/models/tables/company"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/company_report_permission"
	"hongze/hongze_yb/models/tables/company_user_chart_classify_permission"
	"hongze/hongze_yb/models/tables/wx_user"
	"hongze/hongze_yb/models/tables/yb_apply_record"
	"hongze/hongze_yb/utils"
	"time"
)

// GetClassNameListByProductId 根据权限id获取权限分类
func GetClassNameListByProductId(productId int64) (list []*chart_permission.ChartPermission, err error) {
	list, err = chart_permission.GetClassNameListByProductId(productId)
	return
}

// GetPermissionListByProductId 根据product_id获取所有的权限列表
func GetPermissionListByProductId(productId int64) (list []*chart_permission.ChartPermission, err error) {
	list, err = chart_permission.GetListByProductId(productId)
	return
}

// GetValidPermissionByCompany2ProductId 根据客户id和产品id获取有效的权限列表
func GetValidPermissionByCompany2ProductId(companyId, productId int64) (list []*company_report_permission.CompanyReportPermission, err error) {
	where := make(map[string]interface{})
	where["company_id ="] = companyId
	where["product_id ="] = productId
	where["status in"] = []string{"正式", "试用", "永续"}
	list, err = company_report_permission.GetByWhereMap(where)
	return
}

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

// 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   int8   `json:"is_suspend" description:"启用与否字段：1:暂停,0:启用"`
	HasApply    bool   `json:"has_apply" description:"是否有申请过"`
}

// CheckPermissionByFicc 权限校验
func CheckPermissionByFicc(companyId int64, permissionId int) (ok bool, permissionCheckInfo PermissionCheckInfo, err error) {
	//非潜在客户
	var productId int64
	productId = 1
	if companyId > 1 {
		//查询是否 开通ficc的客户
		companyProductInfo, tmpErr := company_product.GetByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = "apply"
				return
			}
			err = tmpErr
			return
		}

		// 如果客户ficc产品的状态是流失，那么也是让去申请
		if companyProductInfo.Status == "流失" {
			permissionCheckInfo.Type = "apply"
			return
		}
		// 获取有效的权限id列表
		validPermissionIdList, tmpErr := GetValidPermissionIdListByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 校验在有效的权限id列表中是否存在该权限
		for _, validPermissionId := range validPermissionIdList {
			//如果有该权限id，那么直接返回校验通过
			if validPermissionId == permissionId {
				ok = true
				return
			}
		}
		//查找对应客户的销售信息

		adminInfo, tmpErr := admin.GetByAdminId(companyProductInfo.SellerID)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		permissionCheckInfo = PermissionCheckInfo{
			Name:   adminInfo.RealName,
			Mobile: adminInfo.Mobile,
			Type:   "contact",
		}
	} else {
		permissionCheckInfo.Type = "apply"
	}

	return
}

// CheckPermissionByPermissionIdList2Ficc 根据权限id集合权限校验（ficc）
func CheckPermissionByPermissionIdList2Ficc(companyId int64, userId int, permissionIdList []int) (ok bool, permissionCheckInfo PermissionCheckInfo, err error) {
	defer func() {
		// 如果无权限，那么就去查询是否申请过
		if ok == false {
			ok, _ = checkPermissionByPermissionIdList2Rai(companyId, permissionIdList)
		}
		if ok == false && permissionCheckInfo.Type == "apply" {
			_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId, 2)	// 活动申请
			//查询是否有申请过，如果有申请过的话，那么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
	}
	var productId int64
	productId = 1
	if companyId > 1 {
		//查询是否 开通ficc的客户
		companyProductInfo, tmpErr := company_product.GetByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = "apply"
				return
			}
			err = tmpErr
			return
		}

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

		//客户信息
		companyInfo, tmpErr := company.GetByCompanyId(companyId)
		if tmpErr != nil {
			// 没有开通ficc的客户
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = "apply"
				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 = "apply"
			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 = "contact"
			return
		}

		//客户状态是：试用暂停状态（联系销售）
		if companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1 {
			permissionCheckInfo.Type = "contact"
			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 = "contact"
	} else {
		permissionCheckInfo.Type = "apply"
	}

	return
}

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

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

	//是否往下校验
	var permissionOk bool
	for _, permissionId := range permissionIdList {
		if permissionId == ficcPermissionId {
			permissionOk = true
		}
	}
	var productId int64
	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
}

// ChartPermissionCheckInfo 图表权限验证信息
type ChartPermissionCheckInfo struct {
	Name         	string       	`json:"name" description:"销售名称"`
	Mobile       	string       	`json:"mobile" description:"手机号"`
	Type			string			`json:"type" description:"无权限，需要前端处理的类型，枚举值：expired, apply, contact"`
	CustomerInfo	CustomerInfo 	`json:"customer_info" description:"客户信息"`
}

// CheckUserChartPermission 验证用户/联系人的图库权限
func CheckUserChartPermission(companyId int64, userId int) (ok bool, permissionCheckInfo ChartPermissionCheckInfo, err error) {
	defer func() {
		// 如果无权限，那么就去查询是否申请过
		if ok == false && permissionCheckInfo.Type == "apply" {
			_, err = yb_apply_record.GetLastNotOpRecordByUserId(userId, 3)	// 图库申请
			// 查询是否有申请过，如果有申请过的话，那么err是nil
			if err == nil {
				permissionCheckInfo.CustomerInfo.HasApply = true
			}
		}
	}()

	var productId int64
	productId = 1
	if companyId > 1 {
		// 查询是否开通FICC
		companyProductInfo, tmpErr := company_product.GetByCompany2ProductId(companyId, productId)
		if tmpErr != nil {
			// 没有开通FICC
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = "apply"
				return
			}
			err = tmpErr
			return
		}

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

		// 客户信息
		companyInfo, tmpErr := company.GetByCompanyId(companyId)
		if tmpErr != nil {
			// 没有开通FICC
			if tmpErr == utils.ErrNoRow {
				permissionCheckInfo.Type = "apply"
				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 = "apply"
			return
		}

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

		// 客户状态为冻结/试用暂停-联系销售
		permissionCheckInfo.Name = adminInfo.RealName
		permissionCheckInfo.Mobile = adminInfo.Mobile
		if companyProductInfo.Status == "冻结" {
			permissionCheckInfo.Type = "contact"
			return
		}
		if companyProductInfo.Status == "试用" && companyProductInfo.IsSuspend == 1 {
			permissionCheckInfo.Type = "contact"
			return
		}

		// 验证用户的图表权限
		permissionInfo, tmpErr := company_user_chart_classify_permission.GetPermissionByUserId(userId)
		if tmpErr != nil {
			if tmpErr == utils.ErrNoRow {
				// 无权限-联系销售
				permissionCheckInfo.Type = "contact"
				return
			}
			err = tmpErr
			return
		}
		nowTime := time.Now()
		if permissionInfo.Enabled != 1 {
			// 权限被禁用-联系销售
			permissionCheckInfo.Type = "contact"
			return
		}
		if nowTime.After(permissionInfo.StartTime) && nowTime.Before(permissionInfo.EndTime) {
			ok = true
		} else {
			// 权限已到期
			permissionCheckInfo.Type = "expired"
			return
		}

		// 都不是默认联系销售
		permissionCheckInfo.Type = "contact"
	} else {
		permissionCheckInfo.Type = "apply"
	}

	return
}