package cases

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

// GetCaseAreaCount 获取案场区域总数
func (m *CaseDAO) GetCaseAreaCount(caseids string) (int, error) {
	var areas []model.SysCaseArea
	dao := m.db.Where("status>" + strconv.Itoa(models.STATUS_DEL)).And("case_id in ('" + strings.Replace(caseids, ",", "','", -1) + "')")
	err := dao.Find(&areas)
	return len(areas), err
}

// GetCaseArea 根据案场获取案场区域
func (m *CaseDAO) GetCaseArea(caseids string, page int, pageSize int) ([]model.SysCaseArea, error) {
	var areas []model.SysCaseArea
	dao := m.db.Where("status>" + strconv.Itoa(models.STATUS_DEL)).And("case_id in ('" + strings.Replace(caseids, ",", "','", -1) + "')")
	err := dao.Limit(pageSize, (page-1)*pageSize).Find(&areas)
	return areas, err
}

// AreaInfo 案场区域
type AreaInfo struct {
	model.SysCaseArea `xorm:"extends"`
	Tables            []model.SysCaseTable
}

// GetCaseAreaByCase 根据案场获取案场区域
func (m *CaseDAO) GetCaseAreaByCase(caseid string) ([]AreaInfo, error) {
	var areas []AreaInfo
	sql := `select * from sys_case_area where status>` + strconv.Itoa(models.STATUS_DEL) + ` and case_id ='` + caseid + `'`
	err := m.db.Sql(sql).Find(&sql)
	return areas, err
}

// GetCaseAreaByID 根据ID获取案场区域
func (m *CaseDAO) GetCaseAreaByID(specid string) (*model.SysCaseArea, error) {
	var areas []model.SysCaseArea
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("area_id=?", specid).Find(&areas)
	if err != nil {
		return nil, err
	}
	if len(areas) > 0 {
		return &areas[0], nil
	}
	return nil, nil
}

// AddCaseArea 新增案场区域
func (m *CaseDAO) AddCaseArea(area *model.SysCaseArea) (*model.SysCaseArea, error) {
	area.AreaId = utils.GetGUID()
	area.Status = models.STATUS_NORMAL
	area.CreateDate = time.Now()
	user := m.ctx.Get("user").(model.SysUser)
	area.CreateUser = user.UserId
	_, err := m.db.Insert(area)
	return area, err
}

// UpdateCaseArea 修改案场区域
func (m *CaseDAO) UpdateCaseArea(area model.SysCaseArea) error {
	var cols = []string{
		"area_name",
		"area_icon",
		"area_icon_white",
		"order",
		"case_id",
	}
	_, err := m.db.Cols(cols...).Where("area_id=?", area.AreaId).Update(area)
	return err
}

// DelCaseArea 刪除案场区域
func (m *CaseDAO) DelCaseArea(areaid string) error {
	var area = model.SysCaseArea{
		AreaId: areaid,
		Status: models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("area_id=?", area.AreaId).Update(area)
	return err
}
