package cygx

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

// 路演精华
type RoadshowEssenceController struct {
	controllers.BaseAuthController
}

// @Title 路演精华内容的保存与发布
// @Description 研究汇总内容的保存与发布接口
// @Param	request	body cygx.AddArticleRoadshowEssenceRep true "type json string"
// @Success 200 操作成功
// @router /roadshowEssence/PreserveAndPublish [post]
func (this *RoadshowEssenceController) PreserveAndPublish() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.AddArticleRoadshowEssenceRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	var pars []interface{}
	var condition string
	chartPermissionId := req.ChartPermissionId
	industrialManagementIdStr := req.IndustrialManagementId
	industrialSubjectIdStr := req.IndustrialSubjectIdStr
	condition = `  AND chart_permission_id = ` + strconv.Itoa(chartPermissionId)
	total, _ := cygx.GetChartPermissionCount(condition, pars)
	if total < 1 {
		br.Msg = "分类ID不存在，请重新填写"
		br.ErrMsg = "分类ID不存在，请重新填写:" + strconv.Itoa(req.ChartPermissionId)
		return
	}
	industrialStrList := strings.Split(industrialManagementIdStr, ",")
	for _, v := range industrialStrList {
		condition = `AND industrial_management_id = ` + v
		totalIndustrialManagement, _ := cygx.GetIndustrialManagementCount(condition, pars)
		if totalIndustrialManagement < 1 {
			br.Msg = "操作失败，对应产业不存在"
			br.ErrMsg = "操作失败，产业不存在IndustrialManagementId：" + v
			return
		}
	}
	if industrialSubjectIdStr != "0" && industrialSubjectIdStr != "" {
		strList := strings.Split(industrialSubjectIdStr, ",")
		for _, v := range strList {
			condition = `AND industrial_subject_id = ` + v + ` AND industrial_management_id IN ( ` + industrialManagementIdStr + `)`
			totalIndustrialSubject, _ := cygx.GetIndustrialSubjectCount(condition, pars)
			if totalIndustrialSubject < 1 {
				br.Msg = "操作失败"
				br.ErrMsg = "操作失败，标的不存在IndustrialSubjectId：" + v
				return
			}
		}
	}
	charInfo, errCategory := cygx.GetCategoryInfoById(chartPermissionId)
	if errCategory != nil {
		br.Msg = "获取品种信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + errCategory.Error()
		return
	}
	var articleId int
	maxArticleIdArticleInfo, errMax := cygx.GetMaxArticleIdInfo()
	if errMax != nil {
		br.Msg = "发布失败"
		br.ErrMsg = "发布失败,Err:" + errMax.Error()
		return
	}
	if maxArticleIdArticleInfo.ArticleId < utils.SummaryArticleId {
		articleId = utils.SummaryArticleId
	} else {
		articleId = maxArticleIdArticleInfo.ArticleId + 1
	}

	detailMap, err := cygx.GetMatchTypeNameByPermissionId(chartPermissionId)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "归类配置信息,Err:" + err.Error()
		return
	}
	item := new(cygx.CygxArticle)
	item.AdminId = AdminUser.AdminId
	item.AdminName = AdminUser.RealName
	item.Title = req.Title
	item.SellerAndMobile = req.SellerAndMobile
	item.PublishDate = utils.StrTimeToTime(req.PublishDate + " 00:00:00")
	item.ChartPermissionIds = strconv.Itoa(req.ChartPermissionId)
	item.Abstract = req.Abstract
	item.Body = cygxService.GetRichtext(req.Body)
	item.BodyText, _ = cygx.GetReportContentTextSub(req.Body)
	item.ReportLink = req.ReportLink
	if item.ReportLink != "" {
		articleIdLink, err := cygxService.GetReportLinkToArticleid(item.ReportLink)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "解析报告链接ID失败，Err:" + err.Error()
			return
		}
		item.LinkArticleId = articleIdLink
	}
	item.IsReport = 1
	item.Source = 1
	item.ReportType = 2
	item.ArticleIdMd5 = utils.MD5(strconv.Itoa(articleId))
	item.Department = "弘则产品组"
	item.ArticleType = "lyjh"
	item.IsClass = 1
	item.CreateDate = time.Now()
	item.UpdateFrequency = "unknow"
	item.CategoryName = charInfo.PermissionName
	item.CategoryId = detailMap.CategoryId
	item.SubCategoryName = "路演精华"
	if req.DoType == 1 {
		item.HavePublish = 1
		item.PublishStatus = 1
	}
	if req.ArticleId == 0 {
		if req.DoType == 1 {
			condition = ` AND article_type = 'lyjh' AND art.have_publish = 1 `
			total, err := cygx.GetCygxArticleCount(condition, pars)
			if err != nil {
				br.Msg = "添加失败"
				br.ErrMsg = "新增获取期数信息失败,Err:" + err.Error()
				return
			}
			item.Periods = strconv.Itoa(total + 1)
		}

		item.ArticleId = articleId
		_, err := cygx.AddArticleRoadshowEssence(item, industrialManagementIdStr, industrialSubjectIdStr)
		if err != nil {
			br.Msg = "添加失败"
			br.ErrMsg = "添加失败,Err:" + err.Error()
			return
		}
	} else {
		articleInfo, errInfo := cygx.GetArticleIdInfoByArticleId(req.ArticleId)
		if errInfo != nil {
			br.Msg = "报告不存在"
			br.ErrMsg = "发布失败,Err:" + errInfo.Error()
			return
		}
		if req.DoType == 1 {
			condition = ` AND article_type = 'lyjh' AND art.have_publish = 1 `
			total, err := cygx.GetCygxArticleCount(condition, pars)
			if err != nil {
				br.Msg = "添加失败"
				br.ErrMsg = "修改获取期数信息失败,Err:" + err.Error()
				return
			}
			item.Periods = strconv.Itoa(total + 1)
		} else {
			item.Periods = articleInfo.Periods
			item.HavePublish = articleInfo.HavePublish
		}
		if articleInfo.HavePublish == 1 {
			item.Periods = articleInfo.Periods
		}
		if item.PublishStatus == 0 {
			item.PublishStatus = articleInfo.PublishStatus
			item.AdminId = articleInfo.AdminId
			item.AdminName = articleInfo.AdminName
		}
		item.ArticleId = req.ArticleId
		item.SummaryManageId = articleInfo.SummaryManageId

		err = cygx.UpdateArticleRoadshowEssence(item, industrialManagementIdStr, industrialSubjectIdStr)
		if err != nil {
			br.Msg = "添加失败"
			br.ErrMsg = "获取期数信息失败,Err:" + err.Error()
			return
		}
	}

	//同步数据到最新表
	if req.ArticleId == 0 {
		if item.PublishStatus == 1 {
			go cygxService.UpdateResourceData(item.ArticleId, "article", "add", time.Now().Format(utils.FormatDateTime))
		}
	} else {
		if item.PublishStatus == 1 {
			go cygxService.UpdateResourceData(item.ArticleId, "article", "update", time.Now().Format(utils.FormatDateTime))
		}
		if req.DoType == 1 {
			go cygxService.UpdateResourceData(item.ArticleId, "article", "add", time.Now().Format(utils.FormatDateTime))
		}
	}

	if req.DoType == 1 {
		go cygxService.SendWxMsgWithroadshowEssence(articleId)
	}
	//生成音频文件
	var content string
	content = "摘要" + item.Abstract + item.Body
	go services.CreateVideoWhithContent(item.ArticleId, item.Title, content, "cygx_article")

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

// @Title 删除路演精华内容
// @Description 删除路演精华内容接口
// @Param   request	body cygx.ResearchSummaryId true "type json string"
// @Success Ret=200
// @router /roadshowEssence/delete [post]
func (this *RoadshowEssenceController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.ResearchSummaryId
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	articleInfo, errInfo := cygx.GetArticleIdInfoByArticleId(articleId)
	if errInfo != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + errInfo.Error()
		return
	}
	if articleInfo.HavePublish == 1 {
		br.Msg = "删除失败"
		br.ErrMsg = "已经存在期数无法删除"
		return
	}
	err = cygx.DeleteArticleReport(articleId)
	if err != nil {
		br.Msg = "删除信息失败"
		br.ErrMsg = "删除信息失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "已删除"
	br.IsAddLog = true
}

// @Title  路演精华内容详情
// @Description  路演精华内容详情接口
// @Param   ArticleId   query   int  true       "报告Id"
// @Success Ret=200 {object} cygx.ArticleRoadshowEssenceDetail
// @router /roadshowEssence/detail [get]
func (this *RoadshowEssenceController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	articleId, _ := this.GetInt("ArticleId")
	detail, err := cygx.GetArticleRoadshowEssenceDetail(articleId)
	if err != nil {
		br.Msg = "内容不存在"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	detail.PublishDate = utils.StrTimeToTime(detail.PublishDate).Format("2006-01-02")
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = detail
}

// @Title 路演精华列表
// @Description 获取路演精华列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   PublishStatus   query   int  false       "发布状态 ，1未发布，1已发布，传2查询所有"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   ChartPermissionId   query   string  false     "行业id"
// @Success 200 {object} cygx.CygxResearchSummaryListRep
// @router /roadshowEssence/list [get]
func (this *RoadshowEssenceController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	publishStatus, _ := this.GetInt("PublishStatus")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	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{}
	condition += ` AND art.article_type = 'lyjh' `
	if startDate != "" {
		condition += ` AND art.publish_date >= ` + "'" + startDate + " 00:00:00'"
	}
	if endDate != "" {
		condition += ` AND art.publish_date <= ` + "'" + endDate + " 23:59:59'"
	}
	if publishStatus == 0 || publishStatus == 1 {
		condition += ` AND art.publish_status = ` + strconv.Itoa(publishStatus)
	}

	if keyWord != "" {
		condition += ` AND (art.title LIKE '%` + keyWord + `%' )  `
	}
	if chartPermissionId > 0 {
		condition += ` AND art.chart_permission_ids = ` + strconv.Itoa(chartPermissionId)
	}

	total, err := cygx.GetCygxArticleCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += ` ORDER BY art.publish_date DESC `
	list, err := cygx.GetArticleRoadshowEssenceList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.Periods != "" && v.Periods != "0" {
			list[k].Periods = "第" + v.Periods + "期"
		} else {
			list[k].Periods = ""
		}
		list[k].PublishDate = utils.StrTimeToTime(v.PublishDate).Format("2006-01-02")
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.CygxResearchSummaryListRep)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title   路演精华的发布与取消发布
// @Description   路演精华的发布与取消发布接口
// @Param	request	body cygx.ResearchSummaryId true "type json string"
// @Success 200 操作成功
// @router /roadshowEssence/PublishAndCancel [post]
func (this *RoadshowEssenceController) PublishAndCancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ResearchSummaryId
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	detail, err := cygx.GetArticleIdInfoByArticleId(articleId)
	if err != nil {
		br.Msg = "内容不存在"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	item := new(cygx.CygxResearchSummaryRep)
	item.ArticleId = articleId

	if detail.PublishStatus == 0 {
		item.PublishStatus = 1
		item.AdminId = AdminUser.AdminId
		item.AdminName = AdminUser.RealName
		go cygxService.SendWxMsgWithroadshowEssence(articleId)
	} else {
		item.AdminId = detail.AdminId
		item.AdminName = detail.AdminName
		item.PublishStatus = 0
	}
	if detail.HavePublish == 0 {
		var pars []interface{}
		var condition string
		condition = ` AND article_type = 'lyjh' AND art.have_publish = 1 `
		total, err := cygx.GetCygxArticleCount(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		item.Periods = strconv.Itoa(total + 1)
	} else {
		item.Periods = detail.Periods
	}
	err = cygx.RoadshowEssencePublishAndCancel(item)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 文章的见范围修改
// @Description 文章的见范围修改接口
// @Param	request	body cygx.SummaryManageIdRep true "type json string"
// @Success 200 操作成功
// @router /roadshowEssence/visibleRange [post]
func (this *RoadshowEssenceController) VisibleRange() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.SummaryManageIdRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	item := new(cygx.CygxArticle)
	articleInfo, errInfo := cygx.GetArticleInfoOtherByArticleId(articleId)
	if articleInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "纪要ID错误"
		return
	}
	if errInfo != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + errInfo.Error()
		return
	}
	item.ArticleId = articleId
	item.Title = articleInfo.Title
	item.BodyText = articleInfo.BodyText
	item.Body = articleInfo.Body
	item.PublishDate = articleInfo.PublishDate
	item.ExpertBackground = articleInfo.ExpertBackground
	item.CategoryId = articleInfo.CategoryId
	if articleInfo.VisibleRange == 0 {
		item.VisibleRange = 1
		item.AdminId = AdminUser.AdminId
		item.AdminName = AdminUser.RealName
		go cygxService.SendWxMsgWithroadshowEssence(articleId)
	} else {
		item.AdminId = articleInfo.AdminId
		item.AdminName = articleInfo.AdminName
		item.PublishStatus = 0
	}
	err = cygx.ArticleVisibleRange(item)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}
