<?php
namespace backend\models\forms;

use backend\models\MailApi;
use backend\models\OpenApi;
use backend\models\SmsApi;
use common\helpers\Idcard;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;

class OpenForm extends Model
{
    public $card0;
    public $card1;
    public $name;
    public $id_card;
    public $email;
    public $mobile;
    public $vcode;
    public $level;
    public $rid;
    public $address;
    public $agree1;
    public $agree2;
    public $agree3;
    public $agree4;
    public $agree5;
    public $agree6;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['card0', 'required', 'message' => '请选择身份证正面照片'],
            ['card0', 'file'],
            ['card1', 'required', 'message' => '请选择身份证反面照片'],
            ['card1', 'file'],
            ['name', 'required', 'message' => '请填写姓名'],
            ['id_card', 'required', 'message' => '身份证号码格式错误'],
            ['id_card', 'checkIdCard'],
            ['email', 'required', 'message' => '请填写电子邮箱'],
            ['email', 'email'],
            //['mobile', 'required', 'message' => '请填写手机号码'],
            //['mobile', 'match', 'pattern' => '/^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\d{8}$/'],
            ['vcode', 'required', 'message' => '请填写邮件验证码'],
            ['vcode', 'checkMailVcode'],
            ['level', 'required'],
            ['level', 'in', 'range' => [100, 200]],
            ['rid', 'integer'],
            ['address', 'required', 'message' => '请填写地址'],
            [['agree1', 'agree2'], 'boolean', 'trueValue' => 'on'],
        ];
    }

    /**
     * @param string $attribute
     * @param array $params
     */
    public function checkIdCard($attribute, $params = [])
    {
        if (!$this->hasErrors()) {
            if (Idcard::getInstance()->isChinaIDCard($this->id_card) == false) {
                $this->addError($attribute, '身份证号码格式错误');
            }
        }
    }

    /**
     * @param string $attribute
     * @param array $params
     */
    public function checkVcode($attribute, $params = [])
    {
        if (!$this->hasErrors()) {
            $api = new SmsApi();
            $result = $api->getCode($this->mobile);
            if ($result['code'] == 1) {
                $code = isset($result['data']['code']) ? trim($result['data']['code']) : '';
                $created = isset($result['data']['created']) ? trim($result['data']['created']) : 0;
                if ($code == $this->vcode && (intval($created / 1000) + 1800) >= time()) {
                    // 验证码正确 有效
                } else {
                    $this->addError($attribute, '手机验证码错误');
                }
            }
        }
    }

    /**
     * @param string $attribute
     * @param array $params
     */
    public function checkMailVcode($attribute, $params = [])
    {
        if (!$this->hasErrors()) {
            $api = new MailApi();
            $result = $api->getMailCode($this->email);
            if ($result['code'] == 1) {
                $code = isset($result['data']['code']) ? trim($result['data']['code']) : '';
                $created = isset($result['data']['created']) ? trim($result['data']['created']) : 0;
                if ($code == $this->vcode && (intval($created / 1000) + 1800) >= time()) {
                    // 验证码正确 有效
                } else {
                    $this->addError($attribute, '邮件证码错误');
                }
            }
        }
    }

    /**
     * @return bool
     */
    public function open()
    {
        if ($this->validate()) {
            $api = new OpenApi();
            $data = [];
            $data['name'] = $this->name;
            $data['id_card'] = $this->id_card;
            $data['email'] = $this->email;
            $webRoot = Yii::getAlias('@webroot');
            if ($this->card0 instanceof UploadedFile) {
                $filename = false;
                for ($i = 0; $i < 2; $i++) {
                    $temp = '/upload/' . date('YmdHis_') . mt_rand(10000, 99999) . '.' . $this->card0->getExtension();
                    if (!is_file($webRoot . $temp)) {
                        $filename = $temp;
                        break;
                    }
                }
                if ($filename != false && $this->card0->saveAs($webRoot . $filename)) {
                    $data['id_card_file_path0'] = $filename;
                }
            }
            if ($this->card1 instanceof UploadedFile) {
                $filename = false;
                for ($i = 0; $i < 2; $i++) {
                    $temp = '/upload/' . date('YmdHis_') . mt_rand(10000, 99999) . '.' . $this->card1->getExtension();
                    if (!is_file($webRoot . $temp)) {
                        $filename = $temp;
                        break;
                    }
                }
                if ($filename != false && $this->card1->saveAs($webRoot . $filename)) {
                    $data['id_card_file_path1'] = $filename;
                }
            }
            $data['rid'] = $this->rid;
            $data['address'] = $this->address;
            $data['level'] = $this->level;
            $result = $api->open($data);
            if ($result['code'] == 1) {
                return true;
            } else {
                if (is_array($result['message'])) {
                    $this->addErrors($result['message']);
                } else {
                    $this->addError('name', $result['message']);
                }
            }
        }
        return !$this->hasErrors();
    }
}