<?php
namespace App\Helper;

use Omnipay\Omnipay;
use App\Models\OrderInfoModel;
use Config, Request,QrCode;

trait PayHelper
{
    private function prepare() {
//        Pingpp::setApiKey(env('PINGPP_APP_KEY'));
//        Pingpp::setPrivateKeyPath(config_path() . 'ppp_pri_key.pem');
    }

    /**
     * 验签
     * @param $data
     * @param $sig
     * @return int
     */
    public function checkPppSignature($data, $sig) {
        $pubKey = file_get_contents(config_path() . 'ppp_pub_key.pem');
        return openssl_verify($data, $sig, $pubKey, 'sha256');
    }

    private function saveOrder($data) {
        $order = new OrderInfoModel();
        $order->code            = $data['code'];
        $order->transaction_id  = $data['transaction_id'];
        $order->user_id         = $data['user_id'];
        $order->goods_id        = $data['goods_id'];
        $order->price           = $data['price'];
        $order->number          = $data['number'];
        $order->amount          = $data['amount'];
        $order->pay_type        = $data['pay_type'];
        if (isset($data['ext_info'])) {
            $order->ext_info = $data['ext_info'];
        }

        if ($order->save()) {
            return $order->find($order->id);
        }
        return false;
    }

    public function createAlipayCharge($data, $profile = 'alipay') {
        $gateways = Config::get('laravel-omnipay.gateways');
        if (array_key_exists($profile, $gateways)) {
            $config = $gateways[$profile];
        } else {
            \Log::error('alipay: 不支持的支付类型, ' . $profile);
            return false;
        }
        $gateway = Omnipay::create($config['driver']);
        $gateway->setEnvironment($config['options']['environment']);
        $gateway->setAppId($config['options']['appid']);
        $gateway->setEncryptKey($config['options']['encrypt_key']);
        $gateway->setPrivateKey($config['options']['prikey']);
        $gateway->setAlipayPublicKey($config['options']['ali_pubkey']);
        $gateway->setNotifyUrl($config['options']['notify_url']);

        $goodsTypes = OrderInfoModel::getAllGoodsTypes();
        if (!isset($data['subject'])) {
            $data['subject'] = sprintf("瞄喵%s充值%d", $goodsTypes[$data['goods']], $data['number']);
        }
        if (!isset($data['goods_id'])) {
            $data['goods_id'] = 0;
        }
        $data['transaction_id'] = date('YmdHis') . mt_rand(1000, 9999);
        $data['code'] = 'ALIPAY_' . $data['transaction_id'];
        $data['price'] = 1;
        $data['amount'] = $data['number'] * $data['price']*100;
        $data['pay_type'] = OrderInfoModel::PAY_TYPE_ALIPAY;

        $request = $gateway->purchase();
        $request->setBizContent([
            'subject'      => $data['subject'],
            'out_trade_no' => $data['transaction_id'],
            'total_amount' => round($data['amount'] / 100, 2),
            'product_code' => 'QUICK_MSECURITY_PAY',//固定值
        ]);
        if ($profile == 'alipay_f2f') {
            $request->setBizContent([
                'subject'      => $data['subject'],
                'out_trade_no' => $data['transaction_id'],
                'total_amount' => round($data['amount'] / 100, 2),
            ]);
        }
//        dd($request);

        $response = $request->send();

        if ($response->isSuccessful()) {
            if ($profile == 'alipay_app' || $profile == 'alipay') {
                $orderString = $response->getOrderString();
            }
            if ($profile == 'alipay_f2f') {
                $code_url = $response->getQrCode();
                $code_path = public_path('qrcodes/'.$data['code'].'.png');
                QrCode::format('png')->size(500)->generate($code_url,$code_path);
                $orderString =  env('APP_URL').'/qrcodes/'.$data['code'].'.png';
            }
            \Log::info("支付宝生成订返回：".$orderString);

            //写订单
            $order = $this->saveOrder($data);
            if ($order !== false) {
                $result = $order->toArray();
                $result['orderString'] = $orderString;
                return $result;
            }
            \Log::error('save order failed');
            return false;
        } else {
            \Log::error('alipay response failed'.$response->getMessage());
            return false;
        }
    }

    public function createWechatpayCharge($data, $profile = 'wechatpay') {
        $gateways = Config::get('laravel-omnipay.gateways');
        if (array_key_exists($profile, $gateways)) {
            $config = $gateways[$profile];
        } else {
            \Log::error('wechatpay: 不支持的支付设置, ' . $profile);
            return false;
        }

        $gateway = Omnipay::create($config['driver']);
//        $gateway->setEnvironment('sandbox');
        $gateway->setAppId($config['options']['appid']);
        $gateway->setMchId($config['options']['merchant_id']);
        $gateway->setApiKey($config['options']['apikey']);
        $gateway->setNotifyUrl($config['options']['notify_url']);

        $goodsTypes = OrderInfoModel::getAllGoodsTypes();
        if (!isset($data['subject'])) {
            $data['subject'] = sprintf("瞄喵%s充值%d", $goodsTypes[$data['goods']], $data['number']);
        }
        if (!isset($data['goods_id'])) {
            $data['goods_id'] = 0;
        }
        $data['transaction_id'] = date('YmdHis') . mt_rand(1000, 9999);
        $data['code'] = 'WECHATPAY_' . $data['transaction_id'];
        $data['price'] = 1;
        $data['amount'] = $data['number'] * $data['price']*100;
        $data['pay_type'] = OrderInfoModel::PAY_TYPE_WECHATPAY;

        $order = [
            'body'              => $data['subject'],
            'out_trade_no'      => $data['transaction_id'],
            'total_fee'         => $data['amount'],
            'spbill_create_ip'  => Request::ip(),
            'fee_type'          => 'CNY'
        ];

        $request  = $gateway->purchase($order);
        $response = $request->send();

//        dd($response);

        if ($response->isSuccessful()) {
            if ($profile == 'wechatpay_app' || $profile == 'wechatpay') {
                $orderString = $response->getAppOrderData();
            }
//            if ($profile == 'wechatpay_native') {
//                $code_url = $response->getCodeUrl();
//                $code_path = public_path('qrcodes/'.$data['code'].'.png');
//                QrCode::format('png')->size(500)->generate($code_url,$code_path);
//                $orderString =  env('APP_URL').'/qrcodes/'.$data['code'].'.png';
//            }
            \Log::debug($orderString);

            //写订单
            $order = $this->saveOrder($data);
            if ($order !== false) {
                $result = $order->toArray();
                $result['orderString'] = $orderString;
                return $result;
            }
            \Log::error('save order failed');
            return false;
        } else {
            \Log::error($response->getData());
            return false;
        }

        //available methods
//        $response->isSuccessful();
//        $response->getData(); //For debug
//        $response->getAppOrderData(); //For WechatPay_App
//        $response->getJsOrderData(); //For WechatPay_Js
//        $response->getCodeUrl(); //For Native Trade Type
    }

}