<?php

namespace app\api\controller\pay;

use app\model\PayDetail;
use support\Db;
use support\Request;
use Yansongda\Pay\Pay;

class WxpayController
{

    public function index(Request $request)
    {
        $params = $request->all();
        \support\Log::info("开始获取微信支付参数",$params);

        if (!isset($params['order_id'])) {
            return json_fail('参数异常');
        }
        if (!isset($params['platform'])){
            return json_fail('缺少平台参数');
        }
        $orderId = $params['order_id'];
        $payDetail = PayDetail::where('join_pay_order_id',$orderId)->where('pay_status','WAITING')->first();
        if (!$payDetail) {
            return json_fail('订单异常');
        }
        if (!empty($params['pay_amount']) && $params['pay_amount'] != $payDetail->pay_amount) {
            return json_fail("支付金额与订单金额不符");
        }

        if ($payDetail->pay_category == 'MEALS'){
            $payObjectJson = [];
            if (!empty($payDetail->join_pay_object_json)) {
                $payObjectJson = json_decode($payDetail->join_pay_object_json, true);
            }
            // 标记发生过支付请求
            $payObjectJson['pay_marking'] = 'Y';
            $payDetail->join_pay_object_json = json_encode($payObjectJson);
        }

        $payData = [
            'out_trade_no' => $orderId,
            'body' => '万悦康养订单',
            'total_fee' => $payDetail->pay_amount * 100,
        ];

        Db::beginTransaction();
        try {
            $payDetail->pay_prepayid = 'WXPAY';
            $payDetail->save();

            if ($params['platform'] == 'android'){  // APP
                $wxpay = Pay::wechat(config('payment.wxpay'))->app($payData)->getContent();
            }elseif ($params['platform'] == 'WeChat'){  // 公众号
                if (empty($params['openid'])){
                    throw new \support\exception\BusinessException("缺少OpenID 参数");
                }
                $payData['openid'] = $params['openid'];
                $config = config('payment.wxpay');
                $wxpay = Pay::wechat($config)->mp($payData);
            }elseif ($params['platform'] == 'mp-weixin'){   // 小程序
                if (empty($params['openid'])){
                    throw new \support\exception\BusinessException("缺少OpenID 参数");
                }
                $payData['openid'] = $params['openid'];
                $wxpay = Pay::wechat(config('payment.wxpay'))->miniapp($payData);
            }else{
                throw new \support\exception\BusinessException("平台参数无效");
            }

            Db::commit();
            \support\Log::info("微信支付参数获取成功",['msg'=>$wxpay]);
            return json_success('', json_decode($wxpay, true));
        } catch (\support\exception\BusinessException $e) {
            Db::rollBack();
            \support\Log::error("微信支付参数获取失败",['msg'=>$e->getMessage()]);
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            \support\Log::error("微信支付参数获取失败",['msg'=>$e->getMessage()]);
            return json_fail('下单失败：'.$e->getMessage());
        }
    }

    private function getConfig()
    {
        return [
            'appid' => 'wx089c26eaf96c3d51', // APP APPID
            'mch_id' => '1680393367',
            'key' => 'c451cedbab8058e3502a35c6dacf0919',
            'notify_url' => 'https://api.wanyuewellness.com.cn/api.pay.notify.php',
            'cert_client' => config_path('cert/wxpay/apiclient_cert.pem'), // optional，退款等情况时用到
            'cert_key' => config_path('cert/wxpay/apiclient_key.pem'),// optional，退款等情况时用到
            'log' => [ // optional
                'file' => runtime_path('logs/wechat.log'),
                'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 5.0,
                'connect_timeout' => 5.0,
                // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
            ],
//            'mode' => 'dev', // optional, dev/hk;当为 `hk` 时，为中国香港 gateway。
        ];
    }
}
