<?php

namespace app\person\validate;

use think\Validate;
use app\common\model\EducationSchool;

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

    protected $rule = [
        "enterpriseName" => "require",
        "enterpriseAddress" => "require",
        "address" => "require",
        "phone" => "require|mobile",
        "cName" => "require",
        "cSex" => "require",
        "cIdcard" => "require|checkIdCard",
        "cBirthday" => "require",
        "cRelation" => "require",
        "nowSchool" => "require",
        "nowGrade" => "require",
        "project" => "require|checkApplySchool",
        "companyStreet" => "require",
        "houseStreet" => "require",
        "year" => "require|checkExistThisYear",
        "personId" => "require",
        "talentId" => "require"
    ];
    protected $message = [
        "enterpriseName.require" => "工作单位不能为空",
        "enterpriseAddress.require" => "工作单位详细地址不能为空",
        "address.require" => "现居地址不能为空",
        "phone.require" => "联系电话不能为空",
        "phone.mobile" => "联系电话格式不合法",
        "cName.require" => "子女姓名不能为空",
        "cSex.require" => "子女性别不能为空",
        "cIdcard.require" => "子女证件号码不能为空",
        "cBirthday.require" => "子女出生日期不能为空",
        "cRelation.require" => "与申报人关系不能为空",
        "nowSchool.require" => "现就读学校不能为空",
        "nowGrade.require" => "现就读年级不能为空",
        "project.require" => "申报项目不能为空",
        "companyStreet.require" => "工作单位所属镇街不能为空",
        "houseStreet.require" => "房产所在镇街不能为空",
        "year.require" => "批次不能为空",
        "personId.require" => "申报人信息不能为空",
        "talentId.require" => "申报人人才申报信息不能为空",
    ];

    protected function checkExistThisYear($value, $rule, $data = []) {
        $where[] = ["year", "=", $value];
        $where[] = ["personId", "=", $data["personId"]];
        $where[] = ["cIdcard", "=", $data["cIdcard"]];
        if ($data["id"]) {
            $where[] = ["id", "<>", $data["id"]];
        }
        $count = EducationSchool::where($where)->count();
        if ($count > 0) {
            return "该子女当年度已有申报记录，添加失败";
        }
        return true;
    }

    protected function checkApplySchool($value, $rule, $data = []) {
        if ($value == 1 && \StrUtil::isEmpOrNull($data["applySchool"])) {
            return "拟申请学校不能为空";
        }
        return true;
    }

    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 "子女证件号码不合法！";
        return true;
    }

}
