package controllers

import (
	"encoding/json"
	"eta/eta_mobile/models"
	"eta/eta_mobile/services"
	"eta/eta_mobile/utils"
	"time"
)

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

// List
// @Title 报告章节列表
// @Description 报告章节列表
// @Param   ClassifyId  query  int  true  "所属分类id"
// @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
	}
	classifyId, _ := this.GetInt("ClassifyId", 0)
	if classifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}

	cond := ` AND report_classify_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, classifyId)
	list, e := models.GetReportChapterTypePageList(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取报告章节列表失败, Err: " + e.Error()
		return
	}
	chapterTypeIdList := make([]int, 0)
	for _, v := range list {
		chapterTypeIdList = append(chapterTypeIdList, v.ReportChapterTypeId)
	}

	mappingList, e := models.GetChapterTypePermissionByChapterTypeIdList(chapterTypeIdList)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取章节类型权限列表失败, Err: " + e.Error()
		return
	}
	mappingMap := make(map[int][]int)
	for _, v := range mappingList {
		mappingMap[v.ReportChapterTypeId] = append(mappingMap[v.ReportChapterTypeId], v.ChartPermissionId)
	}

	respList := make([]*models.ReportChapterTypeListItem, 0)
	for i := range list {
		permissionIds, _ := mappingMap[list[i].ReportChapterTypeId]
		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,
			Enabled:               list[i].Enabled,
			ChartPermissionIdList: permissionIds,
		})
	}

	resp := new(models.ReportChapterTypeListResp)
	resp.List = respList
	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
	}

	if req.ClassifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}

	// 重名校验
	cond := ` AND report_chapter_type_name = ? AND report_classify_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, req.ReportChapterTypeName, req.ClassifyId)
	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)
	maxSort, e := item.GetMaxSort()
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取章节最大排序失败, Err:" + e.Error()
		return
	}
	item.ReportChapterTypeName = req.ReportChapterTypeName
	item.Sort = maxSort + 1
	item.Enabled = 1
	item.CreatedTime = nowTime
	item.LastUpdatedTime = nowTime
	//item.ResearchType = req.ResearchType
	item.ResearchType = "chapter"
	item.ReportClassifyId = req.ClassifyId
	item.IsSet = 0
	item.ReportChapterTypeKey = req.ReportChapterTypeName
	item.TickerTitle = req.ReportChapterTypeName

	if e = item.Create(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增报告章节失败, Err:" + e.Error()
		return
	}

	cond = ` and product_id=1`
	pars = make([]interface{}, 0)
	permissionList, e := services.GetChartPermissionList(cond, pars)
	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
	}

	newPermissions := make([]*models.ReportChapterTypePermission, 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:          item.ResearchType,
			CreatedTime:           nowTime,
		})
	}

	// 设置权限
	e = models.SetReportChapterTypePermission(item.ReportChapterTypeId, newPermissions)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "设置章节类型权限失败, Err: " + e.Error()
		return
	}
	// 清除小程序端的章节缓存
	{
		key := "hongze_yb:report_chapter_type:GetEffectTypeID"
		_ = utils.Rc.Delete(key)
	}

	go func() {
		var syncReq services.ChapterTypeSyncReq
		syncReq.ResearchType = item.ResearchType
		syncReq.ReportChapterTypeId = item.ReportChapterTypeId
		_, _ = services.ReportChapterTypeSync(&syncReq)
	}()
	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
	}

	if req.ClassifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}

	// 重名校验
	cond := ` AND report_chapter_type_name = ? AND report_classify_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, req.ReportChapterTypeName, req.ClassifyId)
	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
	if item.ReportChapterTypeName != req.ReportChapterTypeName {
		item.ReportChapterTypeName = req.ReportChapterTypeName
		err := item.Update([]string{"ReportChapterTypeName"})
		if err != nil {
			br.Msg = "修改失败"
			br.ErrMsg = "修改章节类型失败, Err: " + err.Error()
			return
		}
	}
	cond = ` and product_id=1`
	pars = make([]interface{}, 0)
	permissionList, e := services.GetChartPermissionList(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取品种列表失败, Err: " + e.Error()
		return
	}
	permissionIdName := make(map[int]string)
	nowTime := time.Now().Local()
	for i := range permissionList {
		permissionIdName[permissionList[i].ChartPermissionId] = permissionList[i].PermissionName
	}

	newPermissions := make([]*models.ReportChapterTypePermission, 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:          item.ResearchType,
			CreatedTime:           nowTime,
		})
	}

	// 设置权限
	e = models.SetReportChapterTypePermission(item.ReportChapterTypeId, newPermissions)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "设置章节类型权限失败, Err: " + e.Error()
		return
	}
	// 更新研报章节表冗余
	if originName != req.ReportChapterTypeName {
		go func() {
			_ = models.UpdateReportChapterTypeNameByTypeId(req.ReportChapterTypeId, req.ReportChapterTypeName)
		}()
	}

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

	go func() {
		var syncReq services.ChapterTypeSyncReq
		syncReq.ResearchType = item.ResearchType
		syncReq.ReportChapterTypeId = item.ReportChapterTypeId
		_, _ = services.ReportChapterTypeSync(&syncReq)
	}()
	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 && utils.BusinessCode != utils.BusinessCodeDebug {
		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
	}
	cond := ` and product_id=1`
	pars := make([]interface{}, 0)
	permissionList, e := services.GetChartPermissionList(cond, pars)
	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
	}

	nowTime := time.Now().Local()
	newPermissions := make([]*models.ReportChapterTypePermission, 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,
		})
	}

	// 设置权限
	e = models.SetReportChapterTypePermission(item.ReportChapterTypeId, newPermissions)
	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 && utils.BusinessCode != utils.BusinessCodeDebug {
		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.GetChapterTypePermissionByReportChapterTypeId(typeId)
	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
}

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

	if req.ReportChapterTypeId == 0 {
		br.Msg = "请选择要移动的章节类型"
		return
	}
	e, msg := services.MoveReportChapterType(&req)
	if e != nil {
		br.Msg = msg
		br.ErrMsg = "移动品种失败, Err: " + e.Error()
		return
	}
	go func() {
		var syncReq services.ChapterTypeSyncReq
		_, _ = services.ReportChapterTypeSync(&syncReq)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

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

	if req.ReportChapterTypeId == 0 {
		br.Msg = "请选择正确的章节类型"
		return
	}
	if req.Enabled != 0 && req.Enabled != 1 {
		br.Msg = "请选择正确的启用禁用状态"
		return
	}
	ob := new(models.ReportChapterType)
	item, err := models.GetReportChapterTypeById(req.ReportChapterTypeId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "章节不存在"
			br.ErrMsg = "章节不存在, Err:" + err.Error()
			return
		}
		br.Msg = "获取章节信息失败"
		br.ErrMsg = "获取章节信息失败, Err:" + err.Error()
		return
	}
	if item == nil {
		br.Msg = "章节不存在"
		return
	}
	//设置分类启用、禁用状态
	err = ob.SetEnabled(req.ReportChapterTypeId, req.Enabled)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "设置报告章节状态失败, Err: " + err.Error()
		return
	}
	go func() {
		var syncReq services.ChapterTypeSyncReq
		_, _ = services.ReportChapterTypeSync(&syncReq)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
