package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"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 SendWxMsgSpecialFollow(specialId int) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("研选专栏有新内容审核通过时，给关注此专栏的客户发送模板消息失败，specialId:", specialId, err.Error()), 2)

		}
	}()
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string

	followers, e := cygx.GetYanxuanSpecialFollowUserById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	if len(followers) == 0 {
		return
	}
	specialItem, e := cygx.GetYanxuanSpecialItemById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	var allInUserId string
	for _, v := range followers {
		allInUserId += strconv.Itoa(v) + ","
	}

	allInUserId = strings.TrimRight(allInUserId, ",")

	userList, err := models.GetWxUserListByUserIds(allInUserId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	mobile := make([]string, 0)

	for _, v := range userList {
		mobile = append(mobile, v.Mobile)
	}

	openIdList, e := cygx.GetUserRecordListByMobileArr(mobile)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}

	if len(openIdList) == 0 {
		return
	}
	keyword1 = "研选专栏：" + specialItem.SpecialName
	keyword2 = "发布了新内容，点击查看详情"

	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := ""

	if utils.RunMode == "release" {
		redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_DETAIL + strconv.Itoa(specialId)
	}
	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(specialId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = services.SendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

//func init() {
//	SendWxMsgSpecialAuthor(190, 1)
//}

// 研选专栏审核完成时，给提交人发送模板消息
func SendWxMsgSpecialAuthor(specialId, status int) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("研选专栏审核完成时，给提交人发送模板消息 specialId:", specialId, err.Error()), 2)
		}
	}()
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	var redirectUrl string

	specialItem, e := cygx.GetYanxuanSpecialItemById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	user, e := models.GetWxUserByUserId(specialItem.UserId)
	if e != nil {
		err = errors.New("GetWxUserByUserId, Err: " + e.Error())
		return err
	}
	var mobiles []string
	mobiles = append(mobiles, user.Mobile)
	openIdList, err := cygx.GetUserRecordListByMobileArr(mobiles)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	if len(openIdList) == 0 {
		return
	}

	//first =
	keyword1 = "研选专栏内容审核"
	if status == 1 {
		keyword2 = "已通过审核，点击查看详情"
		if utils.RunMode == "release" {
			redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_DETAIL + strconv.Itoa(specialId)
		}
	} else {
		keyword2 = "未通过审核，点击查看驳回原因"
		if utils.RunMode == "release" {
			redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_CENTER
		}
	}

	keyword3 = "-"
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	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(specialId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	fmt.Println(sendInfo)
	err = services.SendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// SendReviewTemplateMsgAdmin 提交审核时给王芳，汪洋发消息
//func SendReviewTemplateMsgAdmin(req models.ApplyTryReq, usermobile, applyMethod string, isResearch bool) (err error) {
//	defer func() {
//		if err != nil {
//			go utils.SendAlarmMsg("处理试用申请给王芳，汪洋发消息失败, ErrMsg: "+err.Error(), 3)
//		}
//	}()
//	var configCode string
//	//如果是研选的就推送给汪洋跟王芳，否则就推送给王芳
//	if isResearch {
//		configCode = utils.TPL_MSG_WANG_FANG_WANG_YANG
//	} else {
//		configCode = utils.TPL_MSG
//	}
//	cnf, e := models.GetConfigByCode(configCode)
//	if e != nil {
//		err = errors.New("GetConfigByCode, Err: " + e.Error() + configCode)
//		return
//	}
//	openIdList, e := models.GetUserRecordListByMobile(4, cnf.ConfigValue)
//	if e != nil && e.Error() != utils.ErrNoRow() {
//		err = errors.New("GetUserRecordListByMobile, Err: " + e.Error() + cnf.ConfigValue)
//		return err
//	}
//
//	for _, v := range openIdList {
//		go SendPermissionApplyTemplateMsg(req.RealName, req.CompanyName, usermobile, applyMethod, v)
//	}
//
//	return
//}

//func init() {
//	UpdateYanxuanSpecialResourceData(190)
//}

// 更新研选专栏  写入首页最新  cygx_resource_data 表
func UpdateYanxuanSpecialResourceData(sourceId int) {
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("更新研选专栏失败ourceId: ", sourceId, err.Error()), 2)
		}
	}()
	var source = utils.CYGX_OBJ_YANXUANSPECIAL
	var condition string
	var pars []interface{}
	condition = ` AND status = 3  AND  id = ?  `
	pars = append(pars, sourceId)
	total, e := cygx.GetCygxYanxuanSpecialCount(condition, pars)

	if e != nil {
		err = errors.New("GetCygxYanxuanSpecialCount, Err: " + e.Error())
		return
	}
	//如果取消发布了就做删除处理
	if total == 0 {
		e = cygx.DeleteResourceData(sourceId, source)
		if e != nil {
			err = errors.New("DeleteResourceData, Err: " + e.Error())
			return
		}
	} else {
		//判断是否存在，如果不存在就新增，存在就更新
		totalData, e := cygx.GetCygxResourceDataBySourceAndIdCount(sourceId, source)
		if e != nil {
			err = errors.New("GetCygxReportSelectionBySourceAndId, Err: " + e.Error())
			return
		}
		detail, e := cygx.GetYanxuanSpecialItemById(sourceId)
		if e != nil {
			err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
			return
		}

		publishDate := time.Now().Format(utils.FormatDateTime)
		item := new(cygx.CygxResourceData)
		item.SourceId = sourceId
		item.Source = source
		item.PublishDate = publishDate
		item.CreateTime = time.Now()
		item.SearchTitle = detail.Title
		item.SearchContent = ""
		item.SearchOrderTime = publishDate
		if totalData == 0 {
			_, e := cygx.AddCygxResourceData(item)
			if e != nil {
				err = errors.New("AddCygxResourceData, Err: " + e.Error())
				return
			}
		} else {
			e = cygx.UpdateResourceDataByItem(item)
			if e != nil {
				err = errors.New("UpdateResourceDataByItem, Err: " + e.Error())
				return
			}
		}
	}
	return
}

// 研选专栏审批记录
func AddAddCygxYanxuanSpecialApprovalLog(user *models.WxUserItem, specialId, status int, reason string) {
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("获取研选专栏用户信息失败,GetYanxuanSpecialAuthorInfo Err ", err, "userId", user.UserId), 2)
		}
	}()
	detail, e := cygx.GetYanxuanSpecialBySpecialId(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialBySpecialId, Err: " + e.Error())
		return
	}

	specialAuthor, e := cygx.GetCygxYanxuanSpecialAuthorByUserId(detail.UserId)
	if e != nil {
		err = errors.New("GetCygxYanxuanSpecialAuthorByUserId, Err: " + e.Error())
		return
	}

	item := new(cygx.CygxYanxuanSpecialApprovalLog)
	item.UserId = detail.UserId
	item.Content = detail.Content
	item.Tags = detail.Tags
	item.ApprovalStatus = status
	item.ImgUrl = detail.ImgUrl
	item.DocUrl = detail.DocUrl
	item.Reason = reason
	item.Title = detail.Title
	item.Type = detail.Type
	item.CompanyTags = detail.CompanyTags
	item.IndustryTags = detail.IndustryTags
	item.YanxuanSpecialId = specialId
	item.AdminName = user.RealName
	item.AdminUserId = user.UserId
	item.SpecialName = specialAuthor.SpecialName
	item.NickName = specialAuthor.NickName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()

	e = cygx.AddCygxYanxuanSpecialApprovalLog(item)
	if e != nil {
		err = errors.New("AddCygxYanxuanSpecialApprovalLog, Err: " + e.Error())
		return
	}
	return
}

// 获取专栏用户最新的一篇文章信息
func GetBestNewYanxuanSpecialByUserId(userIds []int) (mapResp map[int]string) {
	lenArr := len(userIds)
	if lenArr == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("获取研选专栏用户信息失败,GetBestNewYanxuanSpecialByUserId Err ", err, "userIds", userIds), 2)
		}
	}()
	var condition string
	var pars []interface{}
	condition += `  AND  a.publish_time = ( SELECT max( b.publish_time ) FROM cygx_yanxuan_special b WHERE a.user_id = b.user_id  AND b.STATUS = 3 )  AND user_id  IN (` + utils.GetOrmInReplace(lenArr) + `) AND a.status = 3  GROUP BY user_id ORDER BY publish_time DESC`
	pars = append(pars, userIds)
	list, e := cygx.GetYanxuanSpecialListBycondition(condition, pars, 0, lenArr)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetYanxuanSpecialListBycondition, Err: " + e.Error())
		return
	}
	mapResp = make(map[int]string, 0)
	for _, v := range list {
		mapResp[v.UserId] = v.PublishTime.Format(utils.FormatDateTime)
	}
	return
}
