package cases

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

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

// CaseTableInfo 案场桌位
type CaseTableInfo struct {
	model.SysCaseTable `xorm:"extends"`
	AreaName           string
	CaseName           string
}

// GetCaseTable 根据案场获取桌位
func (m *CaseDAO) GetCaseTable(caseids string, page int, pageSize int) ([]CaseTableInfo, error) {
	var tables []CaseTableInfo
	sql := `select a.*,b.area_name,c.case_name from sys_case_table a 
	inner join sys_case_area b on a.area_id=b.area_id
	inner join sys_case c on a.case_id=c.case_id
	where a.status>` + strconv.Itoa(models.STATUS_DEL) + ` and b.status>` + strconv.Itoa(models.STATUS_DEL) +
		` and c.status>` + strconv.Itoa(models.STATUS_DEL) + ` and a.case_id in ('` +
		strings.Replace(caseids, ",", "','", -1) + `')`

	err := m.db.Sql(sql).Find(&tables)
	return tables, err
}

// GetCaseTableByAreaID 根据区域ID获取桌位信息
func (m *CaseDAO) GetCaseTableByAreaID(areaid string) ([]model.SysCaseTable, error) {
	var tables []model.SysCaseTable
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("area_id=?", areaid).Find(&tables)
	return tables, err
}

// GetCaseTableByID 根据ID获取桌位
func (m *CaseDAO) GetCaseTableByID(tableid string) (*model.SysCaseTable, error) {
	var tables []model.SysCaseTable
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("table_id=?", tableid).Find(&tables)
	if err != nil {
		return nil, err
	}
	if len(tables) > 0 {
		return &tables[0], nil
	}
	return nil, nil
}

// AddCaseTable 新增桌位
func (m *CaseDAO) AddCaseTable(area *model.SysCaseTable) (*model.SysCaseTable, error) {
	area.TableId = 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
}

// UpdateCaseTable 修改桌位
func (m *CaseDAO) UpdateCaseTable(area model.SysCaseTable) error {
	var cols = []string{
		"table_no",
		"order",
		"remark",
		"case_id",
		"area_id",
	}
	_, err := m.db.Cols(cols...).Where("table_id=?", area.TableId).Update(area)
	return err
}

// DelCaseTable 刪除桌位
func (m *CaseDAO) DelCaseTable(tableid string) error {
	var area = model.SysCaseTable{
		TableId: tableid,
		Status:  models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("table_id=?", area.TableId).Update(area)
	return err
}
