package services

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

// 研选专栏有新内容审核通过时,给关注此专栏的客户发送模板消息
func SendWxMsgSpecialFollow(specialId int) (err error) {
	defer func() {
		if err != nil {
			go utils.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 := models.GetYanxuanSpecialFollowUserById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	if len(followers) == 0 {
		return
	}
	specialItem, e := models.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 := ``

	for _, v := range userList {
		mobile += v.Mobile + ","
	}

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

	openIdList, e := models.GetWxOpenIdByMobileList(mobile)
	if e != nil {
		err = errors.New("GetSellerByAdminId, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}

	//first =
	keyword1 = "研选专栏:" + specialItem.SpecialName
	keyword2 = "发布了新内容,点击查看详情"
	keyword3 = "-"
	//keyword4 = "【" + activityInfo.ResearchTheme + "】已有10人预报名"
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := ""
	redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_DETAIL + strconv.Itoa(specialId)
	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(specialId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// SendReviewTemplateMsgAdmin 提交审核时给王芳,葛琳发消息
func SendReviewTemplateMsgAdmin(specialId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("处理试用申请给王芳,汪洋发消息失败, specialId:", specialId, "ErrMsg", err.Error()), 2)
		}
	}()
	var configCode string
	//研选专栏修改之后给这些手机号推送审核模版消息
	configCode = utils.TPL_MSG_YAN_XUAN_SPECIAL_APPROVAL
	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
	}
	specialItem, e := models.GetYanxuanSpecialItemById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(specialItem.UserId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId, Err: " + e.Error())
		return err
	}
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	keyword1 = specialItem.RealName + "【" + user.CompanyName + "】"
	keyword2 = user.Mobile
	keyword3 = time.Now().Format(utils.FormatDateTime)
	keyword4 = "研选专栏提交了内容待审核"
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	redirectUrl := ""
	redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_ENABLE_DETAIL + strconv.Itoa(specialId)
	sendInfo := new(SendWxTemplate)
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdAskMsgXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(specialId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// 研选专栏审核完成时,给提交人发送模板消息
func SendWxMsgSpecialAuthor(specialId, status int) (err error) {
	defer func() {
		if err != nil {
			go utils.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 := models.GetYanxuanSpecialItemById(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
		return
	}
	user, e := models.GetWxUserItemByUserId(specialItem.UserId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId, Err: " + e.Error())
		return err
	}

	openIdList, err := models.GetUserRecordListByMobile(4, user.Mobile)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	keyword1 = "研选专栏内容审核"
	if status == 1 {
		keyword2 = "已通过审核,点击查看详情"
		redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_DETAIL + strconv.Itoa(specialId)
	} else {
		keyword2 = "未通过审核,点击查看驳回原因"
		redirectUrl = utils.WX_MSG_PATH_YX_SPECIAL_CENTER
	}
	keyword3 = "-"
	openIdArr := make([]string, 0)
	for _, v := range openIdList {
		openIdArr = append(openIdArr, v.OpenId)
	}
	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(specialId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
	sendInfo.OpenIdArr = openIdArr
	err = PublicSendTemplateMsg(sendInfo)
	if err != nil {
		return
	}
	return
}

// 更新研选专栏  写入首页最新  cygx_resource_data 表
func UpdateYanxuanSpecialResourceData(sourceId int) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("更新研选专栏失败ourceId: ", sourceId), 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 := models.GetCygxYanxuanSpecialCount(condition, pars)
	if e != nil {
		err = errors.New("GetCygxYanxuanSpecialCount, Err: " + e.Error())
		return
	}
	//如果取消发布了就做删除处理
	if total == 0 {
		e = models.DeleteResourceData(sourceId, source)
		if e != nil {
			err = errors.New("DeleteResourceData, Err: " + e.Error())
			return
		}
	} else {
		//判断是否存在,如果不存在就新增,存在就更新
		totalData, e := models.GetCygxResourceDataBySourceAndIdCount(sourceId, source)
		if e != nil {
			err = errors.New("GetCygxReportSelectionBySourceAndId, Err: " + e.Error())
			return
		}

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

// 获取研选专栏用户信息
func GetYanxuanSpecialAuthorInfo(user *models.WxUserItem) (itemResp *models.SpecialAuthorCheckResp) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("获取研选专栏用户信息失败,GetYanxuanSpecialAuthorInfo Err ", err, "userId", user.UserId), 2)
		}
	}()
	itemResp = new(models.SpecialAuthorCheckResp)
	var condition string
	condition += ` AND a.status = 1 `
	specialUser, e := models.GetYanxuanSpecialAuthor(user.UserId, user.UserId, condition)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetYanxuanSpecialAuthor, Err: " + e.Error())
		return
	}
	if specialUser != nil {
		itemResp.IsAuthor = true
		itemResp.SpecialColumnId = specialUser.Id
		itemResp.HeadImg = specialUser.HeadImg
		//如果昵称 、专栏名称、简介 都不为空就表示信息完善
		if specialUser.SpecialName != "" && specialUser.Introduction != "" && specialUser.NickName != "" {
			itemResp.IsImproveInformation = true
		}
	}
	return
}

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

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

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

	item := new(models.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 = models.AddCygxYanxuanSpecialApprovalLog(item)
	if e != nil {
		err = errors.New("AddCygxYanxuanSpecialApprovalLog, Err: " + e.Error())
		return
	}
	return
}

// 更新文章收藏数量
func UdpateYanxuanSpecialCollect(specialId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("更新文章收藏数量失败,UdpateYanxuanSpecialCollect Err ", err, "specialId:", specialId), 2)
		}
	}()
	detail, e := models.GetYanxuanSpecialBySpecialId(specialId)
	if e != nil {
		err = errors.New("GetYanxuanSpecialBySpecialId, Err: " + e.Error())
		return
	}

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

	var condition string
	var pars []interface{}
	condition = "  AND yanxuan_special_id = ? "
	pars = append(pars, specialId)
	//专栏被收藏的数量
	totalSpecial, e := models.GetCygxYanxuanSpecialCollectCount(condition, pars)
	if e != nil {
		err = errors.New("GetCygxYanxuanSpecialCollectCount, Err: " + e.Error())
		return
	}

	pars = make([]interface{}, 0)
	condition = "  AND yanxuan_special_id  IN (SELECT id FROM cygx_yanxuan_special AS a WHERE user_id = ?)  "
	pars = append(pars, specialAuthor.UserId)
	//作者被收藏的数量
	totalAuthor, e := models.GetCygxYanxuanSpecialCollectCount(condition, pars)
	if e != nil {
		err = errors.New("GetCygxYanxuanSpecialCollectCount, Err: " + e.Error())
		return
	}

	//更新文章被收藏数量
	e = models.UpdateYanxuanSpecialarticleCollectNum(totalSpecial, specialId)
	if e != nil {
		err = errors.New("UpdateYanxuanSpecialarticleCollectNum, Err: " + e.Error())
		return
	}

	//更新作者文章被收藏数量
	e = models.UpdateYanxuanSpecialAuthorArticleCollectNum(totalAuthor, specialAuthor.UserId)
	if e != nil {
		err = errors.New("UpdateYanxuanSpecialAuthorArticleCollectNum, Err: " + e.Error())
		return
	}
	return
}

// 更新作者粉丝数量
func UdpateYanxuanSpecialFansNum(specialUserIdId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("更新作者粉丝数量失败,UdpateYanxuanSpecialFansNum Err ", err, "specialUserIdId", specialUserIdId), 2)
		}
	}()

	var condition string
	var pars []interface{}
	condition = "  AND follow_user_id = ? "
	pars = append(pars, specialUserIdId)
	//作者粉丝数量
	total, e := models.GetCygxYanxuanSpecialFollowCount(condition, pars)
	if e != nil {
		err = errors.New("GetCygxYanxuanSpecialFollowCount, Err: " + e.Error())
		return
	}
	e = models.UpdateYanxuanSpecialAuthorFansNum(total, specialUserIdId)
	if e != nil {
		err = errors.New("UpdateYanxuanSpecialAuthorFansNum, Err: " + e.Error())
		return
	}
	return
}

// UdpateYanxuanSpecialauthorArticleNum 更新作者发布文章的数量
func UdpateYanxuanSpecialauthorArticleNum(authoruserId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg(fmt.Sprint("更新作者发布文章的数量失败,UdpateYanxuanSpecialauthorArticleNum Err ", err, "userId", authoruserId), 2)
		}
	}()
	var condition string
	var pars []interface{}
	condition = ` AND status = 3  AND  user_id = ?  `
	pars = append(pars, authoruserId)
	total, e := models.GetCygxYanxuanSpecialCount(condition, pars)
	if e != nil {
		err = errors.New("GetCygxYanxuanSpecialCount, Err: " + e.Error())
		return
	}
	e = models.UdpateYanxuanSpecialauthorArticleNum(total, authoruserId)
	if e != nil {
		err = errors.New("UdpateYanxuanSpecialauthorArticleNum, Err: " + e.Error())
		return
	}
	return
}

// GetYanxuanSpecialCollectMap 根据用户ID获取所有研选专栏的收藏
func GetYanxuanSpecialCollectMap(userId int) (mapResp map[int]bool, err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("GetYanxuanSpecialCollectMap 根据用户ID获取所有研选专栏的收藏失败 ErrMsg:"+err.Error(), 2)

		}
	}()
	list, e := models.GetCygxYanxuanSpecialCollectByUser(userId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("根据用户ID获取所有文章收藏,GetCygxYanxuanSpecialCollectByUser " + e.Error())
		return
	}
	mapResp = make(map[int]bool, 0)
	if len(list) > 0 {
		for _, v := range list {
			mapResp[v.YanxuanSpecialId] = true
		}
	}
	return
}

// GetYanxuanSpecialDetailUserPower 处理用户查看研选专栏详情的权限
func GetYanxuanSpecialDetailUserPower(user *models.WxUserItem) (havePower bool, err error) {
	if user.UserId == 0 {
		havePower = true
		return
	}
	//研选专栏是否需要校验权限
	detailChart, e := models.GetConfigByCode("yanxuan_special_power_check")
	if e != nil {
		err = errors.New("GetConfigByCode, Err: " + e.Error())
		return
	}
	//如果没有开启校验,直接返回true
	if detailChart.ConfigValue == "0" {
		havePower = true
		return
	}
	//判断用户是否开通了个人研选权限

	userId := user.UserId
	companyId := user.CompanyId
	//判断用户是否开通了个人研选权限
	mfyxUserPermissionTotal := GetMfyxUserPermissionTotal(userId)

	if mfyxUserPermissionTotal == 1 {
		havePower = true
		return
	}

	//用户是否持有有效卡片
	userCardTotal := GetCygxOrderUserCardTotal(user.Mobile)
	if userCardTotal == 1 {
		havePower = true
		return
	}

	//是否是权益客户
	raiCount, e := models.GetCompanyProductCount(companyId, utils.COMPANY_PRODUCT_RAI_ID)
	if e != nil {
		err = errors.New("GetCompanyProductCount, Err: " + e.Error())
		return
	}
	if raiCount == 0 {
		return
	}

	productDetail, e := models.GetCompanyProductDetailByCompanyId(companyId, 2)
	if e != nil {
		err = errors.New("GetCompanyProductDetailByCompanyId, Err: " + e.Error())
		return
	}
	// 永续客户无法查看研选权限
	if productDetail.Status == utils.COMPANY_STATUS_FOREVER {
		return
	}
	permissionStr, e := models.GetCompanyPermission(companyId)
	if e != nil {
		err = errors.New("GetCompanyPermission, Err: " + e.Error())
		return
	}
	if strings.Contains(permissionStr, utils.CHART_PERMISSION_NAME_MF_YANXUAN) {
		havePower = true
		return
	}
	return
}