<?php

namespace app\index\model;

use think\Model;
use app\index\model\BoxModel;
use think\exception\PDOException;

class CabinetModel extends Model{
    // 确定链接表名
    protected $name = 'cabinet';

    /**
     * 插入柜子信息
     * @param $param
     */
    public function insertCabinet($url,$alias,$count,$number,$login_key)
    {
        try
        {
            $this->startTrans();
            $result = $this->save(['req_url' => $url,'alias' => $alias,'box_count' => $count,'cabinet_code' => $number,'login_key' => $login_key]);
            if(false === $result){
                $this->rollback();
                return msg(-1, '', $this->getError());
            }
            else
            {
                $cabinet_number = intval($this->id);
                $boxData = [];
                for ($i=1; $i <= $count; $i++) {
                    $boxData['cabinet_number']  = $cabinet_number;
                    $boxData['box_number']      = $i;
                    $saveAllData[] = $boxData;
                }
                $BoxModel = new BoxModel();
                $result = $BoxModel->saveAll($saveAllData);

                if(false === $result){
                    $this->rollback();
                    return msg(-1, '', $this->getError());
                }else{
                    $this->commit();
                    return msg(1, '', '添加成功');
                }
            }
        }
        catch(PDOException $e){
            $this->rollback();
            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 根据搜索条件获取柜子列表信息
     * @param $where
     * @param $offset
     * @param $limit
     */
    public function getCabinetsByWhere()
    {
        return $this->order('id desc')->select();
    }

    /**
     * 根据搜索条件获取所有的柜子数量
     * @param $where
     */
    public function getAllCabinets()
    {
        return $this->count();
    }

}