<?php
namespace app\workerapi\validate;
use app\common\validate\BaseValidate;

/**
 * @author 林海涛
 * @date 2024/7/10 下午3:41
 */
class MasterWokerInfoValidate  extends BaseValidate
{
    protected $rule = [
        'real_name' => 'require',
        'id_card' => 'require|checkIdCard',
        'id_card_front_img' => 'require',
        'id_card_opposite_img' => 'require',
        'mobile' => 'require|mobile',
        'address' => 'require'
    ];

    protected $message = [
        'real_name.require' => '请输入真实姓名',
        'id_card.require' => '请输入身份证号',
        'id_card.checkIdCard' => '身份证格式有误',
        'id_card_front_img.require' => '请上传身份证正面照',
        'id_card_opposite_img.require' => '请上传身份证反面照',
        'mobile.require' => '请输入手机号',
        'mobile.mobile' => '手机号格式不正确',
        'address.mobile' => '请输入地址',

    ];

    public function checkIdCard($idcard)
    {
        if(empty($idcard)){
            return false;
        }else{
            $idcard = strtoupper($idcard); # 如果是小写x,转化为大写X
            if(strlen($idcard) != 18 && strlen($idcard) != 15){
                return false;
            }
            # 如果是15位身份证，则转化为18位
            if(strlen($idcard) == 15){
                # 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
                if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) {
                    $idcard = substr($idcard, 0, 6) . '18' . substr($idcard, 6, 9);
                } else {
                    $idcard = substr($idcard, 0, 6) . '19' . substr($idcard, 6, 9);
                }
                # 加权因子
                $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                # 校验码对应值
                $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $checksum = 0;
                for ($i = 0; $i < strlen($idcard); $i++) {
                    $checksum += substr($idcard, $i, 1) * $factor[$i];
                }
                $idcard = $idcard . $code[$checksum % 11];
            }
            # 验证身份证开始
            $IDCardBody = substr($idcard, 0, 17); # 身份证主体
            $IDCardCode = strtoupper(substr($idcard, 17, 1)); # 身份证最后一位的验证码

            # 加权因子
            $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            # 校验码对应值
            $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $checksum = 0;
            for ($i = 0; $i < strlen($IDCardBody); $i++) {
                $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
            }
            $validateIdcard = $code[$checksum % 11];    # 判断身份证是否合理
            if($validateIdcard != $IDCardCode){
                return false;
            }else{
                return true;
            }
        }
    }

    public function sceneChangeIdCard()
    {
         return $this->only(['real_name', 'id_card','id_card_front_img','id_card_opposite_img','mobile','address']);
    }
}
