package cases

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

	"github.com/astaxie/beego"
)

// GetKeysByCase 根据案场获取钥匙信息
func (s *CaseServ) GetKeysByCase(caseid, num string, page, pageSize int) (map[string]interface{}, error) {
	cases := s.ctx.Get("cases").([]model.SysUserCase)
	isdict := false
	for _, value := range cases {
		if caseid == value.CaseId {
			isdict = true
		}
	}

	if !isdict {
		return nil, utils.LogError("您没有该案场的权限！")
	}

	if pageSize == 0 {
		pageSize = service.PAGENUM
	}

	keys, err := s.dao.GetKeysByCase(caseid, num, page, pageSize)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	total, err := s.dao.GetKeysCountByCase(caseid, num)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	for index, key := range keys {
		use, err := s.dao.GetCurrentKey(key.KeyId)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
		if use != nil {
			keys[index].CustomerId = use.CustomerId
			keys[index].CustomerName = use.CustomerName
		}
	}

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

// AddKeys 保存钥匙
func (s *CaseServ) AddKeys(orgid, caseid string, beginnum, endnum int) error {
	if endnum < beginnum {
		return utils.LogError("锁柜编号起始编号不能大于截止编号！")
	}

	keys, err := s.dao.GetKeyByNum(caseid, beginnum, endnum)
	if err != nil {
		return err
	}
	if len(keys) > 0 {
		return utils.LogError("锁柜编号存在重复！请检查后再试！")
	}
	for i := beginnum; i <= endnum; i++ {
		key := model.TaCaseKey{
			OrgId:      orgid,
			CaseId:     caseid,
			LockNum:    strconv.Itoa(i),
			LockNo:     i,
			KeyId:      utils.GetGUID(),
			Status:     cases.STATUS_UNLOCK,
			CreateDate: time.Now(),
		}
		_, err := s.dao.AddKey(key)
		if err != nil {
			return err
		}
	}
	return nil
}

// UnLockKey 解锁
func (s *CaseServ) UnLockKey(keyid string) error {
	err := s.dao.UnLockKey(keyid)
	return err
}

// DelKey 刪除
func (s *CaseServ) DelKey(keyid string) error {
	use, err := s.dao.GetCurrentKey(keyid)
	if err != nil {
		return err
	}

	if use != nil {
		return utils.LogError("当前锁柜未解锁！请先解锁再删除！")
	}

	err = s.dao.DelKey(keyid)
	return err
}
