<?php

/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2017/12/9
 * Time: 12:02
 */

namespace App\Libs\Pay\Merchants;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as Wxorder;
use Illuminate\Support\Facades\Log;

class Official implements PayMerchantInterface
{

    private $appid;
    private $secret;
    private $token;
    private $merchant_id;
    private $key;
    private $cert_path;
    private $key_path;
    private $app;

    public function __construct($config)
    {
        $this->appid = $config['appid'];
        $this->merchant_id = $config['merchant_id'];
        $this->key = $config['key'];
        $this->secret = isset($config['secret']) ? $config['secret'] : '';
        $this->token = isset($config['token']) ? $config['token'] : '';
        $this->key_path = isset($config['key_path']) ? $config['key_path'] : '';
        $this->cert_path = isset($config['cert_path']) ? $config['cert_path'] : '';
        $options = [
            'app_id' => $this->appid,
            'secret' => $this->secret,
            'token' => $this->token,
            'payment' => [
                'merchant_id' => $this->merchant_id,
                'key' => $this->key,
                'cert_path' => public_path($this->cert_path),
                'key_path' => public_path($this->key_path)
            ]
        ];
        $this->app = new Application($options);
    }

    public function send(array $data)
    {
        $app =  $this->app;
        $trade_type = isset($data['trade_type']) ? $data['trade_type'] : 'JSAPI';
        $attributes = [
            'trade_type' => $trade_type,
            'body' => $data['body'],
            'detail' => isset($data['detail']) ? $data['detail'] : '',
            'out_trade_no' => $data['trade_no'],
            'total_fee' => $data['price'],
            'notify_url' => env('QUICK_APP_OFFICIAL_PAY_CALL_BACK_URL'),
            'openid' => isset($data['openid']) ? $data['openid'] : '',
            'spbill_create_ip' => $data['create_ip'],
            'attach' => $data['remark']
        ];
        $order = new Wxorder($attributes);
        $result = $app->payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            switch ($trade_type) {
                case 'JSAPI':
                    $data = [
                        'appId' => $result->appid,
                        'package' => 'prepay_id=' . $result->prepay_id,
                        'nonceStr' => $result->nonce_str,
                        'timeStamp' => time(),
                        'signType' => 'MD5',
                    ];
                    $data['paySign'] = $this->makeSign($data);
                    break;
                case 'APP':
                    $data = [
                        'appid' => $result->appid,
                        'partnerid' => $result->mch_id,
                        'prepayid' => $result->prepay_id,
                        'package' => "Sign=WXPay",
                        'noncestr' => $result->nonce_str,
                        'timestamp' => time(),
                    ];
                    $data['sign'] = $this->makeSign($data);
                    break;
                case 'MWEB':
                    $data = [
                        'appId' => $result->appid,
                        'mch_id' => $result->mch_id,
                        'prepay_id' => $result->prepay_id,
                        'nonce_str' => $result->nonce_str,
                        'sign' => $result->sign,
                        'trade_type' => $result->trade_type,
                        'mweb_url' => $result->mweb_url,
                    ];
                    break;
            }
            return $data;
        }
        Log::error('pay error order is: ' . $data['trade_no']);
        Log::error($result);
        return [];
    }

    public function makeSign(array $value)
    {
        $data = $value;
        //签名步骤一：按字典序排序参数
        ksort($data);
        $buff = "";
        foreach ($data as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        //签名步骤二：在string后加入KEY
        $string = $buff . "&key=" . $this->key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    public function notify(array $data = [])
    {
        return $this->app->payment;
    }

    public function query(string $trade_no)
    {
        $result =  $this->app->payment->query($trade_no);
        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS' && $result['trade_state'] === 'SUCCESS') {
            return $result['transaction_id'];
        } else {
            return false;
        }
    }

    public function refund(array $data)
    {
    }
}
