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 init() {
//	SendWxMsgCygxQuestionnaire(2)
//}

// 投票发布时，给所有开通买方研选正式试用的客户
func SendWxMsgCygxQuestionnaire(questionnaireId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("投票发布时，给所有开通买方研选正式试用的客户，questionnaireId:", questionnaireId, err.Error()), 2)
		}
	}()

	//获取问卷详情
	detail, e := cygx.GetCygxQuestionnaireDetail(questionnaireId)
	if e != nil {
		err = errors.New("GetCygxQuestionnaireDetail, Err: " + e.Error())
		return
	}

	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var companyIds []int

	var condition string
	var pars []interface{}
	condition = "  AND  chart_permission_id = 31 AND `status` IN ('正式','试用')  "
	//获取所有开通买方研选正式试用的客户列表
	listCompany, e := company.GetCompanyReportPermissionList(condition, pars, 0, 0)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCygxQuestionnaireDetail, Err: " + e.Error())
		return
	}
	for _, v := range listCompany {
		companyIds = append(companyIds, v.CompanyId)
	}

	//获取相关的用户
	userList, e := models.GetWxUserByCompanyIds(companyIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetWxUserByCompanyIds, Err: " + e.Error())
		return
	}
	mobile := make([]string, 0)
	for _, v := range userList {
		mobile = append(mobile, v.Mobile)
	}

	//获取用户对应的Openid
	openIdList, e := cygx.GetUserRecordListByMobileArr(mobile)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}

	if len(openIdList) == 0 {
		return
	}
	keyword1 = "买方研选【" + detail.ActivityTypeName + "】主题投票"
	keyword2 = "请选择您感兴趣的主题"

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := ""
	if utils.RunMode == "release" {
		redirectUrl = utils.WX_MSG_PATH_QUESTIONNAIRE_DETAIL + strconv.Itoa(questionnaireId)
	}
	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(questionnaireId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	e = services.SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("SendTemplateMsg, Err: " + e.Error())
		return
	}
	return
}
