package smart_report

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/report_approve"
	"eta/eta_mobile/models/smart_report"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/services"
	"eta/eta_mobile/services/data"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/kgiannakakis/mp3duration/src/mp3duration"
	"github.com/rdlucklib/rdluck_tools/paging"
	"html"
	"io/ioutil"
	"os"
	"path"
	"strings"
	"time"
)

// SmartReportController 智能研报
type SmartReportController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增
// @Description 新增
// @Param	request	body smart_report.SmartReportAddReq true "type json string"
// @Success 200 {object} smart_report.SmartReportItem
// @router /add [post]
func (this *SmartReportController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.AddType != 1 && req.AddType != 2 {
		br.Msg = "请选择新增方式"
		return
	}
	if req.ClassifyIdFirst <= 0 || req.ClassifyIdSecond <= 0 {
		br.Msg = "请选择分类"
		return
	}
	req.Title = strings.TrimSpace(req.Title)
	if req.Title == "" {
		br.Msg = "请输入标题"
		return
	}

	reportOB := new(smart_report.SmartReport)
	stageMax, e := reportOB.GetMaxStageByClassifyId(req.ClassifyIdSecond)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取期数失败, Err: " + e.Error()
		return
	}
	stageMax += 1

	// 根据审批开关及审批流判断当前报告状态
	state, e := services.CheckReportCurrState(report_approve.FlowReportTypeSmart, req.ClassifyIdFirst, req.ClassifyIdSecond, 0, models.ReportOperateAdd)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "校验报告当前状态失败, Err: " + e.Error()
		return
	}

	item := new(smart_report.SmartReport)
	item.AddType = req.AddType
	item.ClassifyIdFirst = req.ClassifyIdFirst
	item.ClassifyNameFirst = req.ClassifyNameFirst
	item.ClassifyIdSecond = req.ClassifyIdSecond
	item.ClassifyNameSecond = req.ClassifyNameSecond
	item.Title = req.Title
	item.Abstract = req.Abstract
	item.Author = req.Author
	item.Frequency = req.Frequency
	item.Stage = stageMax
	item.AdminId = sysUser.AdminId
	item.AdminRealName = sysUser.RealName
	item.LastModifyAdminId = sysUser.AdminId
	item.LastModifyAdminName = sysUser.RealName
	item.State = state
	item.CreateTime = time.Now().Local()
	item.ModifyTime = time.Now().Local()
	item.ContentModifyTime = time.Now().Local()
	item.HeadImg = req.HeadImg
	item.EndImg = req.EndImg
	item.CanvasColor = req.CanvasColor
	item.HeadResourceId = req.HeadResourceId
	item.EndResourceId = req.EndResourceId
	item.NeedSplice = 1

	// 继承报告
	if req.AddType == 2 {
		ob := new(smart_report.SmartReport)
		cond := ` AND classify_id_first = ? AND classify_id_second = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, req.ClassifyIdFirst, req.ClassifyIdSecond)
		lastReport, e := ob.GetItemByCondition(cond, pars, "stage DESC")
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取往期研报失败, Err: " + e.Error()
			return
		}
		if lastReport != nil {
			item.Content = lastReport.Content
			item.ContentSub = lastReport.ContentSub
			item.ContentStruct = lastReport.ContentStruct
		}
	}
	if e = item.Create(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增研报失败, Err: " + e.Error()
		return
	}
	uniqueCode := utils.MD5(fmt.Sprint("smart_", item.SmartReportId))
	item.ReportCode = uniqueCode
	if e = item.Update([]string{"ReportCode"}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新研报编码失败, Err: " + e.Error()
		return
	}
	resp := smart_report.FormatSmartReport2Item(item)

	recordItem := &models.ReportStateRecord{
		ReportId:   item.SmartReportId,
		ReportType: 2,
		State:      state,
		AdminId:    this.SysUser.AdminId,
		AdminName:  this.SysUser.AdminName,
		CreateTime: time.Now(),
	}
	go func() {
		_, _ = models.AddReportStateRecord(recordItem)
	}()

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

// Edit
// @Title 编辑
// @Description 编辑
// @Param	request	body smart_report.SmartReportEditReq true "type json string"
// @Success 200 {object} smart_report.SmartReportItem
// @router /edit [post]
func (this *SmartReportController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SmartReportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "报告ID为空"
		return
	}
	if req.ClassifyIdFirst <= 0 || req.ClassifyIdSecond <= 0 {
		br.Msg = "请选择分类"
		return
	}
	req.Title = strings.TrimSpace(req.Title)
	if req.Title == "" {
		br.Msg = "请输入标题"
		return
	}
	var subContent string
	if req.Content != "" {
		req.Content = html.EscapeString(req.Content)
		// 前两个章节
		sub, e := services.GetReportContentSub(req.Content)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "读取报告前两个章节内容失败, Err: " + e.Error()
			return
		}
		subContent = html.EscapeString(sub)
	}
	req.ContentStruct = html.EscapeString(req.ContentStruct)

	ob := new(smart_report.SmartReport)
	item, e := ob.GetItemById(req.SmartReportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取研报失败, Err: " + e.Error()
		return
	}
	if item.State == models.ReportStatePublished || item.State == models.ReportStatePass {
		br.Msg = "报告已发布, 请取消发布后编辑"
		return
	}

	// 内容是否变更, 只有内容产生变更时, 才更新最后更新人和内容更新时间字段
	contentModify := false
	if item.ClassifyIdFirst != req.ClassifyIdFirst ||
		item.ClassifyIdSecond != req.ClassifyIdSecond ||
		item.Title != req.Title ||
		item.Abstract != req.Abstract ||
		item.Frequency != req.Frequency ||
		item.Author != req.Author ||
		utils.MD5(item.Content) != utils.MD5(req.Content) {
		contentModify = true
	}
	cols := []string{"ClassifyIdFirst", "ClassifyNameFirst", "ClassifyIdSecond", "ClassifyNameSecond", "Title", "Abstract", "Author",
		"Frequency", "Content", "ContentSub", "ContentStruct", "ModifyTime", "HeadImg", "EndImg", "CanvasColor", "HeadResourceId", "EndResourceId"}
	item.ClassifyIdFirst = req.ClassifyIdFirst
	item.ClassifyNameFirst = req.ClassifyNameFirst
	item.ClassifyIdSecond = req.ClassifyIdSecond
	item.ClassifyNameSecond = req.ClassifyNameSecond
	item.Title = req.Title
	item.Abstract = req.Abstract
	item.Author = req.Author
	item.Frequency = req.Frequency
	item.Content = req.Content
	item.ContentSub = subContent
	item.ContentStruct = req.ContentStruct
	item.ModifyTime = time.Now().Local()
	item.HeadImg = req.HeadImg
	item.EndImg = req.EndImg
	item.CanvasColor = req.CanvasColor
	item.HeadResourceId = req.HeadResourceId
	item.EndResourceId = req.EndResourceId
	if contentModify {
		item.LastModifyAdminId = sysUser.AdminId
		item.LastModifyAdminName = sysUser.RealName
		item.ContentModifyTime = time.Now().Local()
		cols = append(cols, "LastModifyAdminId", "LastModifyAdminName", "ContentModifyTime")
	}
	if e := item.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新报告失败, Err: " + e.Error()
		return
	}
	resp := smart_report.FormatSmartReport2Item(item)

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

// Remove
// @Title 删除
// @Description 删除
// @Param	request	body smart_report.SmartReportRemoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /remove [post]
func (this *SmartReportController) Remove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportRemoveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SmartReportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "报告ID为空"
		return
	}

	ob := new(smart_report.SmartReport)
	item, e := ob.GetItemById(req.SmartReportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Ret = 200
			br.Success = true
			br.Msg = "操作成功"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取研报失败, Err: " + e.Error()
		return
	}
	if e = item.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除报告失败, Err: " + e.Error()
		return
	}

	// ES更新报告为未发布
	go func() {
		_ = services.SmartReportElasticUpsert(item.SmartReportId, 1)
	}()

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

// Detail
// @Title 详情
// @Description 详情
// @Param   SmartReportId	query	int	true	"智能研报ID"
// @Success 200 {object} smart_report.SmartReportItem
// @router /detail [get]
func (this *SmartReportController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	reportId, _ := this.GetInt("SmartReportId")
	if reportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "报告ID有误"
		return
	}

	ob := new(smart_report.SmartReport)
	item, e := ob.GetItemById(reportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取研报失败, Err: " + e.Error()
		return
	}
	resp := smart_report.FormatSmartReport2Item(item)
	if resp.HeadResourceId > 0 {
		headResource, err := smart_report.GetResourceItemById(resp.HeadResourceId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取资源库版尾失败, Err: " + err.Error()
			return
		}
		if headResource != nil && headResource.ResourceId > 0 {
			resp.HeadImg = headResource.ImgUrl
			resp.HeadStyle = headResource.Style
		}
	}

	if resp.EndResourceId > 0 {
		endResource, err := smart_report.GetResourceItemById(resp.EndResourceId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取资源库版头失败, Err: " + err.Error()
			return
		}
		if endResource != nil && endResource.ResourceId > 0 {
			resp.EndImg = endResource.ImgUrl
			resp.EndStyle = endResource.Style
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Publish
// @Title 发布/取消发布
// @Description 发布/取消发布
// @Param	request	body smart_report.SmartReportPublishReq true "type json string"
// @Success 200 string "操作成功"
// @router /publish [post]
func (this *SmartReportController) Publish() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportPublishReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SmartReportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = "报告ID为空"
		return
	}
	if req.PublishState != smart_report.SmartReportStateWaitPublish && req.PublishState != smart_report.SmartReportStatePublished {
		br.Msg = "参数有误"
		return
	}
	operate := 0
	if req.PublishState == smart_report.SmartReportStateWaitPublish {
		operate = models.ReportOperateCancelPublish
	}
	if req.PublishState == smart_report.SmartReportStatePublished {
		operate = models.ReportOperatePublish
	}

	ob := new(smart_report.SmartReport)
	item, e := ob.GetItemById(req.SmartReportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取研报失败, Err: " + e.Error()
		return
	}

	// 图表刷新状态
	refreshResult := data.CheckBatchChartRefreshResult("report", item.SmartReportId, 0)
	if !refreshResult {
		br.Msg = "图表刷新未完成，请稍后操作"
		br.ErrMsg = "图表刷新未完成，请稍后操作"
		br.IsSendEmail = false
		return
	}

	// 根据审批开关及审批流判断当前报告状态
	state, e := services.CheckReportCurrState(report_approve.FlowReportTypeSmart, item.ClassifyIdFirst, item.ClassifyIdSecond, 0, operate)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "校验报告当前状态失败, Err: " + e.Error()
		return
	}

	cols := []string{"State", "ModifyTime"}
	item.State = state
	item.ModifyTime = time.Now().Local()
	if state == smart_report.SmartReportStatePublished {
		// 主动发布会清除掉预发布设置, 发布时间则取当前时间
		cols = append(cols, "PublishTime", "PrePublishTime")
		item.PublishTime = time.Now().Local()
		item.PrePublishTime = time.Time{}

		// 写入队列
		//var queue smart_report.Report2ImgQueueReq
		//queue.ReportType = 2
		//queue.ReportCode = item.ReportCode
		//_ = utils.Rc.LPush(utils.CACHE_CREATE_REPORT_IMGPDF_QUEUE, queue)
	}

	// 取消发布时同时清除掉Img和PDF的文件地址, 发布时间以及预发布时间
	if state == smart_report.SmartReportStateWaitPublish {
		cols = append(cols, "DetailImgUrl", "DetailPdfUrl", "PublishTime", "PrePublishTime")
		item.DetailImgUrl = ""
		item.DetailPdfUrl = ""
		item.PublishTime = time.Time{}
		item.PrePublishTime = time.Time{}
	}
	if e = item.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新研报失败, Err: " + e.Error()
		return
	}

	recordItem := &models.ReportStateRecord{
		ReportId:   req.SmartReportId,
		ReportType: 2,
		State:      state,
		AdminId:    this.SysUser.AdminId,
		AdminName:  this.SysUser.AdminName,
		CreateTime: time.Now(),
	}
	go func() {
		_, _ = models.AddReportStateRecord(recordItem)
	}()

	if state == smart_report.SmartReportStatePublished {
		// 生成音频
		if item.VideoUrl == "" {
			go services.SmartReportBuildVideoAndUpdate(item)
		}

		// ES更新报告
		go func() {
			_ = services.SmartReportElasticUpsert(item.SmartReportId, models.ReportStatePublished)
		}()

		// 生成报告pdf和长图
		if req.ReportUrl != "" {
			go services.Report2pdfAndJpeg(req.ReportUrl, item.SmartReportId, 3)
		}
	}
	if state == smart_report.SmartReportStateWaitPublish {
		// ES更新报告
		go func() {
			_ = services.SmartReportElasticUpsert(item.SmartReportId, models.ReportStateUnpublished)
		}()
	}

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

// PrePublish
// @Title 设置定时发布
// @Description 设置定时发布
// @Param	request	body smart_report.SmartReportPrePublishReq true "type json string"
// @Success 200 string "操作成功"
// @router /pre_publish [post]
func (this *SmartReportController) PrePublish() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportPrePublishReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	reportId := req.SmartReportId
	if reportId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，报告id不可为空"
		return
	}
	if req.PrePublishTime == "" {
		br.Msg = "发布时间不能为空"
		return
	}
	if req.PreMsgSend != 0 && req.PreMsgSend != 1 {
		br.Msg = "参数错误"
		br.ErrMsg = "是否发送模版消息标识错误"
		return
	}
	preTime, e := time.ParseInLocation(utils.FormatDateTime, req.PrePublishTime, time.Local)
	if e != nil {
		br.Msg = "发布时间格式错误"
		br.ErrMsg = "发布时间格式错误，Err:" + e.Error()
		return
	}
	if preTime.Before(time.Now()) {
		br.Msg = "发布时间不允许选择过去时间"
		return
	}
	if preTime.Before(time.Now().Add(2 * time.Minute)) {
		br.Msg = "发布时间距离当前时间太近了"
		return
	}

	reportOB := new(smart_report.SmartReport)
	item, e := reportOB.GetItemById(reportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在, 请刷新页面"
			return
		}
		br.Msg = "获取报告失败"
		br.ErrMsg = "获取报告失败, Err:" + e.Error()
		return
	}
	if item.Content == "" {
		br.Msg = "报告内容为空, 不可发布"
		return
	}
	if item.State == 2 {
		br.Msg = "报告已发布, 不可设置定时发布"
		return
	}

	// 校验是否开启了审批流
	opening, e := services.CheckReportOpenApprove(report_approve.FlowReportTypeSmart, item.ClassifyIdFirst, item.ClassifyIdSecond, 0)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "校验报告是否开启审批流失败, Err: " + e.Error()
		return
	}
	if opening {
		br.Msg = "报告已开启审批流, 不可设置定时发布"
		return
	}

	item.PrePublishTime = preTime
	item.PreMsgSend = req.PreMsgSend
	cols := []string{"PrePublishTime", "PreMsgSend"}
	if e = item.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新报告预发布失败, Err: " + e.Error()
		return
	}

	// 生成报告pdf和长图
	if req.ReportUrl != "" {
		go services.Report2pdfAndJpeg(req.ReportUrl, item.SmartReportId, 3)
	}

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

// SendMsg
// @Title 消息推送
// @Description 消息推送
// @Param	request	body models.SendTemplateMsgReq true "type json string"
// @Success 200 Ret=200 推送成功
// @router /send_msg [post]
func (this *SmartReportController) SendMsg() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportSendMsgReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SmartReportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, SmartReportId: %d", req.SmartReportId)
		return
	}

	// 避免重复推送
	{
		redisKey := fmt.Sprint(utils.CACHE_SMART_REPORT_SEND_MSG, req.SmartReportId)
		ok := utils.Rc.SetNX(redisKey, 1, time.Second*300)
		if !ok {
			br.Msg = "报告已推送, 请勿重复推送"
			return
		}
		defer func() {
			_ = utils.Rc.Delete(redisKey)
		}()
	}

	reportOB := new(smart_report.SmartReport)
	item, e := reportOB.GetItemById(req.SmartReportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取报告失败, Err: " + e.Error()
		return
	}
	if item.MsgIsSend == 1 {
		br.Msg = "消息已推送，请勿重复操作"
		return
	}
	if item.State != 2 {
		br.Msg = "报告未发布, 不可推送"
		return
	}

	item.MsgIsSend = 1
	item.MsgSendTime = time.Now().Local()
	item.ModifyTime = time.Now().Local()
	if e = item.Update([]string{"MsgIsSend", "MsgSendTime", "ModifyTime"}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新报告推送状态失败, Err: " + e.Error()
		return
	}

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

// SaveContent
// @Title 保存草稿
// @Description 保存草稿
// @Param	request	body smart_report.SmartReportSaveContentReq true "type json string"
// @Success 200 {object} smart_report.SmartReportSaveContentResp
// @router /save_content [post]
func (this *SmartReportController) SaveContent() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportSaveContentReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	resp := new(smart_report.SmartReportSaveContentResp)
	if req.SmartReportId <= 0 {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		br.Data = resp
		return
	}

	reportOB := new(smart_report.SmartReport)
	item, _ := reportOB.GetItemById(req.SmartReportId)
	if item == nil {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		br.Data = resp
		return
	}
	if item.State == smart_report.SmartReportStatePublished {
		br.Msg = "报告已发布, 不允许编辑"
		return
	}

	// 更新编辑状态
	adminIdName := make(map[int]string)
	admins, e := system.GetSysAdminList(``, make([]interface{}, 0), []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取系统用户列表失败, Err: " + e.Error()
		return
	}
	for _, ad := range admins {
		adminIdName[ad.AdminId] = ad.RealName
	}
	editing, e := services.UpdateSmartReportEditing(req.SmartReportId, 1, sysUser.AdminId, sysUser.RealName, adminIdName, this.Lang)
	if e != nil {
		br.Msg = e.Error()
		return
	}
	if editing.Status == 1 {
		br.Msg = editing.Msg
		return
	}

	// 内容有改动
	if req.NoChange != 1 && req.Content != "" && req.ContentStruct != "" {
		req.Content = html.EscapeString(req.Content)
		req.ContentStruct = html.EscapeString(req.ContentStruct)
		sub, e := services.GetReportContentSub(req.Content)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "读取报告前两个章节内容失败, Err: " + e.Error()
			return
		}
		subContent := html.EscapeString(sub)

		item.Content = req.Content
		item.ContentSub = subContent
		item.ContentStruct = req.ContentStruct
		item.ContentModifyTime = time.Now().Local()
		item.LastModifyAdminId = sysUser.AdminId
		item.LastModifyAdminName = sysUser.RealName
		item.ModifyTime = time.Now().Local()
		item.HeadImg = req.HeadImg
		item.EndImg = req.EndImg
		item.CanvasColor = req.CanvasColor
		item.HeadResourceId = req.HeadResourceId
		item.EndResourceId = req.EndResourceId
		cols := []string{"Content", "ContentSub", "ContentStruct", "ContentModifyTime", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime", "HeadImg", "EndImg", "CanvasColor", "HeadResourceId", "EndResourceId"}
		if e = item.Update(cols); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新报告内容失败"
			return
		}

		go func() {
			saveLog := new(smart_report.SmartReportSaveLog)
			saveLog.SmartReportId = item.SmartReportId
			saveLog.Content = item.Content
			saveLog.ContentSub = item.ContentSub
			saveLog.ContentStruct = item.ContentStruct
			saveLog.AdminId = sysUser.AdminId
			saveLog.AdminName = sysUser.RealName
			saveLog.CreateTime = time.Now().Local()
			_ = saveLog.Create()
		}()
	}

	resp.SmartReportId = item.SmartReportId
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.Data = resp
}

// MarkEditStatus
// @Title 标记报告编辑状态
// @Description 标记报告编辑状态接口
// @Param	request	body request.MarkEditEnReport true "type json string"
// @Success 200 标记成功 ；202 标记成功
// @router /mark_edit [post]
func (this *SmartReportController) MarkEditStatus() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 smart_report.SmartReportMarkEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SmartReportId <= 0 {
		br.Msg = "缺少报告Id"
		return
	}
	if req.Status <= 0 {
		br.Msg = "标记状态异常"
		return
	}

	// 获取系统用户列表-用于匹配编辑中的用户
	adminIdName := make(map[int]string)
	admins, e := system.GetSysAdminList(``, make([]interface{}, 0), []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取系统用户列表失败, Err: " + e.Error()
		return
	}
	for _, ad := range admins {
		adminIdName[ad.AdminId] = ad.RealName
	}

	data, e := services.UpdateSmartReportEditing(req.SmartReportId, req.Status, sysUser.AdminId, sysUser.RealName, adminIdName, this.Lang)
	if e != nil {
		br.Msg = e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "标记成功"
	br.Data = data
}

// List
// @Title 报告列表
// @Description 报告列表
// @Param   PageSize			query	int		true	"每页数据条数"
// @Param   CurrentIndex		query	int		true	"当前页页码"
// @Param   TimeType			query	string	false	"筛选的时间类别: publish_time-发布时间, modify_time-更新时间, approve_time-审批时间"
// @Param   StartDate			query   string  false	"开始时间"
// @Param   EndDate				query   string  false	"结束时间"
// @Param   Frequency			query   string  false	"频度"
// @Param   ClassifyIdFirst		query	int		false	"一级分类ID"
// @Param   ClassifyIdSecond	query	int		false	"二级分类ID"
// @Param   State				query	int		false	"发布状态: 1-待发布; 2-已发布"
// @Param   Keyword				query	string	false	"搜索关键词"
// @Success 200 {object} smart_report.SmartReportListResp
// @router /list [get]
func (this *SmartReportController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	type SmartReportListReq struct {
		PageSize         int    `form:"PageSize"`
		CurrentIndex     int    `form:"CurrentIndex"`
		TimeType         string `form:"TimeType"`
		StartDate        string `form:"StartDate"`
		EndDate          string `form:"EndDate"`
		Frequency        string `form:"Frequency"`
		ClassifyIdFirst  int    `form:"ClassifyIdFirst"`
		ClassifyIdSecond int    `form:"ClassifyIdSecond"`
		State            int    `form:"State"`
		Keyword          string `form:"Keyword"`
	}
	params := new(SmartReportListReq)
	if e := this.ParseForm(params); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "入参解析失败, Err: " + e.Error()
		return
	}
	if params.TimeType == "" {
		params.TimeType = "publish_time"
	}
	if params.TimeType != "publish_time" && params.TimeType != "modify_time" && params.TimeType != "approve_time" {
		br.Msg = "请选择正确的时间类型"
		return
	}
	// 更新时间指的是内容更新时间
	if params.TimeType == "modify_time" {
		params.TimeType = "content_modify_time"
	}

	var condition string
	var pars []interface{}
	// 筛选项
	{
		keyword := strings.TrimSpace(params.Keyword)
		if keyword != "" {
			kw := fmt.Sprint("%", keyword, "%")
			condition += fmt.Sprintf(` AND (title LIKE ? OR admin_real_name LIKE ? OR last_modify_admin_name LIKE ?)`)
			pars = append(pars, kw, kw, kw)
		}
		if params.StartDate != "" && params.EndDate != "" {
			st := fmt.Sprintf("%s 00:00:00", params.StartDate)
			ed := fmt.Sprintf("%s 23:59:59", params.EndDate)
			condition += fmt.Sprintf(` AND %s >= ? AND %s <= ?`, params.TimeType, params.TimeType)
			pars = append(pars, st, ed)
		}
		if params.Frequency != "" {
			condition += ` AND frequency = ?`
			pars = append(pars, params.Frequency)
		}
		if params.ClassifyIdFirst > 0 {
			condition += ` AND classify_id_first = ?`
			pars = append(pars, params.ClassifyIdFirst)
		}
		if params.ClassifyIdSecond > 0 {
			condition += ` AND classify_id_second = ?`
			pars = append(pars, params.ClassifyIdSecond)
		}
		if params.State > 0 {
			condition += ` AND state = ?`
			pars = append(pars, params.State)
		}
	}

	resp := new(smart_report.SmartReportListResp)
	reportOB := new(smart_report.SmartReport)
	total, e := reportOB.GetCountByCondition(condition, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取报告总数失败, Err:" + e.Error()
		return
	}
	if total <= 0 {
		page := paging.GetPaging(params.CurrentIndex, params.PageSize, total)
		resp.Paging = page
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}

	// 分页列表
	var startSize int
	if params.PageSize <= 0 {
		params.PageSize = utils.PageSize20
	}
	if params.CurrentIndex <= 0 {
		params.CurrentIndex = 1
	}
	startSize = utils.StartIndex(params.CurrentIndex, params.PageSize)

	// 列表查询过滤掉富文本内容
	fields := []string{
		"smart_report_id", "report_code", "classify_id_first", "classify_name_first", "classify_id_second", "classify_name_second", "add_type",
		"title", "abstract", "author", "frequency", "stage", "video_url", "video_name", "video_play_seconds", "video_size", "detail_img_url", "detail_pdf_url",
		"admin_id", "admin_real_name", "state", "publish_time", "pre_publish_time", "pre_msg_send", "msg_is_send", "msg_send_time", "create_time", "modify_time",
		"last_modify_admin_id", "last_modify_admin_name", "content_modify_time", "pv", "uv", "head_img", "end_img", "canvas_color", "approve_time",
	}
	list, e := reportOB.GetPageItemsByCondition(condition, pars, fields, "", startSize, params.PageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取报告分页列表失败, Err:" + e.Error()
		return
	}

	// 获取系统用户列表-用于匹配编辑中的用户
	adminIdName := make(map[int]string)
	admins, e := system.GetSysAdminList(``, make([]interface{}, 0), []string{}, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取系统用户列表失败, Err: " + e.Error()
		return
	}
	for _, ad := range admins {
		adminIdName[ad.AdminId] = ad.RealName
	}

	for _, v := range list {
		item := smart_report.FormatSmartReport2Item(v)
		mark, e := services.UpdateSmartReportEditing(v.SmartReportId, 2, sysUser.AdminId, sysUser.RealName, adminIdName, this.Lang)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "查询编辑中标记失败, Err:" + e.Error()
			return
		}
		if mark.Status == 0 {
			item.CanEdit = true
		} else {
			item.Editor = mark.Editor
		}
		resp.List = append(resp.List, item)
	}

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

// DetailImg
// @Title 生成长图
// @Description 生成长图
// @Param   SmartReportId	query	int	true	"智能研报ID"
// @Success 200 {object} smart_report.SmartReportSaveContentResp
// @router /detail_img [get]
func (this *SmartReportController) DetailImg() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	reportId, _ := this.GetInt("SmartReportId", 0)
	if reportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, SmartReportId: %d", reportId)
		return
	}

	reportOB := new(smart_report.SmartReport)
	item, e := reportOB.GetItemById(reportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取报告失败, Err: " + e.Error()
		return
	}
	if item.DetailImgUrl != "" {
		br.Data = item.DetailImgUrl
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	// 写入队列
	var queue smart_report.Report2ImgQueueReq
	queue.ReportType = 2
	queue.ReportCode = item.ReportCode
	//_ = utils.Rc.LPush(utils.CACHE_CREATE_REPORT_IMGPDF_QUEUE, queue)

	br.Msg = "图片正在生成中, 请稍后下载"
	return
}

// LastPublishedReport
// @Title 上期已发布的报告
// @Description 上期已发布的报告
// @Param   ClassifyIdFirst		query	int	false	"一级分类ID"
// @Param   ClassifyIdSecond	query	int	false	"二级分类ID"
// @Success 200 {object} smart_report.SmartReportItem
// @router /last_published_report [get]
func (this *SmartReportController) LastPublishedReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	firstId, _ := this.GetInt("ClassifyIdFirst")
	secondId, _ := this.GetInt("ClassifyIdSecond")

	ob := new(smart_report.SmartReport)
	cond := ` AND classify_id_first = ? AND classify_id_second = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, firstId, secondId)
	item, e := ob.GetItemByCondition(cond, pars, "stage DESC")
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取研报失败, Err: " + e.Error()
		return
	}
	resp := smart_report.FormatSmartReport2Item(item)

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

// VoiceUpload
// @Title 音频上传
// @Description 音频上传接口
// @Param   file   query   file  true       "文件"
// @Param   SmartReportId	query   int  true       "报告ID"
// @Success Ret=200 上传成功
// @router /voice_upload [post]
func (this *SmartReportController) VoiceUpload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	reportId, _ := this.GetInt("SmartReportId")
	if reportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, SmartReportId: %d", reportId)
		return
	}
	f, h, err := this.GetFile("file")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}
	defer func() {
		_ = f.Close()
	}()

	reportOb := new(smart_report.SmartReport)
	item, e := reportOb.GetItemById(reportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取报告信息失败, Err:" + err.Error()
		return
	}

	ext := path.Ext(h.Filename)
	uploadDir := utils.STATIC_DIR + "hongze/" + time.Now().Format("20060102")
	if e = os.MkdirAll(uploadDir, 0766); e != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败, Err:" + e.Error()
		return
	}
	ossFileName := utils.GetRandStringNoSpecialChar(28) + ext
	filePath := uploadDir + "/" + ossFileName
	if e = this.SaveToFile("file", filePath); e != nil {
		br.Msg = "文件保存失败"
		br.ErrMsg = "文件保存失败, Err:" + e.Error()
		return
	}
	defer func() {
		_ = os.Remove(filePath)
	}()
	//ossDir := "static/audio/"

	resourceUrl := ``
	//上传到阿里云 和 minio
	//if utils.ObjectStorageClient == "minio" {
	//	resourceUrl, e = services.UploadMinIoToDir(ossFileName, filePath, ossDir, "")
	//	if e != nil {
	//		br.Msg = "文件上传失败"
	//		br.ErrMsg = "文件上传失败, Err:" + e.Error()
	//		return
	//	}
	//} else {
	//	resourceUrl, e = services.UploadAliyunToDir(ossFileName, filePath, ossDir, "")
	//	if e != nil {
	//		br.Msg = "文件上传失败"
	//		br.ErrMsg = "文件上传失败, Err:" + e.Error()
	//		return
	//	}
	//}
	ossClient := services.NewOssClient()
	if ossClient == nil {
		br.Msg = "上传失败"
		br.ErrMsg = "初始化OSS服务失败"
		return
	}
	resourceUrl, e = ossClient.UploadFile(ossFileName, filePath, "")
	if e != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + e.Error()
		return
	}

	resource := new(models.Resource)
	resource.ResourceUrl = resourceUrl
	resource.ResourceType = 2
	resource.CreateTime = time.Now()
	newId, err := models.AddResource(resource)
	if err != nil {
		br.Msg = "资源上传失败"
		br.ErrMsg = "资源上传失败,Err:" + err.Error()
		return
	}
	//fmt.Println(filePath)
	playSeconds, err := mp3duration.Calculate(filePath)
	if playSeconds <= 0 {
		playSeconds, err = utils.GetVideoPlaySeconds(filePath)
		if err != nil {
			br.Msg = "获取音频时间失败"
			br.ErrMsg = "获取音频时间失败,Err:" + err.Error()
			return
		}
	}
	createTime := item.CreateTime.Format("0102")
	videoName := item.Title + "(" + createTime + ")"
	fileBody, err := ioutil.ReadFile(filePath)
	videoSize := len(fileBody)
	sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
	sizeStr := utils.SubFloatToFloatStr(sizeFloat, 2)

	item.VideoUrl = resourceUrl
	item.VideoName = videoName
	item.VideoPlaySeconds = playSeconds
	item.VideoSize = sizeStr
	item.ModifyTime = time.Now().Local()
	updateCols := []string{"VideoUrl", "VideoName", "VideoPlaySeconds", "VideoSize", "ModifyTime"}
	if e = item.Update(updateCols); e != nil {
		br.Msg = "上传失败"
		br.ErrMsg = "上传失败，Err:" + e.Error()
		return
	}

	resp := new(models.ResourceResp)
	resp.Id = newId
	resp.ResourceUrl = resourceUrl
	br.Msg = "上传成功"
	br.Ret = 200
	br.Success = true
	br.Data = resp
	return
}

// SubmitApprove
// @Title 提交审批
// @Description 提交审批接口
// @Param	request	body models.ReportSubmitApproveReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /approve/submit [post]
func (this *SmartReportController) SubmitApprove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	var req models.ReportSubmitApproveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	reportId := req.ReportId
	if reportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, ReportId: %d", req.ReportId)
		return
	}

	reportOb := new(smart_report.SmartReport)
	reportItem, e := reportOb.GetItemById(reportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取报告失败, Err: " + e.Error()
		return
	}

	// 校验当前审批配置, 返回下一个状态
	state, e := services.CheckReportCurrState(report_approve.FlowReportTypeSmart, reportItem.ClassifyIdFirst, reportItem.ClassifyIdSecond, 0, models.ReportOperateSubmitApprove)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "校验报告状态失败, Err: " + e.Error()
		return
	}

	// 下一个状态不为待审批时, 仅更新状态
	if state != models.ReportStateWaitApprove {
		reportItem.State = state
		e = reportItem.Update([]string{"State"})
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新报告状态失败, Err: " + e.Error()
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	// 提交审批
	approveId, e := services.SubmitReportApprove(report_approve.FlowReportTypeSmart, reportItem.SmartReportId, reportItem.Title, reportItem.ClassifyIdFirst, reportItem.ClassifyIdSecond, 0, sysUser.AdminId, sysUser.RealName)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "提交审批失败, Err: " + e.Error()
		return
	}
	reportItem.ApproveId = approveId
	reportItem.State = models.ReportStateWaitApprove
	reportItem.ModifyTime = time.Now().Local()
	e = reportItem.Update([]string{"ApproveId", "State", "ModifyTime"})
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新报告状态失败, Err: " + e.Error()
		return
	}

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

// CancelApprove
// @Title 撤销审批
// @Description 撤销审批
// @Param	request	body models.ReportCancelApproveReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /approve/cancel [post]
func (this *SmartReportController) CancelApprove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	var req models.ReportCancelApproveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	reportId := req.ReportId
	if reportId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, ReportId: %d", req.ReportId)
		return
	}

	reportOb := new(smart_report.SmartReport)
	reportItem, e := reportOb.GetItemById(reportId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "报告已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取报告失败, Err: " + e.Error()
		return
	}

	// 校验当前审批配置, 返回下一个状态
	state, e := services.CheckReportCurrState(report_approve.FlowReportTypeSmart, reportItem.ClassifyIdFirst, reportItem.ClassifyIdSecond, 0, models.ReportOperateCancelApprove)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "校验报告状态失败, Err: " + e.Error()
		return
	}

	// 下一个状态不为待提交时, 仅更新状态
	if state != models.ReportStateWaitSubmit {
		reportItem.State = state
		e = reportItem.Update([]string{"State"})
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "更新报告状态失败, Err: " + e.Error()
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}
	//if reportItem.ApproveId <= 0 {
	//	br.Msg = "报告审批不存在"
	//	br.ErrMsg = fmt.Sprintf("报告审批不存在, ApproveId: %d", reportItem.ApproveId)
	//	return
	//}

	// 撤销审批
	e = services.CancelReportApprove(report_approve.FlowReportTypeSmart, reportItem.SmartReportId, reportItem.ApproveId, sysUser.AdminId, sysUser.RealName)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "撤销审批失败, Err: " + e.Error()
		return
	}
	//reportItem.ApproveId = 0
	//reportItem.State = models.ReportStateWaitSubmit
	//reportItem.ModifyTime = time.Now().Local()
	//e = reportItem.UpdateReport([]string{"ApproveId", "State", "ModifyTime"})
	//if e != nil {
	//	br.Msg = "操作失败"
	//	br.ErrMsg = "更新报告状态失败, Err: " + e.Error()
	//	return
	//}

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