package models

import (
	"eta_gn/eta_api/global"
	"eta_gn/eta_api/utils"
	"fmt"
	"strings"
	"time"

	"github.com/rdlucklib/rdluck_tools/paging"
)

const (
	ReportMessageTypeWriteNotice   = 1 // 撰写通知
	ReportMessageTypeApprovePass   = 2 // 审批通过
	ReportMessageTypeApproveRefuse = 3 // 审批驳回
)

type ReportMessage struct {
	Id            int       `gorm:"primaryKey;column:id;type:int(10) unsigned;not null"`
	SendUserId    int       `gorm:"column:send_user_id" description:"发送人ID"`
	ReceiveUserId int       `gorm:"column:receive_user_id" description:"接受者ID"`
	Content       string    `gorm:"column:content" description:"消息内容"`
	Remark        string    `gorm:"column:remark" description:"备注信息"`
	ExtraContent  string    `gorm:"column:extra_content" description:"额外信息-JSON"`
	ReportType    int       `gorm:"column:report_type" description:"报告类型:1-研报;2-PPT"`
	ReportId      int       `gorm:"column:report_id" description:"报告/PPT-ID"`
	MessageType   int       `gorm:"column:message_type" description:"消息类型:1-撰写通知;2-审批通过;3-审批驳回"`
	IsRead        int       `gorm:"column:is_read" description:"是否已读:0-未读;1-已读"`
	CreateTime    time.Time `gorm:"column:create_time" description:"消息时间"`
	ModifyTime    time.Time `gorm:"column:modify_time" description:"更新时间"`
}

var ReportMessageCols = struct {
	Id            string
	SendUserId    string
	ReceiveUserId string
	Content       string
	Remark        string
	ExtraContent  string
	ReportType    string
	ReportId      string
	MessageType   string
	IsRead        string
	CreateTime    string
}{
	Id:            "id",
	SendUserId:    "send_user_id",
	ReceiveUserId: "receive_user_id",
	Content:       "content",
	Remark:        "remark",
	ExtraContent:  "extra_content",
	ReportType:    "report_type",
	ReportId:      "report_id",
	MessageType:   "message_type",
	IsRead:        "is_read",
	CreateTime:    "create_time",
}

func (m *ReportMessage) TableName() string {
	return "report_message"
}

func (m *ReportMessage) PrimaryId() string {
	return ReportMessageCols.Id
}

func (m *ReportMessage) Create() (err error) {
	err = global.DmSQL["rddp"].Create(m).Error
	return
}

func (m *ReportMessage) CreateMulti(items []*ReportMessage) (err error) {
	if len(items) == 0 {
		return
	}
	err = global.DmSQL["rddp"].CreateInBatches(items, utils.MultiAddNum).Error
	return
}

func (m *ReportMessage) Update(cols []string) (err error) {
	err = global.DmSQL["rddp"].Select(cols).Updates(m).Error
	return
}

func (m *ReportMessage) Del() (err error) {
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = global.DmSQL["rddp"].Exec(sql, m.Id).Error
	return
}

func (m *ReportMessage) MultiDel(menuIds []int) (err error) {
	if len(menuIds) == 0 {
		return
	}
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.PrimaryId(), utils.GetOrmInReplace(len(menuIds)))
	err = global.DmSQL["rddp"].Exec(sql, menuIds).Error
	return
}

func (m *ReportMessage) GetItemById(id int) (item *ReportMessage, err error) {
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
	err = global.DmSQL["rddp"].Raw(sql, id).First(&item).Error
	return
}

func (m *ReportMessage) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *ReportMessage, err error) {
	order := ``
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s %s LIMIT 1`, m.TableName(), condition, order)
	err = global.DmSQL["rddp"].Raw(sql, pars...).First(&item).Error
	return
}

func (m *ReportMessage) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = global.DmSQL["rddp"].Raw(sql, pars...).Scan(&count).Error
	return
}

func (m *ReportMessage) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*ReportMessage, err error) {
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	err = global.DmSQL["rddp"].Raw(sql, pars...).Find(&items).Error
	return
}

func (m *ReportMessage) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*ReportMessage, err error) {
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
	pars = append(pars, startSize)
	pars = append(pars, pageSize)
	err = global.DmSQL["rddp"].Raw(sql, pars...).Find(&items).Error
	return
}

// ReportMessageItem 报告消息
type ReportMessageItem struct {
	Id            int
	SendUserId    int                       `description:"发送人ID"`
	ReceiveUserId int                       `description:"接收者ID"`
	Content       string                    `description:"消息内容"`
	Remark        string                    `description:"备注信息"`
	ReportType    int                       `description:"报告类型:1-研报;2-PPT"`
	ReportId      int                       `description:"报告/PPT-ID"`
	ReportState   int                       `description:"报告当前状态"`
	MessageType   int                       `description:"消息类型:1-撰写通知;2-审批通过;3-审批驳回"`
	IsRead        int                       `description:"是否已读:0-未读;1-已读"`
	CreateTime    string                    `description:"消息时间"`
	ApproveMsg    *ReportMessageApproveItem `description:"审批信息"`
}

// ReportMessageApproveItem 报告消息审批内容
type ReportMessageApproveItem struct {
	Title           string `description:"报告标题"`
	ApproveType     int    `description:"审批类型:1-通过;2-驳回"`
	ApproveUserId   int    `description:"审批人ID"`
	ApproveUserName string `description:"审批人"`
	ApproveRemark   string `description:"审批备注(驳回意见)"`
}

// FormatReportMessage2Item 格式化报告消息
func FormatReportMessage2Item(origin *ReportMessage) (item *ReportMessageItem) {
	item = new(ReportMessageItem)
	if origin == nil {
		return
	}
	item.Id = origin.Id
	item.SendUserId = origin.SendUserId
	item.ReceiveUserId = origin.ReceiveUserId
	item.Content = origin.Content
	item.Remark = origin.Remark
	item.ReportType = origin.ReportType
	item.ReportId = origin.ReportId
	item.MessageType = origin.MessageType
	item.IsRead = origin.IsRead
	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, origin.CreateTime)
	return
}

// ReportMessageListReq 消息列表请求参数
type ReportMessageListReq struct {
	PageSize     int `form:"PageSize"`
	CurrentIndex int `form:"CurrentIndex"`
}

// ReportMessageListResp 消息列表响应体
type ReportMessageListResp struct {
	List        []*ReportMessageItem
	Paging      *paging.PagingItem `description:"分页数据"`
	UnreadTotal int                `description:"消息未读数"`
}

// ReportMessageReadReq 消息已读请求体
type ReportMessageReadReq struct {
	MessageId int `description:"消息ID"`
}