package cases

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

// GetCaseUserByCase 根据案场id获取案场相关人员
func (m *CaseDAO) GetCaseUserByCase(caseid string, page int, pageSize int) ([]model.SysCaseUser, error) {
	var caseusers []model.SysCaseUser
	err := m.db.Where("case_id=?", caseid).And("status>"+strconv.Itoa(models.STATUS_DEL)).Limit(pageSize, (page-1)*pageSize).Find(&caseusers)
	return caseusers, err
}

// GetCaseUserCount 列表数量
func (m *CaseDAO) GetCaseUserCount(caseid string) (int, error) {
	var caseusers []model.SysCaseUser
	err := m.db.Where("case_id=?", caseid).And("status>" + strconv.Itoa(models.STATUS_DEL)).Find(&caseusers)
	if err != nil {
		return 0, err
	}
	return len(caseusers), nil
}

// GetCaseUserByID 根据id获取相关人员
func (m *CaseDAO) GetCaseUserByID(userid string) (*model.SysCaseUser, error) {
	var caseusers []model.SysCaseUser
	err := m.db.Where("case_user_id=?", userid).And("status>" + strconv.Itoa(models.STATUS_DEL)).Find(&caseusers)
	if err != nil {
		return nil, err
	}
	if len(caseusers) > 0 {
		return &caseusers[0], nil
	}
	return nil, nil
}

// GetCaseUserByUserType 根据用户类型获取相关人员
func (m *CaseDAO) GetCaseUserByUserType(caseid, usertype string) ([]model.SysCaseUser, error) {
	var caseusers []model.SysCaseUser
	err := m.db.Where("case_id=?", caseid).And("user_type=?", usertype).And("status>" + strconv.Itoa(models.STATUS_DEL)).Find(&caseusers)
	return caseusers, err
}

// AddCaseUser 新增案场相关人员
func (m *CaseDAO) AddCaseUser(caseuser model.SysCaseUser) (*model.SysCaseUser, error) {
	caseuser.CreateDate = time.Now()
	caseuser.Status = models.STATUS_NORMAL
	caseuser.CaseUserId = utils.GetGUID()
	_, err := m.db.Insert(caseuser)
	return &caseuser, err
}

// UpdateCaseUser 修改案场相关人员
func (m *CaseDAO) UpdateCaseUser(caseuser model.SysCaseUser) error {
	var cols = []string{
		"user_name",
		"tel",
		"user_type",
	}
	_, err := m.db.Cols(cols...).Where("case_user_id=?", caseuser.CaseUserId).Update(caseuser)
	return err
}

// DelCaseUser 删除案场相关人员
func (m *CaseDAO) DelCaseUser(caseuserid string) error {
	var caseuser = model.SysCaseUser{
		CaseUserId: caseuserid,
		Status:     models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("case_user_id=?", caseuserid).Update(caseuser)
	return err
}
