package cygx

import (
	"fmt"
	"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"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 活动
type ActivityVideoCoAntroller struct {
	controllers.BaseAuthController
}

// @Title 活动列表
// @Description 获取活动列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ChartPermissionId   query   string  false     "行业id"
// @Param   ActivityTypeId   query   string  false     "活动类型id"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   SortType          query   string    false		"排序顺序：asc、desc"
// @Success 200 {object} cygx.CygxActivityVideoListRep
// @router /activityVideo/list [get]
func (this *ActivityVideoCoAntroller) ActivityVideoList() {
	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
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	ActivityTypeId, _ := this.GetInt("ActivityTypeId")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	keyWord := this.GetString("KeyWord")
	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 keyWord != "" {
		condition += ` AND (v.video_name LIKE '%` + keyWord + `%' )  `
	}
	//行业名称
	if chartPermissionId > 0 {
		condition += ` AND art.chart_permission_id  = ?  `
		pars = append(pars, chartPermissionId)
	}

	if startDate != "" {
		condition += ` AND art.activity_time >= ` + "'" + startDate + " 00:00:00'"
	}
	if endDate != "" {
		condition += ` AND art.activity_time <= ` + "'" + endDate + " 23:59:59'"
	}
	if ActivityTypeId > 0 {
		condition += ` AND art.activity_type_id  = ?  `
		pars = append(pars, ActivityTypeId)
	}
	total, err := cygx.GetActivityVideoCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	if sortType == "asc" || sortType == "desc" {
		condition += ` ORDER BY v.video_counts   ` + sortType
	} else {
		condition += ` 	ORDER BY art.activity_time DESC  `
	}

	list, errList := cygx.GetActivityVideoListAll(condition, pars, startSize, pageSize)
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errList.Error()
		return
	}
	var activityIds string
	for k, v := range list {
		if v.ChartPermissionNames != "" {
			list[k].ChartPermissionName = v.ChartPermissionNames
		}
		activityIds += strconv.Itoa(v.ActivityId) + ","
	}
	activityIds = strings.TrimRight(activityIds, ",")
	mapIndustrial := make(map[int]string)
	mapSubject := make(map[string]string)
	if activityIds != "" {
		industrialList, err := cygx.GetIndustrialActivityGroupListByactivityIds(activityIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetIndustrialActivityGroupListByactivityIds Err:" + err.Error()
			return
		}
		subjectList, err := cygx.GetSubjectActivityGroupListByactivityIds(activityIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetSubjectActivityGroupListByactivityIds Err:" + err.Error()
			return
		}
		//合并活动对应的多个标的
		for _, v := range subjectList {
			mapSubject[fmt.Sprint(v.ActivityId, "_", v.IndustrialManagementId)] += v.SubjectName + "/"
		}
		//活动对应的产业
		for _, v := range industrialList {
			var labelSubject string
			labelSubject = mapSubject[fmt.Sprint(v.ActivityId, "_", v.IndustrialManagementId)]
			if labelSubject != "" {
				mapIndustrial[v.ActivityId] += v.IndustryName + "--" + strings.TrimRight(labelSubject, "/") + "，"
			} else {
				mapIndustrial[v.ActivityId] += v.IndustryName + "，"
			}
		}
	}
	for k, v := range list {
		if mapIndustrial[v.ActivityId] != "" && v.TemporaryLabel == "" {
			list[k].Label = strings.TrimRight(mapIndustrial[v.ActivityId], "，")
		}
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxActivityVideoListResp, 0)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.CygxActivityVideoListRep)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 音频播放详情
// @Description 音频播放详情接口
// @Param   VideoId   query   int  true       "视频Id"
// @Success Ret=200 发布成功
// @router /activityVideo/deatil [get]
func (this *ActivityVideoCoAntroller) VideoDeatil() {
	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")
	if videoId <= 0 {
		br.Msg = "参数错误"
		return
	}
	var condition string
	var pars []interface{}
	condition += `AND v.video_id= ? `
	pars = append(pars, videoId)
	list, err := cygx.GetActivityVideoHistoryById(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 留言详情excel表格下载
// @Description 留言详情excel表格下载接口
// @Param   VideoId   query   int  true       "视频ID"
// @Success 200 导出成功
// @router /activityVideo/commnetListExport [get]
func (this *ActivityVideoCoAntroller) 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.GetCygxActivityVideoReqDetailByVideoId(videoId)
	if videoInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "报告ID错误"
		return
	}

	var condition string
	var pars []interface{}
	condition += `  AND activity_id =  ? AND video_id = ?  `
	pars = append(pars, videoInfo.ActivityId, 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 留言列表详情
// @Description 获取留言列表详情接口
// @Param    VideoId   query   int  true       "视频ID"
// @Success 200 {object} cygx.ArticleCommentListResp
// @router /activityVideo/commentList [get]
func (this *ActivityVideoCoAntroller) 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.GetCygxActivityVideoReqDetailByVideoId(videoId)
	if videoInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "报告ID错误"
		return
	}

	var condition string
	var pars []interface{}
	condition += `  AND activity_id =  ? AND video_id = ?  `
	pars = append(pars, videoInfo.ActivityId, videoInfo.VideoId)
	list, err := cygx.GetArticleCommentListSearch(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//list, err := cygx.GetArticleCommentListByActivityVideoId(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
}
