package controllers

import (
	"encoding/json"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/report"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/services"
	"eta/eta_mobile/services/data"
	"eta/eta_mobile/utils"
	"html"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

// AddChapter
// @Title 新增晨周报章节内容
// @Description 新增晨周报章节内容
// @Param	request	body models.AddReportChapterReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /chapter/add [post]
func (this *ReportController) AddChapter() {
	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.AddReportChapterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ReportId <= 0 {
		br.Msg = "报告ID有误"
		return
	}

	req.Title = strings.TrimSpace(req.Title)
	if req.Title == `` {
		br.Msg = "章节名称不能为空"
		return
	}

	// 获取报告详情
	reportInfo, err := models.GetReportByReportId(req.ReportId)
	if err != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "报告信息有误, Err: " + err.Error()
		return
	}
	if reportInfo.State == 2 {
		br.Msg = "该报告已发布，不允许新增"
		br.ErrMsg = "该报告已发布，不允许新增"
		return
	}

	//newContent := req.Content
	//// 更新章节及指标
	//contentSub := ""
	//if req.Content != "" {
	//	e := utils.ContentXssCheck(req.Content)
	//	if e != nil {
	//		br.Msg = "存在非法标签"
	//		br.ErrMsg = "存在非法标签, Err: " + e.Error()
	//		return
	//	}
	//	contentClean, e := services.FilterReportContentBr(req.Content)
	//	if e != nil {
	//		br.Msg = "内容去除前后空格失败"
	//		br.ErrMsg = "内容去除前后空格失败, Err: " + e.Error()
	//		return
	//	}
	//	req.Content = contentClean
	//
	//	contentSub, err = services.GetReportContentSub(req.Content)
	//	if err != nil {
	//		br.Msg = "内容分段解析失败"
	//		br.ErrMsg = "编辑报告章节-解析 ContentSub 失败, Err: " + err.Error()
	//		return
	//	}
	//}
	//if req.Content == "" {
	//	req.Content = newContent
	//}

	// 最小单元的分类
	var minClassifyId int
	var minClassifyName string
	if reportInfo.ClassifyIdThird > 0 {
		minClassifyId = reportInfo.ClassifyIdThird
		minClassifyName = reportInfo.ClassifyNameThird
	} else if reportInfo.ClassifyIdSecond > 0 {
		minClassifyId = reportInfo.ClassifyIdSecond
		minClassifyName = reportInfo.ClassifyNameSecond
	} else {
		minClassifyId = reportInfo.ClassifyIdFirst
		minClassifyName = reportInfo.ClassifyNameFirst
	}

	// 判断名称是否重复
	{
		var condition string
		var pars []interface{}

		condition += " AND report_id = ? AND title=? "
		pars = append(pars, req.ReportId, req.Title)
		count, err := models.GetCountReportChapterByCondition(condition, pars)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "判断章节名称是否存在失败,Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "章节名称不允许重复"
			br.ErrMsg = "章节名称不允许重复"
			br.IsSendEmail = false
			return
		}
	}

	reportChapterInfo := new(models.ReportChapter)
	reportChapterInfo.ReportId = reportInfo.Id
	reportChapterInfo.ClassifyIdFirst = minClassifyId
	reportChapterInfo.ClassifyNameFirst = minClassifyName

	reportChapterInfo.Title = req.Title
	reportChapterInfo.AddType = 1
	reportChapterInfo.PublishState = 1
	//reportChapterInfo.Author = req.Author
	//reportChapterInfo.Content = html.EscapeString(req.Content)
	//reportChapterInfo.ContentSub = html.EscapeString(contentSub)
	reportChapterInfo.IsEdit = 1
	//reportChapterInfo.CreateTime = req.CreateTime
	reportChapterInfo.CreateTime = reportInfo.CreateTime
	reportChapterInfo.ModifyTime = time.Now()
	reportChapterInfo.ReportCreateTime = time.Now()
	reportChapterInfo.VideoKind = 2
	reportChapterInfo.Stage = reportInfo.Stage

	reportChapterInfo.LastModifyAdminId = sysUser.AdminId
	reportChapterInfo.LastModifyAdminName = sysUser.RealName
	reportChapterInfo.ContentModifyTime = time.Now()
	//reportChapterInfo.ContentStruct = html.EscapeString(req.ContentStruct)
	//reportChapterInfo.CanvasColor = req.CanvasColor
	//reportChapterInfo.HeadResourceId = req.HeadResourceId
	//reportChapterInfo.EndResourceId = req.EndResourceId

	err, errMsg := services.AddChapterBaseInfoAndPermission(reportInfo, reportChapterInfo, req.PermissionIdList, req.AdminIdList)
	if err != nil {
		br.Msg = "保存失败"
		if errMsg != "" {
			br.Msg = errMsg
		}
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// EditChapterBaseInfoAndPermission
// @Title 修改报告章节的基础信息、授权用户权限、品种权限
// @Description 修改报告章节的基础信息、授权用户权限、品种权限
// @Param	request	body models.EditReportChapterReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /chapter/base_info/edit [post]
func (this *ReportController) EditChapterBaseInfoAndPermission() {
	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.EditReportChapterBaseInfoAndPermissionReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	reportChapterId := req.ReportChapterId
	if reportChapterId <= 0 {
		br.Msg = "报告章节ID有误"
		return
	}

	req.Title = strings.TrimSpace(req.Title)
	if req.Title == `` {
		br.Msg = "章节名称不能为空"
		return
	}

	// 获取章节详情
	reportChapterInfo, err := models.GetReportChapterInfoById(reportChapterId)
	if err != nil {
		br.Msg = "报告章节信息有误"
		br.ErrMsg = "报告章节信息有误, Err: " + err.Error()
		return
	}

	// 判断名称是否重复
	{
		var condition string
		var pars []interface{}

		condition += " AND report_id = ? AND title=? AND report_chapter_id != ? "
		pars = append(pars, reportChapterInfo.ReportId, req.Title, reportChapterId)
		count, err := models.GetCountReportChapterByCondition(condition, pars)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "判断章节名称是否存在失败,Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "章节名称不允许重复"
			br.ErrMsg = "章节名称不允许重复"
			br.IsSendEmail = false
			return
		}
	}

	// 获取报告详情
	reportInfo, err := models.GetReportByReportId(reportChapterInfo.ReportId)
	if err != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "报告信息有误, Err: " + err.Error()
		return
	}
	if reportInfo.State == 2 {
		br.Msg = "该报告已发布，不允许编辑"
		br.ErrMsg = "该报告已发布，不允许编辑"
		return
	}

	// 报告的最后编辑人
	reportInfo.LastModifyAdminId = sysUser.AdminId
	reportInfo.LastModifyAdminName = sysUser.RealName
	reportInfo.ModifyTime = time.Now()

	err, errMsg := services.EditChapterBaseInfoAndPermission(reportInfo, reportChapterInfo, req.Title, req.PermissionIdList, req.AdminIdList)
	if err != nil {
		br.Msg = "保存失败"
		if errMsg != "" {
			br.Msg = errMsg
		}
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// EditDayWeekChapter
// @Title 编辑晨周报章节内容
// @Description 编辑晨周报章节内容
// @Param	request	body models.EditReportChapterReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /editDayWeekChapter [post]
func (this *ReportController) EditDayWeekChapter() {
	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.EditReportChapterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	reportChapterId := req.ReportChapterId
	if reportChapterId <= 0 {
		br.Msg = "报告章节ID有误"
		return
	}
	if req.Content == "" {
		br.Msg = "请输入内容"
		return
	}

	// 获取章节详情
	reportChapterInfo, err := models.GetReportChapterInfoById(reportChapterId)
	if err != nil {
		br.Msg = "报告章节信息有误"
		br.ErrMsg = "报告章节信息有误, Err: " + err.Error()
		return
	}

	// 获取报告详情
	reportInfo, err := models.GetReportByReportId(reportChapterInfo.ReportId)
	if err != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "报告信息有误, Err: " + err.Error()
		return
	}

	// 操作权限校验
	hasAuth, msg, errMsg, isSendEmail := checkOpPermission(sysUser, reportInfo, reportChapterInfo, true, this.Lang)
	if !hasAuth {
		br.Msg = msg
		br.ErrMsg = errMsg
		br.IsSendEmail = isSendEmail
		return
	}

	if reportInfo.State == 2 {
		br.Msg = "该报告已发布，不允许编辑"
		br.ErrMsg = "该报告已发布，不允许编辑"
		return
	}
	if reportChapterInfo.PublishState == 2 {
		br.Msg = "该报告章节已发布，不允许编辑"
		br.ErrMsg = "该报告章节已发布，不允许编辑"
		br.IsSendEmail = false
		return
	}

	updateCols := make([]string, 0)

	// 报告的最后编辑人
	reportInfo.LastModifyAdminId = sysUser.AdminId
	reportInfo.LastModifyAdminName = sysUser.RealName
	reportInfo.ModifyTime = time.Now()

	reqTickerList := req.TickerList
	// 更新章节及指标
	contentSub := ""
	if req.Content != "" {
		req.Content = services.HandleReportContent(req.Content, "del", nil)
		e := utils.ContentXssCheck(req.Content)
		if e != nil {
			br.Msg = "存在非法标签"
			br.ErrMsg = "存在非法标签, Err: " + e.Error()
			return
		}
		contentClean, e := services.FilterReportContentBr(req.Content)
		if e != nil {
			br.Msg = "内容去除前后空格失败"
			br.ErrMsg = "内容去除前后空格失败, Err: " + e.Error()
			return
		}
		req.Content = contentClean

		contentSub, err = services.GetReportContentSub(req.Content)
		if err != nil {
			br.Msg = "内容分段解析失败"
			br.ErrMsg = "编辑报告章节-解析 ContentSub 失败, Err: " + err.Error()
			return
		}
	}

	if req.Title != `` {
		reportChapterInfo.Title = req.Title
		updateCols = append(updateCols, "Title")
	}
	//reportChapterInfo.AddType = req.AddType
	reportChapterInfo.Author = req.Author
	reportChapterInfo.Content = html.EscapeString(req.Content)
	reportChapterInfo.ContentSub = html.EscapeString(contentSub)
	reportChapterInfo.IsEdit = 1
	reportChapterInfo.ModifyTime = time.Now()

	// 担心外部没有传入时间，如果没有传入，那么就不修改
	if req.CreateTime != `` {
		reportChapterInfo.CreateTime = req.CreateTime
		updateCols = append(updateCols, "CreateTime")
	}

	reportChapterInfo.LastModifyAdminId = sysUser.AdminId
	reportChapterInfo.LastModifyAdminName = sysUser.RealName
	reportChapterInfo.ContentModifyTime = time.Now()

	if req.ContentStruct != `` {
		req.ContentStruct = services.HandleReportContentStruct(req.ContentStruct, "del", nil)
	}
	reportChapterInfo.ContentStruct = html.EscapeString(req.ContentStruct)

	updateCols = append(updateCols, "Author", "Content", "ContentSub", "IsEdit", "ModifyTime")

	updateCols = append(updateCols, "LastModifyAdminId", "LastModifyAdminName", "ContentModifyTime", "ContentStruct")

	// 章节报告更新指标
	tickerList := make([]*models.ReportChapterTicker, 0)
	if len(reqTickerList) > 0 {
		nowTime := time.Now()
		for i := 0; i < len(reqTickerList); i++ {
			tickerList = append(tickerList, &models.ReportChapterTicker{
				ReportChapterId: reportChapterInfo.ReportChapterId,
				Sort:            reqTickerList[i].Sort,
				Ticker:          reqTickerList[i].Ticker,
				CreateTime:      nowTime,
				UpdateTime:      nowTime,
			})
		}
	}
	err = models.UpdateChapterAndTicker(reportInfo, reportChapterInfo, updateCols, tickerList)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "报告章节内容保存失败, Err: " + err.Error()
		return
	}

	// 标记更新中
	{
		markStatus, err := services.UpdateReportEditMark(reportChapterInfo.ReportId, reportChapterInfo.ReportChapterId, sysUser.AdminId, 1, sysUser.RealName, this.Lang)
		if err != nil {
			br.Msg = err.Error()
			return
		}
		if markStatus.Status == 1 {
			br.Msg = markStatus.Msg
			return
		}
	}

	// 备份关键数据
	chapters := make([]*models.ReportChapter, 0)
	chapters = append(chapters, reportChapterInfo)
	go services.SaveReportLogs(nil, chapters, sysUser.AdminId, sysUser.RealName)

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// DelChapter
// @Title 编辑晨周报章节内容
// @Description 编辑晨周报章节内容
// @Param	request	body models.EditReportChapterReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /chapter/del [post]
func (this *ReportController) DelChapter() {
	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.DelReportChapterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	reportChapterId := req.ReportChapterId
	if reportChapterId <= 0 {
		br.Msg = "报告章节ID有误"
		return
	}

	// 获取章节详情
	reportChapterInfo, err := models.GetReportChapterInfoById(reportChapterId)
	if err != nil {
		br.Msg = "报告章节信息有误"
		br.ErrMsg = "报告章节信息有误, Err: " + err.Error()
		return
	}

	// 获取报告详情
	reportInfo, err := models.GetReportByReportId(reportChapterInfo.ReportId)
	if err != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "报告信息有误, Err: " + err.Error()
		return
	}

	// 操作权限校验
	hasAuth, msg, errMsg, isSendEmail := checkOpPermission(sysUser, reportInfo, reportChapterInfo, true, this.Lang)
	if !hasAuth {
		br.Msg = msg
		br.ErrMsg = errMsg
		br.IsSendEmail = isSendEmail
		return
	}

	if reportInfo.State == 2 {
		br.Msg = "该报告已发布，不允许编辑"
		br.ErrMsg = "该报告已发布，不允许编辑"
		return
	}

	// 删除章节
	err, errMsg = services.DelChapter(reportInfo, reportChapterInfo, sysUser)
	if err != nil {
		br.Msg = "删除失败"
		if errMsg != "" {
			br.Msg = errMsg
		}
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}

	// 备份关键数据
	chapters := make([]*models.ReportChapter, 0)
	chapters = append(chapters, reportChapterInfo)
	go services.SaveReportLogs(nil, chapters, sysUser.AdminId, sysUser.RealName)

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

// GetReportChapterList
// @Title 获取报告章节列表
// @Description 获取报告章节列表
// @Param   ReportId	query	string	true	"报告ID"
// @Success 200 {object} company.CompanyListResp
// @router /getReportChapterList [get]
func (this *ReportController) GetReportChapterList() {
	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
	}

	reqReportId := this.GetString("ReportId")
	reportId, _ := strconv.Atoi(reqReportId)
	if reportId <= 0 {
		br.Msg = "报告ID有误"
		return
	}

	// 获取报告信息
	reportInfo, err := models.GetReportByReportId(reportId)
	if err != nil {
		br.Msg = "获取报告信息失败"
		br.ErrMsg = "获取报告信息失败, Err: " + err.Error()
		return
	}

	// 权限校验
	isAuth, err := services.CheckReportAuthByReportId(sysUser, reportInfo.AdminId, reportId)
	if err != nil {
		br.Msg = "获取报告权限失败"
		br.ErrMsg = "获取报告权限失败,Err:" + err.Error()
		return
	}
	if !isAuth {
		br.Msg = "无操作权限"
		br.ErrMsg = "无操作权限"
		return
	}

	// 获取章节列表
	chapterList, err := models.GetChapterListByReportId(reportId)
	if err != nil {
		br.Msg = "获取章节列表失败"
		br.ErrMsg = "获取章节列表失败, Err: " + err.Error()
		return
	}
	typeList, err := models.GetReportChapterTypeList()
	if err != nil {
		br.Msg = "获取章节类型列表失败"
		br.ErrMsg = "获取章节类型列表失败, Err: " + err.Error()
		return
	}
	typeIdImg := make(map[int]string)
	for i := 0; i < len(typeList); i++ {
		typeIdImg[typeList[i].ReportChapterTypeId] = typeList[i].EditImgUrl
	}

	resp := make([]models.ReportChapterResp, 0)
	if len(chapterList) > 0 {
		chapterIdList := make([]int, 0)
		// 章节id授权用户列表map
		chapterIdGrandListMap := make(map[int][]int)
		// 章节id关联品种id列表map
		chapterIdPermissionListMap := make(map[int][]int)

		for _, v := range chapterList {
			chapterIdList = append(chapterIdList, v.ReportChapterId)
		}

		// 处理章节id授权用户列表
		{
			chapterGrantObj := report.ReportChapterGrant{}
			chapterGrantList, tmpErr := chapterGrantObj.GetGrantListByIdList(chapterIdList)
			if tmpErr != nil {
				br.Msg = "获取章节id授权用户列表失败"
				br.ErrMsg = "获取章节id授权用户列表失败, Err: " + tmpErr.Error()
				return
			}

			for _, v := range chapterGrantList {
				tmpChapterIdGrandList, ok := chapterIdGrandListMap[v.ReportChapterId]
				if !ok {
					tmpChapterIdGrandList = make([]int, 0)
				}
				chapterIdGrandListMap[v.ReportChapterId] = append(tmpChapterIdGrandList, v.AdminId)
			}
		}

		// 处理章节id关联品种id列表
		{
			obj := report.ReportChapterPermissionMapping{}
			chapterPermissionList, tmpErr := obj.GetPermissionListByIdList(chapterIdList)
			if tmpErr != nil {
				br.Msg = "获取章节id关联品种列表失败"
				br.ErrMsg = "获取章节id关联品种列表失败, Err: " + tmpErr.Error()
				return
			}

			for _, v := range chapterPermissionList {
				tmpChapterIdPermissionList, ok := chapterIdPermissionListMap[v.ReportChapterId]
				if !ok {
					tmpChapterIdPermissionList = make([]int, 0)
				}
				chapterIdPermissionListMap[v.ReportChapterId] = append(tmpChapterIdPermissionList, v.ChartPermissionId)
			}
		}

		// 章节类型的字段
		for _, item := range chapterList {
			// 授权的用户列表
			tmpChapterIdGrandList, ok := chapterIdGrandListMap[item.ReportChapterId]
			if !ok {
				tmpChapterIdGrandList = make([]int, 0)
			}
			// 关联的品种列表
			tmpChapterIdPermissionList, ok := chapterIdPermissionListMap[item.ReportChapterId]
			if !ok {
				tmpChapterIdPermissionList = make([]int, 0)
			}

			tmpChapterItem := models.ReportChapterResp{
				ReportChapterId:  item.ReportChapterId,
				ReportId:         item.ReportId,
				ReportType:       item.ReportType,
				TypeId:           item.TypeId,
				TypeName:         item.TypeName,
				TypeEditImg:      typeIdImg[item.TypeId],
				Title:            item.Title,
				IsEdit:           item.IsEdit,
				Trend:            item.Trend,
				Sort:             item.Sort,
				PublishState:     item.PublishState,
				VideoUrl:         item.VideoUrl,
				VideoName:        item.VideoName,
				VideoPlaySeconds: item.VideoPlaySeconds,
				VideoSize:        item.VideoSize,
				VideoKind:        item.VideoKind,
				ModifyTime:       item.ModifyTime.Format(utils.FormatDate),
				GrandAdminIdList: tmpChapterIdGrandList,
				PermissionIdList: tmpChapterIdPermissionList,
			}
			markStatus, err := services.UpdateReportEditMark(item.ReportId, item.ReportChapterId, this.SysUser.AdminId, 2, this.SysUser.RealName, this.Lang)
			if err != nil {
				br.Msg = "查询标记状态失败"
				br.ErrMsg = "查询标记状态失败，Err:" + err.Error()
				return
			}

			if markStatus.Status == 0 {
				tmpChapterItem.CanEdit = true
			} else {
				tmpChapterItem.Editor = markStatus.Editor
			}

			// 报告章节的操作权限
			tmpChapterItem.IsAuth = services.CheckChapterAuthByAdminIdList(sysUser, reportInfo.AdminId, tmpChapterIdGrandList)

			resp = append(resp, tmpChapterItem)
		}
	}

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

// GetDayWeekChapter
// @Title 获取晨周报章节信息
// @Description 获取晨周报章节信息
// @Param	ReportChapterId  query  int  true  "报告章节ID"
// @Success 200 Ret=200 保存成功
// @router /getDayWeekChapter [get]
func (this *ReportController) GetDayWeekChapter() {
	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
	}

	reportChapterId, _ := this.GetInt("ReportChapterId")
	if reportChapterId <= 0 {
		br.Msg = "参数有误"
		return
	}

	chapterItem, err := models.GetReportChapterItemById(reportChapterId)
	if err != nil {
		br.Msg = "获取章节信息失败"
		br.ErrMsg = "获取章节信息失败, Err: " + err.Error()
		return
	}

	// 获取报告详情
	reportInfo, err := models.GetReportById(chapterItem.ReportId)
	if err != nil {
		br.Msg = "获取报告信息失败"
		br.ErrMsg = "获取报告信息失败, Err: " + err.Error()
		return
	}

	// 权限校验
	isAuth, err := services.CheckReportAuthByReportId(sysUser, reportInfo.AdminId, reportInfo.Id)
	if err != nil {
		br.Msg = "获取报告权限失败"
		br.ErrMsg = "获取报告权限失败,Err:" + err.Error()
		return
	}
	if !isAuth {
		br.Msg = "无操作权限"
		br.ErrMsg = "无操作权限"
		return
	}

	chapterItem.Content = html.UnescapeString(chapterItem.Content)
	chapterItem.ContentSub = html.UnescapeString(chapterItem.ContentSub)
	chapterItem.ContentStruct = html.UnescapeString(chapterItem.ContentStruct)

	businessConf, err := models.GetBusinessConfByKey(models.BusinessConfIsOpenChartExpired)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取配置失败，Err:" + err.Error()
		return
	}

	if businessConf.ConfVal == `true` {
		tokenMap := make(map[string]string)
		chapterItem.Content = services.HandleReportContent(chapterItem.Content, "add", tokenMap)
		chapterItem.ContentStruct = services.HandleReportContentStruct(chapterItem.ContentStruct, "add", tokenMap)
	}

	// 授权用户列表map
	chapterGrantIdList := make([]int, 0)
	// 关联品种id列表map
	chapterPermissionIdList := make([]int, 0)
	// 处理章节id授权用户列表
	{
		chapterGrantObj := report.ReportChapterGrant{}
		chapterGrantList, tmpErr := chapterGrantObj.GetGrantListById(chapterItem.ReportChapterId)
		if tmpErr != nil {
			br.Msg = "获取章节id授权用户列表失败"
			br.ErrMsg = "获取章节id授权用户列表失败, Err: " + tmpErr.Error()
			return
		}

		for _, v := range chapterGrantList {
			chapterGrantIdList = append(chapterGrantIdList, v.AdminId)
		}
	}

	// 处理章节id关联品种id列表
	{
		obj := report.ReportChapterPermissionMapping{}
		chapterPermissionList, tmpErr := obj.GetPermissionListById(chapterItem.ReportChapterId)
		if tmpErr != nil {
			br.Msg = "获取章节id关联品种列表失败"
			br.ErrMsg = "获取章节id关联品种列表失败, Err: " + tmpErr.Error()
			return
		}

		for _, v := range chapterPermissionList {
			chapterPermissionIdList = append(chapterPermissionIdList, v.ChartPermissionId)
		}
	}

	resp := models.ReportChapterItemResp{
		ReportChapterItem: *chapterItem,
		GrandAdminIdList:  chapterGrantIdList,
		PermissionIdList:  chapterPermissionIdList,
	}

	// 获取当前编辑状态
	{
		markStatus, err := services.UpdateReportEditMark(chapterItem.ReportId, chapterItem.ReportChapterId, this.SysUser.AdminId, 2, this.SysUser.RealName, this.Lang)
		if err != nil {
			br.Msg = "查询标记状态失败"
			br.ErrMsg = "查询标记状态失败，Err:" + err.Error()
			return
		}
		if markStatus.Status == 0 {
			resp.CanEdit = true
		} else {
			resp.Editor = markStatus.Editor
		}
	}

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

// ChapterMove
// @Title 移动章节类型
// @Description 移动章节类型
// @Param	request	body models.PermissionMoveReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /chapter/move [post]
func (this *ReportController) ChapterMove() {
	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 models.ReportChapterMoveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}

	if req.ReportChapterId == 0 {
		br.Msg = "请选择要移动的章节"
		return
	}
	e, msg := services.MoveReportChapter(&req)
	if e != nil {
		br.Msg = msg
		br.ErrMsg = "移动品种失败, Err: " + e.Error()
		return
	}

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

// EditChapterTrendTag
// @Title 编辑章节趋势标签
// @Description 编辑章节趋势标签
// @Param	request	body models.EditReportChapterReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /editChapterTrendTag [post]
func (this *ReportController) EditChapterTrendTag() {
	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.EditChapterTrendTagReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReportChapterId <= 0 {
		br.Msg = "章节ID有误"
		return
	}
	if req.Trend == "" {
		br.Msg = "请输入标签"
		return
	}

	chapterInfo, err := models.GetReportChapterInfoById(req.ReportChapterId)
	if err != nil {
		br.Msg = "获取章节信息失败"
		br.ErrMsg = "获取章节信息失败, Err: " + err.Error()
		return
	}

	// 获取报告详情
	reportInfo, err := models.GetReportByReportId(chapterInfo.ReportId)
	if err != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "报告信息有误, Err: " + err.Error()
		return
	}

	// 操作权限校验
	hasAuth, msg, errMsg, isSendEmail := checkOpPermission(sysUser, reportInfo, chapterInfo, false, this.Lang)
	if !hasAuth {
		br.Msg = msg
		br.ErrMsg = errMsg
		br.IsSendEmail = isSendEmail
		return
	}

	// 更新章节标签
	chapterInfo.Trend = req.Trend
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "Trend")
	if err = chapterInfo.UpdateChapter(updateCols); err != nil {
		br.Msg = "更新标签失败"
		br.ErrMsg = "更新标签失败, Err: " + err.Error()
		return
	}

	// 添加关键词
	if err = models.AddTrendTagKeyWord(req.Trend); err != nil {
		br.Msg = "添加标签关键词失败"
		br.ErrMsg = "添加标签关键词失败, Err: " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// GetSunCode 获取太阳码
// @Title 公共模块
// @Description 获取分享海报
// @Param	request	body models.SunCodeReq true "type json string"
// @Success 200 {object} string "获取成功"
// @failure 400 {string} string "获取失败"
// @router /getSunCode [post]
func (this *ReportController) GetSunCode() {
	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.SunCodeReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	var sunCodeUrl string
	//先查，查不到再去生成上传
	item, err := models.GetYbPcSunCode(req.CodeScene, req.CodePage)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "查询太阳码失败！"
		br.ErrMsg = "查询太阳码失败，Err:" + err.Error()
		return
	}
	if item != nil {
		sunCodeUrl = item.SuncodeUrl
	}

	if sunCodeUrl == "" {
		sunCodeUrl, err = services.PcCreateAndUploadSunCode(req.CodeScene, req.CodePage)
		if err != nil {
			br.Msg = "生成太阳码失败！"
			br.ErrMsg = "生成太阳码失败，Err:" + err.Error()
			return
		}
	}

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

// VoiceUpload
// @Title 音频上传
// @Description 音频上传接口
// @Param   file   query   file  true       "文件"
// @Param   ReportChapterId   query   int  true       "报告章节ID"
// @Success Ret=200 上传成功
// @router /chapter/voice/upload [post]
func (this *ReportController) VoiceUpload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	f, h, err := this.GetFile("file")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}

	// 报告章节id
	reportChapterId, err := this.GetInt("ReportChapterId", 0)
	if err != nil {
		br.Msg = "报告章节ID异常"
		br.ErrMsg = "报告章节ID异常,Err:" + err.Error()
		return
	}

	// 报告章节信息
	reportChapterInfo, err := models.GetReportChapterInfoById(reportChapterId)
	if err != nil {
		br.Msg = "获取报告章节信息失败"
		br.ErrMsg = "获取报告章节信息失败,Err:" + err.Error()
		return
	}

	// 报告信息
	reportInfo, err := models.GetReportByReportId(reportChapterInfo.ReportId)
	if err != nil {
		br.Msg = "获取报告信息失败"
		br.ErrMsg = "获取报告信息失败,Err:" + err.Error()
		return
	}

	// 权限校验
	isAuth, err := services.CheckChapterAuthByReportChapterInfo(this.SysUser, reportInfo.AdminId, reportChapterInfo)
	if err != nil {
		br.Msg = "获取报告权限失败"
		br.ErrMsg = "获取报告权限失败,Err:" + err.Error()
		return
	}
	if !isAuth {
		br.Msg = "无操作权限"
		br.ErrMsg = "无操作权限"
		return
	}

	ext := path.Ext(h.Filename)
	dateDir := time.Now().Format("20060102")
	uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
	err = os.MkdirAll(uploadDir, utils.DIR_MOD)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	randStr := utils.GetRandStringNoSpecialChar(28)
	fileName := randStr + ext
	fPath := uploadDir + "/" + fileName
	defer f.Close() //关闭上传文件
	err = this.SaveToFile("file", fPath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + err.Error()
		return
	}

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

	defer func() {
		os.Remove(fPath)
	}()
	item := new(models.Resource)
	item.ResourceUrl = resourceUrl
	item.ResourceType = 2
	item.CreateTime = time.Now()
	newId, err := models.AddResource(item)
	if err != nil {
		br.Msg = "资源上传失败"
		br.ErrMsg = "资源上传失败,Err:" + err.Error()
		return
	}

	//var playSeconds float64
	//playSeconds, err = mp3duration.Calculate(fPath)
	//if playSeconds <= 0 {
	//	playSeconds, err = utils.GetVideoPlaySeconds(fPath)
	//	if err != nil {
	//		br.Msg = "获取音频时间失败"
	//		br.ErrMsg = "获取音频时间失败,Err:" + err.Error()
	//		return
	//	}
	//}
	playSecondsStr, err := utils.GetDuration(fPath) //mp3duration.Calculate(fPath)
	if err != nil {
		utils.FileLog.Info("获取音频时间失败,Err:" + err.Error())
	}

	fileBody, err := os.ReadFile(fPath)
	videoSize := len(fileBody)
	sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
	sizeStr := utils.SubFloatToFloatStr(sizeFloat, 2)

	{
		reportChapterCreateTime, err := time.Parse(utils.FormatDateTime, reportChapterInfo.CreateTime)
		if err != nil {
			br.Msg = "上传失败"
			br.ErrMsg = "上传失败，Err:" + err.Error()
			return
		}
		createTimeStr := reportChapterCreateTime.Format("0102")
		videoName := reportChapterInfo.Title + "(" + createTimeStr + ")"

		reportChapterInfo.VideoUrl = resourceUrl
		reportChapterInfo.VideoName = videoName
		reportChapterInfo.VideoPlaySeconds = playSecondsStr
		reportChapterInfo.VideoSize = sizeStr
		reportChapterInfo.VideoKind = 1
		reportChapterInfo.LastModifyAdminId = this.SysUser.AdminId
		reportChapterInfo.LastModifyAdminName = this.SysUser.RealName
		reportInfo.VoiceGenerateType = 1
		reportChapterInfo.ModifyTime = time.Now()
		err = reportChapterInfo.UpdateChapter([]string{"VideoUrl", "VideoName", "VideoPlaySeconds", "VideoSize", "VideoKind", "LastModifyAdminId", "LastModifyAdminName", "VoiceGenerateType", "ModifyTime"})
		if err != nil {
			br.Msg = "上传失败"
			br.ErrMsg = "修改报告章节的音频信息失败，Err:" + err.Error()
			return
		}

		// 修改报告的最近更新人信息
		reportInfo.LastModifyAdminId = this.SysUser.AdminId
		reportInfo.LastModifyAdminName = this.SysUser.RealName
		reportInfo.ModifyTime = time.Now()
		err = reportInfo.UpdateReport([]string{"LastModifyAdminId", "LastModifyAdminName", "ModifyTime"})
		if err != nil {
			br.Msg = "上传失败"
			br.ErrMsg = "修改报告最后更新人信息失败，Err:" + err.Error()
			return
		}
	}

	// 处理报告中的音频文件分贝
	go services.HandleVideoDecibel(reportChapterInfo)

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

// PublishDayWeekReportChapter
// @Title 发布章节
// @Description 发布章节
// @Param	request	body models.PublishReportChapterReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /publishDayWeekReportChapter [post]
func (this *ReportController) PublishDayWeekReportChapter() {
	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.PublishReportChapterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReportChapterId <= 0 {
		br.Msg = "参数有误"
		return
	}

	// 获取报告详情
	chapterInfo, err := models.GetReportChapterInfoById(req.ReportChapterId)
	if err != nil {
		br.Msg = "章节信息有误"
		br.ErrMsg = "获取章节信息失败, Err: " + err.Error()
		return
	}

	reportInfo, err := models.GetReportByReportId(chapterInfo.ReportId)
	if err != nil {
		br.Msg = "查询报告有误"
		br.ErrMsg = "查询报告信息失败, Err: " + err.Error()
		return
	}
	if reportInfo.State == 2 {
		br.Msg = "该报告已发布，不允许编辑"
		br.ErrMsg = "该报告已发布，不允许编辑"
		return
	}

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

	// 如果是系统章节，那么需要校验下是否已经停更
	if chapterInfo.TypeId > 0 {
		// 获取规则配置
		reportChapterTypeRule, err := models.GetReportChapterTypeById(chapterInfo.TypeId)
		if err != nil {
			br.Msg = "获取配置信息异常"
			br.ErrMsg = "获取配置信息异常, Err: " + err.Error()
			return
		}
		if reportChapterTypeRule.Enabled == 0 {
			br.Msg = "该章节已永久停更"
			br.ErrMsg = "该章节已永久停更 "
			br.IsSendEmail = false
			return
		}
	}

	var publishTime time.Time
	if reportInfo.MsgIsSend == 1 && reportInfo.PublishTime.IsZero() { //如果报告曾经发布过，并且已经发送过模版消息，则章节的发布时间为报告的发布时间
		publishTime = reportInfo.PublishTime
	} else {
		publishTime = time.Now()
	}

	// 更新报告的最后编辑人
	reportInfo.LastModifyAdminId = sysUser.AdminId
	reportInfo.LastModifyAdminName = sysUser.RealName
	reportInfo.ModifyTime = time.Now()
	err = reportInfo.UpdateReport([]string{"LastModifyAdminId", "LastModifyAdminName", "ModifyTime"})
	if err != nil {
		br.Msg = "发布失败"
		br.ErrMsg = "报告最后编辑人保存失败, Err: " + err.Error()
		return
	}

	// 更新章节信息
	chapterInfo.IsEdit = 1
	chapterInfo.PublishState = 2
	chapterInfo.PublishTime = publishTime
	chapterInfo.LastModifyAdminId = this.SysUser.AdminId
	chapterInfo.LastModifyAdminName = this.SysUser.RealName
	chapterInfo.ModifyTime = time.Now()

	updateCols := make([]string, 0)
	updateCols = append(updateCols, "IsEdit", "PublishState", "PublishTime", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime")
	err = chapterInfo.UpdateChapter(updateCols)
	if err != nil {
		br.Msg = "发布失败"
		br.ErrMsg = "报告章节内容保存失败, Err: " + err.Error()
		return
	}

	// 修改报告的最近更新人信息
	go func() {
		reportInfo.LastModifyAdminId = this.SysUser.AdminId
		reportInfo.LastModifyAdminName = this.SysUser.RealName
		reportInfo.ModifyTime = time.Now()
		err = reportInfo.UpdateReport([]string{"LastModifyAdminId", "LastModifyAdminName", "ModifyTime"})
		if err != nil {
			br.Msg = "上传失败"
			br.ErrMsg = "修改报告最后更新人信息失败，Err:" + err.Error()
			return
		}
	}()

	// 更新章节ES
	{
		go services.UpdateReportChapterEs(chapterInfo.ReportChapterId, reportInfo.IsPublicPublish)
	}

	// 同时发布报告
	//if req.PublishReport == 1 {
	//	if _, e := services.PublishDayWeekReport(chapterInfo.ReportId); e != nil {
	//		br.Msg = "章节发布成功，报告发布失败，请手动发布报告"
	//		br.ErrMsg = "发布晨/周报失败, Err: " + e.Error()
	//		return
	//	}
	//}

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

// GetUnPublishReportChapterList
// @Title 获取报告中未发布的章节数
// @Description 获取报告中未发布的章节数
// @Param	ReportId  query  int  true  "报告ID"
// @Success 200 Ret=200 获取成功
// @router /chapter/un_publish/list [get]
func (this *ReportController) GetUnPublishReportChapterList() {
	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
	}

	reportId, _ := this.GetInt("ReportId")
	if reportId <= 0 {
		br.Msg = "参数有误"
		br.IsSendEmail = false
		return
	}
	reportInfo, err := models.GetReportById(reportId)
	if err != nil {
		br.Msg = "报告有误"
		br.ErrMsg = "报告有误, Err: " + err.Error()
		return
	}

	if reportInfo.HasChapter == 0 {
		br.Msg = "报告未包含章节"
		br.IsSendEmail = false
		return
	}

	// 获取未发布的章节列表
	unPublishedList, err := models.GetUnPublishedChapterList(reportInfo.Id)
	if err != nil {
		br.Msg = "获取未发布的章节数失败"
		br.ErrMsg = "获取未发布的章节数失败, Err: " + err.Error()
		return
	}

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

// EditChapterTitle
// @Title 编辑章节标题
// @Description 编辑章节标题
// @Param	request	body models.EditReportChapterReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /chapter/title/edit [post]
func (this *ReportController) EditChapterTitle() {
	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.EditReportChapterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	reportChapterId := req.ReportChapterId
	if reportChapterId <= 0 {
		br.Msg = "报告章节ID有误"
		return
	}

	req.Title = strings.TrimSpace(req.Title)
	if req.Title == `` {
		br.Msg = "章节名称不能为空"
		return
	}

	// 获取章节详情
	reportChapterInfo, err := models.GetReportChapterInfoById(reportChapterId)
	if err != nil {
		br.Msg = "报告章节信息有误"
		br.ErrMsg = "报告章节信息有误, Err: " + err.Error()
		return
	}

	// 判断名称是否重复
	{
		var condition string
		var pars []interface{}

		condition += " AND report_id = ? AND title=? AND report_chapter_id != ? "
		pars = append(pars, reportChapterInfo.ReportId, req.Title, reportChapterId)
		count, err := models.GetCountReportChapterByCondition(condition, pars)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "判断章节名称是否存在失败,Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "章节名称不允许重复"
			br.ErrMsg = "章节名称不允许重复"
			br.IsSendEmail = false
			return
		}
	}

	// 获取报告详情
	reportInfo, err := models.GetReportByReportId(reportChapterInfo.ReportId)
	if err != nil {
		br.Msg = "报告信息有误"
		br.ErrMsg = "报告信息有误, Err: " + err.Error()
		return
	}

	// 操作权限校验
	hasAuth, msg, errMsg, isSendEmail := checkOpPermission(sysUser, reportInfo, reportChapterInfo, true, this.Lang)
	if !hasAuth {
		br.Msg = msg
		br.ErrMsg = errMsg
		br.IsSendEmail = isSendEmail
		return
	}

	if reportInfo.State == 2 {
		br.Msg = "该报告已发布，不允许编辑"
		br.ErrMsg = "该报告已发布，不允许编辑"
		return
	}
	// 报告的最后编辑人
	reportInfo.LastModifyAdminId = sysUser.AdminId
	reportInfo.LastModifyAdminName = sysUser.RealName
	reportInfo.ModifyTime = time.Now()

	reportChapterInfo.Title = req.Title
	reportChapterInfo.LastModifyAdminId = sysUser.AdminId
	reportChapterInfo.LastModifyAdminName = sysUser.RealName
	reportChapterInfo.ModifyTime = time.Now()

	updateCols := make([]string, 0)
	updateCols = append(updateCols, "Title", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime")

	// 更新报告的最近编辑人信息
	if err = reportInfo.UpdateReport([]string{"LastModifyAdminId", "LastModifyAdminName", "ModifyTime"}); err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "报告章节内容保存失败, Err: " + err.Error()
		return
	}
	// 更新章节
	if err = reportChapterInfo.UpdateChapter(updateCols); err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "报告章节内容保存失败, Err: " + err.Error()
		return
	}
	// 标记更新中
	{
		markStatus, err := services.UpdateReportEditMark(reportChapterInfo.ReportId, reportChapterInfo.ReportChapterId, sysUser.AdminId, 1, sysUser.RealName, this.Lang)
		if err != nil {
			br.Msg = err.Error()
			return
		}
		if markStatus.Status == 1 {
			br.Msg = markStatus.Msg
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// CancelPublishReportChapter
// @Title 取消发布章节
// @Description 取消发布章节
// @Param	request	body models.PublishReportChapterReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /chapter/publish/cancel [post]
func (this *ReportController) CancelPublishReportChapter() {
	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.PublishReportChapterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReportChapterId <= 0 {
		br.Msg = "参数有误"
		return
	}

	// 获取章节详情
	chapterInfo, err := models.GetReportChapterInfoById(req.ReportChapterId)
	if err != nil {
		br.Msg = "章节信息有误"
		br.ErrMsg = "获取章节信息失败, Err: " + err.Error()
		return
	}
	// 章节发布状态校验
	if chapterInfo.PublishState == 1 {
		br.Msg = "该章节未发布，不能重复撤销"
		br.ErrMsg = "该章节未发布，不能重复撤销"
		br.IsSendEmail = false
		return
	}

	// 获取报告详情
	reportInfo, err := models.GetReportByReportId(chapterInfo.ReportId)
	if err != nil {
		br.Msg = "查询报告有误"
		br.ErrMsg = "查询报告信息失败, Err: " + err.Error()
		return
	}
	if reportInfo.State == 2 {
		br.Msg = "该报告已发布，不允许撤销章节"
		br.ErrMsg = "该报告已发布，不允许撤销章节"
		br.IsSendEmail = false
		return
	}

	// 更新章节信息
	chapterInfo.PublishState = 1
	chapterInfo.PublishTime = time.Time{}
	chapterInfo.LastModifyAdminId = this.SysUser.AdminId
	chapterInfo.LastModifyAdminName = this.SysUser.RealName
	chapterInfo.ModifyTime = time.Now()

	updateCols := make([]string, 0)
	updateCols = append(updateCols, "PublishState", "PublishTime", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime")
	err = chapterInfo.UpdateChapter(updateCols)
	if err != nil {
		br.Msg = "发布失败"
		br.ErrMsg = "报告章节内容保存失败, Err: " + err.Error()
		return
	}

	// 更新章节ES
	{
		go services.UpdateReportChapterEs(chapterInfo.ReportChapterId, reportInfo.IsPublicPublish)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "撤销成功"
}

// checkOpPermission
// @Description: 操作权限校验
// @author: Roc
// @datetime 2024-11-12 09:58:34
// @param sysUser *system.Admin
// @param reportInfo *models.Report
// @param reportChapterInfo *models.ReportChapter
// @param isMarkStatus bool
// @param lang string
// @return hasAuth bool
// @return msg string
// @return errMsg string
// @return isSendEmail bool
func checkOpPermission(sysUser *system.Admin, reportInfo *models.Report, reportChapterInfo *models.ReportChapter, isMarkStatus bool, lang string) (hasAuth bool, msg, errMsg string, isSendEmail bool) {
	isSendEmail = true

	// 权限校验
	isAuth, err := services.CheckChapterAuthByReportChapterInfo(sysUser, reportInfo.AdminId, reportChapterInfo)
	if err != nil {
		msg = "获取报告权限失败"
		errMsg = "获取报告权限失败,Err:" + err.Error()
		return
	}
	if !isAuth {
		msg = "没有权限"
		errMsg = "没有权限"
		isSendEmail = false
		return
	}

	// 如果不是创建人，那么就要去查看是否授权
	//if reportInfo.AdminId != sysUser.AdminId && !utils.IsAdminRole(sysUser.RoleTypeCode) {
	//	// 授权用户权限校验
	//	chapterGrantObj := report.ReportChapterGrant{}
	//	_, tmpErr := chapterGrantObj.GetGrantByIdAndAdmin(reportChapterInfo.ReportChapterId, sysUser.AdminId)
	//	if tmpErr != nil {
	//		if tmpErr.Error() == utils.ErrNoRow() {
	//			msg = "没有权限"
	//			errMsg = "没有权限"
	//			isSendEmail = false
	//			return
	//		}
	//		msg = "获取章节id授权用户失败"
	//		errMsg = "获取章节id授权用户失败, Err: " + tmpErr.Error()
	//		return
	//	}
	//}

	// 标记更新中
	if isMarkStatus {
		markStatus, err := services.UpdateReportEditMark(reportChapterInfo.ReportId, reportChapterInfo.ReportChapterId, sysUser.AdminId, 1, sysUser.RealName, lang)
		if err != nil {
			msg = err.Error()
			errMsg = err.Error()
			return
		}
		if markStatus.Status == 1 {
			msg = markStatus.Msg
			errMsg = markStatus.Msg
			isSendEmail = false
			return
		}
	}

	// 有权限
	hasAuth = true

	return
}
