<?php
namespace app\common\model;

use app\hander\HelpHander;
use think\Db;
use think\Model;

class AssetAdd extends Model
{

    public function add(){
        $data = [
            'id' => input('id/d',0),
            'title' => input('title','','trim'),
            'org_id' => input('orgId/d',0),
        ];

        $result = validate('AssetAdd')->check($data,[],'');
        if(true !== $result){
            HelpHander::error(validate('AssetAdd')->getError());
        }
        $id = $data['id'];
        unset($data['id']);
        if($id > 0){
            $ret = $this->allowField(true)->save($data,['id'=>$id]);
        }else{
            $ret = $this->allowField(true)->save($data);
        }
        if(!$ret){
            HelpHander::error('操作失败');
        }
        return true;
    }

    public function info($id){
        $info = $this->where('id',$id)->find();
        if(!$info){
            HelpHander::error('数据不存在');
        }
        return $info->toArray();
    }

    public function lists($page,$size,$title,$orgId){
        $map[] = ['org_id','=',$orgId];
        if($title){
            $map[] = ['title','like','%'.$title.'%'];
        }

        $lists = $this
            ->where($map)
            ->page($page,$size)
            ->order('id desc')
            ->select();

        $total = $this->where($map)->count();
        $data = [
            'total' => $total,
            'list' => $lists?$lists->toArray():[]
        ];
        return $data;
    }

    public function all($orgId){
        $map[] = ['org_id','=',$orgId];
        $lists = $this
            ->where($map)
            ->field('id,title')
            ->order('sort asc,id asc')
            ->select();
        return $lists?$lists->toArray():[];
    }

    public function del($id){
        // 检查是否已被使用
        $info = Db::name('asset_items')
            ->where('add_id',$id)
            ->find();
        if($info){
            HelpHander::error('已被使用,无法删除');
        }

        $ret = $this->where('id',$id)->delete();
        if(!$ret){
            HelpHander::error('删除失败');
        }
        return true;
    }

}