package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"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"
)

// 修改活动人数限制之后，对于因为人数已满而失败的用户，推送模板消息
func SendWxMsgWithCygxActivityUpdateLimitPeople(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, e := cygx.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("活动不存在, Err: " + e.Error())
		return
	}
	if activityInfo == nil {
		return
	}
	//已经推送过的不做二次推送
	listSendOpendId, err := models.GeUserTemplateRecordListBysendType(utils.TEMPLATE_MSG_CYGX_ACTIVITY_LIMIT_PEOPLE, strconv.Itoa(activityId))
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	mapSendOpenid := make(map[string]int)
	for _, v := range listSendOpendId {
		mapSendOpenid[v.OpenId] = v.UserId
	}

	var condition string
	var pars []interface{}

	condition = ` AND do_fail_type = 1 AND  activity_id = ?  `
	pars = append(pars, activityId)
	listSignup, e := cygx.GetActivitySignupList(condition, pars)
	if e != nil {
		err = errors.New("GetResourceDataList, Err: " + e.Error())
		return
	}
	var mobileArr []string
	for _, v := range listSignup {
		if v.Mobile != "" {
			mobileArr = append(mobileArr, v.Mobile)
		}
	}
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		return
	}
	//condition = ""
	//pars = make([]interface{}, 0)
	//condition += ` AND u.mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
	//pars = append(pars, mobileArr)

	openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
	if e != nil {
		err = errors.New("GetWxOpenIdBList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for i, v := range openIdList {
		if mapSendOpenid[v.OpenId] > 0 {
			continue
		}
		openIdArr[i] = v.OpenId
	}
	first := "您好，本场活动已增加活动名额至" + activityInfo.LimitPeopleNum + "人,欢迎报名"
	keyword1 := activityInfo.ActivityName
	keyword2 := "已增加活动名额至" + activityInfo.LimitPeopleNum + "人,欢迎报名"
	keyword3 := ""
	keyword4 := ""
	remark := "点击查看活动详情"
	redirectUrl := utils.WX_MSG_PATH_ACTIVITY_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_LIMIT_PEOPLE
	sendInfo.OpenIdArr = openIdArr
	e = services.SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("SendTemplateMsg, Err: " + e.Error())
		return
	}
	return
}

// 销售或后台管理员给用户添加报名之后，进行模版消息推送
func SendWxMsgWithCygxActivitySignUpBySell(items []*cygx.CygxSignupUser) (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))
		}
	}()

	if len(items) == 0 {
		return
	}
	//var condition string
	//var pars []interface{}

	for _, v := range items {
		activityId := v.ActivityId
		uid := v.UserId
		activityInfo, e := cygx.GetAddActivityInfoById(activityId)
		if e != nil {
			err = errors.New("活动不存在, Err: " + e.Error())
			return
		}
		if activityInfo == nil {
			return
		}
		wxUser, e := models.GetWxUserByUserId(uid)
		if e != nil {
			err = errors.New("查询用户信息失败, Err: " + e.Error())
			return
		}
		var mobileArr []string
		mobileArr = append(mobileArr, wxUser.Mobile)
		mobileLen := len(mobileArr)
		if mobileLen == 0 {
			return
		}
		//condition = ""
		//pars = make([]interface{}, 0)
		//condition += ` AND u.mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
		//pars = append(pars, mobileArr)

		openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
		if e != nil {
			err = errors.New("GetWxOpenIdBList, Err: " + e.Error())
			return
		}
		if len(openIdList) == 0 {
			return
		}
		openIdArr := make([]string, len(openIdList))
		for i, v := range openIdList {
			fmt.Println(v.OpenId)
			openIdArr[i] = v.OpenId
		}
		first := "对口销售已为您报名本场活动"
		keyword1 := "销售已为您报名:" + activityInfo.ActivityName
		keyword2 := activityInfo.ActivityTimeText
		keyword3 := ""
		keyword4 := ""
		remark := "点击查看活动详情"
		redirectUrl := utils.WX_MSG_PATH_ACTIVITY_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.WxMsgTemplateIdActivityApplyXzs
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = strconv.Itoa(activityId)
		sendInfo.SendType = utils.TEMPLATE_MSG_ACTIVITY_APPOINTMENT
		sendInfo.OpenIdArr = openIdArr
		e = services.SendTemplateMsg(sendInfo)
		if e != nil {
			err = errors.New("SendTemplateMsg, Err: " + e.Error())
			return
		}
	}
	return
}

// 已结束的活动上传音频或视频后给已关注这个活动关联的产业的正式、试用 客户发送模板信息
func SendWxMsgWithUpdateActivityVideoAndVoice(activityId int, fileName string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("已结束的活动上传音频或视频后给已关注这个活动关联的产业的正式、试用 客户发送模板信息失败，Err："+err.Error()+";activityId:", activityId), 3)
			//utils.FileLogCygx.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
	}()
	activityInfo, e := cygx.GetAddActivityInfoById(activityId)
	if e != nil {
		err = errors.New("活动不存在, Err: " + e.Error())
		return
	}
	if activityInfo == nil {
		return
	}
	industrialList, e := cygx.GetIndustrialActivityGroupListByactivityIds(strconv.Itoa(activityId))
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetIndustrialActivityGroupListByactivityIds: " + e.Error())
		return
	}

	//if len(industrialList) == 0 {
	//	return
	//}

	var industrialManagementIds []int

	for _, v := range industrialList {
		industrialManagementIds = append(industrialManagementIds, v.IndustrialManagementId)
	}
	lenindustrialManagementIds := len(industrialManagementIds)
	if lenindustrialManagementIds == 0 {
		return
	}

	var condition string
	var pars []interface{}

	//获取试用正式权益客户
	condition = "  AND product_id = 2 AND `status` IN('正式','试用')  "
	listCompany, e := company.GetCompanyProductList(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyProductList, Err: " + e.Error())
		return
	}
	var companyIds []int
	for _, v := range listCompany {
		companyIds = append(companyIds, v.CompanyId)
	}
	lencompanyIds := len(companyIds)
	if lencompanyIds == 0 {
		return
	}

	//根据产业关注ID，与有权限的公司ID获取对应的用户列表
	condition = " AND  industrial_management_id IN (" + utils.GetOrmInReplace(lenindustrialManagementIds) + ")  AND company_id IN (" + utils.GetOrmInReplace(lencompanyIds) + ") "
	pars = append(pars, industrialManagementIds, companyIds)
	userFllowList, e := cygx.GetCygxIndustryFllowList(condition, pars, 0, 0)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxIndustryFllowList, Err: " + e.Error())
		return
	}

	//获取这些用户的手机号
	var mobileArr []string
	for _, v := range userFllowList {
		mobileArr = append(mobileArr, v.Mobile)
	}
	mobileLen := len(mobileArr)
	if mobileLen == 0 {
		return
	}

	openIdList, e := cygx.GetUserRecordListByMobileArr(mobileArr)
	if e != nil {
		err = errors.New("GetWxOpenIdBList, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}
	openIdArr := make([]string, len(openIdList))
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}

	keyword1 := fileName
	keyword2 := "路演回放已发布，欢迎查看"
	keyword3 := ""
	keyword4 := ""

	redirectUrl := utils.WX_MSG_PATH_ACTIVITY_DETAIL + strconv.Itoa(activityId)
	sendInfo := new(services.SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4

	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(activityId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_LIMIT_PEOPLE
	sendInfo.OpenIdArr = openIdArr
	e = services.SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("SendTemplateMsg, Err: " + e.Error())
		return
	}
	return
}
