package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

//预报名改为行程确定的活动时，通知预报名阶段感兴趣的客户

//	func init() {
//		DetermineTripCancel(55)
//	}
func DetermineTripBeInterested(activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(msg)
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
		}
	}()
	activityInfo, e := cygx.GetAddActivityInfoSpecialById(activityId)
	if e != nil {
		err = e
		return
	}
	listSignup, e := cygx.GetCygxActivitySpecialSignupList(activityId)
	if e != nil {
		err = e
		fmt.Println(e)
		return
	}
	if len(listSignup) == 0 {
		return
	}

	var mobileArr []string
	for _, v := range listSignup {
		if v.Mobile != "" {
			mobileArr = append(mobileArr, v.Mobile)
		}
	}
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		return
	}
	//var condition string
	//var pars []interface{}
	//if mobileLen > 0 {
	//	condition += ` AND u.mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
	//	pars = append(pars, mobileArr)
	//}
	openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
	if e != nil {
		fmt.Println(e)
		return
	}

	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	var first, keyword1, keyword2, keyword3, keyword4, remark, redirectUrl string
	keyword1 = "专项调研【" + activityInfo.ResearchTheme + "】"
	keyword2 = "已确定行程，请点击查看并报名以锁定席位"
	redirectUrl = utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(services.SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE
	sendInfo.OpenIdArr = openIdArr
	err = services.SendTemplateMsg(sendInfo)
	if err != nil {
		err = errors.New("SendTemplateMsg, Err: " + err.Error())
		return
	}
	return
}

// 取消发布
func DetermineTripCancel(activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(msg)
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
		}
	}()
	activityInfo, e := cygx.GetAddActivityInfoSpecialById(activityId)
	if e != nil {
		err = e
		return
	}
	listSignup, e := cygx.GetCygxActivitySpecialTripListByActivityId(activityId)
	if e != nil {
		err = e
		return
	}
	var mobileArr []string
	for _, v := range listSignup {
		if v.Mobile != "" {
			mobileArr = append(mobileArr, v.Mobile)
		}
	}
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		return
	}
	openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
	if e != nil {
		fmt.Println(e)
		return
	}

	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	var first, keyword1, keyword2, keyword3, keyword4, remark, redirectUrl string
	keyword1 = "专项调研【" + activityInfo.ResearchTheme + "】"
	keyword2 = "因专家安排变动，本次调研活动延期举办，具体时间另行通知"
	redirectUrl = utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(services.SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE
	sendInfo.OpenIdArr = openIdArr
	err = services.SendTemplateMsg(sendInfo)
	if err != nil {
		err = errors.New("SendTemplateMsg, Err: " + err.Error())
		return
	}
	return
}

// 内容变更发布
func DetermineTripChange(activityId int, changeType, changeMsg string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(msg)
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
		}
	}()
	activityInfo, e := cygx.GetAddActivityInfoSpecialById(activityId)
	if e != nil {
		err = e
		return
	}
	listSignup, e := cygx.GetCygxActivitySpecialTripListByActivityId(activityId)
	if e != nil {
		err = e
		fmt.Println(e)
		return
	}
	var mobileArr []string
	for _, v := range listSignup {
		if v.Mobile != "" {
			mobileArr = append(mobileArr, v.Mobile)
		}
	}
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		return
	}

	openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
	if e != nil {
		fmt.Println(e)
		return
	}

	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		openIdArr[i] = v.OpenId
	}
	var first, keyword1, keyword2, keyword3, keyword4, remark, redirectUrl string
	if changeType == "City" {
		keyword1 = "【" + activityInfo.ResearchTheme + "】专项调研发生了城市变更"
	} else if changeType == "dateList" {
		keyword1 = "【" + activityInfo.ResearchTheme + "】专项调研发生了时间变更"
	} else {
		keyword1 = "【" + activityInfo.ResearchTheme + "】专项调研发生了调研形式变更"
	}
	keyword2 = changeMsg
	redirectUrl = utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(services.SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE
	sendInfo.OpenIdArr = openIdArr
	err = services.SendTemplateMsg(sendInfo)
	if err != nil {
		err = errors.New("SendTemplateMsg, Err: " + err.Error())
		return
	}
	return
}

//func init() {
//	SendWxMsgWithCygxActivitySpecialSubscribeNoInterested(7)
//}

// SendWxMsgWithCygxActivitySpecialSubscribeNoInterested  确定行程的活动通知，推送给订阅了调研活动通知且该场活动预报名阶段未点击感兴趣的客户和销售
func SendWxMsgWithCygxActivitySpecialSubscribeNoInterested(activityId int) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLogCygx.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
	}()
	activityInfo, err := cygx.GetAddActivityInfoSpecialById(activityId)
	if err != nil {
		msg = "GetReportInfo Err:" + err.Error()
		return
	}
	openIdList, err := cygx.GeFollowSpecialOpenIdList()
	if err != nil {
		msg = "get openIdList err:" + err.Error()
		return
	}
	listSignup, e := cygx.GetCygxActivitySpecialSignupList(activityId)
	if e != nil {
		err = e
		fmt.Println(e)
		return
	}

	var companyIds []int

	mapSignup := make(map[int]int)
	var arrOpenId []string
	for _, v := range listSignup {
		mapSignup[v.UserId] = v.UserId
	}

	for _, v := range openIdList {
		if _, ok := mapSignup[v.UserId]; !ok {
			arrOpenId = append(arrOpenId, v.OpenId)
			companyIds = append(companyIds, v.CompanyId)
		}
	}
	var condition string
	var pars []interface{}
	companyIdsLen := len(companyIds)
	condition = ` AND p.company_id IN (` + utils.GetOrmInReplace(companyIdsLen) + `)  GROUP BY  p.company_id  `
	pars = append(pars, companyIds)
	listMobile, e := cygx.GetAdminMobileByCompany(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetAdminOpendidByCompany, Err: " + e.Error())
		return
	}
	if len(listMobile) == 0 {
		return
	}

	var mobiles []string
	for _, vOpenid := range listMobile {
		mobiles = append(mobiles, vOpenid.Mobile)
	}

	listSeller, e := cygx.GetUserRecordListByMobileArr(mobiles)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetUserRecordListByMobileArr, Err: " + e.Error())
		return
	}
	if len(listSeller) == 0 {
		return
	}

	for _, vOpenid := range listSeller {
		arrOpenId = append(arrOpenId, vOpenid.OpenId)
	}

	if len(arrOpenId) == 0 {
		return
	}
	mapOpenid := make(map[string]string)
	for _, v := range arrOpenId {
		mapOpenid[v] = v
	}
	openIdArr := make([]string, len(mapOpenid))
	var i int
	for _, v := range mapOpenid {
		openIdArr[i] = v
		i++
	}
	var first string
	var keyword1 string
	var keyword2 string
	//keyword1 = activityInfo.ResearchTheme
	keyword1 = "【" + activityInfo.ResearchTheme + "】专项调研已确定行程"
	//keyword2 = "活动形式："
	if activityInfo.SpecialType == 1 {
		keyword2 += "线上 开始时间：" + activityInfo.ActivityTimeTextByDay
	} else {
		keyword2 += "线下 " + "（" + activityInfo.City + "） 开始时间：" + activityInfo.ActivityTimeTextByDay
	}
	remark := "点击查看活动详情"
	redirectUrl := utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(services.SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_UPDATE
	sendInfo.OpenIdArr = openIdArr
	err = services.SendTemplateMsg(sendInfo)
	return
}

//func init() {
//	SendWxMsgWithCygxActivitySpecialArticle(1000570)
//}

// 发布后，对7天内，相同产业名称的专项调研活动的报名和空降客户，推送模板消息
func SendWxMsgWithCygxActivitySpecialArticle(articleId int) (err error) {

	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("发布后，对7天内，相同产业名称的专项调研活动的报名和空降客户，发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLogCygx.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
	}()
	articleInfo, e := cygx.GetArticleIdInfoByArticleId(articleId)
	if e != nil {
		msg = "获取文章信息失败！articleId:" + strconv.Itoa(articleId)
		err = errors.New("GetArticleIdInfoByArticleId, Err: " + e.Error())
		return
	}
	industrialList, e := cygx.GetIndustrialArticleGroupManagementList(articleInfo.ArticleId)
	if e != nil && err.Error() != utils.ErrNoRow() {
		err = errors.New("获取活动关联的产业列表信息失败,GetIndustrialArticleGroupManagementList Err: " + e.Error())
		return
	}
	var industrialName string
	if len(industrialList) == 0 {
		for _, v := range industrialList {
			industrialName += v.IndustryName + ","
		}
	}
	industrialName = strings.TrimRight(industrialName, ",")
	//10分钟之内的二次编辑不重复推送
	cacheKey := fmt.Sprint("Source:ADMIN", "_ArticleId:", articleInfo.ArticleId)
	isExist := utils.Rc.IsExist(cacheKey)
	if isExist {
		return err
	}

	var condition string
	var pars []interface{}
	//condition = ` AND m.industrial_management_id IN (` + utils.GetOrmInReplace(len(industryIds)) + `)`
	//pars = append(pars, industryIds)

	//condition += ` AND a.activity_time > ? `
	//pars = append(pars, time.Now().AddDate(0, 0, -7))

	//activityList, err := cygx.GetActivitySpecialByIndustryIds(condition, pars)
	//if err != nil {
	//	return
	//}
	//if len(activityList) == 0 {
	//	return
	//}

	//for _, v := range activityList {
	//activityInfo, e := cygx.GetAddActivityInfoSpecialById(v.ActivityId)
	//if e != nil {
	//	err = errors.New("GetAddActivityInfoSpecialById, Err: " + e.Error())
	//	return
	//}

	condition = ` AND category_id = ? AND sub_category_name = '专项调研' `
	pars = append(pars, articleInfo.CategoryId)
	charInfo, e := cygx.GetReportMappingDetail(condition, pars)

	if e != nil {
		err = errors.New("GetReportMappingDetail, Err: " + e.Error())
		return
	}
	//获取有权限的相关公司
	companyList, e := company.GetCompanyReportPermissionUpgradeByChartPermissionId(charInfo.ChartPermissionId)
	if e != nil {
		err = errors.New("GetCompanyReportPermissionUpgradeByChartPermissionId, Err: " + e.Error())
		return
	}
	if len(companyList) == 0 {
		return
	}
	var companyIdArr []int
	for _, v := range companyList {
		companyIdArr = append(companyIdArr, v.CompanyId)
	}

	pars = make([]interface{}, 0)
	condition = ` AND u.company_id IN (` + utils.GetOrmInReplace(len(companyIdArr)) + `)`
	pars = append(pars, companyIdArr)

	listMobile, e := cygx.GetAdminMobileByCompany(condition, pars)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	var mobiles []string
	for _, vOpenid := range listMobile {
		mobiles = append(mobiles, vOpenid.Mobile)
	}

	openIdList, e := cygx.GetUserRecordListByMobileArr(mobiles)
	if e != nil {
		err = errors.New("GetWxOpenIdByMobileList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for i, vO := range openIdList {
		openIdArr[i] = vO.OpenId
	}
	var keyword1 string
	first := ""
	if industrialName != "" {
		keyword1 = "【" + industrialName + "】有报告发布/更新"
	} else {
		keyword1 = articleInfo.Title + "已发布"
	}
	keyword2 := articleInfo.Title
	keyword3 := articleInfo.PublishDate.Format(utils.FormatDate)
	keyword4 := "--"
	remark := "点击查看报告详情"
	redirectUrl := utils.WX_MSG_PATH_ARTICLE_DETAIL + strconv.Itoa(articleInfo.ArticleId)
	sendInfo := new(services.SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.TemplateIdByProductXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(articleInfo.ArticleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	//fmt.Println(sendInfo)
	e = services.SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("SendTemplateMsg, Err: " + e.Error())
		return
	}
	setNX := utils.Rc.SetNX(cacheKey, articleInfo.ArticleId, time.Minute*10)
	if !setNX {
		go alarm_msg.SendAlarmMsg("发送模版消息失败，10分钟之内的活动二次编辑不重复推送，设置Redis Key 过期时间失败：key"+cacheKey, 3)
		return err
	}
	return
}
