<?php
/**
 * Created by PhpStorm.
 * User: phpadmin
 * Date: 2020/11/26
 * Time: 23:20
 */

namespace app\controller\api\user;
use app\common\repositories\user\UserExtractRepository;
use think\facade\Cache;
use app\common\repositories\user\UserBankRepository;
use crmeb\basic\BaseController;
use think\App;
use think\facade\Db;

class UserBank extends BaseController
{
    public $repository;
    public $appid;
    public $appKey;
    public $secretKey;


    public function __construct(App $app,UserExtractRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
        $this->appid='24267127';
        $this->appKey='Utg2bxLY4is7h5DPehVZ63Q4';
        $this->secretKey='yfGMEAO6YQXIE2pqYMiH4MNBE1DcNhyO';
        $this->accessToken = Cache::get('access_token');
        if(!$this->accessToken){
            $this->getToken();
        }

    }




    function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);

        return $data;
    }

    /*获取access_token*/
    public  function  getToken()
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = 'client_credentials';
        $post_data['client_id'] = $this->appKey;
        $post_data['client_secret'] = $this->secretKey;
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);
        $res = $this->request_post($url, $post_data);
        $res = json_decode($res,true);
//        Db::name('log')->insert(['data'=>json_encode($res)]);
        $this->accessToken = Cache::set('access_token',$res['access_token'],86400);

    }

    /*营业执照识别*/
    public function  businessLicense(){
        $image_url = $this->request->param(['image_url']);
        if(!$image_url){
            return app("json")->fail("参数丢失");
        }
        $token =  $this->accessToken;
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=' . $token;
        $img = file_get_contents($image_url['image_url']);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $res = $this->request_post($url, $bodys);
        $res = json_decode($res,true);
        $data['credit_code'] = $res['words_result']['社会信用代码']['words']??'';
        $data['business_addr'] = $res['words_result']['地址']['words']??'';
        $data['mer_name'] = $res['words_result']['单位名称']['words']??'';
        return app("json")->success("ok",$data);
    }

    /*银行卡识别*/
    public function bankCardGet(){
        $image_url = $this->request->param(['image_url']);
        if(!$image_url){
          return app("json")->fail("参数丢失");
        }
        $image_url=$this->resize_image($image_url['image_url']);
        $image_url="http://" . $this->request->host(true) .$image_url;
//        Db::name('log')->insert(['data'=>$image_url]);
        $token = $this->accessToken;
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard?access_token=' . $token;
        $img = file_get_contents($image_url);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $res = $this->request_post($url, $bodys);
//        Db::name('log')->insert(['data'=>$res]);
        $res = json_decode($res,true);
        $res['result']['icon'] = '';
        $res['result']['bank_card_number'] = '';
        if(isset($res['result']['bank_card_number'])){
            $res['result']['bank_card_number'] = preg_replace('# #', '', $res['result']['bank_card_number']);
        }
        return app("json")->success("ok",$res['result']);
    }

    public function resize_image($img_url)
    {
//        https://app.bjtdba.com/uploads/def/20210302/2d31574c539cfec5080f07446a25dcf7.jpg
//                             '/uploads/def/20220104/414831.jpg';
        $filename =$img_url;
        $percent = 0.4;
        $rand=rand(111111,999999);
        $newname='./public/uploads/def/'.date('Ymd').'/'.$rand.'.jpg';
        if(!is_dir('./public/uploads/def/'.date('Ymd').'/')){
            mkdir('./public/uploads/def/'.date('Ymd'),0777,true);
        }
        list($width, $height) = getimagesize($filename);
        $new_width = $width * $percent;
        $new_height = $height * $percent;
        $image_p = imagecreatetruecolor($new_width, $new_height);
        $image = imagecreatefromjpeg($filename);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        if(!imagejpeg($image_p,$newname)){
//            Db::name('log')->insert(['data'=>'文件添加失败']);
            return 12312312;
        }
        return '/uploads/def/'.date('Ymd').'/'.$rand.'.jpg';
    }
    public  function  account(){
        $image_url = $this->request->param(['image_url']);
        if(!$image_url){
            return app("json")->fail("参数丢失");
        }
        $token = $this->accessToken;
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $token;
        $img = file_get_contents($url);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img
        );
        $res = $this->request_post($url, $bodys);
        var_dump($res);
    }

    /**
     * 银行卡列表
     */
    public function listBank()
    {
        $where['user_id'] = $this->request->uid();
        $result =  $this->repository->listBank($where);
        return app("json")->success($result);
    }

    /*添加银行卡*/
    public function createBank(){

//        $data = $this->request->param(['account','valid_date','bank_card_type','bank_name','user_name','phone','user_card','bank_open_name']);
        $data = $this->request->param(['account','bank_card_type','bank_name','user_name','user_card','bank_open_name','pic']);
        $data['user_id'] = $this->request->uid();
        $result =  $this->repository->createBank($data);
        if(isset($result['code']) && $result['code'] == 400){
            return app("json")->fail($result['msg']);
        }
        return app("json")->success('添加成功',$result);
    }



    /*更换银行卡*/
    public function  changeBank($id){
//        if(!$id){
//            return  app("json")->fail("参数丢失");
//        }
        $data = $this->request->param(['account','bank_card_type','bank_name','user_name','user_card','bank_open_name','pic']);
//        $data = $this->request->param(['account','valid_date','bank_card_type','bank_name','user_name','phone']);
        $data['user_id'] = $this->request->uid();
        $data['info'] = $data['user_name'];
//        $where['id'] = $id;
        $where['user_id'] = $this->request->uid();
        $where['account_type'] = 3;
        return app("json")->success('更换成功',$this->repository->saveBank($where,$data));
    }

}
