<template>
  <section class="page-grid">
    <section class="panel">
      <div class="page-hero-card sales-chain-hero delivery-ledger-hero">
        <div class="page-hero-copy">
          <p class="eyebrow">发货台账</p>
          <h3>交付查询、物流信息与批次追溯</h3>
          <p class="page-hero-subtitle">按销售订单聚合发货流水、物流信息和批次追溯，快速查看最新交付状态。</p>
        </div>
        <div class="page-hero-actions">
          <span class="panel-tag">只读台账</span>
        </div>
      </div>

      <div v-if="feedbackMessage" class="feedback-banner">{{ feedbackMessage }}</div>
      <div v-if="errorMessage" class="feedback-banner error-banner">{{ errorMessage }}</div>

      <TableControls
        v-model:search="deliveryControls.search.value"
        v-model:sort-key="deliveryControls.sortKey.value"
        v-model:sort-direction="deliveryControls.sortDirection.value"
        :sort-options="deliveryControls.sortOptions"
        placeholder="搜索销售订单号、发货单号、客户、产品、收货人、运单号、状态"
      />

      <div class="table-wrap">
        <table class="data-table compact-table">
          <thead>
            <tr>
              <th>销售订单号</th>
              <th>客户</th>
              <th>产品</th>
              <th>发货次数</th>
              <th>最近发货时间</th>
              <th>累计发货数量</th>
              <th>运费合计</th>
              <th>最近收货人</th>
              <th>联系电话</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="group in paginatedDeliveryGroups" :key="group.group_key">
              <td>
                <button class="link-button" type="button" @click="openDetailDrawer(group)">
                  {{ group.order_no }}
                </button>
              </td>
              <td>{{ group.customer_name || "-" }}</td>
              <td>{{ group.product_names || "-" }}</td>
              <td>{{ group.delivery_count }}</td>
              <td>{{ formatDateTime(group.latest_delivery_date) }}</td>
              <td>{{ formatQty(group.total_delivery_qty) }}</td>
              <td>{{ formatFreight(group.total_freight_amount) }}</td>
              <td>{{ group.latest_consignee_name || "-" }}</td>
              <td>{{ group.latest_consignee_phone || "-" }}</td>
              <td><StatusBadge :value="group.status" :text="formatStatusLabel(group.status)" /></td>
            </tr>
            <tr v-if="!filteredDeliveryGroups.length">
              <td colspan="10" class="empty-row">暂无发货记录</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="deliveryPage" v-model:page-size="deliveryPageSize" :total="filteredDeliveryGroups.length" />
    </section>

    <FormDrawer
      :open="detailDrawerOpen"
      eyebrow="销售订单发货流水"
      :title="activeDeliveryGroup ? activeDeliveryGroup.order_no : '发货流水'"
      tag="销售订单聚合"
      size="xl"
      @close="detailDrawerOpen = false"
    >
      <section class="drawer-subsection">
        <div class="subsection-head">
          <strong>发货单流水</strong>
          <span class="panel-tag">{{ visibleDeliveries.length }} 单</span>
        </div>
        <TableControls
          v-model:search="deliveryFlowControls.search.value"
          v-model:sort-key="deliveryFlowControls.sortKey.value"
          v-model:sort-direction="deliveryFlowControls.sortDirection.value"
          :sort-options="deliveryFlowControls.sortOptions"
          placeholder="搜索发货单号、收货人、运单号、状态"
        />
        <DrawerDataTable
          :rows="paginatedGroupDeliveries"
          :columns="deliveryFlowDrawerColumns"
          row-key="delivery_id"
          empty-text="暂无发货单流水"
        >
          <template #cell-delivery_no="{ row }">
            <span class="drawer-cell-code" :title="row.delivery_no || ''">{{ row.delivery_no || "-" }}</span>
          </template>
          <template #cell-logistics_photo_url="{ row }">
            <button v-if="row.logistics_photo_url" class="link-button" type="button" @click="openLogisticsPhoto(row.logistics_photo_url)">查看</button>
            <span v-else>-</span>
          </template>
          <template #cell-status="{ row }">
            <StatusBadge :value="row.status" :text="formatStatusLabel(row.status)" />
          </template>
        </DrawerDataTable>
        <PaginationBar v-model:page="deliveryFlowPage" v-model:page-size="deliveryFlowPageSize" :total="filteredGroupDeliveries.length" />
      </section>

      <section class="drawer-subsection">
        <div class="subsection-head">
          <strong>发货明细流水</strong>
          <span class="panel-tag">{{ visibleItems.length }} 条</span>
        </div>
        <TableControls
          v-model:search="itemControls.search.value"
          v-model:sort-key="itemControls.sortKey.value"
          v-model:sort-direction="itemControls.sortDirection.value"
          :sort-options="itemControls.sortOptions"
          placeholder="搜索发货单号、产品、库存批次号、来源库存批次号"
        />
        <DrawerDataTable
          v-model:expanded-rows="expandedDeliveryItemRows"
          :rows="paginatedItems"
          :columns="deliveryItemDrawerColumns"
          row-key="delivery_item_id"
          empty-text="暂无发货明细流水"
        >
          <template #cell-delivery_no="{ row }">
            <span class="drawer-cell-code" :title="row.delivery_no || ''">{{ row.delivery_no || "-" }}</span>
          </template>
          <template #cell-source_inventory_lot_no="{ row }">
            <span class="drawer-cell-code" :title="sourceInventoryLotNo(row)">{{ sourceInventoryLotNo(row) }}</span>
          </template>
          <template #cell-lot_no="{ row }">
            <span class="drawer-cell-code" :title="row.lot_no || ''">{{ row.lot_no || "-" }}</span>
          </template>
          <template #cell-status="{ row }">
            <StatusBadge :value="row.status" :text="formatStatusLabel(row.status)" />
          </template>
          <template #detail="{ row }">
            <div class="drawer-row-detail-grid">
              <article><span>发货单号</span><strong>{{ row.delivery_no || "-" }}</strong></article>
              <article><span>原材料</span><strong>{{ formatSourceMaterial(row) }}</strong></article>
              <article><span>来源库存批次号</span><strong>{{ sourceInventoryLotNo(row) }}</strong></article>
              <article><span>成品批次</span><strong>{{ row.lot_no || "-" }}</strong></article>
              <article><span>状态</span><strong><StatusBadge :value="row.status" :text="formatStatusLabel(row.status)" /></strong></article>
            </div>
          </template>
        </DrawerDataTable>
        <PaginationBar v-model:page="itemPage" v-model:page-size="itemPageSize" :total="filteredItems.length" />
      </section>
    </FormDrawer>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";

import DrawerDataTable from "../components/DrawerDataTable.vue";
import FormDrawer from "../components/FormDrawer.vue";
import PaginationBar from "../components/PaginationBar.vue";
import StatusBadge from "../components/StatusBadge.vue";
import TableControls from "../components/TableControls.vue";
import { fetchResource, openResource } from "../services/api";
import { formatStatusLabel } from "../utils/dictionaries";
import { formatAmount, formatDateTime, formatQty, formatWeight } from "../utils/formatters";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const deliveries = ref([]);
const deliveryItems = ref([]);
const activeDeliveryGroupKey = ref("");
const feedbackMessage = ref("");
const errorMessage = ref("");
const detailDrawerOpen = ref(false);
const expandedDeliveryItemRows = ref([]);

const deliveryLedgerRows = computed(() => buildDeliveryLedgerRows(deliveries.value, deliveryItems.value));
const activeDeliveryGroup = computed(() =>
  deliveryLedgerRows.value.find((item) => item.group_key === activeDeliveryGroupKey.value) || null
);
const visibleDeliveries = computed(() => activeDeliveryGroup.value?.deliveries || []);
const visibleItems = computed(() => {
  const deliveryIds = new Set(visibleDeliveries.value.map((item) => Number(item.delivery_id)));
  return deliveryItems.value.filter((item) => deliveryIds.has(Number(item.delivery_id)));
});

const deliveryControls = useTableControls(deliveryLedgerRows, {
  searchFields: [
    "order_no",
    "customer_name",
    "product_names",
    "delivery_nos",
    "latest_consignee_name",
    "latest_consignee_phone",
    "waybill_nos",
    "status"
  ],
  sortOptions: [
    { key: "order_no", label: "销售订单号" },
    { key: "customer_name", label: "客户" },
    { key: "product_names", label: "产品" },
    { key: "delivery_count", label: "发货次数" },
    { key: "latest_delivery_date", label: "最近发货时间" },
    { key: "total_delivery_qty", label: "发货数量" },
    { key: "total_freight_amount", label: "运费合计" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "latest_delivery_date",
  defaultSortDirection: "desc"
});
const deliveryFlowControls = useTableControls(visibleDeliveries, {
  searchFields: ["delivery_no", "consignee_name", "consignee_phone", "logistics_waybill_no", "status"],
  sortOptions: [
    { key: "delivery_no", label: "发货单号" },
    { key: "delivery_date", label: "发货时间" },
    { key: "total_delivery_qty", label: "发货数量" },
    { key: "logistics_freight_amount", label: "运费" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "delivery_date",
  defaultSortDirection: "desc"
});
const itemControls = useTableControls(visibleItems, {
  searchFields: ["delivery_no", "product_name", "lot_no", "source_material_lot_no", "source_material_sub_batch_no", "status"],
  sortOptions: [
    { key: "delivery_no", label: "发货单号" },
    { key: "source_material_lot_no", label: "来源库存批次号", field: (row) => sourceInventoryLotNo(row) },
    { key: "product_name", label: "产品" },
    { key: "delivery_qty", label: "数量" },
    { key: "delivery_weight_kg", label: "重量" }
  ],
  defaultSortKey: "source_material_lot_no",
  defaultSortDirection: "asc"
});
const filteredDeliveryGroups = deliveryControls.rows;
const filteredGroupDeliveries = deliveryFlowControls.rows;
const filteredItems = itemControls.rows;
const deliveryFlowDrawerColumns = computed(() => [
  { key: "delivery_no", label: "发货单号", type: "code", width: "22%" },
  { key: "delivery_date", label: "发货时间", type: "date", width: "16%", format: (value) => formatDateTime(value) },
  { key: "consignee_name", label: "收货人", width: "12%", format: (value) => value || "-" },
  { key: "consignee_phone", label: "联系电话", width: "13%", format: (value) => value || "-" },
  { key: "logistics_waybill_no", label: "运单号", width: "14%", format: (value) => value || "-" },
  { key: "logistics_freight_amount", label: "运费", type: "number", width: "90px", format: (value) => formatFreight(value) },
  { key: "logistics_photo_url", label: "辅助照片", width: "86px" },
  { key: "total_delivery_qty", label: "发货数量", type: "number", width: "98px", format: (value) => formatQty(value) },
  { key: "status", label: "状态", type: "status", width: "88px", format: (value) => formatStatusLabel(value) }
]);
const deliveryItemDrawerColumns = computed(() => [
  { key: "delivery_no", label: "发货单号", type: "code", width: "18%" },
  { key: "product_name", label: "产品", type: "longText", width: "18%" },
  { key: "source_material_summary", label: "原材料", type: "longText", width: "18%", format: (_value, row) => formatSourceMaterial(row) },
  { key: "source_inventory_lot_no", label: "来源库存批次号", compactLabel: "来源批次", type: "code", width: "20%" },
  { key: "lot_no", label: "成品批次", type: "code", width: "15%" },
  { key: "delivery_qty", label: "数量", type: "number", width: "86px", format: (value) => formatQty(value) },
  { key: "delivery_weight_kg", label: "重量", type: "number", width: "92px", format: (value) => formatWeight(value) },
  { key: "status", label: "状态", type: "status", width: "88px", format: (value) => formatStatusLabel(value) },
  { key: "source_material_code", label: "原材料编码", detailOnly: true },
  { key: "source_material_name", label: "原材料名称", detailOnly: true }
]);
const {
  page: deliveryPage,
  pageSize: deliveryPageSize,
  rows: paginatedDeliveryGroups
} = usePagination(filteredDeliveryGroups);
const {
  page: deliveryFlowPage,
  pageSize: deliveryFlowPageSize,
  rows: paginatedGroupDeliveries
} = usePagination(filteredGroupDeliveries);
const {
  page: itemPage,
  pageSize: itemPageSize,
  rows: paginatedItems
} = usePagination(filteredItems);

function joinUniqueNames(names) {
  const values = names.map((name) => String(name || "").trim()).filter(Boolean);
  return Array.from(new Set(values)).join("、");
}

function buildDeliveryLedgerRows(deliveryRows = [], itemRows = []) {
  const itemsByDeliveryId = new Map();
  itemRows.forEach((item) => {
    const deliveryId = Number(item.delivery_id || 0);
    if (!itemsByDeliveryId.has(deliveryId)) {
      itemsByDeliveryId.set(deliveryId, []);
    }
    itemsByDeliveryId.get(deliveryId).push(item);
  });

  const groups = new Map();
  deliveryRows.forEach((delivery) => {
    const salesOrderId = Number(delivery.sales_order_id || 0);
    const groupKey = salesOrderId ? `sales-order:${salesOrderId}` : `direct-delivery:${delivery.delivery_id}`;
    if (!groups.has(groupKey)) {
      groups.set(groupKey, {
        group_key: groupKey,
        sales_order_id: salesOrderId || null,
        order_no: delivery.order_no || `直接客户发货 · ${delivery.delivery_no}`,
        customer_name: delivery.customer_name || "",
        deliveries: [],
        delivery_items: [],
        delivery_count: 0,
        total_delivery_qty: 0,
        total_line_amount: 0,
        total_freight_amount: 0,
        latest_delivery_date: null,
        latest_consignee_name: "",
        latest_consignee_phone: "",
        product_names: "",
        delivery_nos: "",
        waybill_nos: "",
        status: "-"
      });
    }

    const group = groups.get(groupKey);
    const deliveryItemsForRow = itemsByDeliveryId.get(Number(delivery.delivery_id || 0)) || [];
    group.deliveries.push(delivery);
    group.delivery_items.push(...deliveryItemsForRow);
    group.delivery_count += 1;
    group.total_delivery_qty += Number(delivery.total_delivery_qty || 0);
    group.total_line_amount += Number(delivery.total_line_amount || 0);
    group.total_freight_amount += Number(delivery.logistics_freight_amount || 0);
    if (isLaterDate(delivery.delivery_date, group.latest_delivery_date)) {
      group.latest_delivery_date = delivery.delivery_date;
      group.latest_consignee_name = delivery.consignee_name || "";
      group.latest_consignee_phone = delivery.consignee_phone || "";
    }
  });

  return Array.from(groups.values())
    .map((group) => {
      const productNamesFromItems = joinUniqueNames(group.delivery_items.map((item) => item.product_name));
      const productNamesFromDeliveries = joinUniqueNames(group.deliveries.map((delivery) => delivery.product_names));
      const deliveryNos = joinUniqueNames(group.deliveries.map((delivery) => delivery.delivery_no));
      const waybillNos = joinUniqueNames(group.deliveries.map((delivery) => delivery.logistics_waybill_no));
      return {
        ...group,
        product_names: productNamesFromItems || productNamesFromDeliveries || "-",
        delivery_nos: deliveryNos,
        waybill_nos: waybillNos,
        status: aggregateDeliveryStatus(group.deliveries)
      };
    })
    .sort((left, right) => compareDateDesc(left.latest_delivery_date, right.latest_delivery_date));
}

function aggregateDeliveryStatus(rows) {
  const statuses = Array.from(new Set(rows.map((row) => String(row.status || "").trim()).filter(Boolean)));
  if (!statuses.length) {
    return "-";
  }
  return statuses.length === 1 ? statuses[0] : "多状态";
}

function isLaterDate(candidate, current) {
  if (!current) {
    return Boolean(candidate);
  }
  return new Date(candidate || 0).getTime() > new Date(current || 0).getTime();
}

function compareDateDesc(left, right) {
  return new Date(right || 0).getTime() - new Date(left || 0).getTime();
}

function formatSourceMaterial(item) {
  const codeName = [item.source_material_code, item.source_material_name].filter(Boolean).join(" · ");
  return codeName || item.source_material_summary || "-";
}

function sourceInventoryLotNo(item) {
  return item?.source_material_lot_no || item?.source_material_sub_batch_no || "-";
}

async function openLogisticsPhoto(url) {
  if (!url) {
    return;
  }
  try {
    await openResource(url);
  } catch (error) {
    errorMessage.value = error.message || "辅助照片打开失败";
  }
}

function formatFreight(value) {
  if (value === null || value === undefined || value === "") {
    return "-";
  }
  return `¥${formatAmount(value)}`;
}

function openDetailDrawer(group) {
  activeDeliveryGroupKey.value = group.group_key;
  expandedDeliveryItemRows.value = [];
  deliveryFlowPage.value = 1;
  itemPage.value = 1;
  detailDrawerOpen.value = true;
}

async function loadAll() {
  const [deliveryRows, deliveryItemRows] = await Promise.all([
    fetchResource("/sales/deliveries?limit=500", []),
    fetchResource("/sales/delivery-items?limit=500", [])
  ]);
  deliveries.value = deliveryRows;
  deliveryItems.value = deliveryItemRows;
}

onMounted(async () => {
  await loadAll();
});
</script>
