<?php
namespace app\common\validate;

use think\Db;
use think\Validate;

class AppIcon extends Validate{

    protected $rule = [
        'name|名称'  =>  'require|checkUnique|length:1,20',
        'mode'  =>  'require|checkMode',
        'icon'  =>  'require',
    ];

    protected $message = [
        'name.length' => '名称必须20字以内',
        'icon.require' => '未选择图标',
    ];

    protected $scene = [

    ];

    // 自定义验证规则
    protected function checkUnique($value,$rule,$data=[])
    {
        $info = Db::name('app_icon')->where('name',$data['name'])->where('del',0)->find();
        if($data['id'] <= 0 && $info){
            return '名称已被使用';
        }
        if($info && $data['id'] > 0 && $info['id'] != $data['id']){
            return '名称已被使用';
        }
        return true;
    }

    protected function checkMode($value,$rule,$data=[])
    {
        $info = Db::name('app_icon')->where('mode',$data['mode'])->where('del',0)->find();
        if($data['id'] <= 0 && $info){
            return '标识已被使用';
        }
        if($info && $data['id'] > 0 && $info['id'] != $data['id']){
            return '标识已被使用';
        }
        return true;
    }

}