<?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;

class PayController
{
    protected $middleware = [
        Auth::class,
    ];

    /**
     * 创建支付订单
     */
    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);
            return $alipay->send();
//            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("支付订单不存在或支付方式不匹配");
            }

            // 构造微信订单
            $order = [
                'out_trade_no' => $orderNo,
                'description' => $payment['order_type'] == PayService::ORDER_TYPE_COURSE ?
                    '课程购买' : '证书购买',
                'amount' => [
                    'total' => intval($payment['pay_amount'] * 100), // 转为分
                ],
            ];

            // 发起支付
            $response = Pay::wechat(PayService::getPayConfig(PayService::PAY_METHOD_WECHAT))->scan($order);

            return json([
                'code' => 200,
                'data' => [
                    'code_url' => $response->code_url,
                    'order_no' => $orderNo
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

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

        try {
            $data = $alipay->verify();

            // 处理支付回调
            $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()
    {
        $wechat = Pay::wechat(PayService::getPayConfig(PayService::PAY_METHOD_WECHAT));

        try {
            $data = $wechat->verify();

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

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

    /**
     * 查询支付状态
     */
    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()]);
        }
    }
}