package data_manage_permission

import (
	"encoding/json"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage/data_manage_permission"
	data_manage_permissionServ "eta/eta_mobile/services/data/data_manage_permission"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

// MessageList
// @Title 资产消息列表
// @Description 资产消息列表
// @Param   PageSize			query	int		true	"每页数据条数"
// @Param   CurrentIndex		query	int		true	"当前页页码"
// @Success 200 {object} data_manage_permission.DataPermissionMessageListResp
// @router /message/list [get]
func (c *DataMangePermissionController) MessageList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	// 分页
	pageSize, _ := c.GetInt("PageSize")
	currentIndex, _ := c.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	resp := new(data_manage_permission.DataPermissionMessageListResp)
	resp.List = make([]*data_manage_permission.DataPermissionMessageItem, 0)
	cond := fmt.Sprintf(` AND %s = ?`, data_manage_permission.DataPermissionMessageCols.ReceiveUserId)
	pars := make([]interface{}, 0)
	pars = append(pars, sysUser.AdminId)
	order := fmt.Sprintf(`%s ASC, %s DESC`, data_manage_permission.DataPermissionMessageCols.IsRead, data_manage_permission.DataPermissionMessageCols.CreateTime)

	messageOb := new(data_manage_permission.DataPermissionMessage)
	total, e := messageOb.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取资产消息列表总数失败, Err: " + e.Error()
		return
	}
	list, e := messageOb.GetPageItemsByCondition(cond, pars, []string{}, order, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取资产消息列表失败, Err: " + e.Error()
		return
	}
	for _, v := range list {
		t := data_manage_permission.FormatDataPermissionMessage2Item(v)
		resp.List = append(resp.List, t)
	}

	// 未读消息数
	cond += fmt.Sprintf(` AND %s = ?`, data_manage_permission.DataPermissionMessageCols.IsRead)
	pars = append(pars, 0)
	unreadTotal, e := messageOb.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取资产消息列表总数失败, Err: " + e.Error()
		return
	}
	resp.UnreadTotal = unreadTotal

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

// MessageRead
// @Title 消息已读
// @Description 消息已读
// @Param	request	body data_manage_permission.DataPermissionMessageReadReq true "type json string"
// @Success 200 string "操作成功"
// @router /message/read [post]
func (c *DataMangePermissionController) MessageRead() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req data_manage_permission.DataPermissionMessageReadReq
	if e := json.Unmarshal(c.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	if req.MessageId <= 0 {
		br.Msg = "参数有误"
		br.ErrMsg = fmt.Sprintf("参数有误, MessageId: %d", req.MessageId)
		return
	}

	messageOb := new(data_manage_permission.DataPermissionMessage)
	messageItem, e := messageOb.GetItemById(req.MessageId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "消息不存在, 请刷新页面"
			return
		}
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批消息失败, Err: " + e.Error()
		return
	}

	// 不等于0的时候，说明已经操作过了，就不重复操作了
	if messageItem.IsRead != 0 {
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	if messageItem.ReceiveUserId != int32(sysUser.AdminId) {
		br.Msg = "标记已读失败，不是本人消息"
		br.ErrMsg = "标记已读失败，不是本人消息 "
		br.IsSendEmail = false
		return
	}
	messageItem.IsRead = 1
	messageItem.ModifyTime = time.Now().Local()
	cols := []string{"IsRead", "ModifyTime"}
	if e = messageItem.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新消息已读失败, Err: " + e.Error()
		return
	}

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

// MessageDetail
// @Title 资产消息详情
// @Description 资产消息详情
// @Param   MessageId			query	int		true	"消息ID"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Source   query   int  false       "来源 ：1：手工数据指标 2：上海钢联数据库 3：ETA指标库 4：ETA预测指标 5：图库 6：ETA表格"
// @Param   SubSource   query   int  false       "子来源 ：目前作用于ETA表格，2024-3-26 14:12:09"
// @Success 200 {object} data_manage_permission.MessageDetailListResp
// @router /message/detail [get]
func (c *DataMangePermissionController) MessageDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	messageId, _ := c.GetInt("MessageId", 0)
	if messageId <= 0 {
		br.Msg = "请选择消息"
		br.ErrMsg = "请选择消息"
		br.IsSendEmail = false
		return
	}
	source, _ := c.GetInt("Source")
	// 子来源（目前作用于ETA表格，2024-3-26 14:12:09）
	subSource, _ := c.GetInt("SubSource")

	pageSize, _ := c.GetInt("PageSize")
	currentIndex, _ := c.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	resp := data_manage_permission.MessageDetailListResp{}
	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	messageOb := new(data_manage_permission.DataPermissionMessage)
	messageItem, e := messageOb.GetItemById(messageId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "消息不存在, 请刷新页面"
			return
		}
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批消息失败, Err: " + e.Error()
		return
	}

	total, list, err := data_manage_permissionServ.GetMessageDetail(messageItem, source, subSource, startSize, pageSize)
	if err != nil {
		//br.Success = true
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

	page = paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	resp.List = list

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