<?php
/**
 * 测试票据生成脚本
 * 用法：php test_ticket.php
 * 
 * 流程：
 * 1. 查找/创建测试商品（item_type=ticket）
 * 2. 查找/创建测试用户
 * 3. 创建已支付订单
 * 4. 触发 TicketService::onOrderPaid()
 */

define('ROOT_PATH', __DIR__ . '/');
define('APP_PATH', __DIR__ . '/app/');

// 加载 ThinkPHP 引导
require ROOT_PATH . 'think';

use app\plugins\vr_ticket\service\TicketService;
use app\plugins\vr_ticket\service\BaseService;
use think\facade\Db;

// ============================================================
// Step 1: 查找测试商品（item_type=ticket 或 venue_data 非空）
// ============================================================
echo "[1] 查找票务商品...\n";
$goods = Db::name('Goods')->where('id', 118)->find();
if (empty($goods)) {
    die("商品ID 118不存在！\n");
}

// 确保 venue_data 或 item_type 有值
$isTicket = !empty($goods['venue_data']) || ($goods['item_type'] ?? '') === 'ticket';
if (!$isTicket) {
    echo "商品118不是票务商品，先设置 item_type=ticket\n";
    Db::name('Goods')->where('id', 118)->update(['item_type' => 'ticket']);
    $goods = Db::name('Goods')->where('id', 118)->find();
    echo "已更新 item_type=ticket\n";
}
echo "商品: {$goods['title']} (ID={$goods['id']})\n";
echo "item_type={$goods['item_type']}, venue_data=" . (empty($goods['venue_data'])?'空':'有内容') . "\n";

// ============================================================
// Step 2: 查找测试用户
// ============================================================
echo "\n[2] 查找测试用户...\n";
$user = Db::name('User')->order('id', 'asc')->find();
if (empty($user)) {
    die("没有测试用户！\n");
}
echo "用户: {$user['username']} (ID={$user['id']})\n";

// ============================================================
// Step 3: 创建测试订单（已支付状态）
// ============================================================
echo "\n[3] 创建测试订单...\n";
$now = time();
$order_no = 'TEST' . date('YmdHis') . rand(100, 999);
$order_id = Db::name('Order')->insertGetId([
    'order_no'          => $order_no,
    'user_id'           => $user['id'],
    'goods_id'         => $goods['id'],
    'title'            => $goods['title'],
    'total_price'      => 0.01,
    'pay_status'       => 1,          // 已支付
    'pay_time'         => $now,
    'status'            => 1,
    'address_id'       => 0,
    'extension_data'    => json_encode([
        'attendee' => [
            'real_name' => '张三',
            'phone'     => '13800138000',
            'id_card'   => '110101199001011234',
        ]
    ], JSON_UNESCAPED_UNICODE),
    'add_time'         => $now,
    'upd_time'         => $now,
]);
echo "订单创建成功: order_no=$order_no, order_id=$order_id\n";

// ============================================================
// Step 4: 创建订单商品
// ============================================================
echo "\n[4] 创建订单商品...\n";
// 获取商品规格
$spec = Db::name('GoodsSpecBase')
    ->where('goods_id', $goods['id'])
    ->where('id', '>', 0)
    ->find();

if (empty($spec)) {
    // 如果没有规格，创建虚拟规格
    $spec_id = Db::name('GoodsSpecBase')->insertGetId([
        'goods_id'   => $goods['id'],
        'spec_id'    => 0,
        'spec_name'  => '默认座位',
        'spec_type'  => 'seat:A',
        'price'      => 0.01,
        'stock'      => 1,
        'add_time'   => $now,
    ]);
    $spec = ['id' => $spec_id, 'spec_name' => '默认座位', 'price' => 0.01, 'goods_price' => 0.01, 'spec_base_id' => $spec_id, 'goods_id' => $goods['id']];
    echo "无现有规格，创建了虚拟规格: spec_id=$spec_id\n";
}

$order_goods_id = Db::name('OrderGoods')->insertGetId([
    'order_id'       => $order_id,
    'goods_id'       => $goods['id'],
    'title'          => $goods['title'],
    'price'          => $spec['price'] ?? 0.01,
    'cost'           => 0,
    'stock'          => 1,
    'spec_id'        => $spec['spec_id'] ?? 0,
    'spec_name'      => $spec['spec_name'] ?? '',
    'spec_base_id'   => $spec['id'] ?? 0,
    'goods_price'    => $spec['goods_price'] ?? ($spec['price'] ?? 0.01),
    'order_no'       => $order_no,
    'user_id'        => $user['id'],
    'add_time'       => $now,
]);
echo "订单商品创建成功: order_goods_id=$order_goods_id\n";

// ============================================================
// Step 5: 触发票据生成
// ============================================================
echo "\n[5] 触发 onOrderPaid...\n";
$params = [
    'business_id'  => $order_id,
    'business_ids' => [$order_id],
    'user_id'      => $user['id'],
];

$result = TicketService::onOrderPaid($params);
echo "onOrderPaid 返回: " . json_encode($result, JSON_UNESCAPED_UNICODE) . "\n";

// ============================================================
// Step 6: 检查生成的票据
// ============================================================
echo "\n[6] 检查生成的票据...\n";
$tickets = Db::name(BaseService::table('tickets'))
    ->where('order_id', $order_id)
    ->select()
    ->toArray();

if (empty($tickets)) {
    echo "❌ 没有生成票据！\n";
} else {
    echo "✅ 成功生成 " . count($tickets) . " 张票据:\n";
    foreach ($tickets as $t) {
        echo "  - ID={$t['id']}, ticket_code={$t['ticket_code']}, 观演人={$t['real_name']}, status={$t['verify_status']}\n";
    }
}

echo "\n完成！\n";
