package english_report

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
)

// EnglishVideoController 英文研报-线上路演
type EnglishVideoController struct {
	controllers.BaseAuthController
}

// CoverList
// @Title 封面库列表
// @Description 封面库
// @Param   PageSize		query  int  false  "每页数据量"
// @Param   CurrentIndex	query  int  false  "页码"
// @Success 200 {object} models.EnglishVideoCoverListResp
// @router /video/cover/list [get]
func (this *EnglishVideoController) 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)
	total, resp, err := services.GetEnglishVideoCoverList(condition, pars, "", startSize, pageSize)
	if err != nil {
		br.Msg = "获取封面库列表失败"
		br.ErrMsg = "GetEnglishVideoCoverList 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.EnglishVideoCoverSaveReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /video/cover/save [post]
func (this *EnglishVideoController) 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 models.EnglishVideoCoverSaveReq
	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
	}

	data, errMsg, err := services.SaveEnglishVideoCover(req.Id, req.CoverName, req.CoverUrl)
	if err != nil {
		br.Msg = errMsg
		br.ErrMsg = "SaveEnglishVideoCover ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.Data = data
}

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

// @Title 新增/编辑路演视频
// @Description 新增/编辑路演视频
// @Param	request	body models.SaveEnglishVideoReq true "type json string"
// @Success 200 {object} models.SaveEnglishVideoResp
// @router /video/save [post]
func (this *EnglishVideoController) Save() {
	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 models.SaveEnglishVideoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Title == "" {
		br.Msg = "请输入标题"
		return
	}
	if req.ClassifyIdFirst <= 0 {
		br.Msg = "请输入一级分类"
		return
	}
	if req.ClassifyIdSecond <= 0 {
		br.Msg = "请选择二级分类"
		return
	}
	if req.VideoUrl == "" {
		br.Msg = "请输入视频地址"
		return
	}
	if req.VideoCoverUrl == "" {
		br.Msg = "请输入视频封面地址"
		return
	}
	if req.VideoSeconds == "" {
		br.Msg = "请输入视频时长"
		return
	}
	if req.Overview == "" {
		br.Msg = "请输入overview"
		return
	}
	if req.Abstract == "" {
		br.Msg = "请输入摘要"
		return
	}
	id, videoCode, err, errMsg := services.SaveEnglishVideo(req, sysUser)
	if err != nil {
		br.Msg = err.Error()
		br.ErrMsg = errMsg
		return
	}
	resp := new(models.SaveEnglishVideoResp)
	resp.Id = id
	resp.VideoCode = videoCode
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = resp
}

// @Title 获取路演视频详情接口
// @Description 获取路演视频详情接口
// @Param	request	body models.EnglishVideoDetail true "type json string"
// @Success 200 {object} models.EnglishVideoDetailView
// @router /video/detail [get]
func (this *EnglishVideoController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	id, err := this.GetInt("Id")
	if err != nil {
		br.Msg = "获取参数失败！"
		br.ErrMsg = "获取参数失败，Err:" + err.Error()
		return
	}
	if id <= 0 {
		br.Msg = "请选择路演视频记录"
		return
	}
	item, err := models.GetEnglishVideoById(id)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "路演视频不存在"
			return
		}
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

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

// @Title 获取报告列表接口
// @Description 获取报告列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} models.ReportListResp
// @router /video/list [get]
func (this *EnglishVideoController) 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")

	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 title LIKE '%` + keyWord + `%' `
	}

	total, err := models.GetEnglishVideoListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list := make([]*models.EnglishVideoList, 0)
	list, err = models.GetEnglishVideoList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.EnglishVideoListResp)
	if len(list) == 0 {
		list = make([]*models.EnglishVideoList, 0)
		resp.Paging = page
		resp.List = list
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
	}
	// 查询分类信息
	var classifyIdSecondSlice []int
	classifyNameMap := make(map[int]*models.EnglishClassifyFullName)
	for _, item := range list {
		classifyIdSecondSlice = append(classifyIdSecondSlice, item.ClassifyIdSecond)
	}
	if len(classifyIdSecondSlice) > 0 {
		nameList, err := models.GetEnglishClassifyFullNameByIds(classifyIdSecondSlice)
		if err != nil {
			br.Msg = "获取分类名称失败"
			br.ErrMsg = "获取分类名称失败, ERR:" + err.Error()
			return
		}

		for _, v := range nameList {
			classifyNameMap[v.Id] = v
		}
	}

	// todo 获取邮件配置-是否有权限群发
	conf := new(models.EnglishReportEmailConf)
	authKey := "english_report_email_conf"
	confAuth, e := company.GetConfigDetailByCode(authKey)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取群发邮件权限失败, Err: " + e.Error()
		return
	}
	if confAuth.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "群发邮件配置为空"
		return
	}
	if e := json.Unmarshal([]byte(confAuth.ConfigValue), &conf); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "群发邮件配置有误"
		return
	}
	authOk := false
	authArr := strings.Split(conf.SendAuthGroup, ",")
	if utils.InArrayByStr(authArr, sysUser.RoleTypeCode) {
		authOk = true
	}

	// todo 是否有群发邮件失败的记录，标记红点
	failList, e := models.GetEnglishReportEmailLogFailList(1)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取群发邮件记录失败, Err: " + e.Error()
		return
	}
	failMap := make(map[int]bool, 0)
	for i := range failList {
		failMap[failList[i].ReportId] = true
	}

	for _, item := range list {
		if item.State == 2 {
			//列表中展示分享地址
			//item.ShareUrl = "https://share.hzinsights.com/reportEn?code=" + item.ReportCode
		}
		item.EmailAuth = authOk
		if c, ok := failMap[item.Id]; ok {
			item.EmailHasFail = c
		}

		// 邮箱PV大于0的时候, 不展示最初版本的PV
		if item.PvEmail > 0 {
			item.Pv = 0
		}
		//处理分类名
		//处理分类名
		if n, ok := classifyNameMap[item.ClassifyIdSecond]; ok {
			if n.RootId == 0 {
				item.FullClassifyName = strings.Join([]string{n.ParentName, n.ClassifyName}, "/")
			} else {
				item.FullClassifyName = strings.Join([]string{n.RootName, n.ParentName, n.ClassifyName}, "/")
			}
			item.ClassifyIdRoot = n.RootId
			item.ClassifyNameRoot = n.RootName
		}
	}

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

// @Title 发布报告接口
// @Description 发布报告
// @Param	request	body models.EnglishVideoReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /video/publish [post]
func (this *EnglishVideoController) PublishVideo() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.EnglishVideoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	id := req.Id
	if id <= 0 {
		br.Msg = "请选择要发布的路演视频"
		return
	}
	videoInfo, err := models.GetEnglishVideoById(id)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "路演视频不存在"
			return
		}
		br.Msg = "获取路演视频失败"
		br.ErrMsg = "获取路演视频失败,Err:" + err.Error()
		return
	}

	var tmpErr error

	if videoInfo.VideoUrl == "" {
		br.Msg = "视频地址为空，不可发布"
		br.ErrMsg = "视频地址为空，不需要生成, id:" + strconv.Itoa(videoInfo.Id)
		return
	}

	if videoInfo.Title == "" {
		br.Msg = "标题为空，不可发布"
		br.ErrMsg = "标题为空，不需要生成, id:" + strconv.Itoa(videoInfo.Id)
		return
	}
	if videoInfo.State == 2 {
		br.Msg = "已发布，无需重复发布"
		return
	}
	if tmpErr = models.PublishEnglishVideoById(videoInfo.Id); tmpErr != nil {
		br.Msg = "路演视频发布失败"
		br.ErrMsg = "路演视频发布失败, Err:" + tmpErr.Error() + ", id:" + strconv.Itoa(videoInfo.Id)
		return
	}
	// 路演视频搜索
	go func() {
		_ = services.UpdateEnglishVideoEs(videoInfo.Id, 2)
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "发布成功"
}

// @Title 取消发布报告接口
// @Description 取消发布报告
// @Param	request	body models.EnglishVideoReq true "type json string"
// @Success 200 Ret=200 取消发布成功
// @router /video/publish/cancel [post]
func (this *EnglishVideoController) PublishCancleVideo() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.EnglishVideoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，路演视频id不可为空"
		return
	}
	videoInfo, err := models.GetEnglishVideoById(req.Id)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "路演视频不存在"
			return
		}
		br.Msg = "获取路演视频失败"
		br.ErrMsg = "获取路演视频失败,Err:" + err.Error()
		return
	}

	if videoInfo.State == 1 {
		br.Msg = "已取消发布，无需重复取消"
		return
	}
	err = models.PublishCancelEnglishVideo(req.Id)
	if err != nil {
		br.Msg = "取消发布失败"
		br.ErrMsg = "取消发布失败,Err:" + err.Error()
		return
	}
	// 更新es里的报告状态
	go func() {
		_ = services.UpdateEnglishVideoEs(videoInfo.Id, 1)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "取消发布成功"
}

// @Title 删除路演视频接口
// @Description 删除路演视频
// @Param	request	body models.EnglishVideoReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /video/delete [post]
func (this *EnglishVideoController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.EnglishVideoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "请选择要发布的路演视频"
		return
	}
	videoInfo, err := models.GetEnglishVideoById(req.Id)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "路演视频不存在"
			return
		}
		br.Msg = "获取路演视频失败"
		br.ErrMsg = "获取路演视频失败,Err:" + err.Error()
		return
	}
	// 更新es里的路演视频状态
	_ = services.UpdateEnglishVideoEs(videoInfo.Id, 1)
	if videoInfo.State == 2 {
		br.Msg = "路演视频已发布，不可删除"
		return
	}
	if err = models.DeleteEnglishVideo(req.Id); err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除路演视频失败, Err: " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}
