<?php

namespace app\common\validate;

use think\Validate;
use app\common\model\Person as PersonModel;

class Person extends Validate {

    protected $rule = [
        'username' => 'require|max:50|unique:un_person',
        'password' => 'require',
        'name' => 'require|max:100',
        'idCard' => 'require|checkIdCard',
        'sex' => 'require',
        'phone' => 'require|mobile|unique:un_person',
        'address' => 'max:100',
        'email' => 'email'
    ];
    protected $message = [
        'username.require' => '请填写账号!',
        'username.max' => '账号最多50个字符!',
        'username.unique' => '该账号已被注册',
        'password.require' => '请填写密码!',
        'name.require' => '请输入姓名',
        'name.max' => '姓名最多100个字符!',
        'idCard.require' => '请填写证件号码!',
        'sex.require' => '性别必须选择',
        'phone.require' => '请填写手机号',
        "phone.mobile" => "请填写正确的手机号",
        'phone.unique' => '该手机号已被注册',
        'address.max' => '联系地址最多100个字符!',
        'email.email' => '不是正确的邮箱格式'
    ];

    protected function checkIdCard($value, $rule, $data = []) {
        if (!\app\common\api\IdCardApi::isValid($value) && !preg_match("/^([a-zA-z]|[0-9]){5,17}$/", $value) && !preg_match("/^[a-zA-Z0-9]{6,10}$/", $value) && !preg_match("/^([0-9]{8}|[0-9]{10})$/", $value))
            return "请填写正确的证件号码！";
        $info = PersonModel::where('idCard', $value)->where('active', 1)->where('id', '<>', $data['id'])->find();
        if ($info) {
            return "该证件号码已被注册";
        } else {
            return true;
        }
    }

    protected $scene = [
        'add' => ['username', 'password', 'name', 'idCard', 'sex', 'phone'],
        'basic' => ['address'],
    ];

}
