<?php

namespace app\api\controller;

use app\api\middleware\Auth;
use app\api\service\AlipayTradeService;
use app\api\service\UtilService;
use app\BaseController;
use app\model\Payment;
use think\facade\Log;
use think\facade\View;
use veitool\make\Controller;
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)
    {
        $userRole = UtilService::checkUserRole($params['user_id']);
        if ($userRole!=1)
        {
            return json(['code' => 0, 'msg' => '企业账号不能购买']);
        }

        // 在调用 PayService::createPayment() 之前先检查是否存在有效支付记录
        $existingPayment = Db::name('payment')
            ->where([
                'user_id' => $params['user_id'],
                'order_id' => $params['order_id'],
                'pay_method' => $params['pay_method'],
                'order_type' => $params['order_type'],
                'pay_amount' => $params['amount'],
                'pay_status' => 0, // 未支付
            ])
            ->where('expire_time', '>', time()+300) // 未过期
            ->order('id', 'desc')
            ->find();

        if ($existingPayment) {
            // 返回已存在的支付记录
            return json([
                'code' => 1,
                'data' => [
                    'payment_id' => $existingPayment['id'],
                    'order_no' => $existingPayment['order_no']
                ]
            ]);
        }

        // 创建支付订单
        $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("支付订单不存在或支付方式不匹配");
            }
            if ($payment['pay_status'] == PayService::PAY_STATUS_SUCCESS) {
                throw new \Exception("订单已支付");
            }

            $url = url('PayController/alipay_go', ['orderNo' => $orderNo], true, true);
            $data['url'] = (string)$url;
            return json(['code' => 1, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            Log::error("支付创建错误: {$orderNo} - " . $e->getMessage());
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    //支付宝去支付 支付链接
    public function alipay_go($orderNo)
    {
        $payment = Db::name('payment')
            ->where('order_no', $orderNo)
            ->find();
        if (empty($payment)) {
            echo '订单不存在';
            exit;
        }
        // 构造支付宝订单
        $biz_content = [
            'product_code' => 'FAST_INSTANT_TRADE_PAY',
            'out_trade_no' => $orderNo,
            'total_amount' => $payment['pay_amount'],
            'subject' => $payment['subject'],
//            'subject' => $payment['order_type'] == PayService::ORDER_TYPE_COURSE ?
//                '课程购买' : '证书购买',

        ];

        // 发起支付
        $pay = new AlipayTradeService();
        $pay->ReturnUrl = url('PayController/alipayretuanurl', [], true, true);
        $pay->NotifyUrl = url('PayController/alipayNotify', [], true, true);
        $result = $pay->pcpaypage($biz_content);
        echo $result;

    }


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

        try {
            // 查询支付订单
            $payment = Db::name('payment')
                ->where('order_no', $orderNo)
                ->where('pay_status', 0)
                ->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['subject'],
                '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()
    {
        $post = input();
        $alipaySevice = new AlipayTradeService();
        $result = $alipaySevice->check($post);
        Log::write('支付宝后台回调');
        Log::write($post);
        if ($result) {//验证成功
            Log::write('支付宝后台回调验签成功');

            //商户订单号
            $out_trade_no = $post['out_trade_no'];
//            //支付宝交易号
//            $trade_no = $post['trade_no'];
//            //交易状态
//            $trade_status = $post['trade_status'];
//            $total_amount = $post['total_amount'];
            if ($post['trade_status'] == 'TRADE_FINISHED') {

            } elseif ($post['trade_status'] == 'TRADE_SUCCESS') {
                $biz_content['out_trade_no'] = $out_trade_no;
                $result = $alipaySevice->payquery($biz_content);
                if ($result->code == 10000 && $result->trade_status == 'TRADE_SUCCESS') {
                    PayService::handlePaymentNotify($out_trade_no, (array)$result);
                }
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            echo "success";    //请不要修改或删除
        } else {
            //验证失败
            Log::write('支付宝后台回调验签失败');
            echo "fail";

        }
    }

    /**
     * 支付宝回调处理前台回调
     */
    public function alipayretuanurl()
    {

        return redirect('https://www.kuajingxl.com');
//        $get = input();
//        $biz_content['out_trade_no'] = $get['out_trade_no'];
//        $alipaySevice = new AlipayTradeService();
//        $result = $alipaySevice->payquery($biz_content);
//        if ($result->code == 10000 && $result->trade_status == 'TRADE_SUCCESS') {
//            PayService::handlePaymentNotify($get['out_trade_no'], (array)$result);
//        }
    }

    /**
     * 微信支付回调处理
     */
    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 {
            $wechatPayService = new WeChatPayService();
            $order = $wechatPayService->queryOrderByOutTradeNo($orderNo);

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

            $res = json_decode($order, true);
            if ($res['trade_state'] == 'SUCCESS') {
                // 处理业务逻辑

                $res = PayService::handlePaymentNotify($res['out_trade_no'], $res);
                return json(['code' => 1, 'msg' => 'success', 'data' => $res]);
            } else {
                throw new \Exception("订单处理失败");
            }

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