<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Support\Print\Documents;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Models\DberpSalesOutboundOrder;
use App\Models\DberpSalesOutboundOrderItem;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\Print\Contracts\DberpDocumentPrintPresenter;
use App\Support\Print\DberpPrintViewSupport;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Carbon;

final class SalesOutboundPrintPresenter implements DberpDocumentPrintPresenter
{
    public const string DOCUMENT_KEY = 'sales-outbound';

    public function __construct(
        private readonly DberpPermissionService $permissionService,
    ) {}

    public function documentKey(): string
    {
        return self::DOCUMENT_KEY;
    }

    public function userCanPrint(?Authenticatable $user): bool
    {
        return $this->permissionService->allows($user, DberpPermissionService::VIEW_SALES_OUTBOUND);
    }

    public function prepareViewData(int|string $recordId): array
    {
        $order = DberpSalesOutboundOrder::query()
            ->with([
                'customer',
                'warehouse',
                'handlerEmployee',
                'salesOrder',
                'items' => fn ($query) => $query->orderBy('sort_order')->orderBy('id'),
            ])
            ->findOrFail($recordId);

        $status = InventoryDocumentStatus::tryFrom((string) $order->status);
        $statusLabel = $status?->label() ?? (string) $order->status;
        $showVoidWatermark = $status === InventoryDocumentStatus::Voided || $order->voided_at !== null;

        return [
            'view' => 'print.documents.sales-outbound',
            'documentTitle' => (string) __('dberp.print.documents.sales_outbound'),
            'statusLabel' => $statusLabel,
            'showVoidWatermark' => $showVoidWatermark,
            'printTime' => Carbon::now(),
            'company' => DberpPrintViewSupport::companyProfile(),
            'headerFields' => $this->headerFields($order, $statusLabel),
            'lines' => $order->items->values()->map(
                fn (DberpSalesOutboundOrderItem $item, int $index): array => $this->formatLine($item, $index + 1),
            ),
            'totals' => $this->totals($order),
            'signatures' => [
                (string) __('dberp.print.signatures.maker'),
                (string) __('dberp.print.signatures.warehouse_ship'),
                (string) __('dberp.print.signatures.customer_sign'),
                (string) __('dberp.print.signatures.recheck'),
            ],
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function headerFields(DberpSalesOutboundOrder $order, string $statusLabel): array
    {
        $fields = [
            [
                'label' => (string) __('dberp.fields.document_code'),
                'value' => (string) $order->code,
            ],
            [
                'label' => (string) __('dberp.fields.business_time'),
                'value' => $order->business_time?->format('Y-m-d H:i') ?? '—',
            ],
            [
                'label' => (string) __('dberp.print.labels.document_status'),
                'value' => $statusLabel,
            ],
            [
                'label' => (string) __('dberp.print.labels.customer'),
                'value' => (string) ($order->customer?->name ?? '—'),
            ],
            [
                'label' => (string) __('dberp.print.labels.warehouse'),
                'value' => (string) ($order->warehouse?->name ?? '—'),
            ],
        ];

        if ($order->salesOrder !== null) {
            $fields[] = [
                'label' => (string) __('dberp.print.labels.related_order'),
                'value' => (string) $order->salesOrder->code,
            ];
        }

        $customerContact = DberpPrintViewSupport::joinContactParts(
            (string) ($order->customer_contact_person_snapshot ?? ''),
            (string) ($order->customer_mobile_snapshot ?? ''),
            (string) ($order->customer_phone_snapshot ?? ''),
        );
        if ($customerContact !== '') {
            $fields[] = [
                'label' => (string) __('dberp.fields.contact_person'),
                'value' => $customerContact,
            ];
        }

        if ($order->handlerEmployee !== null) {
            $fields[] = [
                'label' => (string) __('dberp.fields.handler_employee'),
                'value' => (string) $order->handlerEmployee->name,
            ];
        }

        if (filled($order->remark)) {
            $fields[] = [
                'label' => (string) __('dberp.fields.remark'),
                'value' => (string) $order->remark,
            ];
        }

        return $fields;
    }

    /**
     * @return array{row_number: int, product_code: string, product_name: string, sku_spec: string, unit_name: string, quantity: string, batch_serial: string, remark: string}
     */
    private function formatLine(DberpSalesOutboundOrderItem $item, int $rowNumber): array
    {
        return [
            'row_number' => $rowNumber,
            'product_code' => (string) ($item->product_code ?? '—'),
            'product_name' => (string) ($item->product_name ?? '—'),
            'sku_spec' => DberpPrintViewSupport::formatSkuSpec($item->sku_code, $item->spec_text),
            'unit_name' => (string) ($item->unit_name ?? '—'),
            'quantity' => DberpNumberFormatter::quantity($item->ship_quantity),
            'batch_serial' => DberpPrintViewSupport::formatBatchAndSerial($item->batch_no, $item->serial_numbers),
            'remark' => filled($item->remark) ? (string) $item->remark : '',
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function totals(DberpSalesOutboundOrder $order): array
    {
        $totals = [];

        if ($order->total_shipped_quantity !== null) {
            $totals[] = [
                'label' => (string) __('dberp.fields.shipped_quantity'),
                'value' => DberpNumberFormatter::quantity($order->total_shipped_quantity),
            ];
        }

        if ($order->total_amount !== null && (float) $order->total_amount > 0) {
            $totals[] = [
                'label' => (string) __('dberp.fields.total_amount'),
                'value' => DberpNumberFormatter::money($order->total_amount),
            ];
        }

        return $totals;
    }
}
