package services

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/smart_report"
	"eta/eta_api/services/alarm_msg"
	"eta/eta_api/utils"
	"fmt"
	"html"
	"strconv"
	"time"
)

// SmartReportBuildVideoAndUpdate 生成音频
func SmartReportBuildVideoAndUpdate(item *smart_report.SmartReport) {
	if item == nil {
		return
	}
	var err error
	defer func() {
		if err != nil {
			tips := fmt.Sprintf("智能研报-音频生成, errMsg: %s", err.Error())
			go alarm_msg.SendAlarmMsg(tips, 2)
		}
	}()

	videoUrl, videoName, videoSize, videoPlaySeconds, e := CreateReportVideo(item.Title, item.Content, time.Now().Local().Format(utils.FormatDateTime))
	if e != nil {
		err = fmt.Errorf("create audio err: %s", e.Error())
		return
	}
	item.VideoUrl = videoUrl
	item.VideoName = videoName
	item.VideoSize = videoSize
	item.VideoPlaySeconds = videoPlaySeconds
	item.ModifyTime = time.Now().Local()
	cols := []string{"VideoUrl", "VideoName", "VideoSize", "VideoPlaySeconds", "ModifyTime"}
	if e = item.Update(cols); e != nil {
		err = fmt.Errorf("smart report update err: %s", e.Error())
		return
	}
}

// UpdateSmartReportEditing 更新研报当前更新状态
// status 枚举值 1：编辑中，0：完成编辑, 2：只做查询
func UpdateSmartReportEditing(reportId, status, thisUserId int, thisUserName string, adminIdName map[int]string) (ret models.MarkReportResp, err error) {
	key := fmt.Sprint(utils.CACHE_SMART_REPORT_EDITING, reportId)
	ret.Status = 0
	ret.Msg = "无人编辑"

	opUserId, e := utils.Rc.RedisInt(key)
	var opUser models.MarkReportItem
	var classifyNameFirst string
	if e != nil {
		opUserInfoStr, tErr := utils.Rc.RedisString(key)
		if tErr == nil {
			tErr = json.Unmarshal([]byte(opUserInfoStr), &opUser)
			if tErr == nil {
				opUserId = opUser.AdminId
			}
		}
	}

	if opUserId > 0 && opUserId != thisUserId {
		editor := opUser.Editor
		if editor == "" {
			editor = adminIdName[opUserId]
		}
		ret.Status = 1
		ret.Msg = fmt.Sprintf("当前%s正在编辑报告", editor)
		ret.Editor = editor
		return
	}

	if status == 1 {
		nowUser := &models.MarkReportItem{AdminId: thisUserId, Editor: thisUserName, ReportClassifyNameFirst: classifyNameFirst}
		bt, e := json.Marshal(nowUser)
		if e != nil {
			err = fmt.Errorf("格式化编辑者信息失败")
			return
		}
		if opUserId > 0 {
			utils.Rc.Do("SETEX", key, int64(180), string(bt)) //3分钟缓存
		} else {
			utils.Rc.SetNX(key, string(bt), time.Second*60*3) //3分钟缓存
		}
	} else if status == 0 {
		//清除编辑缓存
		_ = utils.Rc.Delete(key)
	}
	return
}

// SmartReportElasticUpsert 新增/编辑报告es
func SmartReportElasticUpsert(smartReportId int, state int) (err error) {
	if smartReportId <= 0 {
		return
	}

	reportOB := new(smart_report.SmartReport)
	item, e := reportOB.GetItemById(smartReportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			// 可能被删了就直接忽略掉
			return
		}
		err = fmt.Errorf("获取报告失败, Err: %s", e.Error())
		return
	}

	esReport := new(smart_report.ElasticSmartReport)
	esReport.SmartReportId = item.SmartReportId
	esReport.Title = item.Title
	esReport.Abstract = item.Abstract
	esReport.BodyContent = utils.TrimHtml(html.UnescapeString(item.Content))
	esReport.PublishTime = item.PublishTime.Format(utils.FormatDateTime)
	esReport.PublishState = state
	esReport.Author = item.Author
	esReport.ClassifyIdFirst = item.ClassifyIdFirst
	esReport.ClassifyNameFirst = item.ClassifyNameFirst
	esReport.ClassifyIdSecond = item.ClassifyIdSecond
	esReport.ClassifyNameSecond = item.ClassifyNameSecond
	esReport.StageStr = strconv.Itoa(item.Stage)
	esReport.Frequency = item.Frequency
	if err = EsAddOrEditSmartReport(utils.SmartReportIndexName, strconv.Itoa(item.SmartReportId), esReport); err != nil {
		return
	}
	return
}
