package message

import (
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/utils"
	"strings"

	"github.com/astaxie/beego"
)

// GetLocationList 获取列表
func (s *MessageServ) GetLocationList(issys, orgid string) ([]model.TdCmsImageLocation, error) {
	list, err := s.dao.GetLocationList(issys, orgid)
	return list, err
}

// GetLocationByID 获取详细信息
func (s *MessageServ) GetLocationByID(id string) (*model.TdCmsImageLocation, error) {
	location, err := s.dao.GetLocationById(id)
	return location, err
}

// SaveLocation 保存
func (s *MessageServ) SaveLocation(location model.TdCmsImageLocation) (*model.TdCmsImageLocation, error) {
	if location.LocationId == "" {
		sort, err := s.dao.GetLocationMaxSort("0", location.OrgId)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
		location.OrderNo = sort + 1
		newlocation, err := s.dao.AddLocation(location)
		return newlocation, err
	}
	err := s.dao.UpdateLocation(location)
	return &location, err
}

// DelLocation 删除
func (s *MessageServ) DelLocation(locationID string) error {
	loc, err := s.dao.GetLocationById(locationID)
	if err != nil {
		return err
	}
	err = s.dao.UpdateLocationSortByID(loc.OrderNo)
	if err != nil {
		return err
	}
	err = s.dao.DelLocation(locationID)
	return err
}

// UpdateLocationSort 更新顺序
func (s *MessageServ) UpdateLocationSort(locations string) error {
	if locations == "" {
		return utils.LogError("没有需要修改的5A信息！")
	}
	arrlocation := strings.Split(locations, ",")
	for _, loc := range arrlocation {
		loc := strings.Split(loc, ":")
		if len(loc) < 2 {
			return utils.LogError("修改信息不全！")
		}
		err := s.dao.UpdateLocationSort(loc)
		if err != nil {
			return err
		}
	}
	return nil
}
