package cases

import (
	"spaceofcheng/services/models/cases"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service"
	"spaceofcheng/services/utils"

	"github.com/astaxie/beego"
)

// GetCaseArea 获取案场区域
func (s *CaseServ) GetCaseArea(caseids string, page int, pageSize int) (map[string]interface{}, error) {
	if pageSize == 0 {
		pageSize = service.PAGENUM
	}
	if page == 0 {
		page = 1
	}
	areas, err := s.dao.GetCaseArea(caseids, page, pageSize)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	total, err := s.dao.GetCaseAreaCount(caseids)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	return map[string]interface{}{
		"list":     areas,
		"pagesize": pageSize,
		"pagenum":  total,
		"page":     page,
	}, err
}

// GetCaseAreaByID 根据区域ID获取区域
func (s *CaseServ) GetCaseAreaByID(areaid string) (*model.SysCaseArea, error) {
	areas, err := s.dao.GetCaseAreaByID(areaid)
	return areas, err
}

// SaveCaseArea 保存区域
func (s *CaseServ) SaveCaseArea(area model.SysCaseArea) (*model.SysCaseArea, error) {
	var err error
	if area.AreaName == "" {
		return nil, utils.LogError("区域名称不能为空！")
	}

	if area.AreaId == "" {
		_, err = s.dao.AddCaseArea(&area)
	} else {
		err = s.dao.UpdateCaseArea(area)
	}
	return &area, err
}

// DelCaseArea 删除区域
func (s *CaseServ) DelCaseArea(areaid string) error {
	err := s.dao.DelCaseArea(areaid)
	return err
}

// GetAreaByCase 根据案场获取区域信息
func (s *CaseServ) GetAreaByCase(caseid string) ([]cases.AreaInfo, error) {
	areas, err := s.dao.GetCaseAreaByCase(caseid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	for index, area := range areas {
		tables, err := s.dao.GetCaseTableByAreaID(area.AreaId)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
		areas[index].Tables = tables
	}

	return areas, nil
}
