package services

import (
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/models/company"
	"hongze/hongze_cygx/utils"
	"strings"
)

var (
	UserPermissionOperationModeApply      = "Apply"
	UserPermissionOperationModeCall       = "Call"
	UserPermissionPopupMsgApplyActivity   = "您暂无权限参加此活动，若想参加可以申请开通对应的试用权限"
	UserPermissionPopupMsgCallActivity    = "您暂无权限参加此活动，若想参加可以联系对口销售"
	UserPermissionPopupMsgApplyMicroVideo = "您暂无权限查看此视频，若想查看可以申请开通对应的试用权限"
	UserPermissionPopupMsgCallMicroVideo  = "您暂无权限查看此视频若想查看可以联系对口销售"
)

// GetUserRaiPermissionInfo 获取权限类型及信息
// HasPermission 是否有权限：1-有权限; 2-无权限; 3-潜在客户未提交申请; 4-潜在客户已提交申请 5-仅有FICC权限
func GetUserRaiPermissionInfo(userId, companyId int) (authInfo models.UserPermissionAuthInfo, permissionArr []string, err error) {
	// 用户申请记录
	applyCount, e := models.GetApplyRecordCount(userId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("获取用户申请信息失败, Err: " + e.Error())
		return
	}

	// 潜在用户
	if companyId <= 1 {
		authInfo.HasPermission = 3
		if applyCount > 0 {
			authInfo.HasPermission = 4
		}
		authInfo.OperationMode = UserPermissionOperationModeApply
		authInfo.PopupMsg = UserPermissionPopupMsgApplyActivity
		return
	}

	// 销售信息
	ficcSeller, e := models.GetSellerByCompanyIdCheckFicc(companyId, utils.COMPANY_PRODUCT_FICC_ID)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("获取FICC销售信息失败, Err: " + e.Error())
		return
	}
	raiSeller, e := models.GetSellerByCompanyIdCheckFicc(companyId, utils.COMPANY_PRODUCT_RAI_ID)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("获取权益销售信息失败, Err: " + e.Error())
		return
	}
	if raiSeller != nil {
		authInfo.SellerMobile = raiSeller.Mobile
		authInfo.SellerName = raiSeller.RealName
	}
	// 仅有FICC权限
	if ficcSeller != nil && raiSeller == nil {
		authInfo.HasPermission = 5
		authInfo.OperationMode = UserPermissionOperationModeApply
		authInfo.PopupMsg = UserPermissionPopupMsgApplyActivity
		return
	}

	// permissions示例: 医药,消费,科技,智造,策略,专家,买方研选
	permissions, e := models.GetCompanyPermissionName(companyId)
	if e != nil {
		err = errors.New("获取客户权限失败, Err: " + e.Error())
		return
	}
	if permissions == "" {
		// 无权益权限
		if raiSeller != nil {
			// 有销售信息
			authInfo.HasPermission = 2
			authInfo.OperationMode = UserPermissionOperationModeCall
			authInfo.PopupMsg = UserPermissionPopupMsgCallActivity
			return
		}
		// 无销售信息, 无申请, 视作潜在用户
		authInfo.HasPermission = 3
		authInfo.OperationMode = UserPermissionOperationModeApply
		return
	}
	// 有基本的权益权限
	authInfo.HasPermission = 1
	permissionArr = strings.Split(permissions, ",")
	return
}

// 查询研选的权限状态
func GetUserRaiPermissionYanXuanInfo(user *models.WxUserItem) (hasPermission int, err error) {
	//判断用户是否开通了个人研选权限
	mfyxUserPermissionTotal := GetMfyxUserPermissionTotal(user.UserId)
	if mfyxUserPermissionTotal == 1 {
		hasPermission = 1
		return
	}
	var condition string
	var pars []interface{}
	condition = " AND company_id = ?  AND status  IN ('正式','试用')  AND chart_permission_id = ?   ORDER BY company_report_permission_id DESC LIMIT 1  "
	pars = append(pars, user.CompanyId, utils.CHART_PERMISSION_ID_YANXUAN)
	companyReportPermissionDetail, e := models.GetCompanyReportPermissionDetailByCondition(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyReportPermissionDetailByCondition, Err: " + e.Error())
		return
	}
	//如果用户没有研选权限，那么就获取他对应的状态码
	if companyReportPermissionDetail == nil {
		hasPermission, _, _, _, e = GetUserHasPermissionArticle(user)
		if e != nil {
			err = errors.New("GetUserHasPermissionArticle, Err: " + e.Error())
			return
		}
	} else {
		hasPermission = 1
	}
	return
}

// 获取权益销售姓名
func GetSellerName(user *models.WxUserItem) (sellerName, mobile string, sellerId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("获取权益销售姓名失败 GetSellerName, err：", err.Error()), 2)
		}
	}()
	companyId := user.CompanyId
	//潜在客户没有销售
	if user.CompanyId <= 1 {
		return
	}
	//权益客户
	raiCount, e := models.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_RAI_ID)
	if e != nil {
		err = errors.New("GetCompanyProductCount, Err: " + e.Error())
		return
	}
	//仅开通FICC的客户不展示销售姓名
	if raiCount == 0 {
		return
	}
	sealldetail, e := models.GetRaiSellerByCompanyId(companyId)
	if e != nil {
		err = errors.New("GetRaiSellerByCompanyId, Err: " + e.Error())
		return
	}
	sellerName = sealldetail.RealName
	sellerId = sealldetail.AdminId
	mobile = sealldetail.Mobile
	return
}

// 用户详情页获取用户权限状态  https://hzstatic.hzinsights.com/static/images/202402/20240205/LpE6dspJCLzfQoCoE8SFMDiLuxXk.png（状态码说明）这一期先不改2024-05-24。
func GetUserDetailPermissionCode(userId, companyId int) (permission int, err error) {
	// 用户申请记录
	applyCount, e := models.GetApplyRecordCount(userId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("获取用户申请信息失败, Err: " + e.Error())
		return
	}
	if companyId == 1 {
		// 潜在用户
		if applyCount > 0 {
			permission = 5
		} else {
			permission = 4
		}
	} else {
		//权益客户
		raiCount, e := company.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_RAI_ID)
		if e != nil {
			err = errors.New("获取用户申请信息失败, Err: " + e.Error())
			return
		}
		if raiCount == 1 {
			if applyCount > 0 {
				permission = 5
			} else {
				permission = 3
			}
		} else {
			if applyCount > 0 {
				permission = 5
			} else {
				permission = 2
			}
		}
	}
	return
}

// 获取用户权限状态  https://hzstatic.hzinsights.com/static/images/202402/20240205/LpE6dspJCLzfQoCoE8SFMDiLuxXk.png（状态码说明）
func GetUserPermissionCode(userId, companyId int) (permission int, err error) {
	// 用户申请记录
	applyCount, e := models.GetApplyRecordCount(userId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("获取用户申请信息失败, Err: " + e.Error())
		return
	}

	if companyId == 1 {
		// 潜在用户
		if applyCount > 0 {
			permission = 6
		} else {
			permission = 7
		}
	} else {
		//权益客户
		raiCount, e := models.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_RAI_ID)
		if e != nil {
			err = errors.New("获取用户申请信息失败, Err: " + e.Error())
			return
		}
		if raiCount == 1 {
			if applyCount > 0 {
				permission = 2
			} else {
				permission = 3
			}
		} else {
			//ficc 客户
			ficcCount, e := models.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_FICC_ID)
			if e != nil {
				err = errors.New("获取用户申请信息失败, Err: " + e.Error())
				return
			}
			if ficcCount == 1 {
				if applyCount > 0 {
					permission = 4
				} else {
					permission = 5
				}
			}
		}
	}
	return
}
