<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;


class Index extends BaseController
{

    function pay(){
        return view();
    }

    protected $baseUrl = 'http://localhost';
    protected $client;


    public function initialize()
    {
        parent::initialize();

        $this->url_user = "http://pm.yz314.com/index.php/";
        $this->url_www  = "http://pm.yz314.com/index.php/";

        //$this->client = new \GuzzleHttp\Client( [ 'base_uri' => 'http://www.s.cn', 'http_errors' => false,  ]);
        $this->cookieJar = new \GuzzleHttp\Cookie\CookieJar();

        $options = [
            'base_uri' => $this->url_user,
            'timeout'  => 10.0,
            'cookies'  => $this->cookieJar,
            'cookies'  => true,
            //'proxy' => 'http://192.168.16.16:8888',
            // 'allow_redirects' => false,
        ];

        $options['proxy'] = 'http://192.168.16.96:8888';

        $this->client = new \GuzzleHttp\Client($options);


    }

    /**
     * @param $url
     * @param $method
     * @param $param
     * @param string $type
     * 'json' => ['foo' => 'bar']
     * 'multipart' => [    [    'name'     => 'field_name',    'contents' => 'abc'    ]]
     * @return mixed
     */
    function request($url, $method, $param, $header = [])
    {

        $method = strtolower($method);
        //if(empty($type)){
        //$type = ($method == 'post') ? 'form_params' : 'query';
        //}
        if (empty($header)) {
//            $header = [
//                'User-Agent' => 'testing/1.0',
//                'X-Wtfs-Signature'     => 'testtesttesttesttest-test-test-test-testtesttesttest',
//                'Referer' => 'http://pm.yz314.com//front/view/app/user/bindPhone.html',
//            ];
        }

        if ($method == 'post') {
            $r = $this->client->request('POST', $url, [
                "form_params" => $param,
                'cookies'     => $this->cookieJar,
                'headers'     => $header,
            ]);
        } else {
            $r = $this->client->request('GET', $url, [
                'query'   => $param,
                'cookies' => $this->cookieJar,
                'headers' => $header,
            ]);
        }
        return $r;

    }


    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V6<br/><span style="font-size:30px">13载初心不改 - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }

    protected $users = [
        [
            'keyID'     => '123456',
            'keySecret' => '',
        ]
    ];


    /**
     * $templateId
     * $param
     * $phone_number
     * countryID
     */
    function sms_send()
    {
        //Db::name('user');

        $param = I('paramValues');

        $dbUserInfo = [];
        $dbUserInfo['keyID']= "123456";
        $dbUserInfo['keySecret']= "12345678";



        $headerAuth = [];
        $postNonce= I('nonce');
        $postTime= I('time');
        $postKey_id = $headerAuth['key_id'];
        $postSign = $headerAuth['sign'];


        $sign = $this->makeSign($postNonce,$postTime,$dbUserInfo['key_secret']);
        if($sign != $postSign){
            $ret=[];
            $ret['code']=0;
            $ret['msg']='authentication failure';
            echo json_encode($ret);
            exit;
        }

        $templateId = I('template_id');
        $templateId = "sms_123456";
        $phoneNumber = I('phoneNumber'); //8615812345678

        $templateContent = '短信内容 {$content} [test]';
        $smsContent = str_replace('{$user}',$param['user'],$templateContent);

        $countryID = I('countryID');

        $countryID = 'CN';




        $url                     = "https://www.huaweiita.com:17131/apiaccess/sms/sendTemplateSms/v1";
        $params                  = [];
        $params['smsTemplateId'] = '695db7b5-6d4f-4791-aea0-f733f2ef06ce';

        $params['paramValues']   = $param; //        paramValues:{"user":"XXX"}
        $params['msisdn']        = $phoneNumber;
        $params['countryID']     = $countryID;


        $ret = curl_post_json($url, json_encode($params));











        //$sign      = "";


    }

    function makeSign($nonce,$time,$key){
        $signRawString = $nonce . $time . $key;
        return base64_encode(hash('sha256',$signRawString));

    }

    /**
     *
     * 检测签名
     */
    public function CheckSign()
    {

        $sign = $this->MakeSign();
        if($this->GetSign() == $sign){
            return true;
        }
        throw new WxPayException("签名错误！");
    }




    function send()
    {
        $url                     = "https://www.huaweiita.com:17131/apiaccess/sms/sendTemplateSms/v1";
        $params                  = [];
        $params['smsTemplateId'] = '695db7b5-6d4f-4791-aea0-f733f2ef06ce';
        $paramValues             = [];
        $paramValues['user']     = 'test1';
        $params['paramValues']   = $paramValues; //        paramValues:{"user":"XXX"}
        $params['msisdn']        = '8615821868265';
        $params['countryID']     = 'CN';


        $ret = curl_post_json($url, json_encode($params));
    }

    function province()
    {


        $r           = Db::name('province')->select();
        $all         = [];
        $all['name'] = 'all';

        $allProvince = [];
        foreach ($r as $k => $v) {

            $mCity                 = Db::name('city');
            $where                 = [];
            $where['provinceCode'] = $v['code'];
            $rCity                 = $mCity->where($where)->select()->toArray();
            //          echo  $mCity->getLastSql();
            //$cityNames = array_column($rCity,'name');
            $cityNames = [];
//var_dump($rCity);

            $cityOfCurrentProvince = [];
            foreach ($rCity as $kCity => $vCity) {
                $mArea                  = Db::name('area');
                $area                   = [];
                $where2                 = [];
                $where2['provinceCode'] = $vCity['provinceCode'];
                $where2['cityCode']     = $vCity['code'];
                $rArea                  = $mArea->where($where2)->select()->toArray();
                $areaNames              = array_column($rArea, 'name');

                $city             = [];
                $city['name']     = $vCity['name'];
                $city['children'] = $areaNames;

                $cityOfCurrentProvince[] = $city;

            }

            $province             = [];
            $province['name']     = $v['name'];
            $province['children'] = $cityOfCurrentProvince;

            $allProvince[] = $province;


        }
        $all['children'] = $allProvince;
        file_put_contents('./data.json', json_encode($all, JSON_UNESCAPED_UNICODE));
        dump($allProvince);
        exit;
    }


    function payment()
    {

        $url                     = "https://www.apifabric.com.cn/apiaccess/payment/paymentGateway/checkout/v1/payment";

        $params = [
            'originalAmount' => '6',
            'currency' => 'USD',
            'intent' => 'sale',
            'shortCode' => '100000703',
            'commodityDesc' => 'PGW payment',
            'note2Payer' => 'Good Choice',
            'merchantInvoiceNumber' => 'abc',
            'discountedAmount' => '1',
        ];

        $params['originalAmount'] = I('price');


        //$params = '{"originalAmount":"6","currency":"USD","intent":"sale","shortCode":"100000703","commodityDesc":"PGW payment","note2Payer":"Good Choice","merchantInvoiceNumber":"abc","discountedAmount":"1"}';

        //$params = var_export(json_decode($params,true),true);
        $params = json_encode($params);

        $headers[] = 'X-APP-Key: APP ID';
        $headers[] = 'Authorization:Bearer Access-Token';
        $headers[] = 'Content-Type: application/json; charset=UTF-8';
        $ret       = curl_post_json_pay($url, $params, $headers);
        //echo $ret;exit;
        $ret = json_decode($ret,true);
        $ret['isSuccess'] = true;
        return jsonp($ret);

    }

    function execute()
    {
        //{"payeeName":"100000703","paymentID":"PP27F16000000000051006","commodityDesc":"PGW payment","note2Payer":"Good Choice","mctBusinessType":"Acquiring","createTime":"20190715172333","custPaymentType":"Consumption","amount":"9.00","originalAmount":"10.00","discountedAmount":"1.00","paymentStatus":"Unpaid","merchantInvoiceNumber":"abc","merchantName":"test3","intent":"sale"}
        //

        $paymentID          = 'PP27F16000000000051006';
        $url                = "https://www.apifabric.com.cn/apiaccess/payment/paymentGateway/checkout/v1/{$paymentID}/execute";
        $params             = [];
        $params['couponID'] = '1';
        $params             = json_encode($params);

        $headers[] = 'X-APP-Key: APP ID';
        $headers[] = 'Authorization:Bearer Access-Token';
        $headers[] = 'Content-Type: application/json; charset=UTF-8';
        $ret       = curl_post_json_pay($url, $params, $headers);

    }

    function recharge()
    {
        $url                       = "http://test.jifenfu.net:59085/orderCard2!order.do";
        $params                    = [];
        $params['signMsg']         = '';
        $params['submitTimestamp'] = '';
        $params['pid']             = '';
        $params['cardBatchNo']     = '';
        $params['password']        = '';
        $params['orderId']         = '';
        $params['customerNo']      = '';
        $params['orderQuantity']   = '';
        $params['orderTime']       = '';
        $params['orderPoints']     = '';

        $sign =

        $response = $this->request($url, 'post', $params);


        //$ret    = curl_post_json($url, json_encode($params));
    }
}
