package services

import (
	"context"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strconv"
	"time"
)

func GetArticleHistoryByUser(articleIds []int, user *models.WxUserItem) (mapResp map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取用户的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenIds := len(articleIds)
	if lenIds == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND article_id IN (` + utils.GetOrmInReplace(lenIds) + `) AND  user_id = ?`
	pars = append(pars, articleIds, user.UserId)
	list, err := models.GetCygxArticleHistoryRecordNewpvListPv(condition, pars)
	if err != nil {
		return
	}
	mapResp = make(map[int]int, 0)
	for _, v := range list {
		mapResp[v.ArticleId] = v.Pv
	}
	return
}

func GetArticleHistoryByArticleId(articleIds []int) (mapResp map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取用户的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenIds := len(articleIds)
	if lenIds == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND article_id IN (` + utils.GetOrmInReplace(lenIds) + `) `
	pars = append(pars, articleIds)
	listCy, e := models.GetCygxArticleHistoryRecordNewpvListPvCy(condition, pars)
	if e != nil {
		err = errors.New("GetCygxArticleHistoryRecordNewpvListPvCy, Err: " + e.Error())
		return
	}
	mapResp = make(map[int]int, 0)
	for _, v := range listCy {
		mapResp[v.ArticleId] = v.Pv
	}

	listCl, e := models.GetCygxArticleHistoryRecordNewpvListPvCl(condition, pars)
	if e != nil {
		err = errors.New("GetCygxArticleHistoryRecordNewpvListPvCy, Err: " + e.Error())
		return
	}
	for _, v := range listCl {
		mapResp[v.ArticleId] += v.Pv
	}
	return
}

// 记录用户文章浏览记录
func ArticleHistory(articleId int, user *models.WxUserItem) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("记录用户文章浏览记录，失败"+err.Error(), 2)
		}
	}()

	uid := user.UserId
	key := "CYGX_ARTICLE_" + strconv.Itoa(articleId) + "_" + strconv.Itoa(uid)
	if !utils.Rc.IsExist(key) {
		//新增浏览记录
		//这个表貌似没怎么用了，暂时保留记录
		record := new(models.CygxArticleViewRecord)
		record.UserId = uid
		record.ArticleId = articleId
		record.CreateTime = time.Now()
		record.Mobile = user.Mobile
		record.Email = user.Email
		record.CompanyId = user.CompanyId
		record.CompanyName = user.CompanyName
		_, e := models.AddCygxArticleViewRecord(record)
		if e != nil {
			err = errors.New("AddCygxArticleViewRecord, Err: " + e.Error())
			return
		}

		e = models.ModifyReportLastViewTime(uid)
		if e != nil {
			err = errors.New("ModifyReportLastViewTime, Err: " + e.Error())
			return
		}
		utils.Rc.Put(key, 1, 2*time.Second)
	}
	return
}

// 记录用户文章浏览记录带时长
func ArticleHistoryStopTime(articleId, stopTime, outType int, user *models.WxUserItem) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("记录用户文章浏览记录带时长，失败"+err.Error(), 2)
		}
	}()
	if stopTime < 3 {
		return
	}
	uid := user.UserId

	key := "CYGX_ARTICLE_PV" + strconv.Itoa(articleId) + "_" + strconv.Itoa(uid) + "_" + strconv.Itoa(user.CompanyId) + "_" + strconv.Itoa(outType)
	if !utils.Rc.IsExist(key) {
		record := new(models.CygxArticleHistoryRecordNewpv)
		record.UserId = uid
		record.ArticleId = articleId
		record.CreateTime = time.Now().Add(-time.Second * time.Duration(stopTime))
		record.ModifyTime = time.Now()
		record.Mobile = user.Mobile
		record.Email = user.Email
		record.CompanyId = user.CompanyId
		record.CompanyName = user.CompanyName
		record.StopTime = stopTime
		record.OutType = outType
		record.RegisterPlatform = utils.REGISTER_PLATFORM
		record.Source = "MOBILE"
		newId, e := models.AddCygxArticleViewRecordNewpv(record)
		if e != nil {
			err = errors.New("AddCygxArticleViewRecordNewpv, Err: " + e.Error())
			return
		}
		recordRedis := new(ReportViewRecord)
		recordRedis.UserId = user.UserId
		recordRedis.ReportId = articleId
		recordRedis.Mobile = user.Mobile
		recordRedis.Email = user.Email
		recordRedis.RealName = user.RealName
		recordRedis.CompanyName = user.CompanyName
		recordRedis.StopTime = stopTime
		recordRedis.ViewTime = record.CreateTime.Format(utils.FormatDateTime)
		recordRedis.OutId = int(newId)
		//recordRedis.CreateTime = time.Now()
		go PushViewRecordNewRedisData(recordRedis, user.CompanyId)
		go ArticleWxUserRaiLabelRedisAdd(articleId, user.UserId, record.CreateTime)
		utils.Rc.Put(key, 1, 2*time.Second)
	}
	go ArticleHistoryUserLabelLogAdd(articleId, uid)
	return
}

//func init() {
//	AddAllArticleAndYanxuanHistory()
//}

// 定时任务更新文章和研选专栏记录
func AddAllArticleAndYanxuanHistory(cont context.Context) (err error) {
	//func AddAllArticleAndYanxuanHistory() (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("同步阅读记录到es失败;AddAllArticleHistory Err:"+err.Error(), 2)
		}
	}()

	var pars []interface{}
	var condition string

	var companyIds []int
	condition = " AND  product_id = 2  AND STATUS IN ( '正式', '试用', '冻结' ) "
	list, e := models.GetCompanyProductList(condition, pars)
	if e != nil {
		err = errors.New("GetCompanyProductList, Err: " + e.Error())
		return
	}

	for _, v := range list {
		companyIds = append(companyIds, v.CompanyId)
	}

	//添加文章记录
	{
		condition = ""
		pars = make([]interface{}, 0)
		condition = " AND art.company_id IN (" + utils.GetOrmInReplace(len(companyIds)) + ") AND   art.is_del = 0  AND art.create_time >= ?   AND art.create_time <= ?  "
		pars = append(pars, companyIds, time.Now().AddDate(0, 0, -1).Format(utils.FormatDate), time.Now().Format(utils.FormatDate))
		total, e := models.GetCygxArticleHistoryRecordAllCountBycondition(condition, pars)
		if e != nil {
			err = errors.New("GetCygxArticleHistoryRecordAllCount, Err: " + e.Error())
			return
		}
		for i := 0; i <= total/2000; i++ {
			allList, e := models.GetCygxArticleHistoryRecordAllList(condition, pars, 2000*i, 2000)
			if e != nil {
				err = errors.New("GetCygxArticleHistoryRecordAllList, Err: " + e.Error())
				return
			}
			var items []*models.CygxArticleAndYanxuanRecord
			for _, v := range allList {
				item := new(models.CygxArticleAndYanxuanRecord)
				item.SourceId = v.ArticleId
				item.Source = utils.CYGX_OBJ_ARTICLE
				item.UserId = v.UserId
				item.RealName = v.RealName
				item.Mobile = v.Mobile
				item.Email = v.Email
				item.CompanyId = v.CompanyId
				item.CompanyName = v.CompanyName
				item.CompanyId = v.CompanyId
				item.CreateTime = v.CreateTime
				item.ModifyTime = v.ModifyTime
				item.StopTime = v.StopTime
				if v.Source == "CELUE" {
					item.RegisterPlatform = 3
				} else if v.Source == "WEB" {
					item.RegisterPlatform = 2
				} else {
					item.RegisterPlatform = 1
				}
				items = append(items, item)
			}
			e = models.AddCygxArticleAndYanxuanRecordMulti(items)
			if e != nil {
				err = errors.New("AddCygxArticleAndYanxuanRecordMulti, Err: " + e.Error())
				return
			}
		}
	}

	//添加研选专栏记录
	{
		condition = ""
		pars = make([]interface{}, 0)
		condition = " AND   art.create_time >= ?   AND art.create_time <= ?   AND  user_id > 0 "
		pars = append(pars, time.Now().AddDate(0, 0, -1).Format(utils.FormatDate), time.Now().Format(utils.FormatDate))
		totalYanxuanSpecial, e := models.GetCygxYanxuanSpecialRecordCount(condition, pars)
		if e != nil {
			err = errors.New("GetCygxYanxuanSpecialRecordCount, Err: " + e.Error())
			return
		}
		for i := 0; i <= totalYanxuanSpecial/2000; i++ {
			listYanxuanSpecialRecord, e := models.GetCygxYanxuanSpecialRecordRespList(condition, pars, 2000*i, 2000)
			if e != nil {
				err = errors.New("GetCygxYanxuanSpecialRecordRespList, Err: " + e.Error())
				return
			}
			var items []*models.CygxArticleAndYanxuanRecord
			for _, v := range listYanxuanSpecialRecord {
				item := new(models.CygxArticleAndYanxuanRecord)
				item.SourceId = v.YanxuanSpecialId
				item.Source = utils.CYGX_OBJ_YANXUANSPECIAL
				item.UserId = v.UserId
				item.RealName = v.RealName
				item.Mobile = v.Mobile
				item.Email = v.Email
				item.CompanyId = v.CompanyId
				item.CompanyName = v.CompanyName
				item.CompanyId = v.CompanyId
				item.CreateTime = v.CreateTime
				item.ModifyTime = v.ModifyTime
				item.StopTime = v.StopTime
				item.PermissionCode = v.PermissionCode
				item.RegisterPlatform = v.RegisterPlatform
				items = append(items, item)
			}
			e = models.AddCygxArticleAndYanxuanRecordMulti(items)
			if e != nil {
				err = errors.New("AddCygxArticleAndYanxuanRecordMulti, Err: " + e.Error())
				return
			}
		}
	}

	return
}
