<?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\Business\Inventory\Enums\StocktakeResultType;
use App\Business\Inventory\Enums\StocktakeScopeType;
use App\Models\DberpStocktakeOrder;
use App\Models\DberpStocktakeOrderItem;
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 StocktakeOrderPrintPresenter implements DberpDocumentPrintPresenter
{
    public const string DOCUMENT_KEY = 'stocktake-order';

    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_STOCKTAKE_ORDER);
    }

    public function prepareViewData(int|string $recordId): array
    {
        $order = DberpStocktakeOrder::query()
            ->with([
                'warehouse',
                'stocktakeEmployee',
                'scopeCategory',
                'scopeProduct',
                '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.stocktake-order',
            'documentTitle' => (string) __('dberp.print.documents.stocktake_order'),
            'statusLabel' => $statusLabel,
            'showVoidWatermark' => $showVoidWatermark,
            'printTime' => Carbon::now(),
            'company' => DberpPrintViewSupport::companyProfile(),
            'headerFields' => $this->headerFields($order, $statusLabel),
            'lines' => $order->items->values()->map(
                fn (DberpStocktakeOrderItem $item, int $index): array => $this->formatLine($item, $index + 1),
            ),
            'totals' => [],
            'signatures' => [
                (string) __('dberp.print.signatures.maker'),
                (string) __('dberp.print.signatures.stocktake_person'),
                (string) __('dberp.print.signatures.recheck'),
                (string) __('dberp.print.signatures.warehouse_confirm'),
            ],
        ];
    }

    /**
     * @return list<array{label: string, value: string}>
     */
    private function headerFields(DberpStocktakeOrder $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.warehouse'),
                'value' => (string) ($order->warehouse?->name ?? '—'),
            ],
            [
                'label' => (string) __('dberp.print.labels.stocktake_scope'),
                'value' => $this->scopeLabel($order),
            ],
        ];

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

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

        return $fields;
    }

    private function scopeLabel(DberpStocktakeOrder $order): string
    {
        $scopeType = StocktakeScopeType::tryFrom((string) $order->scope_type);
        $base = $scopeType !== null
            ? (string) __('dberp.options.stocktake_scope_type.'.$scopeType->value)
            : (string) $order->scope_type;

        if ($scopeType === StocktakeScopeType::Category && $order->scopeCategory !== null) {
            return $base.' / '.(string) $order->scopeCategory->name;
        }

        if ($scopeType === StocktakeScopeType::Product && $order->scopeProduct !== null) {
            return $base.' / '.(string) $order->scopeProduct->name;
        }

        return $base;
    }

    /**
     * @return array{row_number: int, product_code: string, product_name: string, sku_spec: string, unit_name: string, book_quantity: string, actual_quantity: string, difference_quantity: string, result_type: string, batch_serial: string, remark: string}
     */
    private function formatLine(DberpStocktakeOrderItem $item, int $rowNumber): array
    {
        $resultType = StocktakeResultType::tryFrom((string) $item->result_type);
        $resultLabel = $resultType?->label()
            ?? (filled($item->result_type)
                ? (string) (__('dberp.options.stocktake_result_type.'.(string) $item->result_type) ?? (string) $item->result_type)
                : '—');

        return [
            'row_number' => $rowNumber,
            'product_code' => (string) ($item->product_sku_code ?? '—'),
            'product_name' => (string) ($item->product_sku_name ?? '—'),
            'sku_spec' => DberpPrintViewSupport::formatSkuSpec($item->product_sku_code, $item->product_sku_spec),
            'unit_name' => (string) ($item->unit_name ?? '—'),
            'book_quantity' => DberpNumberFormatter::quantity($item->book_quantity),
            'actual_quantity' => DberpNumberFormatter::quantity($item->actual_quantity),
            'difference_quantity' => DberpNumberFormatter::quantity($item->difference_quantity),
            'result_type' => filled($resultLabel) ? (string) $resultLabel : '—',
            'batch_serial' => DberpPrintViewSupport::formatBatchAndSerial(null, $item->serial_numbers),
            'remark' => filled($item->remark) ? (string) $item->remark : '',
        ];
    }
}
