package services

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

func SpecialTripPopupMsg(activityInfo *models.CygxActivitySpecialDetail, user *models.WxUserItem) (signupStatus int, popupMsg, popupMsg2 string, err error) {
	//SignupStatus  int    `description:"返回状态：1：成功 、2 ：人数已满 、3：调研次数已用完、 4：超时"`
	signupStatus = 1
	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime) //时间字符串格式转时间格式
	if time.Now().After(resultTime.Add(-time.Minute * 60)) {
		signupStatus = 4
		popupMsg = "活动开始前1小时内无法报名，请联系对口销售处理"
		return
	}

	errMsg, e := CheckTripRemainingtimesBycompany(user, activityInfo)
	if e != nil {
		err = errors.New("获取客户剩余报名次数失败 GetActivitySpecialUserType, Err: " + e.Error())
		return
	}
	if errMsg != "" {
		popupMsg = errMsg
		signupStatus = 3
		return
	}
	var condition string
	var pars []interface{}

	condition += ` AND activity_id =  ? AND  is_cancel = 0 `
	pars = append(pars, activityInfo.ActivityId)

	tripTota, e := models.GetActivitySpecialTripCountByActivityId(condition, pars)
	if e != nil {
		err = errors.New("GetCygxActivitySpecialDetailList, Err: " + e.Error())
		return
	}
	if activityInfo.LimitPeopleNum-tripTota < 1 {
		signupStatus = 2
		popupMsg = "此活动报名人数已满，请留意下期活动"
		return
	}
	//signupStatus = 4
	popupMsg = "感谢参与，本次报名会扣除一次贵司在弘则的调研点数。"
	popupMsg2 = "由于每场活动人数有限，如果不能参加请提前48小时取消，未及时取消导致影响其他客户报名将会维持扣点。"
	return
}

// 校验是否还有剩余次数
func CheckTripRemainingtimesBycompany(user *models.WxUserItem, activityInfo *models.CygxActivitySpecialDetail) (errMsg string, err error) {
	msgTemplate := "您的专项调研次数已用完，如仍想参加，请与您的对口销售商议"
	companyId := user.CompanyId
	chartPermissionName := activityInfo.ChartPermissionName

	companyDetail, e := models.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err:" + e.Error())
		return
	}
	//永续客户不限制次数
	if companyDetail.Status == utils.COMPANY_STATUS_FOREVER {
		return
	}
	var condition string
	var pars []interface{}
	condition = " AND  company_id  = ?  AND points  > 0   ORDER BY  chart_permission_id DESC  "
	pars = append(pars, companyId)
	activitySpecialPermissionPointsList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}
	//如果没有剩余的点数，就返回
	if len(activitySpecialPermissionPointsList) == 0 {
		errMsg = msgTemplate
		return
	}

	//判断是不是策略行业的活动，策略的任何一个行业有剩余点数都能参加
	//if chartPermissionName == utils.CE_LUE_NAME {
	if utils.InArrayByStr(utils.ACTIVITY_SPECIAL_TRIP_PERMISSION_NAME_OTHER, activityInfo.ChartPermissionName) {
		return
	} else {
		for _, v := range activitySpecialPermissionPointsList {
			if v.ChartPermissionName == chartPermissionName || v.ChartPermissionId == 0 {
				return
			} // 如果对应行业有剩余次数，或者是属于大套餐且有次数，那么校验也通过
		}
	}
	return

}

// GetSpecialBillMaxChartPermissionId  获取专项调研剩余点数最多的行业
func GetSpecialBillMaxChartPermissionId(user *models.WxUserItem) (maxChartPermissionId int, maxChartPermissionName string, err error) {
	companyId := user.CompanyId
	var condition string
	var pars []interface{}
	condition = " AND  company_id  = ?  AND points  > 0   ORDER BY  points DESC LIMIT 1   "
	pars = append(pars, companyId)

	activitySpecialPermissionPointsList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}
	for _, v := range activitySpecialPermissionPointsList {
		maxChartPermissionId = v.ChartPermissionId
		maxChartPermissionName = v.ChartPermissionName
	}
	return
}

// DeductTripRemainingtimesByUser 扣除用户专项调研剩余次数
func DeductTripRemainingtimesByUser(user *models.WxUserItem, activityInfo *models.CygxActivitySpecialDetail) (err error) {
	msgTemplate := "您的专项调研次数已用完，如仍想参加，请与您的对口销售商议"
	companyId := user.CompanyId
	//chartPermissionName := activityInfo.ChartPermissionName

	companyProduct, e := company.GetCompanyProductByCompanyIdAndProductId(companyId, utils.COMPANY_PRODUCT_RAI_ID)
	if e != nil {
		err = errors.New("GetCompanyProductByCompanyIdAndProductId, Err:" + e.Error())
		return
	}

	var condition string
	var pars []interface{}
	var maxChartPermissionId int // 剩余点数最多的行业
	var points float64           // 剩余点数
	var activitySpecialPermissionPointsList []*models.CygxActivitySpecialPermissionPoints
	//永续客户不限次数需要单独处理
	if companyProduct.Status == utils.COMPANY_STATUS_FOREVER {
		condition = " AND  company_id  = ?   ORDER BY  points DESC LIMIT 1   "
		pars = append(pars, companyId)
		activitySpecialPermissionPointsList, e = models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
			return
		}
		//如果永续客户不存在单独的行业剩余点数记录，那么就添加一条 -1 的记录作为初始化数据
		if len(activitySpecialPermissionPointsList) == 0 {
			item := new(models.CygxActivitySpecialPermissionPoints)
			item.CompanyId = companyProduct.CompanyId
			item.Points = -1
			item.CompanyName = companyProduct.CompanyName
			//item.ChartPermissionId = activityInfo.ChartPermissionId
			//item.ChartPermissionName = activityInfo.ChartPermissionName
			item.CreateTime = time.Now()
			item.ModifyTime = time.Now()
			e = models.AddCygxActivitySpecialPermissionPoints(item)
			if e != nil {
				err = errors.New("AddCygxActivitySpecialPermissionPoints, Err:" + e.Error())
				return
			}
			return
		}
	} else {
		condition = " AND  company_id  = ?  AND points  > 0   ORDER BY  points DESC LIMIT 1   "
		pars = append(pars, companyId)

		//判断是不是策略、固收、周期行业的活动，如果不是策略就获取对应行业的点数 ，策略的任何一个行业有剩余点数都能参加
		//if chartPermissionName != utils.CE_LUE_NAME && chartPermissionName != utils.GU_SHOU_NAME {
		if !utils.InArrayByStr(utils.ACTIVITY_SPECIAL_TRIP_PERMISSION_NAME_OTHER, activityInfo.ChartPermissionName) {
			pars = make([]interface{}, 0)
			condition = " AND  company_id  = ?  AND ( chart_permission_id  = ? OR  chart_permission_id =0 )    AND points  > 0   ORDER BY  points DESC LIMIT 1   "
			pars = append(pars, companyId, activityInfo.ChartPermissionId)
		}
		activitySpecialPermissionPointsList, e = models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
			return
		}
	}
	//如果没有剩余的点数，就返回
	if len(activitySpecialPermissionPointsList) == 0 {
		err = errors.New(msgTemplate)
		return
	}
	for _, v := range activitySpecialPermissionPointsList {
		maxChartPermissionId = v.ChartPermissionId
		points = v.Points - 1
	}
	//更新对应行业剩余点数
	e = models.UpdateCygxActivitySpecialPermissionPoints(points, companyId, maxChartPermissionId)
	if e != nil {
		err = errors.New("UpdateCygxActivitySpecialPermissionPoints, Err:" + e.Error())
		return
	}
	return
}

// RebateTripRemainingtimesByUser 返点用户专项调研剩余次数
func RebateTripRemainingtimesByUser(user *models.WxUserItem, activityInfo *models.CygxActivitySpecialDetail) (err error) {
	companyId := user.CompanyId
	//chartPermissionName := activityInfo.ChartPermissionName
	var condition string
	var pars []interface{}
	condition = " AND  company_id  = ?    ORDER BY  points DESC LIMIT 1   "
	pars = append(pars, companyId)

	//判断是不是策略、固收、周期行业的活动，如果不是策略就获取对应行业的点数 ，策略的任何一个行业有剩余点数都能参加
	//if chartPermissionName != utils.CE_LUE_NAME && chartPermissionName != utils.GU_SHOU_NAME {
	if !utils.InArrayByStr(utils.ACTIVITY_SPECIAL_TRIP_PERMISSION_NAME_OTHER, activityInfo.ChartPermissionName) {
		pars = make([]interface{}, 0)
		condition = " AND  company_id  = ? AND  (chart_permission_id  = ?   OR chart_permission_id = 0 )    LIMIT 1   "
		pars = append(pars, companyId, activityInfo.ChartPermissionId)
	} else {
		lastTripBill, e := models.GetCygxActivitySpecialTripBillLastDetialByActivityId(activityInfo.ActivityId, user.UserId)
		if e != nil {
			err = errors.New("GetActivitySpecialTripCountByActivitySpecial, Err: " + e.Error())
			return
		}

		pars = make([]interface{}, 0)
		condition = " AND  company_id  = ? AND  (chart_permission_id  = ?   OR chart_permission_id = 0 )   LIMIT 1   "
		pars = append(pars, companyId, lastTripBill.ChartPermissionId)
	}
	activitySpecialPermissionPointsList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}

	var maxChartPermissionId int // 剩余点数最多的行业(返点行业)
	var points float64           // 剩余点数
	for _, v := range activitySpecialPermissionPointsList {
		maxChartPermissionId = v.ChartPermissionId
		points = v.Points + 1
	}
	//更新对应行业剩余点数
	e = models.UpdateCygxActivitySpecialPermissionPoints(points, companyId, maxChartPermissionId)
	if e != nil {
		err = errors.New("UpdateCygxActivitySpecialPermissionPoints, Err:" + e.Error())
		return
	}
	return
}

// 预处理专项调研流水明细表描述内容
func HandleActivitySpecialTripBillTotalText(companyId int) (totalText string, err error) {
	//companyId := user.CompanyId
	companyDetail, e := models.GetCompanyDetailByIdGroup(companyId)
	if e != nil {
		err = errors.New("GetCompanyDetailByIdGroup, Err:" + e.Error())
		return
	}

	var condition string
	var pars []interface{}
	pars = make([]interface{}, 0)
	condition = " AND  company_id  = ?  AND points  != 0   ORDER BY  chart_permission_id DESC  "
	pars = append(pars, companyId)
	activitySpecialPermissionPointsList, e := models.GetCygxActivitySpecialPermissionPointsList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxActivitySpecialPermissionPointsList, Err:" + e.Error())
		return
	}
	//永续客户次数累加
	if companyDetail.Status == utils.COMPANY_STATUS_FOREVER {
		var points float64
		for _, v := range activitySpecialPermissionPointsList {
			points += v.Points
		}
		totalText = fmt.Sprint(points, "次") //追加永续客户展示规则（2024-02-23）
		return
	}

	var itemBillTotal []string
	itemBillTotalMap := make(map[string]string)
	for _, v := range activitySpecialPermissionPointsList {
		if v.ChartPermissionId > 0 {
			itemBillTotal = append(itemBillTotal, fmt.Sprint(v.ChartPermissionName, v.Points, "次")) // 行业套餐客户展示规则
			itemBillTotalMap[v.ChartPermissionName] = fmt.Sprint(v.ChartPermissionName, v.Points, "次")
		}
		if v.ChartPermissionId == 0 {
			totalText = fmt.Sprint(v.Points, "次") // 大套餐客户展示规则，
		}
	}

	if len(itemBillTotal) > 0 {
		permissionNameSlice := []string{"医药", "消费", "科技", "智造"}
		var itemBillTotalNew []string
		for _, v := range permissionNameSlice {
			if itemBillTotalMap[v] == "" {
				itemBillTotalNew = append(itemBillTotalNew, fmt.Sprint(v, "0次"))
			} else {
				itemBillTotalNew = append(itemBillTotalNew, itemBillTotalMap[v])
			}
		}
		totalText = strings.Join(itemBillTotalNew, "+")
	}
	return
}

// 用户搜专项调研操作操作行为，模板消息推送
func ActivitySpecialUserRmind(user *models.WxUserItem, activityId, TripStatus int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("用户搜专项调研操作操作行为，模板消息推送失败"+err.Error(), 2)
		}
	}()
	countUser, err := models.GetUserRemind(user.UserId)
	if err != nil {
		return err
	}
	if countUser == 0 {
		return err
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//获取销售手机号
	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	if sellerItemQy != nil {

		sllerAndShareMobileArr, e := GetCompanySellerAndShareMobileByRai(user.CompanyId) //获取所属销售以及对应销售的手机号
		if e != nil {
			err = errors.New("GetCompanySellerAndShareMobileByRai, Err: " + e.Error())
			return
		}
		sllerAndShareMobiles := strings.Join(sllerAndShareMobileArr, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(sllerAndShareMobiles)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		activityInfo, e := models.GetCygxActivitySpecialDetailById(user.UserId, activityId)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialDetailById, Err: " + e.Error())
			return
		}
		if activityInfo == nil {
			return
		}
		//TripStatus            int    `description:"行程进行状态 1：预报名，2：确定行程"`
		if TripStatus == 1 {
			keyword2 = fmt.Sprint("互动：专项调研预报名,", user.RealName, "--", user.CompanyName)
		} else {
			keyword2 = fmt.Sprint("互动：活动报名,", user.RealName, "--", user.CompanyName)
		}
		keyword1 = activityInfo.ResearchTheme
		//keyword2 = "__"
		remark = "点击查看活动详情"
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		redirectUrl := utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(activityId)
		sendInfo := new(SendWxTemplate)
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Keyword4 = keyword4
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.WxMsgTemplateIdArticleUserRemind
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = strconv.Itoa(activityId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		err = PublicSendTemplateMsg(sendInfo)
		if err != nil {
			return
		}
	}
	return
}

// 确定行程用户报名模版消息推送
func ActivitySpecialUserAddTrip(user *models.WxUserItem, activityId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("确定行程用户报名模版消息推送，模板消息推送失败"+err.Error(), 2)
		}
	}()
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//获取销售手机号
	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	cnf, _ := models.GetConfigByCode("tpl_msg")

	if cnf != nil && sellerItemQy != nil {
		openIdList, e := models.GetWxOpenIdByMobileList(cnf.ConfigValue + "," + sellerItemQy.Mobile)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		activityInfo, e := models.GetCygxActivitySpecialDetailById(user.UserId, activityId)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialDetailById, Err: " + e.Error())
			return
		}
		if activityInfo == nil {
			return
		}
		keyword1 = fmt.Sprint(user.RealName, "--", user.CompanyName, "(所属销售：", sellerItemQy.RealName, ")")
		keyword2 = user.Mobile
		keyword3 = time.Now().Format(utils.FormatDateTime)
		keyword4 = "报名专项调研【" + activityInfo.ResearchTheme + "】 "
		remark = ""
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		redirectUrl := utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(activityId)
		sendInfo := new(SendWxTemplate)
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Keyword4 = keyword4
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.WxMsgTemplateIdApplyXzs
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = strconv.Itoa(activityId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		err = PublicSendTemplateMsg(sendInfo)
		if err != nil {
			return
		}
	}
	return
}
