package cases

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

// GetEquipmentList 获取体检设备
func (m *CaseDAO) GetEquipmentList(caseids string, page, pageSize int) ([]model.SysCaseEquipment, error) {
	var equipments []model.SysCaseEquipment
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("case_id in ('"+strings.Replace(caseids, ",", "','", -1)+"')").Limit(pageSize, (page-1)*pageSize).Find(&equipments)
	return equipments, err
}

// GetEquipmentCount 获取体检设备总数
func (m *CaseDAO) GetEquipmentCount(caseids string) (int, error) {
	var caseEquipment []model.SysCaseEquipment
	err := m.db.Where("status>" + strconv.Itoa(models.STATUS_DEL)).And("case_id in ('" + strings.Replace(caseids, ",", "','", -1) + "')").Find(&caseEquipment)
	return len(caseEquipment), err
}

// GetCaseEquipmentByID 根据ID获取体检设备
func (m *CaseDAO) GetCaseEquipmentByID(equipmentid string) (*model.SysCaseEquipment, error) {
	var caseEquipment []model.SysCaseEquipment
	err := m.db.Where("status>"+strconv.Itoa(models.STATUS_DEL)).And("equipment_id=?", equipmentid).Find(&caseEquipment)
	if err != nil {
		return nil, err
	}
	if len(caseEquipment) > 0 {
		return &caseEquipment[0], nil
	}
	return nil, nil
}

// AddCaseEquipment 新增体检设备
func (m *CaseDAO) AddCaseEquipment(caseEquipment *model.SysCaseEquipment) (*model.SysCaseEquipment, error) {
	caseEquipment.EquipmentId = utils.GetGUID()
	caseEquipment.Status = models.STATUS_NORMAL
	caseEquipment.CreateDate = time.Now()
	user := m.ctx.Get("user").(model.SysUser)
	caseEquipment.CreateUser = user.UserId
	_, err := m.db.Insert(caseEquipment)
	return caseEquipment, err
}

// UpdateCaseEquipment 修改体检设备
func (m *CaseDAO) UpdateCaseEquipment(caseEquipment model.SysCaseEquipment) error {
	var cols = []string{
		"name",
		"equipment_code",
		"case_id",
	}
	_, err := m.db.Cols(cols...).Where("equipment_id=?", caseEquipment.EquipmentId).Update(caseEquipment)
	return err
}

// DelCaseEquipment 刪除体检设备
func (m *CaseDAO) DelCaseEquipment(equipmentid string) error {
	var caseEquipment = model.SysCaseEquipment{
		EquipmentId: equipmentid,
		Status:      models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("equipment_id=?", caseEquipment.EquipmentId).Update(caseEquipment)
	return err
}
