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"
	"strconv"
	"strings"
	"time"
)

// 系列问答视频
type AskserieVideoController struct {
	controllers.BaseAuthController
}

// @Title 新增
// @Description 新增系列问答接口
// @Param	request	body cygx.AddProductInteriorReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /askserie_video/preserveAndEdit [post]
func (this *AskserieVideoController) PreserveAndPublish() {
	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.AddAskserieVideoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.VideoName = utils.RemoveFileSuffixName(req.VideoName) //去掉后缀名称
	askserieVideoId := req.AskserieVideoId
	videoName := req.VideoName
	videoUrl := req.VideoUrl
	videoDuration := req.VideoDuration
	chartPermissionId := req.ChartPermissionId
	chartPermissionName := req.ChartPermissionName
	industrialManagementIds := req.IndustrialManagementIds
	backgroundImg := req.BackgroundImg
	shareImg := req.ShareImg
	// 产业ID校验
	if industrialManagementIds != "" {
		industrialManagementIdList := strings.Split(industrialManagementIds, ",")
		for _, v := range industrialManagementIdList {
			_, err := strconv.Atoi(v)
			if err != nil {
				br.Msg = "参数解析异常！"
				br.ErrMsg = "产业ID不规范，Err:" + err.Error() + industrialManagementIds
				return
			}
		}
	}

	item := new(cygx.CygxAskserieVideo)
	item.AskserieVideoId = askserieVideoId
	item.VideoName = videoName
	item.VideoUrl = videoUrl
	item.VideoDuration = videoDuration
	item.ChartPermissionId = chartPermissionId
	item.ChartPermissionName = chartPermissionName
	item.PublishStatus = 1
	item.BackgroundImg = backgroundImg

	item.AdminId = sysUser.AdminId
	item.ModifyDate = time.Now()
	item.PublishDate = time.Now()
	item.CreateTime = time.Now()

	if askserieVideoId == 0 {
		shareImg, _ = cygxService.MakeCygxMp3HtmlImg(videoDuration, 0) //生成分享图片
		item.ShareImg = shareImg
		//新增
		newId, err := cygx.AddCygxAskserieVideo(item, industrialManagementIds)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
		askserieVideoId = int(newId)
	} else {
		//更新
		detail, err := cygx.GetCygxAskserieVideoDetail(askserieVideoId)
		if err != nil {
			br.Msg = "详情不存在"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		//如果时长有变更就更新分享图片
		if detail.VideoDuration != videoDuration {
			shareImg, _ = cygxService.MakeCygxMp3HtmlImg(videoDuration, 0) //生成分享图片
			item.ShareImg = shareImg
		}

		err = cygx.UpdateCygxAskserieVideo(item, industrialManagementIds)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
	}

	go cygxService.UpdateAskserieVideoResourceData(askserieVideoId) //写入首页最新  cygx_resource_data 表
	go elastic.EsAddAskserieVideo(askserieVideoId)                  // 写入es 综合搜索
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title 列表
// @Description 列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Param   PublishStatus   query   int  true       "发布状态: -1-默认全部; 0-未发布; 1-已关注"
// @Param   ChartPermissionId   query   string  false       "行业Id"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   SortType          query   string    false		"排序顺序：asc、desc"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /askserie_video/list [get]
func (this *AskserieVideoController) 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
	}
	resp := new(cygx.GetCygxAskserieVideoRespListResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	publishStatus, _ := this.GetInt("PublishStatus", -1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)
	sortType := this.GetString("SortType")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	//发布状态查询
	if publishStatus == 0 || publishStatus == 1 || publishStatus == 3 {
		condition += ` AND art.publish_status = ? `
		pars = append(pars, publishStatus)
	}
	//起始日期查询
	if startDate != "" && endDate != "" {
		condition += ` 	AND art.publish_date  BETWEEN ?   AND  ? `
		pars = append(pars, startDate+" 00:00:00", endDate+" 23:59:59")
	}
	//行业查询
	if chartPermissionId > 0 {
		condition += ` 	AND art.chart_permission_id = ?`
		pars = append(pars, chartPermissionId)
	}
	if keyWord != "" {
		condition += ` AND ( video_name LIKE '%` + keyWord + `%' ) `
	}
	total, err := cygx.GetCygxAskserieVideoCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	var conditionOrder string
	if sortType == "asc" || sortType == "desc" {
		conditionOrder += ` ORDER BY art.video_counts   ` + sortType
	} else {
		conditionOrder += ` 	ORDER BY art.modify_date DESC  `
	}
	//condition += "	ORDER BY art.modify_date DESC  "
	condition += conditionOrder
	list, err := cygx.GetCygxAskserieVideoList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var askserieVideoIds []int
	for _, v := range list {
		askserieVideoIds = append(askserieVideoIds, v.AskserieVideoId)
	}

	mapLabel := cygxService.GetCygxAskserieVideoLabelMap(askserieVideoIds) // 标签
	for _, v := range list {
		v.IndustryName = mapLabel[v.AskserieVideoId]
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  详情
// @Description 获取详情接口
// @Param   AskserieVideoId   query   int  true       "ID"
// @Success Ret=200 {object} cygx.GetCygxProductInteriorDetailResp
// @router /askserie_video/detail [get]
func (this *AskserieVideoController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(cygx.GetCygxAskserieVideoDetailResp)
	askserieVideoId, _ := this.GetInt("AskserieVideoId")
	if askserieVideoId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	detail, err := cygx.GetCygxAskserieVideoDetail(askserieVideoId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	//产业标签
	industrialListMap := cygxService.GetCygxAskserieVideoLabelListMap([]int{askserieVideoId})
	detail.ListIndustrial = industrialListMap[askserieVideoId]
	resp.Detail = detail

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

// @Title  播放记录详情
// @Description 播放记录详情接口
// @Param   AskserieVideoId   query   int  true       "ID"
// @Success Ret=200 {object} cygx.GetCygxProductInteriorDetailResp
// @router /askserie_video/history_list [get]
func (this *AskserieVideoController) HistoryList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(cygx.CygxCygxAskserieVideoHistoryRecordListResp)
	askserieVideoId, _ := this.GetInt("AskserieVideoId")
	if askserieVideoId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	_, err := cygx.GetCygxAskserieVideoDetail(askserieVideoId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND askserie_video_id = ?  ORDER BY id DESC  `
	pars = append(pars, askserieVideoId)
	list, err := cygx.GetCygxAskserieVideoHistoryRecordList(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

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

// @Title  留言记录详情
// @Description 留言记录详情接口
// @Param   AskserieVideoId   query   int  true       "ID"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success Ret=200 {object} cygx.GetCygxProductInteriorDetailResp
// @router /askserie_video/collection_list [get]
func (this *AskserieVideoController) CollectionList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(cygx.CygxAskserieVideoCollectionListResp)
	askserieVideoId, _ := this.GetInt("AskserieVideoId")
	if askserieVideoId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	_, err := cygx.GetCygxAskserieVideoDetail(askserieVideoId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND askserie_video_id = ?  ORDER BY id DESC  `
	pars = append(pars, askserieVideoId)
	list, err := cygx.GetCygxAskserieVideoCollectionList(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]
	}
	resp.List = list
	//导出excel
	if isExport {
		CollectionListExport(this, resp, br)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// VoiceAndVideoCommentListExport 导出Excel
func CollectionListExport(this *AskserieVideoController, resp *cygx.CygxAskserieVideoCollectionListResp, br *models.BaseResponse) {
	//创建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 resp.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
	}
	downloadFileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 发布/取消发布
// @Description 发布/取消发布接口
// @Param	request	body cygx.ProductInteriorIdReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /askserie_video/publishAndcancel [post]
func (this *AskserieVideoController) PublishReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.AskserieVideoIdIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	askserieVideoId := req.AskserieVideoId
	if askserieVideoId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，id不可为空"
		return
	}
	detail, err := cygx.GetCygxAskserieVideoDetail(askserieVideoId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var status int
	if detail.PublishStatus != 1 {
		status = 1
	} else {
		status = 3
	}
	err = cygx.EditCygxAskserieVideoStatus(status, askserieVideoId)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	go cygxService.UpdateAskserieVideoResourceData(askserieVideoId) //写入首页最新  cygx_resource_data 表
	go elastic.EsAddAskserieVideo(askserieVideoId)                  // 写入es 综合搜索
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
