package cygx

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/services/elastic"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// 活动类型
type MicroRoadshowController struct {
	controllers.BaseAuthController
}

// @Title 微路演视频列表
// @Description 微路演视频列表
// @Success 200 {object} cygx.MicroRoadshowVideoListResp
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   StartDate   query   string  false       "开始时间"
// @Param   EndDate   query   string  false       "结束时间"
// @Param   PublishStatus   query   string  false       "发布状态"
// @Param   ChartPermissionId   query   string  false       "行业Id"
// @Param   VideoId   query   string  false       "视频Id"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段 "
// @router /microRoadshow/video/list [get]
func (this *MicroRoadshowController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	publishStatus, _ := this.GetInt("PublishStatus", -1)
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)
	var condition string
	var pars []interface{}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	if keyWord != "" {
		condition += ` AND (video_name LIKE '%` + keyWord + `%' ) `
	}

	if startDate != "" {
		condition += ` AND publish_date>=? `
		pars = append(pars, startDate+" 00:00:00")
	}

	if endDate != "" {
		condition += ` AND publish_date<=? `
		pars = append(pars, endDate+" 23:59:59")
	}

	if chartPermissionId > 0 {
		condition += ` AND chart_permission_id=? `
		pars = append(pars, chartPermissionId)
	}

	if publishStatus > -1 {
		condition += ` AND publish_status=? `
		pars = append(pars, publishStatus)
	}

	sortStr := ``
	if sortParam != "" && sortType != "" {
		if sortParam == "videoCounts" {
			if sortType == "asc" {
				sortStr = " ORDER BY  video_counts "
			} else {
				sortStr = " ORDER BY  video_counts DESC "
			}
		}
	} else {
		sortStr = " ORDER BY publish_date DESC "
	}

	total, err := cygx.GetMicroRoadshowVideoListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := cygx.GetMicroRoadshowVideoList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	respList := make([]*cygx.CygxMicroRoadshowVideoResp, 0)

	for _, video := range list {
		respItem := cygx.CygxMicroRoadshowVideoResp{
			VideoId:             video.VideoId,
			VideoName:           video.VideoName,
			ChartPermissionId:   video.ChartPermissionId,
			ChartPermissionName: video.ChartPermissionName,
			IndustryId:          video.IndustryId,
			IndustryName:        video.IndustryName,
			PublishStatus:       video.PublishStatus,
			ModifyDate:          video.ModifyDate,
			PublishDate:         video.PublishDate.Format(utils.FormatDate),
			VideoDuration:       video.VideoDuration,
			VideoCounts:         video.VideoCounts,
			VideoUrl:            video.VideoUrl,
			CreateTime:          video.CreateTime,
			ImgUrl:              video.ImgUrl,
			ShareImgUrl:         video.ShareImgUrl,
			DetailImgUrl:        video.DetailImgUrl,
			CommentNum:          video.CommentNum,
		}
		respList = append(respList, &respItem)
	}
	if list == nil {
		list = make([]*cygx.CygxMicroRoadshowVideo, 0)

	}
	resp := new(cygx.MicroRoadshowVideoListResp)
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = respList
	resp.Paging = page

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 保存视频
// @Description 保存视频接口
// @Param	request	body cygx.VideoAddReq true "type json string"
// @Success 200 保存成功
// @router /microRoadshow/video/add [post]
func (this *MicroRoadshowController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.VideoAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.VideoName == "" {
		br.Msg = "视频名不能为空"
		return
	}
	if req.VideoUrl == "" {
		br.Msg = "视频播放地址不能为空"
		return
	}
	if req.IndustryId == 0 {
		br.Msg = "产业不能为空"
		return
	}
	if req.ImgUrl == "" {
		br.Msg = "视频封面不能为空"
		return
	}
	if req.ShareImgUrl == "" {
		br.Msg = "视频分享图不能为空"
		return
	}

	if req.DetailImgUrl == "" {
		br.Msg = "详情页封面不能为空"
		return
	}
	var nameItem *cygx.PermissionNameAndIndustryName
	nameItem, err = cygx.GetPermissionNameAndIndustryNameByIndustryId(req.IndustryId)
	if err != nil {
		br.Msg = "查询行业及产业是否存在失败！"
		br.ErrMsg = "查询行业及产业是否存在失败，Err:" + err.Error()
		return
	}

	charInfo, errCategory := cygx.GetCategoryInfoById(nameItem.PermissionId)
	if errCategory != nil {
		br.Msg = "获取品种信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + errCategory.Error()
		return
	}
	nameItem.PermissionName = charInfo.PermissionName
	publishDate, err := time.Parse(utils.FormatDate, req.PublishDate)
	if err != nil {
		br.Msg = "时间格式转换失败"
		br.ErrMsg = "时间格式转换失败,Err:" + err.Error()
		return
	}
	//判断该产业下是否已经存在其他视频
	exist, err := cygx.GetMicroRoadshowVideoByIndustryId(req.IndustryId)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "查询视频详情失败"
			br.ErrMsg = "查询视频详情失败,Err:" + err.Error()
			return
		}
	} else {
		if req.VideoId > 0 && req.VideoId != exist.VideoId {
			br.Msg = "该产业下已有产业视频"
			return
		}
		if req.VideoId == 0 {
			br.Msg = "该产业下已有产业视频"
			return
		}
	}
	shareImg, _ := cygxService.MakeCygxMp4HtmlImg(req.VideoDuration, 0) //生成分享图片
	req.ShareImgUrl = shareImg
	nameItem.IndustryName = utils.RemoveFileSuffixName(nameItem.IndustryName) //去掉后缀名称
	if req.VideoId > 0 {
		//更新
		item := cygx.CygxMicroRoadshowVideo{
			VideoId:             req.VideoId,
			VideoName:           "5min" + "【" + nameItem.IndustryName + "】" + "逻辑解析",
			ChartPermissionId:   nameItem.PermissionId,
			ChartPermissionName: nameItem.PermissionName,
			IndustryId:          req.IndustryId,
			IndustryName:        nameItem.IndustryName,
			ModifyDate:          time.Now().Format(utils.FormatDateTime),
			PublishStatus:       req.PublishOrSave,
			PublishDate:         publishDate,
			VideoDuration:       req.VideoDuration,
			VideoUrl:            req.VideoUrl,
			ImgUrl:              req.ImgUrl,
			ShareImgUrl:         req.ShareImgUrl,
			DetailImgUrl:        req.DetailImgUrl,
		}
		err = cygx.EditVideo(&item)
		if err != nil {
			br.Msg = "编辑失败"
			br.ErrMsg = "编辑失败,Err:" + err.Error()
			return
		}
		if req.PublishOrSave == 1 {
			go cygxService.SendWxMsgWithCygxMicroRoadshowVideo(req.VideoId)
		}

		//go cygxService.UpdateResourceData(req.VideoId, "roadshow", "update", publishDate.Format(utils.FormatDateTime))
		go cygxService.UpdateMicroRoadshowResourceData(req.VideoId) //写入首页最新  cygx_resource_data 表
		go elastic.AddComprehensiveRoadshow(req.VideoId)            //Es添加微路演
		br.Ret = 200
		br.Success = true
		br.Msg = "编辑成功"
	} else {
		videoCount, err := cygx.GetMicroRoadshowVideoByTitle(req.VideoName)
		if err != nil {
			br.Msg = "判断标题是否存在失败！"
			br.ErrMsg = "判断标题是否存在失败，Err:" + err.Error()
			return
		}

		if videoCount > 0 {
			br.Msg = "标题已存在！"
			br.IsSendEmail = false
			return
		}

		item := cygx.CygxMicroRoadshowVideo{
			VideoName:           "5min" + "【" + nameItem.IndustryName + "】" + "逻辑解析",
			ChartPermissionId:   nameItem.PermissionId,
			ChartPermissionName: nameItem.PermissionName,
			IndustryId:          req.IndustryId,
			IndustryName:        nameItem.IndustryName,
			PublishStatus:       req.PublishOrSave,
			ModifyDate:          time.Now().Format(utils.FormatDateTime),
			PublishDate:         publishDate,
			VideoDuration:       req.VideoDuration,
			VideoUrl:            req.VideoUrl,
			ImgUrl:              req.ImgUrl,
			ShareImgUrl:         req.ShareImgUrl,
			DetailImgUrl:        req.DetailImgUrl,
			CreateTime:          time.Now().Format(utils.FormatDateTime),
		}
		newId, err := cygx.AddMicroRoadshowVideo(&item)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}

		if req.PublishOrSave == 1 {
			go cygxService.SendWxMsgWithCygxMicroRoadshowVideo(int(newId))
			//go cygxService.UpdateResourceData(int(newId), "roadshow", "add", publishDate.Format(utils.FormatDateTime))
			go cygxService.UpdateMicroRoadshowResourceData(int(newId)) //写入首页最新  cygx_resource_data 表
			go elastic.AddComprehensiveRoadshow(req.VideoId)           //Es添加微路演
		}

		br.Ret = 200
		br.Success = true
		br.Msg = "保存成功"
	}
}

// @Title 编辑视频
// @Description 编辑视频接口
// @Param	request	body cygx.VideoEditReq true "type json string"
// @Success Ret=200 编辑成功
// @router /microRoadshow/video/edit [post]
func (this *MicroRoadshowController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.VideoEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.VideoName == "" {
		br.Msg = "标题不能为空"
		return
	}
	if req.VideoUrl == "" {
		br.Msg = "视频地址不能为空"
		return
	}
	publishDate, err := time.Parse(utils.FormatDate, req.PublishDate)
	if err != nil {
		br.Msg = "时间格式转换失败"
		br.ErrMsg = "时间格式转换失败,Err:" + err.Error()
		return
	}
	var nameItem *cygx.PermissionNameAndIndustryName
	nameItem, err = cygx.GetPermissionNameAndIndustryNameByIndustryId(req.IndustryId)
	if err != nil {
		br.Msg = "查询行业及产业是否存在失败！"
		br.ErrMsg = "查询行业及产业是否存在失败，Err:" + err.Error()
		return
	}
	item := cygx.CygxMicroRoadshowVideo{
		VideoId:           req.VideoId,
		VideoName:         "5min" + "【" + nameItem.IndustryName + "】" + "逻辑解析",
		ChartPermissionId: req.ChartPermissionId,
		IndustryId:        req.IndustryId,
		ModifyDate:        time.Now().Format(utils.FormatDateTime),
		PublishDate:       publishDate,
		VideoDuration:     req.VideoDuration,
		VideoUrl:          req.VideoUrl,
	}
	err = cygx.EditVideo(&item)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}
	go elastic.AddComprehensiveRoadshow(req.VideoId) //Es添加微路演
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// @Title 取消视频发布
// @Description 取消视频发布接口
// @Param   VideoId   query   int  true       "视频Id"
// @Param   PublishOrCancle   query   int  true       "发布或取消发布"
// @Success Ret=200 发布成功
// @router /microRoadshow/video/publish [get]
func (this *MicroRoadshowController) PublishCancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	videoId, _ := this.GetInt("VideoId")
	publishOrCancle, _ := this.GetInt("PublishOrCancle")

	if videoId <= 0 {
		br.Msg = "参数错误"
		return
	}

	err := cygx.PublishVideoCancel(videoId, publishOrCancle)
	if err != nil {
		br.Msg = "取消发布失败"
		br.ErrMsg = "取消发布失败，Err:" + err.Error()
		return
	}
	videoInfo, _ := cygx.GetMicroRoadshowVideoByVideoId(videoId)
	if videoInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "视频ID错误"
		return
	}
	br.Ret = 200
	br.Success = true
	if publishOrCancle == 0 {
		br.Msg = "取消发布成功"
		//go cygxService.UpdateResourceData(int(videoId), "roadshow", "delete", time.Now().Format(utils.FormatDateTime))
		go cygxService.UpdateMicroRoadshowResourceData(int(videoId)) //写入首页最新  cygx_resource_data 表
	} else {
		go cygxService.SendWxMsgWithCygxMicroRoadshowVideo(videoId)
		//go cygxService.UpdateResourceData(int(videoId), "roadshow", "add", videoInfo.PublishDate.Format(utils.FormatDateTime))
		go cygxService.UpdateMicroRoadshowResourceData(int(videoId)) //写入首页最新  cygx_resource_data 表
		br.Msg = "发布成功"
	}
	go elastic.AddComprehensiveRoadshow(videoId) //Es添加微路演
}

// @Title 视频详情
// @Description 视频详情接口
// @Param   VideoId   query   int  true       "视频Id"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success Ret=200 发布成功
// @router /microRoadshow/video/deatil [get]
func (this *MicroRoadshowController) Deatil() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	videoId, _ := this.GetInt("VideoId")
	//pageSize, _ := this.GetInt("PageSize")
	//currentIndex, _ := this.GetInt("CurrentIndex")

	if videoId <= 0 {
		br.Msg = "参数错误"
		return
	}

	//var startSize int
	//if pageSize <= 0 {
	//	pageSize = utils.PageSize20
	//}
	//if currentIndex <= 0 {
	//	currentIndex = 1
	//}
	//startSize = paging.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	condition += `AND video_id= ? `
	pars = append(pars, videoId)

	//total, err := cygx.GetMicroRoadshowVideoListCount(condition, pars)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
	//	return
	//}

	list, err := cygx.GetMicroRoadshowVideoHistoryById(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取历史详情失败"
		br.ErrMsg = "获取历史详情失败，Err:" + err.Error()
		return
	}

	for _, v := range list {
		v.RegisterPlatform = utils.CYGX_REGISTER_PLATFORM_MAP[v.RegisterPlatform]
	}
	//resp := new(cygx.MicroRoadshowVideoHistoryListResp)
	//page := paging.GetPaging(currentIndex, pageSize, total)
	//resp.List = list
	//resp.Paging = page

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 微路演音频列表
// @Description 微路演音频列表
// @Success 200 {object} cygx.MicroRoadshowVideoListResp
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   StartDate   query   string  true       "开始时间"
// @Param   EndDate   query   string  true       "结束时间"
// @Param   ChartPermissionId   query   string  true       "行业Id"
// @Param   ActivityTypeId   query   string  true       "活动类型ID"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段 "
// @router /microRoadshow/voice/list [get]
func (this *MicroRoadshowController) VoiceList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	activityTypeId, _ := this.GetInt("ActivityTypeId")
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)
	var condition string
	var pars []interface{}

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	if keyWord != "" {
		condition += ` AND (v.voice_name LIKE '%` + keyWord + `%' ) `
	}

	if startDate != "" {
		condition += ` AND a.activity_time>=? `
		pars = append(pars, startDate)
	}

	if endDate != "" {
		condition += ` AND a.activity_time<=? `
		pars = append(pars, endDate)
	}

	if chartPermissionId > 0 {
		condition += ` AND a.chart_permission_id=? `
		pars = append(pars, chartPermissionId)
	}

	if activityTypeId > 0 {
		condition += ` AND a.activity_type_id=? `
		pars = append(pars, activityTypeId)
	}

	sortStr := ``
	if sortParam != "" && sortType != "" {
		if sortParam == "voiceCounts" {
			if sortType == "asc" {
				sortStr = " ORDER BY  v.voice_counts "
			} else {
				sortStr = " ORDER BY  v.voice_counts DESC "
			}
		}
	} else {
		sortStr = " ORDER BY  a.activity_time DESC "
	}

	total, err := cygx.GetMicroRoadshowVoiceListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := cygx.GetMicroRoadshowVoiceList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resplist := make([]*cygx.CygxMicroRoadshowVoiceRsep, 0)
	for _, voice := range list {
		respItem := cygx.CygxMicroRoadshowVoiceRsep{
			ActivityVoiceId:     voice.ActivityVoiceId,
			ActivityId:          voice.ActivityId,
			VoiceName:           voice.VoiceName,
			ChartPermissionId:   voice.ChartPermissionId,
			ChartPermissionName: voice.ChartPermissionName,
			IndustryId:          voice.IndustryId,
			IndustryName:        voice.IndustryName,
			ModifyTime:          voice.ModifyTime,
			PublishDate:         voice.PublishDate,
			VoicePlaySeconds:    voice.VoicePlaySeconds,
			VoiceCounts:         voice.VoiceCounts,
			VoiceUrl:            voice.VoiceUrl,
			CreateTime:          voice.CreateTime,
			Label:               voice.Label,
			ActivityTypeId:      voice.ActivityTypeId,
			ActivityTypeName:    voice.ActivityTypeName,
			ActivityTime:        voice.ActivityTime.Format(utils.FormatDate),
			ActivityTimeText:    voice.ActivityTimeText,
			CommentNum:          voice.CommentNum,
		}
		resplist = append(resplist, &respItem)
	}

	if list == nil {
		list = make([]*cygx.CygxMicroRoadshowVoice, 0)
	}
	resp := new(cygx.MicroRoadshowVoiceListResp)
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = resplist
	resp.Paging = page

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 音频播放详情
// @Description 音频播放详情接口
// @Param   VoiceId   query   int  true       "视频Id"
// @Success Ret=200 发布成功
// @router /microRoadshow/voice/deatil [get]
func (this *MicroRoadshowController) VoiceDeatil() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	voiceId, _ := this.GetInt("VoiceId")
	videoId, _ := this.GetInt("VideoId")

	//参数ID做兼容
	if voiceId == 0 {
		voiceId = videoId
	}

	if voiceId <= 0 {
		br.Msg = "参数错误"
		return
	}

	var condition string
	var pars []interface{}

	condition += `AND v.activity_voice_id= ? `
	pars = append(pars, voiceId)

	list, err := cygx.GetMicroRoadshowVoiceHistoryById(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	for _, v := range list {
		v.RegisterPlatform = utils.CYGX_REGISTER_PLATFORM_MAP[v.RegisterPlatform]
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 留言详情excel表格下载
// @Description 留言详情excel表格下载接口
// @Param   VideoId   query   int  true       "视频ID"
// @Success 200 导出成功
// @router /microRoadshow/commentListExport/video [get]
func (this *MicroRoadshowController) CommentListExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	videoId, _ := this.GetInt("VideoId")
	videoInfo, _ := cygx.GetMicroRoadshowVideoByVideoId(videoId)
	if videoInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "视频ID错误"
		return
	}

	var condition string
	var pars []interface{}
	condition += `  AND activity_id =  0 AND video_id = ?  `
	pars = append(pars, videoInfo.VideoId)
	list, err := cygx.GetArticleCommentListSearch(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("名单")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "公司名称"
	cellC := rowTitle.AddCell()
	cellC.Value = "留言"
	cellD := rowTitle.AddCell()
	cellD.Value = "提交时间"

	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.CompanyName
		cellC := row.AddCell()
		cellC.Value = item.Content
		cellD := row.AddCell()
		cellD.Value = item.CreateTime
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "留言列表" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Success = true
	br.Ret = 200
	br.Msg = "导出成功"
}

// @Title 留言详情excel表格下载
// @Description 留言详情excel表格下载接口
// @Param    ActivityId   query   int  true       "活动Id"
// @Success 200 导出成功
// @router /microRoadshow/commentListExport/voice [get]
func (this *MicroRoadshowController) VoiceCommentListExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	videoInfo, _ := cygx.GetMicroRoadshowVoiceById(activityId)
	if videoInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "音频ID错误"
		return
	}
	var condition string
	var pars []interface{}
	condition += `  AND activity_voice_id = ? `
	pars = append(pars, videoInfo.ActivityVoiceId)
	list, err := cygx.GetArticleCommentListSearch(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("名单")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "公司名称"
	cellC := rowTitle.AddCell()
	cellC.Value = "留言"
	cellD := rowTitle.AddCell()
	cellD.Value = "提交时间"

	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.CompanyName
		cellC := row.AddCell()
		cellC.Value = item.Content
		cellD := row.AddCell()
		cellD.Value = item.CreateTime
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "留言列表" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Success = true
	br.Ret = 200
	br.Msg = "导出成功"
}

// @Title 留言列表详情
// @Description 获取留言列表详情接口
// @Param   VideoId  query   int  true       "视频ID"
// @Success 200 {object} cygx.ArticleCommentListResp
// @router /microRoadshow/commentList/video [get]
func (this *MicroRoadshowController) CommentList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	videoId, _ := this.GetInt("VideoId")
	videoInfo, _ := cygx.GetMicroRoadshowVideoByVideoId(videoId)
	if videoInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "视频ID错误"
		return
	}

	var condition string
	var pars []interface{}
	condition += `  AND activity_id =  0 AND video_id = ?  `
	pars = append(pars, videoInfo.VideoId)
	list, err := cygx.GetArticleCommentListSearch(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//list, err := cygx.GetArticleCommentListByVideoId(videoId)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败，Err:" + err.Error()
	//	return
	//}
	resp := new(cygx.ArticleCommentListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 留言列表详情
// @Description 获取留言列表详情接口
// @Param    ActivityId   query   int  true       "活动Id"
// @Success 200 {object} cygx.ArticleCommentListResp
// @router /microRoadshow/commentList/voice [get]
func (this *MicroRoadshowController) VoiceCommentList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	videoInfo, _ := cygx.GetMicroRoadshowVoiceById(activityId)
	if videoInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "音频ID错误"
		return
	}
	var condition string
	var pars []interface{}
	condition += `  AND activity_voice_id = ? `
	pars = append(pars, videoInfo.ActivityVoiceId)
	list, err := cygx.GetArticleCommentListSearch(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.ArticleCommentListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
