package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"eta/eta_api/models"
	"eta/eta_api/utils"
	"time"
)

// ReportChapterTypeController 报告章节配置
type ReportChapterTypeController struct {
	BaseAuthController
}

// List
// @Title 报告章节列表
// @Description 报告章节列表
// @Param   ReportType  query  string  true  "报告类型: day-晨报; week-周报"
// @Success 200 {object} models.ReportChapterTypePageListResp
// @router /chapter_type/list [get]
func (this *ReportChapterTypeController) List() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	reportType := this.GetString("ReportType")
	typeArr := []string{utils.REPORT_TYPE_DAY, utils.REPORT_TYPE_WEEK}
	if !utils.InArrayByStr(typeArr, reportType) {
		br.Msg = "请选择报告类型"
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	cond := ` AND research_type = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, reportType)
	total, e := models.GetReportChapterTypeCount(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取报告章节列表总数失败, Err: " + e.Error()
		return
	}
	list, e := models.GetReportChapterTypePageList(cond, pars, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取报告章节列表失败, Err: " + e.Error()
		return
	}
	respList := make([]*models.ReportChapterTypeListItem, 0)
	for i := range list {
		respList = append(respList, &models.ReportChapterTypeListItem{
			ReportChapterTypeId:   list[i].ReportChapterTypeId,
			ReportChapterTypeName: list[i].ReportChapterTypeName,
			Sort:                  list[i].Sort,
			CreatedTime:           list[i].CreatedTime.Format(utils.FormatDateTime),
			ResearchType:          list[i].ResearchType,
			SelectedImage:         list[i].SelectedImage,
			UnselectedImage:       list[i].UnselectedImage,
			WordsImage:            list[i].YbBottomIcon, // 此处的不一样
			EditImgUrl:            list[i].EditImgUrl,
			IsShow:                list[i].IsShow,
		})
	}

	resp := new(models.ReportChapterTypePageListResp)
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = respList
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Add
// @Title 新增报告章节
// @Description 新增报告章节
// @Param	request  body  models.ReportChapterTypeAddReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /chapter_type/add [post]
func (this *ReportChapterTypeController) Add() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req models.ReportChapterTypeAddReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReportChapterTypeName == "" {
		br.Msg = "请输入章节名称"
		return
	}
	typeArr := []string{utils.REPORT_TYPE_DAY, utils.REPORT_TYPE_WEEK}
	if !utils.InArrayByStr(typeArr, req.ResearchType) {
		br.Msg = "请选择报告类型"
		return
	}
	// 重名校验
	cond := ` AND report_chapter_type_name = ? AND research_type = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, req.ReportChapterTypeName, req.ResearchType)
	exists, e := models.GetReportChapterTypeByCondition(cond, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "操作失败"
		br.ErrMsg = "获取重名报告章节失败, Err:" + e.Error()
		return
	}
	if exists != nil {
		br.Msg = "章节名称已存在"
		return
	}

	nowTime := time.Now().Local()
	item := new(models.ReportChapterType)
	item.ReportChapterTypeName = req.ReportChapterTypeName
	item.Sort = req.Sort
	item.Enabled = 1
	item.CreatedTime = nowTime
	item.LastUpdatedTime = nowTime
	item.ResearchType = req.ResearchType
	item.ReportChapterTypeName = req.ReportChapterTypeName
	item.SelectedImage = req.SelectedImage
	item.UnselectedImage = req.UnselectedImage
	item.PcSelectedImage = req.SelectedImage
	item.PcUnselectedImage = req.UnselectedImage
	item.EditImgUrl = req.EditImgUrl
	item.IsSet = 0
	item.YbIconUrl = req.UnselectedImage
	item.YbBottomIcon = req.WordsImage
	item.IsShow = req.IsShow
	item.ReportChapterTypeThumb = req.EditImgUrl
	item.BannerUrl = req.UnselectedImage
	item.ReportChapterTypeKey = req.ReportChapterTypeName
	item.TickerTitle = req.ReportChapterTypeName
	if e = item.Create(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增报告章节失败, Err:" + e.Error()
		return
	}

	// 清除小程序端的章节缓存
	{
		key := "hongze_yb:report_chapter_type:GetEffectTypeID"
		_ = utils.Rc.Delete(key)
	}

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

// Edit
// @Title 编辑报告章节
// @Description 编辑报告章节
// @Param	request  body  models.ReportChapterTypeEditReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /chapter_type/edit [post]
func (this *ReportChapterTypeController) Edit() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req models.ReportChapterTypeEditReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReportChapterTypeId <= 0 {
		br.Msg = "章节ID有误"
		return
	}
	if req.ReportChapterTypeName == "" {
		br.Msg = "请输入章节名称"
		return
	}
	typeArr := []string{utils.REPORT_TYPE_DAY, utils.REPORT_TYPE_WEEK}
	if !utils.InArrayByStr(typeArr, req.ResearchType) {
		br.Msg = "请选择报告类型"
		return
	}
	// 重名校验
	cond := ` AND report_chapter_type_name = ? AND research_type = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, req.ReportChapterTypeName, req.ResearchType)
	exists, e := models.GetReportChapterTypeByCondition(cond, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "操作失败"
		br.ErrMsg = "获取重名报告章节失败, Err:" + e.Error()
		return
	}
	if exists != nil && exists.ReportChapterTypeId != req.ReportChapterTypeId {
		br.Msg = "章节名称已存在"
		return
	}

	item, e := models.GetReportChapterTypeById(req.ReportChapterTypeId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取报告章节失败, Err:" + e.Error()
		return
	}
	originName := item.ReportChapterTypeName

	item.ReportChapterTypeName = req.ReportChapterTypeName
	item.Sort = req.Sort
	item.ResearchType = req.ResearchType
	item.SelectedImage = req.SelectedImage
	item.UnselectedImage = req.UnselectedImage
	item.PcSelectedImage = req.SelectedImage
	item.PcUnselectedImage = req.UnselectedImage
	item.EditImgUrl = req.EditImgUrl
	item.YbIconUrl = req.UnselectedImage
	item.YbBottomIcon = req.WordsImage
	item.IsShow = req.IsShow
	item.ReportChapterTypeThumb = req.EditImgUrl
	item.BannerUrl = req.UnselectedImage
	item.ReportChapterTypeKey = req.ReportChapterTypeName
	item.TickerTitle = req.ReportChapterTypeName
	updateCols := []string{"ReportChapterTypeName", "Sort", "ResearchType", "SelectedImage", "UnselectedImage",
		"PcSelectedImage", "PcUnselectedImage", "EditImgUrl", "YbIconUrl", "YbBottomIcon", "IsShow",
		"ReportChapterTypeThumb", "BannerUrl", "ReportChapterTypeKey", "TickerTitle",
	}
	if e = item.Update(updateCols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新报告章节失败, Err:" + e.Error()
		return
	}

	// 更新研报章节表冗余
	if originName != req.ReportChapterTypeName {
		go func() {
			_ = models.UpdateReportChapterTypeNameByTypeId(item.ReportChapterTypeId, req.ReportChapterTypeName)
		}()
	}

	// 清除小程序端的章节缓存
	{
		key := "hongze_yb:report_chapter_type:GetEffectTypeID"
		_ = utils.Rc.Delete(key)
	}

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

// Del
// @Title 删除报告章节
// @Description 删除报告章节
// @Param	request  body  models.ReportChapterTypeDelReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /chapter_type/del [post]
func (this *ReportChapterTypeController) Del() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req models.ReportChapterTypeDelReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReportChapterTypeId <= 0 {
		br.Msg = "参数有误"
		return
	}

	item, e := models.GetReportChapterTypeById(req.ReportChapterTypeId)
	if e != nil {
		br.Msg = "章节不存在或已被删除"
		return
	}
	// 是否有关联报告
	count, e := models.CountReportChapterByTypeId(req.ReportChapterTypeId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取章节类型关联报告数失败, Err:" + e.Error()
		return
	}
	if count > 0 {
		br.Msg = "该章节有关联报告，不允许删除"
		return
	}
	if e = models.DeleteReportChapterType(req.ReportChapterTypeId, item.ResearchType); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除章节类型失败, Err:" + e.Error()
		return
	}

	// 清除小程序端的章节缓存
	{
		key := "hongze_yb:report_chapter_type:GetEffectTypeID"
		_ = utils.Rc.Delete(key)
	}

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

// AuthSetting
// @Title 章节权限设置
// @Description 章节权限设置
// @Param	request	body request.EditActivityReq true "type json string"
// @Success 200 string "操作成功"
// @router /chapter_type/auth_setting [post]
func (this *ReportChapterTypeController) AuthSetting() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	// 非自用直接返回
	if utils.BusinessCode != utils.BusinessCodeRelease && utils.BusinessCode != utils.BusinessCodeSandbox {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	var req models.ReportChapterTypeAuthSettingReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReportChapterTypeId <= 0 {
		br.Msg = "参数有误"
		return
	}
	if len(req.ChartPermissionIdList) == 0 {
		br.Msg = "请选择权限"
		return
	}

	item, e := models.GetReportChapterTypeById(req.ReportChapterTypeId)
	if e != nil {
		br.Msg = "章节不存在或已被删除"
		return
	}
	permissionList, e := models.GetChartPermissionList()
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取权限列表失败, Err: " + e.Error()
		return
	}
	permissionIdName := make(map[int]string)
	for i := range permissionList {
		permissionIdName[permissionList[i].ChartPermissionId] = permissionList[i].PermissionName
	}

	researchType := item.ResearchType
	nowTime := time.Now().Local()
	newPermissions := make([]*models.ReportChapterTypePermission, 0)       // 报告章节权限表(新)
	newWeekPermissions := make([]*models.ChartPermissionChapterMapping, 0) // 报告章节权限表(老)
	for i := range req.ChartPermissionIdList {
		newPermissions = append(newPermissions, &models.ReportChapterTypePermission{
			ReportChapterTypeId:   item.ReportChapterTypeId,
			ReportChapterTypeName: item.ReportChapterTypeName,
			ChartPermissionId:     req.ChartPermissionIdList[i],
			PermissionName:        permissionIdName[req.ChartPermissionIdList[i]],
			ResearchType:          researchType,
			CreatedTime:           nowTime,
		})
		if researchType == utils.REPORT_TYPE_WEEK {
			newWeekPermissions = append(newWeekPermissions, &models.ChartPermissionChapterMapping{
				ChartPermissionId:   req.ChartPermissionIdList[i],
				ReportChapterTypeId: item.ReportChapterTypeId,
				ResearchType:        researchType,
			})
		}
	}

	// 设置权限
	e = models.SetReportChapterTypePermission(item.ReportChapterTypeId, researchType, newPermissions, newWeekPermissions)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "设置章节类型权限失败, Err: " + e.Error()
		return
	}

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

// PermissionList
// @Title 报告章节权限列表
// @Description 报告章节权限列表
// @Param   ReportChapterTypeId  query  int  true  "章节类型ID"
// @Success 200 {object} response.CommunityQuestionListResp
// @router /chapter_type/permission_list [get]
func (this *ReportChapterTypeController) PermissionList() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	if utils.BusinessCode != utils.BusinessCodeRelease && utils.BusinessCode != utils.BusinessCodeSandbox {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	typeId, _ := this.GetInt("ReportChapterTypeId")
	if typeId <= 0 {
		br.Msg = "参数有误"
		return
	}
	item, e := models.GetReportChapterTypeById(typeId)
	if e != nil {
		br.Msg = "章节不存在或已被删除"
		return
	}
	list, e := models.GetChapterTypePermissionByTypeIdAndResearchType(typeId, item.ResearchType)
	if e != nil {
		br.Msg = "章节不存在或已被删除"
		br.ErrMsg = "获取章节类型权限列表失败, Err: " + e.Error()
		return
	}
	respList := make([]*models.ChartPermissionSearchKeyWordMapping, 0)
	for i := range list {
		respList = append(respList, &models.ChartPermissionSearchKeyWordMapping{
			ChartPermissionId: list[i].ChartPermissionId,
			KeyWord:           item.ReportChapterTypeName,
		})
	}

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