package message

import (
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/utils"
	"strconv"
	"time"

	"github.com/go-xorm/xorm"
)

// MessageDAO 当前数据库操作对象
type MessageDAO struct {
	ctx *utils.Context
	db  *xorm.Session
}

// NewMessageDAO New Inst
func NewMessageDAO(ctx *utils.Context) *MessageDAO {
	return &MessageDAO{
		ctx: ctx,
		db:  ctx.DB,
	}
}

// GetCmsInfoList 获取消息列表
func (m *MessageDAO) GetCmsInfoList(title, orgid string, page int, pageSize int) ([]model.TaCmsInfo, error) {
	var cmsinfos []model.TaCmsInfo

	dao := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("org_id=?", orgid)
	if title != "" {
		dao.And("info_name like '%" + title + "%'")
	}

	err := dao.Limit(pageSize, (page-1)*pageSize).Desc("create_date").Find(&cmsinfos)
	return cmsinfos, err
}

// GetCmsInfoListCount 消息列表
func (m *MessageDAO) GetCmsInfoListCount(title, orgid string) (int, error) {
	var cmsinfos []model.TaCmsInfo

	dao := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("org_id=?", orgid)
	if title != "" {
		dao.And("info_name like '%" + title + "%'")
	}

	err := dao.Find(&cmsinfos)
	if err != nil {
		return 0, err
	}
	return len(cmsinfos), nil
}

// GetCmsInfoByLocation 根据位置获取消息信息
func (m *MessageDAO) GetCmsInfoByLocation(locationid, orgid string) ([]model.TaCmsInfo, error) {
	var cmsinfos []model.TaCmsInfo

	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("org_id=?", orgid).And("location_id=?", locationid).Find(&cmsinfos)
	return cmsinfos, err
}

// GetCmsInfoByID 获取单条消息记录
func (m *MessageDAO) GetCmsInfoByID(id string) (*model.TaCmsInfo, error) {
	var cmsinfos []model.TaCmsInfo
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("info_id=?", id).Find(&cmsinfos)
	if err != nil {
		return nil, err
	}
	return &cmsinfos[0], nil
}

// AddCmsInfo 新增消息记录
func (m *MessageDAO) AddCmsInfo(cmsinfo model.TaCmsInfo) (*model.TaCmsInfo, error) {
	cmsinfo.InfoId = utils.GetGUID()
	cmsinfo.Status = models.STATUS_NORMAL
	cmsinfo.CreateDate = time.Now()
	user := m.ctx.Get("user").(model.SysUser)
	cmsinfo.CreateUser = user.UserId
	_, err := m.db.Insert(cmsinfo)
	return &cmsinfo, err
}

// UpdateCmsInfo 修改
func (m *MessageDAO) UpdateCmsInfo(cmsinfo model.TaCmsInfo) error {
	var cols = []string{
		"info_name",
		"info_url",
		"location_id",
		"case_id",
	}
	_, err := m.db.Cols(cols...).Where("info_id=?", cmsinfo.InfoId).Update(cmsinfo)
	return err
}

// DelCmsInfo 删除
func (m *MessageDAO) DelCmsInfo(infoid string) error {
	var info = model.TaCmsInfo{
		InfoId: infoid,
		Status: models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("info_id=?", info.InfoId).Update(info)
	return err
}
