package collection

import (
	"errors"
	"fmt"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/rddp/report"
	"hongze/hongze_yb/models/tables/rddp/report_chapter"
	"hongze/hongze_yb/models/tables/yb_community_video"
	"hongze/hongze_yb/models/tables/yb_road_video"
	"hongze/hongze_yb/models/tables/yb_user_collection"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strings"
	"sync"
	"time"
)

// 收藏类型
const (
	CollectionTypeReport    = iota + 1 // 研报
	CollectionTypeVideo                // 视频社区
	CollectionTypeRoadVideo            // 微路演视频
)

// AddCollection 加入收藏
func AddCollection(userInfo user.UserInfo,  collectionType, primaryId, extendId, sourceAgent int) (collectionId int, err error) {
	userId := int(userInfo.UserID)
	if userId <= 0 || collectionType <= 0 || primaryId <= 0 {
		return
	}

	title := ""
	nowTime := time.Now().Local()
	publishTime := nowTime

	// 判断是否曾收藏过
	var cond string
	var pars []interface{}
	cond += `user_id = ?`
	pars = append(pars, userId)
	cond += ` AND collection_type = ?`
	pars = append(pars, collectionType)
	cond += ` AND primary_id = ?`
	pars = append(pars, primaryId)
	if extendId > 0 {
		cond += ` AND extend_id = ?`
		pars = append(pars, extendId)
	}
	exist, e := yb_user_collection.GetItemByCondition(cond, pars)
	if e != nil && e != utils.ErrNoRow {
		err = errors.New("获取用户收藏失败, Err: " + e.Error())
		return
	}
	if exist != nil && exist.CollectionID > 0 {
		// 可能手快重复收藏
		collectionId = exist.CollectionID
		if exist.State == 1 {
			return
		}
		// 重新收藏
		exist.State = 1
		exist.CreateTime = nowTime
		exist.ModifyTime = nowTime
		updateCols := []string{"State", "CreateTime", "ModifyTime"}
		if e = exist.Update(updateCols); e != nil {
			collectionId = 0
			err = errors.New("重新收藏失败, Err: " + e.Error())
			return
		}
		return
	}

	// 收藏类型：1-研报; 2-视频社区; 3-微路演视频
	switch collectionType {
	case CollectionTypeReport:
		// 晨周报章节
		if extendId > 0 {
			chapter, e := report_chapter.GetItemById(extendId)
			if e != nil {
				err = errors.New("获取章节失败, Err: " + e.Error())
				return
			}
			title = chapter.Title
			publishTime = chapter.PublishTime
			break
		}
		rp, e := report.GetPublishByReportId(primaryId)
		if e != nil {
			err = errors.New("获取报告失败, Err: " + e.Error())
			return
		}
		title = rp.Title
		publishTime = rp.PublishTime
	case CollectionTypeVideo:
		video, e := yb_community_video.GetItemById(primaryId)
		if e != nil {
			err = errors.New("获取视频失败, Err: " + e.Error())
			return
		}
		title = video.Title
		publishTime = video.PublishTime
	case CollectionTypeRoadVideo:
		roadVideo, e := yb_road_video.GetItemById(primaryId)
		if e != nil {
			err = errors.New("获取路演视频失败, Err: " + e.Error())
			return
		}
		title = roadVideo.Title
		publishTime = roadVideo.PublishTime
	default:
		err = errors.New(fmt.Sprintf("收藏类型有误, 当前收藏类型%d", collectionType))
		return
	}
	companyName := "潜在客户"
	companyStatus := "潜在"
	sellerId := 0
	if userInfo.CompanyID > 0 {
		//查询ficc产品信息和ficc销售信息
		companyInfo, e := company_product.GetByCompany2ProductId(userInfo.CompanyID, 1)
		if e != nil && e != utils.ErrNoRow {
			err = errors.New("获取客户信息失败, Err: " + e.Error())
			return
		}
		if companyInfo != nil && companyInfo.CompanyID > 0 {
			companyStatus = companyInfo.Status
			companyName = companyInfo.CompanyName
			sellerId = companyInfo.SellerID
		}
	}

	// 新增收藏
	item := &yb_user_collection.YbUserCollection{
		CollectionType: collectionType,
		UserID:         userId,
		RealName:       userInfo.RealName,
		CompanyID:      int(userInfo.CompanyID),
		CompanyName:    companyName,
		CompanyStatus:  companyStatus,
		SellerID:       sellerId,
		PrimaryID:      primaryId,
		ExtendID:       extendId,
		State:          1,
		SourceAgent:    sourceAgent,
		Title:          title,
		PublishTime:    publishTime,
		CreateTime:     nowTime,
		ModifyTime:     nowTime,
	}
	if e := item.Create(); e != nil {
		err = errors.New("新增收藏失败, Err: " + e.Error())
		return
	}
	collectionId = item.CollectionID
	return
}

// CancelCollection 取消收藏
func CancelCollection(userId, collectionId int) (err error) {
	item, e := yb_user_collection.GetItemById(collectionId)
	if e != nil {
		err = errors.New("获取收藏失败, Err: " + e.Error())
		return
	}
	if item.CollectionID <= 0 {
		err = errors.New("收藏信息有误")
		return
	}
	if item.State != 1 {
		err = errors.New("收藏状态有误")
		return
	}
	if item.UserID != userId {
		err = errors.New(fmt.Sprintf("收藏人信息有误, 操作人ID: %d, 被操作人ID: %d", userId, item.UserID))
		return
	}
	updateCols := []string{"State", "ModifyTime"}
	item.State = 0
	item.ModifyTime = time.Now().Local()
	if e = item.Update(updateCols); e != nil {
		err = errors.New("更新收藏失败, Err: " + e.Error())
		return
	}
	return
}

// GetCollectionList 收藏列表
func GetCollectionList(userId, fromType, currPage, pageSize int, keywords string) (total int, respList []*response.CollectionList, err error) {
	respList = make([]*response.CollectionList, 0)
	if fromType <= 0 {
		fromType = 0
	}

	// 查询收藏列表
	var cond string
	var pars []interface{}
	cond += `state = 1 AND user_id = ?`
	pars = append(pars, userId)
	if fromType > 0 {
		cond += ` AND collection_type = ?`
		pars = append(pars, fromType)
	}
	if keywords != "" {
		cond += ` AND title LIKE ?`
		pars = append(pars, fmt.Sprint("%", keywords, "%"))
	}
	collectionTotal, e := yb_user_collection.GetPageListTotalByCondition(cond, pars)
	if e != nil {
		err = errors.New("获取收藏列表总数失败, Err: " + e.Error())
		return
	}
	total = int(collectionTotal)
	collections, e := yb_user_collection.GetPageListByCondition(cond, pars, currPage, pageSize)
	if e != nil {
		err = errors.New("获取收藏列表失败, Err: " + e.Error())
		return
	}

	// 遍历收藏列表取出各类型的ID
	reportIdArr := make([]int, 0)
	chapterIdArr := make([]int, 0)
	videoIdArr := make([]int, 0)
	roadVideoIdArr := make([]int, 0)
	for i := range collections {
		switch collections[i].CollectionType {
		case CollectionTypeReport:
			if collections[i].ExtendID > 0 {
				chapterIdArr = append(chapterIdArr, collections[i].ExtendID)
				break
			}
			reportIdArr = append(reportIdArr, collections[i].PrimaryID)
		case CollectionTypeVideo:
			videoIdArr = append(videoIdArr, collections[i].PrimaryID)
		case CollectionTypeRoadVideo:
			roadVideoIdArr = append(roadVideoIdArr, collections[i].PrimaryID)
		}
	}

	// 查询相应收藏类型详情
	var chapterErr, reportErr, videoErr, roadVideoErr error
	chapterMap := make(map[int]*report_chapter.ReportChapter, 0)
	reportMap := make(map[int]*report.Report, 0)
	videoMap := make(map[int]*yb_community_video.YbCommunityVideo, 0)
	roadVideoMap := make(map[int]*yb_road_video.YbRoadVideo, 0)

	wg := sync.WaitGroup{}

	// 章节
	wg.Add(1)
	go func() {
		defer wg.Done()

		if len(chapterIdArr) == 0 {
			return
		}
		chapters, e := report_chapter.GetListByChapterIds(chapterIdArr)
		if e != nil {
			chapterErr = errors.New("获取章节失败, Err: " + e.Error())
			return
		}
		for i := range chapters {
			chapterMap[chapters[i].ReportChapterId] = chapters[i]
		}
	}()

	// 报告
	wg.Add(1)
	go func() {
		defer wg.Done()

		if len(reportIdArr) == 0 {
			return
		}
		reports, e := report.GetListByReportIds(reportIdArr)
		if e != nil {
			reportErr = errors.New("获取报告失败, Err: " + e.Error())
			return
		}
		for i := range reports {
			reportMap[reports[i].Id] = reports[i]
		}
	}()

	// 视频
	wg.Add(1)
	go func() {
		defer wg.Done()

		if len(videoIdArr) == 0 {
			return
		}
		videos, e := yb_community_video.GetListByVideoIds(videoIdArr)
		if e != nil {
			videoErr = errors.New("获取视频失败, Err: " + e.Error())
			return
		}
		for i := range videos {
			videoMap[videos[i].CommunityVideoID] = videos[i]
		}
	}()

	// 路演视频
	wg.Add(1)
	go func() {
		defer wg.Done()

		if len(roadVideoIdArr) == 0 {
			return
		}
		roadVideos, e := yb_road_video.GetListByVideoIds(roadVideoIdArr)
		if e != nil {
			roadVideoErr = errors.New("获取视频失败, Err: " + e.Error())
			return
		}
		for i := range roadVideos {
			roadVideoMap[roadVideos[i].RoadVideoID] = roadVideos[i]
		}
	}()

	wg.Wait()

	if chapterErr != nil {
		err = chapterErr
		return
	}
	if reportErr != nil {
		err = reportErr
		return
	}
	if videoErr != nil {
		err = videoErr
		return
	}
	if roadVideoErr != nil {
		err = roadVideoErr
		return
	}

	// 响应列表
	titlePre := `<div style="-webkit-line-clamp: 2;-webkit-box-orient: vertical;display: -webkit-box;overflow: hidden;text-overflow: ellipsis;">`
	titleSuf := `</div>`
	highlightPre := `<span style="color:#E3B377">`
	highlightSuf := `</span>`
	for i := range collections {
		v := &response.CollectionList{
			CollectionId:   collections[i].CollectionID,
			CollectionType: collections[i].CollectionType,
			PrimaryId:      collections[i].PrimaryID,
			ExtendId:       collections[i].ExtendID,
			CreateTime:     collections[i].CreateTime.Format(utils.FormatDate),
		}
		// 收藏类型：1-研报; 2-视频社区; 3-微路演视频
		switch collections[i].CollectionType {
		case CollectionTypeReport:
			// 晨周报章节
			if collections[i].ExtendID > 0 {
				cp := chapterMap[collections[i].ExtendID]
				if cp != nil {
					v.PublishTime = cp.PublishTime.Format(utils.FormatDate)
					v.ClassifyName = utils.REPORT_CHAPTER_TYPE_NAME_MAP[cp.ReportType]
					v.Author = cp.Author
					v.Title = cp.Title
				}
				break
			}
			rp := reportMap[collections[i].PrimaryID]
			if rp != nil {
				v.PublishTime = rp.PublishTime.Format(utils.FormatDate)
				v.ClassifyName = rp.ClassifyNameFirst
				v.ClassifySecondName = rp.ClassifyNameSecond
				v.Author = rp.Author
				v.Title = rp.Title
			}
		case CollectionTypeVideo:
			vd := videoMap[collections[i].PrimaryID]
			if vd != nil {
				v.PublishTime = vd.PublishTime.Format(utils.FormatDate)
				v.ImgUrl = vd.CoverImgURL
				v.Title = vd.Title
			}
		case CollectionTypeRoadVideo:
			rv := roadVideoMap[collections[i].PrimaryID]
			if rv != nil {
				v.PublishTime = rv.PublishTime.Format(utils.FormatDate)
				v.ImgUrl = rv.CoverImgURL
				v.Author = rv.AdminRealName
				v.Title = rv.Title
			}
		default:
			break
		}
		// 标题富文本及高亮
		v.Title = fmt.Sprint(titlePre, v.Title, titleSuf)
		if keywords != "" {
			kw := fmt.Sprint(highlightPre, keywords, highlightSuf)
			v.Title = strings.ReplaceAll(v.Title, keywords, kw)
		}
		respList = append(respList, v)
	}

	return
}

// GetUserCollectByItem 获取用户是否已收藏
func GetUserCollectByItem(userId, collectionType, primaryId, extendId int) (collectionId int, err error) {
	if userId <= 0 || collectionType <= 0 || primaryId <= 0 {
		return
	}

	var cond string
	var pars []interface{}
	cond += `state = 1 AND user_id = ?`
	pars = append(pars, userId)
	cond += ` AND collection_type = ?`
	pars = append(pars, collectionType)
	cond += ` AND primary_id = ?`
	pars = append(pars, primaryId)
	if extendId > 0 {
		cond += ` AND extend_id = ?`
		pars = append(pars, extendId)
	}

	item, e := yb_user_collection.GetItemByCondition(cond, pars)
	if e != nil && e != utils.ErrNoRow {
		err = errors.New("获取用户收藏失败, Err: " + e.Error())
		return
	}
	if item != nil && item.CollectionID > 0 {
		collectionId = item.CollectionID
	}
	return
}

// GetUserCollectByItem 获取用户是否已收藏-列表(视频列表、路演视频列表)
func GetUserCollectByList(userId, collectionType int, primaryIds []int) (collectMap map[int]int, err error) {
	collectMap = make(map[int]int, 0)
	if userId <= 0 || collectionType <= 0 || len(primaryIds) == 0 {
		return
	}

	var cond string
	var pars []interface{}
	cond += `state = 1 AND user_id = ?`
	pars = append(pars, userId)
	cond += ` AND collection_type = ?`
	pars = append(pars, collectionType)
	cond += ` AND primary_id IN (?)`
	pars = append(pars, primaryIds)

	list, e := yb_user_collection.GetListByCondition(cond, pars)
	if e != nil {
		err = errors.New("获取用户收藏列表失败, Err: " + e.Error())
		return
	}
	for i := range list {
		if utils.InArrayByInt(primaryIds, list[i].PrimaryID) {
			collectMap[list[i].PrimaryID] = list[i].CollectionID
		}
	}
	return
}
