package message

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

// GetImgList 获取轮播图列表
func (m *MessageDAO) GetImgList(orgid string, page int, pageSize int) ([]model.TaCmsImages, error) {
	var imgs []model.TaCmsImages
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("org_id=?", orgid).Limit(pageSize, (page-1)*pageSize).Desc("create_date").Find(&imgs)
	return imgs, err
}

// GetImgListCount 获取轮播图count
func (m *MessageDAO) GetImgListCount(orgid string) (int, error) {
	var imgs []model.TaCmsImages
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("org_id=?", orgid).Find(&imgs)
	if err != nil {
		return 0, err
	}
	return len(imgs), nil
}

// GetImgByLocation 根据位置获取轮播图信息
func (m *MessageDAO) GetImgByLocation(locationid, orgid string) ([]model.TaCmsImages, error) {
	var imgs []model.TaCmsImages
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("org_id=?", orgid).And("location_id=?", locationid).Asc("sort").Find(&imgs)
	return imgs, err
}

// GetImgByID 根据ID获取轮播图信息
func (m *MessageDAO) GetImgByID(imgid string) (*model.TaCmsImages, error) {
	var imgs []model.TaCmsImages

	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("image_id=?", imgid).Find(&imgs)
	if err != nil {
		return nil, err
	}
	if len(imgs) > 0 {
		return &imgs[0], nil
	}
	return nil, nil
}

// AddCmsImg 保存轮播图
func (m *MessageDAO) AddCmsImg(info model.TaCmsImages) (*model.TaCmsImages, error) {
	info.ImageId = utils.GetGUID()
	// info.Status = models.STATUS_NORMAL
	info.CreateDate = time.Now()
	user := m.ctx.Get("user").(model.SysUser)
	info.CreateUser = user.UserId
	_, err := m.db.Insert(info)
	return &info, err
}

// UpdateCmsImg 修改
func (m *MessageDAO) UpdateCmsImg(img model.TaCmsImages) error {
	var cols = []string{
		"image_url",
		"forward_type",
		"forward_url",
		"forward_resource_id",
		"sort",
		"title",
		"location_id",
		"status",
	}
	_, err := m.db.Cols(cols...).Where("image_id=?", img.ImageId).Update(img)
	return err
}

// DelCmsImg 删除
func (m *MessageDAO) DelCmsImg(imgid string) error {
	var info = model.TaCmsImages{
		ImageId: imgid,
		Status:  models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("image_id=?", info.ImageId).Update(info)
	return err
}
