<?php

namespace Modules\Project\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use SMG\Support\Traits\HasHttpRequest;

class DistributorRequest extends FormRequest
{
    use HasHttpRequest;

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $request = $this;
        if (!isset($this->id_type)) {
            $this['id_type'] = '身份证';
        }

        switch ($this->method()) {
            case 'POST':
                $user = \Auth::user();
                $userId = $user->id;

                return [
                    'true_name' => 'required|between:[2,20]|regex:/^([\xe4-\xe9][\x80-\xbf]{2}){2,20}$/',
                    'id_card_no' => [
                        'required',
                        //'between:15,18',
                        function ($attribute, $value, $fail) use ($request) {
                            $user = \Auth::user();
                            $distributor = $user->distributor()->exists();
                            if ($distributor) {
                                return $fail($attribute.' '.'error_msg:已提交申请');
                            }

                            $info = $this->get_card_info($value);
                            if (is_array($info) && $info['error_code'] !== 0) {
                                return $fail($attribute.' '.'error_code:'.$info['error_code'].':'.$info['reason']);
                            }
                        },
                    ],
                    'phone' => 'bail|required|regex:/^1[345789][0-9]{9}$/',
                    'file_id_1' => 'exists:files,id,type,distributor,user_id,'.$userId,
                    'file_id_2' => 'exists:files,id,type,distributor,user_id,'.$userId,
                ];

                break;
            case 'PUT':
                return [

                ];
                break;
        }
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 获取聚合查询身份证信息接口参数
     *
     * @param string $id_card_no 号码
     * @param string $dtype      返回数据格式
     *
     * @return string
     */
    private function get_card_info($id_card_no = '', $dtype = 'json')
    {
        $appkey = '68fde9f67cf6cf0b6867bc606c42d456';

        $url = 'http://apis.juhe.cn/idcard/index';
        $params = [
            'cardno' => $id_card_no,//身份证号码
            'dtype' => $dtype,//返回数据格式：json或xml,默认json
            'key' => $appkey,//你申请的key
        ];

        $respond = $this->httpGet($url, $params);

        return $respond;
    }
}
