package message

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

const (
	ISSYS = 0
)

// GetLocationList 获取位置字典
func (m *MessageDAO) GetLocationList(issys, org_id string) ([]model.TdCmsImageLocation, error) {
	var locations []model.TdCmsImageLocation
	s := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("org_id=?", org_id)
	if issys != "" {
		s = s.And("is_sys=?", issys)
	}
	err := s.Asc("order_no").Find(&locations)
	return locations, err
}

// GetLocationMaxSort 获取最大的位置
func (m *MessageDAO) GetLocationMaxSort(issys, org_id string) (int, error) {
	var location []map[string][]byte
	sql := `select max(order_no) as order_no from td_cms_image_location where is_sys=` + issys + ` and org_id ='` + org_id + `'`
	location, err := m.db.Query(sql)
	if err != nil {
		return 0, err
	}
	if len(location) > 0 {
		sort := string(location[0]["order_no"])
		if sort != "" {
			sortno, err := strconv.Atoi(string(location[0]["order_no"]))
			return sortno, err
		}
		return 0, err
	}
	return 0, nil
}

// GetLocationById 根据ID获取明细
func (m *MessageDAO) GetLocationById(id string) (*model.TdCmsImageLocation, error) {
	var location []model.TdCmsImageLocation
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("location_id=?", id).Find(&location)
	if err != nil {
		return nil, err
	}
	return &location[0], nil
}

// AddLocation 新增
func (m *MessageDAO) AddLocation(location model.TdCmsImageLocation) (*model.TdCmsImageLocation, error) {
	location.LocationId = utils.GetGUID()
	location.Status = models.STATUS_NORMAL
	location.IsSys = ISSYS
	_, err := m.db.Insert(location)
	return &location, err
}

// UpdateLocation 修改
func (m *MessageDAO) UpdateLocation(location model.TdCmsImageLocation) error {
	var cols = []string{
		"location_name",
		"location_code",
		"title",
		"consult",
		"type_img",
		"order_no",
	}
	_, err := m.db.Cols(cols...).Where("location_id=?", location.LocationId).Update(location)
	return err
}

// DelLocation 删除
func (m *MessageDAO) DelLocation(location_id string) error {
	var location = model.TdCmsImageLocation{
		LocationId: location_id,
		Status:     models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("location_id=?", location.LocationId).Update(location)
	return err
}

// UpdateLocationSort 修改顺序
func (m *MessageDAO) UpdateLocationSort(loc []string) error {
	orderno, err := strconv.Atoi(loc[1])
	if err != nil {
		return err
	}
	var location = model.TdCmsImageLocation{
		LocationId: loc[0],
		OrderNo:    orderno,
	}
	var cols = []string{
		"order_no",
	}
	_, err = m.db.Cols(cols...).Where("location_id=?", location.LocationId).Update(location)
	return err
}

// UpdateLocationSortByID 根据id修改之后的顺序
func (m *MessageDAO) UpdateLocationSortByID(orderno int) error {
	sql := `update td_cms_image_location set order_no = order_no - 1 where order_no > ` + strconv.Itoa(orderno)
	_, err := m.db.Exec(sql)
	return err
}
