<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\admin\validate;

use think\Validate;

/**
 * Description of User
 *
 * @author sgq
 */
class User extends Validate {

    protected $rule = [
        'account' => 'require|max:50|checkUnique:sys_user',
        'name' => 'require|max:50|regex:/^[\x{4e00}-\x{9fa5}\(\)（）\da-zA-Z&]{2,50}$/u',
        'type' => 'require|checkInSelect:type,1,2,3,4,5,6',
        'password' => 'require|min:8|regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$/',
        're_password' => 'require|confirm:password',
        'phone' => 'require|mobile',
        'companyId' => 'require',
        'roleId' => 'require',
        'email' => 'email',
        'birthday' => "dateFormat:Y-m-d",
        "sex" => "checkInSelect:sex,1,2"
    ];
    protected $message = [
        'account.require' => '请填写账户!',
        'account.max' => '账户最多50个字符!',
        'account.checkUnique' => '该账户已被注册',
        'name.require' => '请输入姓名',
        'name.max' => '姓名最多50个字符!',
        'name.regex' => '姓名只能是中文',
        'type.require' => "请选择账号类型",
        'password.require' => '请填写密码!',
        'password.min' => '密码最少长度8位',
        'password.regex' => '密码应包含字母与数字两种字符',
        're_password.require' => '请输入重复密码',
        're_password.confirm' => '两次密码输入不一致',
        "phone.require" => "请填写手机号",
        "phone.mobile" => "请填写正确的手机号",
        "companyId.require" => "请选择所属单位",
        "roleId.require" => "请选择角色",
        "email.email" => "电子邮箱格式错误",
        "birthday.dateFormat" => "生日必需是有效日期格式[yyyy-MM-dd]"
    ];
    protected $scene = [
        'add' => ['account', 'name', 'type', 'password', 're_password', 'phone', 'companyId', 'email', 'birthday', "sex"],
        'edit' => ['account', 'name', 'type', 'phone', 'companyId', 'email', 'birthday', "sex"],
        'info' => ['name', 'phone', 'email', 'birthday', "sex"],
        'change_pwd' => ['old_password', 'password', "re_password"],
    ];

    protected function checkUnique($value, $rule, $data = [], $field) {
        $db = $this->db->name($rule);
        $pk = $db->getPk();
        $map = [];
        $map[] = [$field, "=", $data[$field]];
        $map[] = ["status", "<>", 3];        
        if ($data[$pk]) {
            $map[] = [$pk, "<>", $data[$pk]];
        }
        if ($db->where($map)->field($pk)->find()) {
            return false;
        }
        return true;
    }

    protected function checkInSelect($value, $rule, $data = []) {
        $title = "";
        $select = explode(",", $rule);
        $type = array_shift($select);
        switch ($type) {
            case "type":
                $title = "账号类型";
                break;
            case "sex":
                $title = "性别";
                break;
        }
        return in_array($value, $select) ?: "{$title}只能在预设列表中选择";
    }

}
