<?php

namespace Tests\Feature;

use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminPlatformOrderExportTest extends TestCase
{
    use RefreshDatabase;

    private function parseCsvToRows(string $content): array
    {
        // 去 BOM，避免表头第一列带 \xEF\xBB\xBF
        if (str_starts_with($content, "\xEF\xBB\xBF")) {
            $content = substr($content, 3);
        }

        $fp = fopen('php://temp', 'r+');
        fwrite($fp, $content);
        rewind($fp);

        $rows = [];
        while (($row = fgetcsv($fp)) !== false) {
            if ($row === [null] || $row === false) {
                continue;
            }
            $rows[] = $row;
        }
        fclose($fp);

        return $rows;
    }

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    public function test_platform_admin_can_export_platform_orders_csv(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'export_order_test',
            'name' => '导出测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_EXPORT_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => [
                    'message' => '模拟失败',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);

        // batch_synced_24h 筛选导出：构造一条 24h 内、一条超 24h 的订单
        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_EXPORT_BATCH_RECENT',
            'order_type' => 'renewal',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'activated_at' => now(),
            'meta' => [
                'batch_activation' => [
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                    'scope' => 'filtered',
                ],
            ],
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_EXPORT_BATCH_OLD',
            'order_type' => 'renewal',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now()->subHours(30),
            'paid_at' => now()->subHours(30),
            'activated_at' => now()->subHours(30),
            'meta' => [
                'batch_activation' => [
                    'at' => now()->subHours(30)->toDateTimeString(),
                    'admin_id' => 1,
                    'scope' => 'filtered',
                ],
            ],
        ]);

        $res = $this->get('/admin/platform-orders/export?download=1');

        $res->assertOk();
        $res->assertHeader('content-type', 'text/csv; charset=UTF-8');

        // StreamedResponse 在测试环境下需用 streamedContent() 获取内容
        $content = $res->streamedContent();

        // 解析 CSV 后按“表头/行数据”断言，避免未来表头顺序/分隔符等变更造成脆断。
        $rows = $this->parseCsvToRows($content);
        $this->assertGreaterThanOrEqual(2, count($rows));

        $headers = $rows[0];
        $this->assertContains('订单号', $headers);
        $this->assertContains('同步失败原因', $headers);
        $this->assertContains('订阅ID', $headers);
        $this->assertContains('BMPA失败原因', $headers);
        $this->assertContains('最近批量标记支付并生效时间', $headers);
        $this->assertContains('最近批量标记支付并生效管理员', $headers);
        $this->assertContains('最近批量生效时间', $headers);
        $this->assertContains('最近批量生效管理员', $headers);
        $this->assertContains('退款总额', $headers);
        $this->assertContains('对账不一致', $headers);
        $this->assertContains('退款不一致', $headers);

        // 至少应包含我们造的那条订单
        $found = false;
        foreach ($rows as $r) {
            if (in_array('PO_EXPORT_0001', $r, true)) {
                $found = true;
                break;
            }
        }
        $this->assertTrue($found, 'CSV should contain row for PO_EXPORT_0001');

        // include_meta=1 时应包含 meta(JSON) 列
        $res2 = $this->get('/admin/platform-orders/export?download=1&include_meta=1');
        $res2->assertOk();
        $content2 = $res2->streamedContent();
        $this->assertStringContainsString('原始meta(JSON)', $content2);
        $this->assertStringContainsString('subscription_activation_error', $content2);

        // batch_synced_24h=1 导出应只包含 24h 内批量同步过的订单
        $res3 = $this->get('/admin/platform-orders/export?download=1&batch_synced_24h=1');
        $res3->assertOk();
        $content3 = $res3->streamedContent();
        $this->assertStringContainsString('PO_EXPORT_BATCH_RECENT', $content3);
        $this->assertStringNotContainsString('PO_EXPORT_BATCH_OLD', $content3);

        // site_subscription_id 精确过滤导出：只导出订阅ID命中的订单
        $sub = \App\Models\SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_EXPORT_FILTER_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addMonth(),
            'activated_at' => now()->subDay(),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_no' => 'PO_EXPORT_SUB_FILTER_0001',
            'order_type' => 'renewal',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'activated_at' => now(),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => null,
            'order_no' => 'PO_EXPORT_SUB_FILTER_0002',
            'order_type' => 'renewal',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'activated_at' => now(),
        ]);

        $res4 = $this->get('/admin/platform-orders/export?download=1&site_subscription_id=' . $sub->id);
        $res4->assertOk();
        $content4 = $res4->streamedContent();
        $this->assertStringContainsString('PO_EXPORT_SUB_FILTER_0001', $content4);
        $this->assertStringNotContainsString('PO_EXPORT_SUB_FILTER_0002', $content4);
    }

    public function test_guest_cannot_export_platform_orders_csv(): void
    {
        $this->seed();

        $this->get('/admin/platform-orders/export')
            ->assertRedirect('/admin/login');
    }

    public function test_platform_admin_can_export_platform_orders_csv_with_lead_id_column(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'export_order_lead_id_test',
            'name' => '导出线索ID测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $lead = \App\Models\PlatformLead::query()->create([
            'name' => 'Lead Export',
            'mobile' => '13800000999',
            'company' => 'Export Inc',
            'status' => 'new',
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_EXPORT_LEAD_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [
                'platform_lead_id' => $lead->id,
            ],
        ]);

        $otherLead = \App\Models\PlatformLead::query()->create([
            'name' => 'Lead Export Other',
            'mobile' => '13800000888',
            'company' => 'Other Inc',
            'status' => 'new',
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_EXPORT_LEAD_0002',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [
                'platform_lead_id' => $otherLead->id,
            ],
        ]);

        $res = $this->get('/admin/platform-orders/export?download=1&lead_id=' . $lead->id);
        $res->assertOk();

        $content = $res->streamedContent();
        $this->assertStringContainsString('线索ID', $content);
        $this->assertStringContainsString('PO_EXPORT_LEAD_0001', $content);
        $this->assertStringContainsString((string) $lead->id, $content);

        // lead_id 精确过滤：不应导出其它线索的订单
        $this->assertStringNotContainsString('PO_EXPORT_LEAD_0002', $content);

        // 更稳健断言：逐行解析 CSV，确保“线索ID”列全部等于目标 lead_id
        $contentNoBom = ltrim($content, "\xEF\xBB\xBF");
        $lines = array_values(array_filter(preg_split("/\r\n|\n|\r/", $contentNoBom)));
        $this->assertGreaterThanOrEqual(2, count($lines));

        $headers = str_getcsv($lines[0]);
        $leadIdx = array_search('线索ID', $headers, true);
        $this->assertNotFalse($leadIdx);

        for ($i = 1; $i < count($lines); $i++) {
            $row = str_getcsv($lines[$i]);
            $this->assertSame((string) $lead->id, (string) ($row[$leadIdx] ?? ''));
        }
    }

}
