<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/13
 * Time: 9:53
 */
namespace Modules\Project\Services;

use Modules\Project\Entities\Bank;
use Modules\Project\Entities\Card;

class CardService extends BaseService
{
    public function __construct(Card $card, Bank $bank)
    {
        $this->model = $card;
        $this->bankModel = $bank;
    }

    public function update($id, $data)
    {
        return parent::update($id, $data); // TODO: Change the autogenerated stub
    }

    public function delete($id)
    {
        $this->model = $this->model->find($id);

        return $this->model->delete($id);
    }

    public function insert($data)
    {
        $user_id = \Auth()->id();
        $has_default = $this->model->where('user_id', $user_id)->where('is_default', 1)->exists();
        $data['is_default'] = $has_default ? 0 : 1;
        $data['user_id'] = $user_id;

        $bank = $this->bankModel->where('code', $data['code'])->first();
        if ($bank) {
            $data['org'] = $bank->org;
        }

        return $this->model = $this->model->create($data);
    }

    public function checkUserCard($id)
    {
        $user_id = \Auth()->id();
        $has_card = $this->model->where('user_id', '=', $user_id)->where('id', '=', $id)->exists();
        if ($has_card) {
            return 1;
        } else {
            abort(404, '要操作的银行卡不存在');
        }
    }

    public function setDefault($card_id)
    {
        $user_id = \Auth()->id();
        $this->model->where('user_id', $user_id)->update(['is_default' => 0]);

        return $this->update($card_id, ['is_default' => 1]);
    }

    public function verifyBankNumber($card_number)
    {
        $info = $this->get_bank_info($card_number);

        if ($info['validated'] == 1) {
            $return['code'] = $info['bank'];
            $return['type'] = $info['cardType'];

            return $return;
        } else {
            $error = \Illuminate\Validation\ValidationException::withMessages([
                'number' => ['银行卡验证失败'],
            ]);
            throw $error;
        }
    }

    /**
     * 获取银行卡号接口参数
     *
     * @param string $card_number 银行卡号
     *
     * @return string
     */
    private function get_bank_info($card_number = '')
    {
        $url = 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo='.$card_number.'&cardBinCheck=true';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // https请求 不验证证书和hosts
        $respond = curl_exec($ch);
        curl_close($ch);

        $arr = explode(PHP_EOL, $respond);
        $info = json_decode(end($arr), true);

        return $info;
    }
}
