package yb

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	ybModels "hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/request"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/yb"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

// 研报视频社区
type CommunityVideoController struct {
	controllers.BaseAuthController
}

// List
// @Title 视频列表
// @Description 视频列表
// @Param   Keywords  query  string  false  "关键词"
// @Param   SortParam   query   string  false     "排序字段参数，用来排序的字段， 枚举值：'ClickNum':点击量"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} response.CommunityQuestionListResp
// @router /community/video/list [get]
func (this *CommunityVideoController) List() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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
	}

	condition := ""
	pars := make([]interface{}, 0)
	keywords := this.GetString("Keywords", "")
	if keywords != "" {
		keywords = "%" + keywords + "%"
		condition += ` AND v.title LIKE ? `
		pars = append(pars, keywords)
	}

	var startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	// 排序相关
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")
	orderStr := ""
	if sortType != "" && strings.ToLower(sortType) != "desc" && strings.ToLower(sortType) != "asc" {
		br.Msg = "请输入正确的排序类型"
		return
	}
	if sortParam == "ClickNum" {
		orderStr = "  ORDER BY l.click_num"
		if sortType != "" {
			orderStr += " " + sortType
		} else {
			orderStr += " DESC"
		}

		orderStr += ", v.modify_time DESC"
	}
	total, resp, err := yb.GetCommunityVideoList(condition, pars, orderStr, startSize, pageSize)
	if err != nil {
		br.Msg = "获取视频列表失败"
		br.ErrMsg = "Yb-VideoList ErrMsg:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Save
// @Title 保存视频
// @Description 保存视频
// @Param	request  body  request.CommunityVideoSaveReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/save [post]
func (this *CommunityVideoController) Save() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoSaveReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Title == "" {
		br.Msg = "请输入标题"
		return
	}
	if req.VarietyTagId == 0 {
		br.Msg = "请选择标签"
		return
	}
	if req.CoverImgUrl == "" {
		br.Msg = "请上传封面图"
		return
	}
	if req.VideoUrl == "" {
		br.Msg = "请上传视频"
		return
	}
	data, errMsg, err := yb.SaveCommunityVideo(req.VideoId, req.VarietyTagId, req.Title, req.CoverImgUrl, req.VideoUrl, req.VideoSeconds)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "Yb-SaveVideo ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.Data = data
}

// Delete
// @Title 删除视频
// @Description 删除视频
// @Param	request  body  request.CommunityVideoOptionReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/delete [post]
func (this *CommunityVideoController) Delete() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoOptionReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.VideoId <= 0 {
		br.Msg = "参数有误"
		return
	}
	errMsg, err := yb.SoftDeleteCommunityVideo(req.VideoId)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "Yb-DeleteVideo ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Publish
// @Title 发布/取消视频
// @Description 发布/取消视频
// @Param	request  body  request.CommunityVideoPublishReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/publish [post]
func (this *CommunityVideoController) Publish() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoPublishReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.VideoId <= 0 {
		br.Msg = "参数有误"
		return
	}
	errMsg, err := yb.PublishCommunityVideo(req.VideoId, req.PublishState)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "Yb-PublishVideo ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// SendThs
// @Title 推送客群消息
// @Description 推送客群消息
// @Param	request  body  request.CommunityVideoOptionReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/send_ths [post]
func (this *CommunityVideoController) SendThs() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoOptionReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.VideoId <= 0 {
		br.Msg = "参数有误"
		return
	}
	errMsg, err := yb.SendCommunityVideoThsMsg(req.VideoId)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "Yb-SendVideoThsMsg ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// VideoPlayLogList
// @Title 获取视频点击量列表
// @Description 获取视频点击量列表
// @Param   VideoId	query	int	false	"视频ID"
// @Param   SortType	query	int	false	"播放时长排序：默认倒序; 1-倒序(多一个数方便前端回显); 2-正序"
// @Success 200 {object} response.QuestionClickLogListResp
// @router /community/video/click/logs [get]
func (this *CommunityVideoController) VideoPlayLogList() {
	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 = "请输入正确的视频ID"
		return
	}
	// 播放时长排序：1-DESC; 2-ASC;
	sortType, _ := this.GetInt("SortType")

	var startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, resp, err := yb.GetVideoPlayLogList(videoId, 1, startSize, pageSize, sortType)
	if err != nil {
		br.Msg = "获取问答列表失败"
		br.ErrMsg = "QuestionList ErrMsg:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, int(total))
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// SendTemplateMsg
// @Title 推送模板消息
// @Description 推送模板消息
// @Param	request  body  request.CommunityVideoOptionReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/send_template_msg [post]
func (this *CommunityVideoController) SendTemplateMsg() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoOptionReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.VideoId <= 0 {
		br.Msg = "参数有误"
		return
	}
	errMsg, err := yb.SendCommunityVideoTemplateMsg(req.VideoId)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "Yb-SendCommunityVideoTemplateMsg ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// CoverList
// @Title 封面库列表
// @Description 封面库
// @Param   PageSize		query  int  false  "每页数据量"
// @Param   CurrentIndex	query  int  false  "页码"
// @Success 200 {object} response.CommunityVideoCoverListResp
// @router /community/video/cover_list [get]
func (this *CommunityVideoController) CoverList() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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
	}

	condition := ""
	pars := make([]interface{}, 0)

	var startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	coverType, _ := this.GetInt("Type", 0)
	if coverType > 0 {
		condition += " and type=?"
		pars = append(pars, coverType)
	}

	total, resp, err := yb.GetCommunityVideoCoverList(condition, pars, "", startSize, pageSize)
	if err != nil {
		br.Msg = "获取封面库列表失败"
		br.ErrMsg = "Yb-GetCommunityVideoCoverList ErrMsg:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// CoverSave
// @Title 保存封面图
// @Description 保存封面图
// @Param	request  body  request.CommunityVideoCoverSaveReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/cover_save [post]
func (this *CommunityVideoController) CoverSave() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoCoverSaveReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.CoverName == "" {
		br.Msg = "请输入封面名称"
		return
	}
	if req.CoverUrl == "" {
		br.Msg = "请上传封面图"
		return
	}
	if req.Type == 0 {
		br.Msg = "选择封面类型"
		return
	}
	data, errMsg, err := yb.SaveCommunityVideoCover(req.CoverId, req.CoverName, req.CoverUrl, req.Type)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "Yb-SaveCommunityVideoCover ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.Data = data
}

// CoverDelete
// @Title 删除封面图
// @Description 删除封面图
// @Param	request  body  request.CommunityVideoCoverOptionReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/cover_delete [post]
func (this *CommunityVideoController) CoverDelete() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoCoverOptionReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.CoverId <= 0 {
		br.Msg = "参数有误"
		return
	}
	errMsg, err := yb.SoftDeleteCommunityVideoCover(req.CoverId)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "Yb-SoftDeleteCommunityVideoCover ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// SendMsg
// @Title 推送消息(模板/客群)
// @Description 推送消息(模板/客群)
// @Param	request  body  request.CommunityVideoOptionReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /community/video/send_msg [post]
func (this *CommunityVideoController) SendMsg() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 request.CommunityVideoOptionReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.VideoId <= 0 {
		br.Msg = "参数有误"
		return
	}

	// 加锁，避免重复点击造成的多次推送
	{
		redisKey := fmt.Sprint("community_video:send:msg:", req.VideoId)
		ok := utils.Rc.SetNX(redisKey, 1, time.Second*300)
		if !ok {
			br.Msg = "消息已推送, 请勿重复推送"
			return
		}
		defer func() {
			_ = utils.Rc.Delete(redisKey)
		}()
	}

	item, e := ybModels.GetVideoById(req.VideoId)
	if e != nil {
		br.Msg = "视频不存在或已被删除"
		br.ErrMsg = "获取视频信息失败, Err: " + e.Error()
		return
	}
	if item.PublishState != 1 {
		br.Msg = "视频未发布, 不可推送"
		return
	}
	if item.SendThsState == 1 && item.SendTemplateState == 1 {
		br.Msg = "请勿重复推送"
		return
	}

	nowTime := time.Now().Local()
	updateCols := make([]string, 0)
	// 可能存在历史数据两个只推了一个所以此处加个判断
	// 模板消息
	if item.SendTemplateState == 0 {
		updateCols = append(updateCols, "SendTemplateState", "SendTemplateTime")
		item.SendTemplateState = 1
		item.SendTemplateTime = nowTime
		go func() {
			_ = services.SendYbCommunityVideoWxMsgV2(item.CommunityVideoId, item.VarietyTagId, item.VarietyTagName, item.Title, item.PublishTime.Format(utils.FormatDateTime))
		}()
	}

	// 客群消息
	if item.SendThsState == 0 {
		updateCols = append(updateCols, "SendThsState", "SendThsTime")
		item.SendThsState = 1
		item.SendThsTime = nowTime
		//go func() {
		//	_ = services.SendYbCommunityVideoThs(item.CommunityVideoId, item.Title)
		//}()
	}

	// 更新状态
	if e := item.Update(updateCols); e != nil {
		br.Msg = "推送失败"
		br.ErrMsg = "更新视频信息失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
