<?php

namespace app\api\controller;
use app\api\middleware\Auth;
use app\BaseController;
use think\facade\Log;
use think\facade\View;
use Yansongda\Pay\Pay;
use app\api\service\PayService;
use think\facade\Db;
use think\App;
use app\api\service\WeChatPayService;

class PayController
{
//--ignore-platform-req=ext-swoole

    /**
     * 创建支付订单
     */
    public function create($params)
    {
//        $params = request()->only([
//            'order_id',
//            'order_type',
//            'pay_method',
//            'amount',
//            'user_id'
//        ]);
//
//        // 验证参数
//        $validate = validate('Pay');
//        if (!$validate->scene('create')->check($params)) {
//            return json(['code' => 400, 'msg' => $validate->getError()]);
//        }

        // 创建支付订单
        $result = PayService::createPayment(
            $params['user_id'],
            $params['order_id'],
            $params['amount'],
            $params['pay_method'],
            $params['order_type'],
            request()->param()
        );

        if (!$result['status']) {
            return json(['code' => 0, 'msg' => $result['msg']]);
        }

        return json([
            'code' => 1,
            'data' => [
                'payment_id' => $result['data']['payment_id'],
                'order_no' => $result['data']['order_no']
            ]
        ]);
    }

    /**
     * 发起支付宝支付
     */
    public function alipay()
    {
        $orderNo = request()->param('order_no');

        try {
            // 查询支付订单
            $payment = Db::name('payment')
                ->where('order_no', $orderNo)
                ->find();
            if (!$payment || $payment['pay_method'] != PayService::PAY_METHOD_ALIPAY) {
                throw new \Exception("支付订单不存在或支付方式不匹配");
            }

            // 构造支付宝订单
            $order = [
                'out_trade_no' => $orderNo,
                'total_amount' => $payment['pay_amount'],
                'subject' => $payment['order_type'] == PayService::ORDER_TYPE_COURSE ?
                    '课程购买' : '证书购买',
            ];


            // 发起支付
            $alipay = Pay::alipay(PayService::getPayConfig(PayService::PAY_METHOD_ALIPAY))->web($order);
            halt($alipay);
            return redirect($alipay->getTargetUrl());
        } catch (\Exception $e) {
            Log::error("支付创建错误: {$orderNo} - " . $e->getMessage());
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 发起微信支付
     */
    public function wechat()
    {
        $orderNo = request()->param('order_no');

        try {
            // 查询支付订单
            $payment = Db::name('payment')
                ->where('order_no', $orderNo)
                ->find();

            if (!$payment || $payment['pay_method'] != PayService::PAY_METHOD_WECHAT) {
                throw new \Exception("支付订单不存在或支付方式不匹配");
            }
            // halt(intval($payment['pay_amount'] * 100));
            // 构造微信订单
            $order = [
                'out_trade_no' => $orderNo,
                'description' => $payment['order_type'] == PayService::ORDER_TYPE_COURSE ?
                    '课程购买' : '证书购买',
                'amount' => [
                    'total' => intval($payment['pay_amount'] * 100), // 转为分
                ],
            ];
            $wechatPay = new WeChatPayService();
            $result = $wechatPay->createNativeOrder($order['out_trade_no'], $order['amount']['total'], $order['description']);
            return json(['code' => 1, 'msg' =>'success','data'=>$result]);

        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 支付宝回调处理
     */
    public function alipayNotify()
    {
        $alipay = Pay::alipay(PayService::getPayConfig(PayService::PAY_METHOD_ALIPAY));

        try {
            $data = Pay::alipay()->callback();

            // 处理支付回调
            $result = PayService::handlePaymentNotify($data->out_trade_no, $data->all());

            if ($result) {
                return $alipay->success();
            } else {
                return json(['code' => 500, 'msg' => '处理失败']);
            }
        } catch (\Exception $e) {
            Log::error('支付宝回调异常: ' . $e->getMessage());
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 微信支付回调处理
     */
    public function wechatNotify()
    {

        try {
            $wechatPayService = new WeChatPayService();
            $res = $wechatPayService->handleNotify();
            if($res)
            {
                return json(['code' => 'success', 'msg' => '成功']);
            }

            return json(['code' => 'FAIL', 'msg' => '失败'],500);
        } catch (\Exception $e) {
            return json(['code' => 'FAIL', 'msg' => '失败'],500);

        }
    }

    /**
     * 查询支付状态
     */
    public function query()
    {
        $orderNo = request()->param('order_no');

        try {
            $payment = Db::name('fj_payment')
                ->where('order_no', $orderNo)
                ->find();

            if (!$payment) {
                throw new \Exception("支付订单不存在");
            }

            return json([
                'code' => 200,
                'data' => [
                    'order_no' => $payment['order_no'],
                    'pay_status' => $payment['pay_status'],
                    'pay_time' => $payment['pay_time'],
                    'pay_amount' => $payment['pay_amount']
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
}