package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

// GetMicroRoadShowDefaultImgConfig 获取微路演默认图/分享图配置
func GetMicroRoadShowDefaultImgConfig() (audioMap, videoMap, audioShareMap, videoShareMap map[int]string, err error) {
	audioMap = make(map[int]string, 0)
	videoMap = make(map[int]string, 0)
	audioShareMap = make(map[int]string, 0)
	videoShareMap = make(map[int]string, 0)
	key := models.MicroRoadshowDefaultImgKey
	conf, e := models.GetConfigByCode(key)
	if e != nil {
		err = errors.New("获取微路演默认图配置失败, Err: " + e.Error())
		return
	}
	if conf.ConfigValue == "" {
		err = errors.New("获取微路演默认图配置有误")
		return
	}
	list := new(models.MicroRoadShowDefaultImgList)
	if e = json.Unmarshal([]byte(conf.ConfigValue), &list); e != nil {
		err = errors.New("微路演默认图配置配置值解析失败, Err: " + e.Error())
		return
	}
	audioList := list.Audio
	for i := range audioList {
		audioMap[audioList[i].ChartPermissionId] = audioList[i].ImgUrl
		audioShareMap[audioList[i].ChartPermissionId] = audioList[i].ShareImg
	}
	videoList := list.Video
	for i := range videoList {
		videoMap[videoList[i].ChartPermissionId] = videoList[i].ImgUrl
		videoShareMap[videoList[i].ChartPermissionId] = videoList[i].ShareImg
	}
	return
}

// GetHomeNewestList 获取首页最新列表
func GetHomeNewestList(userId, companyId, startSize, pageSize int, condition string, pars []interface{}) (resp []*models.HomeArticle, total int, err error) {
	resp = make([]*models.HomeArticle, 0)
	unionList, e := models.GetHomeNewestListUnionList(condition, pars, startSize, pageSize)
	if e != nil {
		err = errors.New("获取首页最新列表失败")
		return
	}
	unionTotal, e := models.GetHomeNewestListUnionCount(condition, pars)
	if e != nil {
		err = errors.New("获取首页最新列表总数失败")
		return
	}
	total = unionTotal

	// 用户权限
	authInfo, permissionArr, e := GetUserRaiPermissionInfo(userId, companyId)
	if e != nil {
		err = errors.New("获取用户权限失败, Err: " + e.Error())
		return
	}

	// 获取默认图配置
	audioMap, videoMap, audioShareMap, videoShareMap, e := GetMicroRoadShowDefaultImgConfig()
	if e != nil {
		err = errors.New("获取微路演默认图配置失败, Err: " + e.Error())
		return
	}

	// 此处没有直接使用HomeArticle结构体而是多加了一层, 纯粹是为了方便前端区分纪要和微路演音频=_=!
	for _, v := range unionList {
		item := new(models.HomeArticle)
		item.HomeType = v.HomeType
		// 纪要
		if item.HomeType == 0 {
			item.ArticleId = v.ArticleId
			item.Title = v.Title
			item.TitleEn = v.TitleEn
			item.UpdateFrequency = v.UpdateFrequency
			item.CreateDate = v.CreateDate
			item.PublishDate = v.PublishDate
			item.Body = v.Body
			item.BodyHtml = v.BodyHtml
			item.Abstract = v.Abstract
			item.CategoryName = v.CategoryName
			item.SubCategoryName = v.SubCategoryName
			item.ExpertBackground = v.ExpertBackground
			item.IsResearch = v.IsResearch
			item.Pv = v.Pv
			item.ImgUrlPc = v.ImgUrlPc
			item.CategoryId = v.CategoryId
			item.HttpUrl = v.HttpUrl
			item.IsNeedJump = v.IsNeedJump
			item.Source = v.Source
			item.Annotation = v.Annotation
		}
		// 音频
		if v.HomeType == 1 {
			ad := new(models.MicroAudioUnionList)
			ad.Id = v.Id
			ad.AudioTitle = v.AudioTitle
			ad.AudioResourceUrl = v.AudioResourceUrl
			ad.AudioType = v.AudioType
			ad.AudioPublishTime = utils.StrTimeToTime(v.AudioPublishTime).Format(utils.FormatDate)
			ad.AudioImgUrl = v.AudioImgUrl
			ad.AudioChartPermissionId = v.AudioChartPermissionId
			ad.AudioChartPermissionName = v.AudioChartPermissionName
			ad.AudioPlaySeconds = v.AudioPlaySeconds
			ad.AudioPlaySeconds = v.AudioPlaySeconds
			ad.AudioActivityId = v.AudioActivityId
			item.MicroAudio = ad
			// 默认图
			if ad.AudioImgUrl == "" {
				if ad.AudioType == 1 {
					ad.AudioImgUrl = audioMap[ad.AudioChartPermissionId]
				} else {
					ad.AudioImgUrl = videoMap[ad.AudioChartPermissionId]
				}
			}
			// 分享图
			if ad.AudioType == 1 {
				ad.AudioShareImg = audioShareMap[ad.AudioChartPermissionId]
			} else {
				ad.AudioShareImg = videoShareMap[ad.AudioChartPermissionId]
			}
			// 权限
			au := new(models.UserPermissionAuthInfo)
			au.SellerName = authInfo.SellerName
			au.SellerMobile = authInfo.SellerMobile
			au.HasPermission = authInfo.HasPermission
			au.OperationMode = authInfo.OperationMode
			if au.HasPermission == 1 {
				// 非宏观权限进一步判断是否有权限
				if ad.AudioChartPermissionId != utils.HONG_GUAN_ID && !utils.InArrayByStr(permissionArr, ad.AudioChartPermissionName) {
					au.HasPermission = 2
				}
			}
			// 无权限的弹框提示
			if au.HasPermission != 1 {
				if au.OperationMode == UserPermissionOperationModeCall {
					if ad.AudioType == 1 {
						au.PopupMsg = UserPermissionPopupMsgCallActivity
					} else {
						au.PopupMsg = UserPermissionPopupMsgCallMicroVideo
					}
				} else {
					if ad.AudioType == 1 {
						au.PopupMsg = UserPermissionPopupMsgApplyActivity
					} else {
						au.PopupMsg = UserPermissionPopupMsgApplyMicroVideo
					}
				}
			}
			ad.AuthInfo = au
		}
		resp = append(resp, item)
	}
	return
}

// GetMicroRoadShowPageList 获取微路演列表添加活动视频 更新与8.1版本
func GetMicroRoadShowPageListV8(pageSize, currentIndex, audioId, videoId, activityVideoId int, filter, keywords, audioIds, videoIds, activityVideoIds, chartPermissionIds string) (respList []*models.MicroRoadShowPageList, total int, err error) {
	var e error
	// 根据每页数据量获取音视频配比
	startSize := utils.StartIndex(currentIndex, pageSize)
	videoList := make([]*models.MicroRoadShowPageList, 0)
	if keywords != "" {
		keywords = "%" + keywords + "%"
	}

	//音频的查询
	var audioCond string
	var audioPars []interface{}
	// 如果筛选条件为指定视频ID或只看视频则不做音频查询
	//if videoId > 0 || activityVideoId > 0 || filter == 1 {
	//	audioCond = ""
	//} else {
	// 活动已发布且已结束
	audioCond += ` AND b.publish_status = 1 AND b.active_state = 3`
	//活动音频，设置有效时间为30天，失效后该活动就不再支持音频回放。有效期起始时间为活动的开始时间
	//endTime := time.Now().AddDate(0, 0, -30).Format("2006-01-02 15:04:05")
	//audioCond += ` AND b.activity_time > ? `
	//audioPars = append(audioPars, endTime)
	if keywords != "" {
		audioCond += ` AND ( a.voice_name LIKE ? OR b.label LIKE ? )`
		audioPars = append(audioPars, keywords, keywords)
	}
	if audioId > 0 {
		audioCond += ` AND a.activity_voice_id = ?`
		audioPars = append(audioPars, audioId)
	}
	if audioIds != "" {
		sliceId := strings.Split(audioIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		audioCond += ` AND a.activity_voice_id IN (` + idSqlStr + `)`
	}

	//}
	//视频的处理
	var videoCond string
	var videoCondAct string
	var videoPars []interface{}
	var videoParsAct []interface{}
	//if audioId > 0 || filter == 2 {
	//	videoCond = ""
	//} else {
	if keywords != "" {
		videoCond += ` AND video_name LIKE ?`
		videoPars = append(videoPars, keywords)
		videoCondAct += ` AND (video_name LIKE ?  OR art.label LIKE ?)`
		videoParsAct = append(videoParsAct, keywords, keywords)
	}
	if videoId > 0 {
		videoCond += ` AND video_id = ?`
		videoPars = append(videoPars, videoId)
	}
	if activityVideoId > 0 {
		videoCondAct += ` AND video_id = ?`
		videoParsAct = append(videoParsAct, activityVideoId)
	}
	if activityVideoIds != "" {
		sliceId := strings.Split(activityVideoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCondAct += ` AND v.video_id IN (` + idSqlStr + `)`
	}

	//如果传了路演的或者活动的视频ID只查询一个
	if videoId > 0 {
		videoCondAct += ` AND video_id = 0 `
		audioCond += ` AND a.activity_voice_id = 0 `
	}
	if activityVideoId > 0 {
		videoCond += ` AND video_id = 0 `
		audioCond += ` AND a.activity_voice_id = 0 `
	}
	if audioId > 0 {
		videoCondAct += ` AND video_id = 0 `
		videoCond += ` AND video_id = 0 `
	}
	if strings.Contains(filter, "1") && !strings.Contains(filter, "2") {
		audioCond += ` AND a.activity_voice_id = 0 `
	} else if !strings.Contains(filter, "1") && strings.Contains(filter, "2") {
		videoCondAct += ` AND video_id = 0 `
		videoCond += ` AND video_id = 0 `
	}

	if strings.Contains(filter, "3") && !strings.Contains(filter, "4") {
		audioCond += ` AND a.activity_voice_id = 0 `
		videoCondAct += ` AND video_id = 0 `
	} else if strings.Contains(filter, "3") && !strings.Contains(filter, "4") {
		videoCond += ` AND video_id = 0 `
	}
	if videoIds != "" {
		sliceId := strings.Split(videoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCond += ` AND video_id IN (` + idSqlStr + `)`
	}
	videoCond += ` AND publish_status = 1`

	if chartPermissionIds != "" {
		videoCond += ` AND chart_permission_id IN (` + chartPermissionIds + `)`
		audioCond += ` AND b.chart_permission_id IN (` + chartPermissionIds + `)`
		videoCondAct += ` AND art.chart_permission_id IN (` + chartPermissionIds + `)`
	}

	//}
	total, videoList, e = models.GetMicroRoadShowVideoPageListV8(startSize, pageSize, videoCond, videoPars, videoCondAct, videoParsAct, audioCond, audioPars)
	if e != nil {
		err = errors.New("获取微路演音视频列表失败, Err: " + e.Error())
		return
	}
	respList = videoList
	return
}

// GetMicroRoadShowPageList 获取微路演列表添加活动视频 更新与8.1版本
func GetMicroRoadShowPageListV12(pageSize, currentIndex, sourceId, tableType int, filter, keywords, searchType, chartPermissionIds string) (respList []*models.MicroRoadShowPageList, total int, err error) {
	//Type                int    `description:"类型: 1-活动音频; 2-活动视频； 3-产业视频; 4-系列问答"`
	var e error
	// 根据每页数据量获取音视频配比
	startSize := utils.StartIndex(currentIndex, pageSize)
	videoList := make([]*models.MicroRoadShowPageList, 0)

	var audioAct string // 活动音频 1
	var audioActPars []interface{}

	var videoAct string // 活动视频 2
	var videoActPars []interface{}

	//视频的处理
	var videoMico string //产业视频 3
	var videoMicoPars []interface{}

	var conditionAskserie string // 系列问答 4
	var askseriePars []interface{}

	if sourceId > 0 && tableType > 0 {
		//先给不相干的表查询ID = 0
		audioAct += ` AND b.chart_permission_id  = 0 `
		videoAct += ` AND b.chart_permission_id = 0`
		videoMico += ` AND a.chart_permission_id  = 0 `
		conditionAskserie += ` AND a.chart_permission_id   = 0 `
		switch tableType {
		case 1:
			audioAct += ` OR  a.activity_id =  ` + strconv.Itoa(sourceId)
		case 2:
			videoAct += ` OR  a.activity_id =  ` + strconv.Itoa(sourceId)
		case 3:
			videoMico += ` OR  a.video_id =  ` + strconv.Itoa(sourceId)
		case 4:
			conditionAskserie += ` OR  a.askserie_video_id =  ` + strconv.Itoa(sourceId)
		}
	}

	if filter == "1" {
		audioAct += ` AND b.chart_permission_id  = 0 `
	} else if filter == "2" {
		videoAct += ` AND b.chart_permission_id = 0 `
		videoMico += ` AND a.chart_permission_id  = 0 `
		conditionAskserie += ` AND a.chart_permission_id = 0 `
	}

	if searchType != "" {
		// @Param   SearchType	string	int		true	"搜索类型: 1-路演回放; 2-问答系列； 3-调研反馈   多个用 , 隔开"
		videoMico += ` AND a.chart_permission_id  = 0 ` // 产业视频不在搜索范围内
		if strings.Contains(searchType, "1") && !strings.Contains(searchType, "3") {
			audioAct += ` AND a.file_type = 1 `
			videoAct += ` AND a.file_type = 1 `
		}

		if !strings.Contains(searchType, "1") && strings.Contains(searchType, "3") {

			audioAct += ` AND  a.file_type = 2 `
			videoAct += ` AND  a.file_type = 2 `
		}

		if !strings.Contains(searchType, "2") {
			conditionAskserie += ` AND a.chart_permission_id   = 0 `
		}

		if !strings.Contains(searchType, "3") && !strings.Contains(searchType, "1") {
			audioAct += ` AND b.chart_permission_id  = 0  `
			videoAct += ` AND b.chart_permission_id  = 0 `
		}
	}

	if keywords != "" {
		keywords = "%" + keywords + "%"

		audioAct += ` AND  a.voice_name LIKE ? `
		videoAct += ` AND  a.video_name LIKE ? `
		videoMico += ` AND  a.video_name LIKE ? `
		conditionAskserie += ` AND  a.video_name LIKE ? `

		audioActPars = append(audioActPars, keywords)
		videoActPars = append(videoActPars, keywords)
		videoMicoPars = append(videoMicoPars, keywords)
		askseriePars = append(askseriePars, keywords)
	}
	//行业筛选
	if chartPermissionIds != "" {
		audioAct += ` AND  b.chart_permission_id IN (` + chartPermissionIds + `)`
		videoAct += ` AND b.chart_permission_id IN (` + chartPermissionIds + `)`
		videoMico += ` AND a.chart_permission_id IN (` + chartPermissionIds + `)`
		conditionAskserie += ` AND a.chart_permission_id IN (` + chartPermissionIds + `)`
	}
	//发布状态
	audioAct += ` AND  b.publish_status = 1 AND  b.chart_permission_id  != 31  AND  a.is_hide = 0 `
	videoAct += ` AND  b.publish_status = 1 AND  b.chart_permission_id  != 31  AND  a.is_hide = 0 `
	videoMico += ` AND  a.publish_status = 1 AND  a.chart_permission_id  != 31 `
	conditionAskserie += ` AND  a.publish_status = 1  AND  a.chart_permission_id  != 31 `

	total, videoList, e = models.GetMicroRoadShowVideoPageListV12(startSize, pageSize, audioAct, audioActPars, videoAct, videoActPars, videoMico, videoMicoPars, conditionAskserie, askseriePars)
	if e != nil {
		err = errors.New("获取微路演音视频列表失败, Err: " + e.Error())
		return
	}
	for _, v := range videoList {
		v.LabelType = v.Type
		if v.Type == 1 || v.Type == 2 {
			v.LabelType = v.ActivityFileType
		}
	}

	respList = videoList
	return
}

// GetMicroRoadShowPageListIkWord  添加IK分词联想词 获取微路演列表添加活动视频 更新与8.1版本
func CountMicroRoadShowPageListIkWord(audioId, videoId, activityVideoId int, keywordArr []string, filter, audioIds, videoIds, activityVideoIds string) (total int, err error) {
	var e error
	var keywords string
	if len(keywordArr) > 0 {
		keywords = KeyWordArrSqlRegexpAll(keywordArr)
	}
	//if keywords == "" {
	//	return
	//}
	//音频的查询
	var audioCond string
	var audioPars []interface{}
	// 如果筛选条件为指定视频ID或只看视频则不做音频查询
	//if videoId > 0 || activityVideoId > 0 || filter == 1 {
	//	audioCond += ` AND a.activity_voice_id  = 0 `
	//} else {
	// 活动已发布且已结束
	audioCond += ` AND b.publish_status = 1 AND b.active_state = 3`
	if keywords != "" {
		audioCond += ` AND (a.voice_name REGEXP ? OR b.label REGEXP ? ) `
		audioPars = append(audioPars, keywords, keywords)
	}
	if audioId > 0 {
		audioCond += ` AND a.activity_voice_id = ?`
		audioPars = append(audioPars, audioId)
	}
	if audioIds != "" {
		sliceId := strings.Split(audioIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		audioCond += ` AND a.activity_voice_id IN (` + idSqlStr + `)`
	}
	//}
	//视频的处理
	var videoCond string
	var videoCondAct string
	var videoPars []interface{}
	var videoParsAct []interface{}
	//if audioId > 0 || filter == 2 {
	//	videoCond = ""
	//} else {
	if keywords != "" {
		videoCond += ` AND video_name REGEXP ? `
		videoPars = append(videoPars, keywords)
		videoCondAct += ` AND (video_name REGEXP ?  OR art.label REGEXP ? )`
		videoParsAct = append(videoParsAct, keywords, keywords)
	}
	if videoId > 0 {
		videoCond += ` AND video_id = ? `
		videoPars = append(videoPars, videoId)
	}
	if activityVideoId > 0 {
		videoCondAct += ` AND video_id = ?`
		videoParsAct = append(videoParsAct, activityVideoId)
	}
	if activityVideoIds != "" {
		sliceId := strings.Split(activityVideoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCondAct += ` AND v.video_id IN (` + idSqlStr + `)`
	}

	//如果传了路演的或者活动的视频ID只查询一个
	if videoId > 0 {
		videoCondAct += ` AND video_id = 0 `
		audioCond += ` AND a.activity_voice_id = 0 `
	}
	if activityVideoId > 0 {
		videoCond += ` AND video_id = 0 `
		audioCond += ` AND a.activity_voice_id = 0 `
	}
	if audioId > 0 {
		videoCondAct += ` AND video_id = 0 `
		videoCond += ` AND video_id = 0 `
	}

	if strings.Contains(filter, "1") && !strings.Contains(filter, "2") {
		audioCond += ` AND a.activity_voice_id = 0 `
	} else if !strings.Contains(filter, "1") && strings.Contains(filter, "2") {
		videoCondAct += ` AND video_id = 0 `
		videoCond += ` AND video_id = 0 `
	}

	if strings.Contains(filter, "3") && !strings.Contains(filter, "4") {
		audioCond += ` AND a.activity_voice_id = 0 `
		videoCondAct += ` AND video_id = 0 `
	} else if strings.Contains(filter, "3") && !strings.Contains(filter, "4") {
		videoCond += ` AND video_id = 0 `
	}

	if videoIds != "" {
		sliceId := strings.Split(videoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCond += ` AND video_id IN (` + idSqlStr + `)`
	}
	videoCond += ` AND publish_status = 1`
	//}
	total, e = models.CountMicroRoadShowVideoPageList(videoCond, videoPars, videoCondAct, videoParsAct, audioCond, audioPars)
	if e != nil {
		err = errors.New("获取微路演音视频列表失败, Err: " + e.Error())
		return
	}
	return
}

// GetMicroRoadShowPageListIkWord  添加IK分词联想词 获取微路演列表添加活动视频 更新与8.1版本
func GetMicroRoadShowPageListIkWord(startSize, pageSize, audioId, videoId, activityVideoId int, keywordArr []string, filter, audioIds, videoIds, activityVideoIds, keywords string) (respList []*models.MicroRoadShowPageList, err error) {

	videoList := make([]*models.MicroRoadShowPageList, 0)
	var e error
	var keywordsIk string
	if len(keywordArr) > 1 {
		keywordsIk = KeyWordArrSqlRegexp(keywordArr)
	}
	if keywords != "" {
		keywords = "%" + keywords + "%"
	}
	//音频的查询
	var audioCond string
	var audioPars []interface{}
	// 如果筛选条件为指定视频ID或只看视频则不做音频查询
	//if videoId > 0 || activityVideoId > 0 || filter == 1 {
	//	audioCond += ` AND a.activity_voice_id  = 0 `
	//} else {
	// 活动已发布且已结束
	audioCond += ` AND b.publish_status = 1 AND b.active_state = 3`
	if keywordsIk != "" {
		audioCond += ` AND ( a.voice_name REGEXP ? OR b.label REGEXP ? )`
		audioCond += ` AND ( a.voice_name NOT LIKE ? AND  b.label NOT LIKE ? )`
		audioPars = append(audioPars, keywordsIk, keywordsIk, keywords, keywords)
	}
	if audioId > 0 {
		audioCond += ` AND a.activity_voice_id = ?`
		audioPars = append(audioPars, audioId)
	}
	if audioIds != "" {
		sliceId := strings.Split(audioIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		audioCond += ` AND a.activity_voice_id IN (` + idSqlStr + `)`
	}
	//}
	//视频的处理
	var videoCond string
	var videoCondAct string
	var videoPars []interface{}
	var videoParsAct []interface{}
	//if audioId > 0 || filter == 2 {
	//	videoCond = ""
	//} else {
	if keywordsIk != "" {
		videoCond += ` AND video_name REGEXP ?`
		videoPars = append(videoPars, keywordsIk)

		videoCondAct += ` AND ( v.video_name REGEXP ? OR art.label REGEXP ? )`
		videoCondAct += ` AND ( v.video_name NOT LIKE ? AND art.label NOT LIKE ? )`

		//videoCondAct += ` AND video_name REGEXP ?`
		videoParsAct = append(videoParsAct, keywordsIk, keywordsIk, keywords, keywords)
	}
	if videoId > 0 {
		videoCond += ` AND video_id = ?`
		videoPars = append(videoPars, videoId)
	}
	if activityVideoId > 0 {
		videoCondAct += ` AND video_id = ?`
		videoParsAct = append(videoParsAct, activityVideoId)
	}
	if activityVideoIds != "" {
		sliceId := strings.Split(activityVideoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCondAct += ` AND v.video_id IN (` + idSqlStr + `)`
	}

	//如果传了路演的或者活动的视频ID只查询一个
	if videoId > 0 {
		videoCondAct += ` AND video_id = 0 `
		audioCond += ` AND a.activity_voice_id = 0 `
	}
	if activityVideoId > 0 {
		videoCond += ` AND video_id = 0 `
		audioCond += ` AND a.activity_voice_id = 0 `
	}
	if audioId > 0 {
		videoCondAct += ` AND video_id = 0 `
		videoCond += ` AND video_id = 0 `
	}

	if strings.Contains(filter, "1") && !strings.Contains(filter, "2") {
		audioCond += ` AND a.activity_voice_id = 0 `
	} else if !strings.Contains(filter, "1") && strings.Contains(filter, "2") {
		videoCondAct += ` AND video_id = 0 `
		videoCond += ` AND video_id = 0 `
	}

	if strings.Contains(filter, "3") && !strings.Contains(filter, "4") {
		audioCond += ` AND a.activity_voice_id = 0 `
		videoCondAct += ` AND video_id = 0 `
	} else if strings.Contains(filter, "3") && !strings.Contains(filter, "4") {
		videoCond += ` AND video_id = 0 `
	}

	if videoIds != "" {
		sliceId := strings.Split(videoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCond += ` AND video_id IN (` + idSqlStr + `)`
	}
	videoCond += ` AND publish_status = 1`
	//}
	videoList, e = models.GetMicroRoadShowVideoPageListIkWord(startSize, pageSize, videoCond, videoPars, videoCondAct, videoParsAct, audioCond, audioPars)
	if e != nil {
		err = errors.New("获取微路演音视频列表失败分词, Err: " + e.Error())
		return
	}
	respList = videoList
	return
}

// 我的收藏
func GetMicroRoadShowMycollect(pageSize, currentIndex int, audioIds, videoIds, activityVideoIds string) (respList []*models.MicroRoadShowPageList, total int, err error) {
	var e error
	// 根据每页数据量获取音视频配比
	startSize := utils.StartIndex(currentIndex, pageSize)
	videoList := make([]*models.MicroRoadShowPageList, 0)

	//音频的查询
	var audioCond string
	var audioPars []interface{}
	// 如果筛选条件为指定视频ID或只看视频则不做音频查询
	// 活动已发布且已结束
	audioCond += ` AND b.publish_status = 1 AND b.active_state = 3`
	if audioIds != "" {
		sliceId := strings.Split(audioIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		audioCond += ` AND a.activity_voice_id IN (` + idSqlStr + `)`
	} else {
		audioCond += ` AND a.activity_voice_id = 0 `
	}
	//视频的处理
	var videoCond string
	var videoCondAct string
	if activityVideoIds != "" {
		sliceId := strings.Split(activityVideoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCondAct += ` AND v.video_id IN (` + idSqlStr + `)`
	} else {
		videoCondAct += ` AND v.video_id  = 0 `
	}
	var videoPars []interface{}
	var videoParsAct []interface{}
	if videoIds != "" {
		sliceId := strings.Split(videoIds, ",")
		var idSqlStr string
		for _, v := range sliceId {
			idSqlStr += "'" + v + "',"
		}
		idSqlStr = strings.TrimRight(idSqlStr, ",")
		videoCond += ` AND video_id IN (` + idSqlStr + `)`
	} else {
		videoCond += ` AND video_id  = 0 `
	}
	videoCond += ` AND publish_status = 1`

	total, videoList, e = models.GetMicroRoadShowVideoPageListV8(startSize, pageSize, videoCond, videoPars, videoCondAct, videoParsAct, audioCond, audioPars)
	if e != nil {
		err = errors.New("获取微路演音视频列表失败, Err: " + e.Error())
		return
	}
	respList = videoList
	return
}

// 我的收藏
func GetMicroRoadShowMycollectV12(pageSize, currentIndex int, audioIds, activityVideoIds, roadshowIdsStr, askserieVideoIds string, user *models.WxUserItem) (respList []*models.MicroRoadShowPageList, total int, err error) {
	//Type                int    `description:"类型: 1-活动音频; 2-活动视频； 3-产业视频; 4-系列问答"`
	var e error
	// 根据每页数据量获取音视频配比
	startSize := utils.StartIndex(currentIndex, pageSize)
	videoList := make([]*models.MicroRoadShowPageList, 0)

	var audioAct string // 活动音频 1
	var audioActPars []interface{}

	var videoAct string // 活动视频 2
	var videoActPars []interface{}

	//视频的处理
	var videoMico string //产业视频 3
	var videoMicoPars []interface{}

	var conditionAskserie string // 系列问答 4
	var askseriePars []interface{}

	if audioIds != "" {
		sliceId := strings.Split(audioIds, ",")
		audioAct += ` AND a.activity_voice_id IN (` + strings.Join(sliceId, ",") + `)`
	} else {
		audioAct += ` AND a.activity_voice_id = 0 `
	}

	if activityVideoIds != "" {
		sliceId := strings.Split(activityVideoIds, ",")
		videoAct += ` AND a.video_id IN (` + strings.Join(sliceId, ",") + `)`
	} else {
		videoAct += ` AND a.video_id = 0 `
	}

	if roadshowIdsStr != "" {
		sliceId := strings.Split(roadshowIdsStr, ",")
		videoMico += ` AND a.video_id IN (` + strings.Join(sliceId, ",") + `)`
	} else {
		videoMico += ` AND a.video_id = 0 `
	}

	if askserieVideoIds != "" {
		sliceId := strings.Split(askserieVideoIds, ",")
		conditionAskserie += ` AND a.askserie_video_id IN (` + strings.Join(sliceId, ",") + `)`
	} else {
		conditionAskserie += ` AND a.askserie_video_id = 0 `
	}

	//发布状态
	audioAct += ` AND  b.publish_status = 1 `
	videoAct += ` AND  b.publish_status = 1 `
	videoMico += ` AND  a.publish_status = 1 `
	conditionAskserie += ` AND  a.publish_status = 1 `

	total, videoList, e = models.GetMicroRoadShowVideoPageListV12(startSize, pageSize, audioAct, audioActPars, videoAct, videoActPars, videoMico, videoMicoPars, conditionAskserie, askseriePars)
	if e != nil {
		err = errors.New("获取微路演音视频列表失败, Err: " + e.Error())
		return
	}
	userId := user.UserId
	listMycollect, e := models.GetUserMicroRoadshowCollectList(userId)
	if e != nil {
		err = errors.New("GetUserMicroRoadshowCollectList, Err: " + e.Error())
		return
	}
	mapaudioIds := make(map[int]int)         //活动音频
	mapvideoIds := make(map[int]int)         // 微路演视频
	mapactivityVideoIds := make(map[int]int) // 活动视频
	mapAskserieVideoIds := make(map[int]int) // 活动视频
	for _, item := range listMycollect {
		if item.ActivityVoiceId > 0 {
			mapaudioIds[item.ActivityVoiceId] = item.ActivityVoiceId
		} else if item.VideoId > 0 {
			mapvideoIds[item.VideoId] = item.VideoId
		} else if item.ActivityVideoId > 0 {
			mapactivityVideoIds[item.ActivityVideoId] = item.ActivityVideoId
		}
	}

	listAskserieVideoCollect, e := models.GetUserCygxAskserieVideoCollectList(userId)
	if e != nil {
		err = errors.New("GetUserCygxAskserieVideoCollectList, Err: " + e.Error())
		return
	}

	for _, v := range listAskserieVideoCollect {
		if v.AskserieVideoId > 0 {
			mapAskserieVideoIds[v.AskserieVideoId] = v.AskserieVideoId
		}
	}

	for _, item := range videoList {
		if item.Type == 1 {
			//音频
			if mapaudioIds[item.Id] > 0 {
				item.IsCollect = true
			}
		} else if item.Type == 2 {
			//活动视频
			if mapactivityVideoIds[item.Id] > 0 {
				item.IsCollect = true
			}
		} else if item.Type == 3 {
			//微路演视频
			if mapvideoIds[item.Id] > 0 {
				item.IsCollect = true
			}
		} else if item.Type == 4 {
			//系列问答视频
			if mapAskserieVideoIds[item.SourceId] > 0 {
				item.IsCollect = true
			}
		}
	}

	for _, v := range videoList {
		v.LabelType = v.Type
		if v.Type == 1 || v.Type == 2 {
			v.LabelType = v.ActivityFileType
		}
	}

	respList = videoList
	return
}

// GetMicroRoadshowVideoMap 获取已经发布的微路演的产业ID
func GetMicroRoadshowVideoMap() (items map[int]int, err error) {
	list, e := models.GetMicroRoadshowVideoList()
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("获取已经发布的微路演的产业失败，GetMicroRoadshowVideoList " + e.Error())
		return
	}
	mapindustrialId := make(map[int]int)
	for _, v := range list {
		mapindustrialId[v.IndustryId] = v.IndustryId
	}
	items = mapindustrialId
	return
}

func GetindustryVideo(user *models.WxUserItem, industrialManagementId int) (industryVideo *models.MicroVideoSimpleInfo, AuthInfo *models.UserPermissionAuthInfo, err error) {
	total, e := models.GetMicroRoadshowVideoByIndustryIdCount(industrialManagementId)
	if e != nil {
		err = errors.New("获取产业关联的视频失败，GetMicroRoadshowVideoByIndustryIdCount " + e.Error())
		return
	}
	if total == 0 {
		return
	}
	// 用户权限
	authInfo, permissionArr, e := GetUserRaiPermissionInfo(user.UserId, user.CompanyId)
	if e != nil {
		err = errors.New("获取用户权限失败，GetUserRaiPermissionInfo " + e.Error())
		return
	}
	videoSimple := new(models.MicroVideoSimpleInfo)
	// 权限
	var au *models.UserPermissionAuthInfo
	video, e := models.GetMicroRoadshowVideoByIndustryId(industrialManagementId)
	if e != nil {
		err = errors.New("获取产业关联的视频失败，GetMicroRoadshowVideoByIndustryId " + e.Error())
		return
	} else {
		videoSimple.Id = video.VideoId
		videoSimple.Title = "5min【" + video.IndustryName + "】逻辑解析"
		videoSimple.BackgroundImg = video.ImgUrl
		videoSimple.DetailImgUrl = video.DetailImgUrl
		if videoSimple.BackgroundImg == "" {
			// 获取默认图配置
			_, videoMap, _, _, e := GetMicroRoadShowDefaultImgConfig()
			if e != nil {
				err = errors.New("获取视频默认配置图失败，GetMicroRoadshowVideoByIndustryId " + e.Error())
				return
			}
			videoSimple.BackgroundImg = videoMap[video.ChartPermissionId]
		}
		videoSimple.PlaySeconds = video.VideoDuration
		videoSimple.ResourceUrl = video.VideoUrl
		au = new(models.UserPermissionAuthInfo)
		au.SellerName = authInfo.SellerName
		au.SellerMobile = authInfo.SellerMobile
		au.HasPermission = authInfo.HasPermission
		au.OperationMode = authInfo.OperationMode
		if au.HasPermission == 1 {
			// 非宏观权限进一步判断是否有权限
			if video.ChartPermissionId != utils.HONG_GUAN_ID && !utils.InArrayByStr(permissionArr, video.ChartPermissionName) {
				au.HasPermission = 2
			}
		}
		// 无权限的弹框提示
		if au.HasPermission != 1 {
			if au.OperationMode == UserPermissionOperationModeCall {
				au.PopupMsg = UserPermissionPopupMsgCallMicroVideo
			} else {
				au.PopupMsg = UserPermissionPopupMsgApplyMicroVideo
			}
			videoSimple.ResourceUrl = ""
		}
	}
	industryVideo = videoSimple
	AuthInfo = au
	return
}

// 用户微路演视频回放操作操作行为，模板消息推送
func MicroRoadshowVideoUserRmind(user *models.WxUserItem, videoId int) (err error) {
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("用户音视频回放操作操作行为，模板消息推送失败"+err.Error(), 2)
		}
	}()
	countUser, err := models.GetUserRemind(user.UserId)
	if err != nil {
		return err
	}
	if countUser == 0 {
		return err
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//获取销售手机号
	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	if sellerItemQy != nil {
		sllerAndShareMobileArr, e := GetCompanySellerAndShareMobileByRai(user.CompanyId) //获取所属销售以及对应销售的手机号
		if e != nil {
			err = errors.New("GetCompanySellerAndShareMobileByRai, Err: " + e.Error())
			return
		}
		sllerAndShareMobiles := strings.Join(sllerAndShareMobileArr, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(sllerAndShareMobiles)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		videoInfo, e := models.GetMicroRoadshowVideoByVideoId(videoId)
		if e != nil {
			err = errors.New("GetCygxActivitySpecialDetailById, Err: " + e.Error())
			return
		}
		if videoInfo == nil {
			return
		}
		first = fmt.Sprint(user.RealName, "--", user.CompanyName, ",有新的互动：播放微路演详视频")
		keyword1 = videoInfo.VideoName
		keyword2 = fmt.Sprint("互动：播放微路演详视频,", user.RealName, "--", user.CompanyName)
		remark = "点击查看微路演详情"
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		redirectUrl := utils.WX_MSG_PATH_ACTIVITY_INDUSTRYR_EPORT + strconv.Itoa(videoInfo.IndustryId)
		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(videoId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		err = PublicSendTemplateMsg(sendInfo)
		if err != nil {
			return
		}
	}
	return
}

// 记录产业视频播放记录
func AddMicroRoadshowVideoRecord(user *models.WxUserItem, videoId, playSeconds int) {
	//if playSeconds == 0 {
	//	return
	//}
	key := utils.CYGX_VIDEO_HISTORY_KEY + utils.CYGX_OBJ_ROADSHOW + strconv.Itoa(videoId) + "_" + strconv.Itoa(user.UserId)
	if utils.Rc.IsExist(key) {
		return
	}
	utils.Rc.Put(key, 1, 10*time.Minute)
	var err error
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("记录用户活动音频播放记录失败 AddMicroRoadshowVideoRecord Err:", err.Error(), "videoId：", videoId, "UserId：", user.UserId), 2)
		}
	}()
	item := new(models.CygxMicroRoadshowVideoHistory)
	item.UserId = user.UserId
	item.RealName = user.RealName
	item.VideoId = videoId
	item.PlaySeconds = strconv.Itoa(playSeconds)
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.RegisterPlatform = utils.REGISTER_PLATFORM
	sellerItem, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
		return
	}
	if sellerItem != nil {
		item.SellerName = sellerItem.RealName
	}

	//if !utils.Rc.IsExist(key) {
	//添加记录
	e = models.AddCygxMicroRoadshowVideoHistory(item)
	if e != nil {
		err = errors.New("AddCygxMicroRoadshowVideoHistory, Err: " + e.Error())
		return
	}
	//播放记录加1
	e = models.UpdateCygxMicroRoadshowVideo(videoId)
	if e != nil {
		err = errors.New("UpdateCygxActivityVideoCounts, Err: " + e.Error())
		return
	}
	go MicroRoadshowVideoUserRmind(user, videoId)

	//utils.Rc.Put(key, 1, 10*time.Minute)
	//} else {
	//	//更新停留时长
	//	lastItem, e := models.GetLastCygxMicroRoadshowVideoHistory(videoId, user.UserId)
	//	if e != nil {
	//		err = errors.New("GetLastCygxMicroRoadshowVideoHistory, Err: " + e.Error())
	//		return
	//	}
	//	//更新播放时间
	//	e = models.UpdateLastCygxMicroRoadshowVideoHistory(strconv.Itoa(playSeconds), lastItem.Id)
	//	if e != nil {
	//		err = errors.New("UpdateLastCygxMicroRoadshowVideoHistory, Err: " + e.Error())
	//		return
	//	}
	//}

	//if playSeconds != 0 {
	//	lastItem, e := models.GetLastCygxMicroRoadshowVideoHistory(videoId, user.UserId)
	//	if e != nil {
	//		err = errors.New("GetLastCygxMicroRoadshowVideoHistory, Err: " + e.Error())
	//		return
	//	}
	//	e = models.UpdateLastCygxActivityVideoHistory(strconv.Itoa(playSeconds), lastItem.Id)
	//	if e != nil {
	//		err = errors.New("UpdateLastCygxActivityVideoHistory, Err: " + e.Error())
	//		return
	//	}
	//	utils.Rc.Put(key, 1, 10*time.Second)
	//} else {
	//	e = models.AddCygxMicroRoadshowVideoHistory(item)
	//	if e != nil {
	//		err = errors.New("AddCygxMicroRoadshowVideoHistory, Err: " + e.Error())
	//		return
	//	}
	//	e = models.UpdateCygxMicroRoadshowVideo(videoId)
	//	if e != nil {
	//		err = errors.New("UpdateCygxActivityVideoCounts, Err: " + e.Error())
	//		return
	//	}
	//	go MicroRoadshowVideoUserRmind(user, videoId)
	//}

	return
}

// 记录所有微路演音视频播放记录
func AddAllCygxVoiceAndVideoHistory(user *models.WxUserItem, sourceId, sourceType, playSeconds int) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("记录所有微路演音视频播放记录失败 AddAllCygxVoiceAndVideoHistory Err:", err.Error(), "sourceId：", sourceId, "UserId：", user.UserId), 2)
		}
	}()
	item := new(models.CygxVoiceAndVideoHistory)
	item.UserId = user.UserId
	item.RealName = user.RealName
	item.SourceId = sourceId
	item.SourceType = sourceType
	item.PlaySeconds = strconv.Itoa(playSeconds)
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.RegisterPlatform = utils.REGISTER_PLATFORM
	sellerItem, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
		return
	}
	if sellerItem != nil {
		item.SellerName = sellerItem.RealName
	}
	_, e = models.AddCygxVoiceAndVideoHistory(item)
	if e != nil {
		err = errors.New("AddCygxVoiceAndVideoHistory, Err: " + e.Error())
		return
	}
	return
}

// 获取满足路演回放的活动类型
func GetActivityLYHFMapByActivityIds(activityIds []int) (mapResp map[int]bool) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("获取满足路演回放的活动类型 GetActivityLYHFMapByActivityIds，失败,活动ID："+fmt.Sprint(activityIds)+err.Error(), 2)
		}
	}()
	var condition string
	var pars []interface{}
	lenArr := len(activityIds)
	if lenArr == 0 {
		return
	}
	condition = ` AND activity_id IN (` + utils.GetOrmInReplace(lenArr) + `)  `
	pars = append(pars, activityIds)
	list, e := models.GetCygxActivityList(condition, pars, 0, lenArr)
	if e != nil {
		err = errors.New("GetIndustrialManagementNewList, Err: " + e.Error())
		return
	}
	mapResp = make(map[int]bool, 0)
	for _, v := range list {
		mapResp[v.ActivityId] = true
	}
	return
}
