<template>
  <section class="page-grid">
    <section class="panel">
      <div class="panel-header">
        <div>
          <p class="eyebrow">工单台账</p>
          <h3>按生产工单追踪领料、用料、余料归还与成品入库进度</h3>
        </div>
        <div class="workflow-inline-actions">
          <span class="panel-tag">生产执行</span>
        </div>
      </div>

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

      <TableControls
        v-model:search="workOrderControls.search.value"
        v-model:sort-key="workOrderControls.sortKey.value"
        v-model:sort-direction="workOrderControls.sortDirection.value"
        :sort-options="workOrderControls.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="workOrder in paginatedWorkOrders" :key="workOrder.work_order_id" :class="{ 'row-selected': selectedWorkOrderId === workOrder.work_order_id }">
              <td>
                <button class="link-button" type="button" @click="openDetailDrawer(workOrder)">
                  {{ workOrder.work_order_no || "-" }}
                </button>
              </td>
              <td>{{ formatProductName(workOrder) }}</td>
              <td>{{ workOrder.material_summary || "-" }}</td>
              <td>
                <span class="drawer-cell-code" :title="workOrder.source_lot_summary || ''">{{ workOrder.source_lot_summary || "-" }}</span>
              </td>
              <td>{{ formatQty(workOrder.planned_qty) }}</td>
              <td>{{ formatWeight(workOrder.issued_weight_kg) }}</td>
              <td>{{ formatWeight(workOrder.used_material_weight_kg) }}</td>
              <td>{{ formatWeight(workOrder.returned_material_weight_kg) }}</td>
              <td>{{ formatQty(workOrder.finished_received_qty) }}</td>
              <td>{{ formatStatusLabel(workOrder.status) }}</td>
            </tr>
            <tr v-if="!filteredWorkOrders.length">
              <td colspan="10" class="empty-row">暂无工单台账</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="workOrderPage" v-model:page-size="workOrderPageSize" :total="filteredWorkOrders.length" />
    </section>

    <Teleport to="body">
      <div v-if="detailDrawerOpen" class="workflow-drawer-mask dual-drawer-mask work-order-detail-mask" @click.self="closeDetailDrawer">
        <div class="dual-drawer-shell">
          <aside class="workflow-drawer compact-side-drawer">
            <header class="workflow-drawer-head">
              <div>
                <p class="eyebrow">工单入库上限</p>
                <h3>{{ activeWorkOrder?.work_order_no || "生产工单" }}</h3>
              </div>
              <button class="ghost-button" type="button" @click="closeDetailDrawer">关闭</button>
            </header>

            <div class="drawer-row-detail-grid">
              <article v-for="card in limitCards" :key="card.key">
                <span>{{ card.label }}</span>
                <strong>{{ card.value }}</strong>
              </article>
            </div>

            <TableControls
              v-model:search="materialControls.search.value"
              v-model:sort-key="materialControls.sortKey.value"
              v-model:sort-direction="materialControls.sortDirection.value"
              :sort-options="materialControls.sortOptions"
              placeholder="搜索原材料、来源库存批次号"
            />

            <DrawerDataTable
              v-model:expanded-rows="expandedWorkOrderMaterialRows"
              :rows="paginatedMaterials"
              :columns="workOrderMaterialDrawerColumns"
              row-key="ledger_material_key"
              empty-text="暂无领料批次明细"
            >
              <template #cell-source_lot_no="{ row }">
                <span class="drawer-cell-code" :title="row.source_lot_no || ''">{{ row.source_lot_no || "-" }}</span>
              </template>
              <template #detail="{ row }">
                <div class="drawer-row-detail-grid">
                  <article><span>原材料编码</span><strong>{{ row.material_code || "-" }}</strong></article>
                  <article><span>原材料</span><strong>{{ row.material_name || "-" }}</strong></article>
                  <article><span>来源库存批次号</span><strong>{{ row.source_lot_no || "-" }}</strong></article>
                  <article><span>领料金额</span><strong>¥{{ formatAmount(row.amount) }}</strong></article>
                  <article><span>单位成本</span><strong>¥{{ formatAmount(row.unit_cost) }}/kg</strong></article>
                </div>
              </template>
            </DrawerDataTable>
            <PaginationBar v-model:page="materialPage" v-model:page-size="materialPageSize" :total="filteredMaterials.length" />
          </aside>

          <aside class="workflow-drawer compact-side-drawer">
            <header class="workflow-drawer-head">
              <div>
                <p class="eyebrow">工序明细</p>
                <h3>{{ activeWorkOrder?.product_name || "工序执行链" }}</h3>
              </div>
            </header>

            <TableControls
              v-model:search="operationControls.search.value"
              v-model:sort-key="operationControls.sortKey.value"
              v-model:sort-direction="operationControls.sortDirection.value"
              :sort-options="operationControls.sortOptions"
              placeholder="搜索工序、状态"
            />

            <DrawerDataTable
              v-model:expanded-rows="expandedWorkOrderOperationRows"
              :rows="paginatedOperations"
              :columns="workOrderOperationDrawerColumns"
              row-key="work_order_operation_id"
              empty-text="暂无工序明细"
            >
              <template #detail="{ row }">
                <div class="drawer-row-detail-grid">
                  <article><span>工序</span><strong>{{ row.operation_name || "-" }}</strong></article>
                  <article><span>已报工</span><strong>{{ formatQty(row.report_qty) }}</strong></article>
                  <article><span>良品数</span><strong>{{ formatQty(row.good_qty) }}</strong></article>
                  <article><span>报废数</span><strong>{{ formatQty(row.scrap_qty) }}</strong></article>
                  <article><span>状态</span><strong>{{ formatStatusLabel(row.status) }}</strong></article>
                </div>
              </template>
            </DrawerDataTable>
            <PaginationBar v-model:page="operationPage" v-model:page-size="operationPageSize" :total="filteredOperations.length" />
          </aside>
        </div>
      </div>
    </Teleport>
  </section>
</template>

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

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

const workOrders = ref([]);
const selectedWorkOrderId = ref(null);
const errorMessage = ref("");
const detailDrawerOpen = ref(false);
const expandedWorkOrderMaterialRows = ref([]);
const expandedWorkOrderOperationRows = ref([]);

const activeWorkOrder = computed(() => workOrders.value.find((item) => item.work_order_id === selectedWorkOrderId.value) || null);
const visibleMaterials = computed(() =>
  (activeWorkOrder.value?.materials || []).map((item, index) => ({
    ...item,
    ledger_material_key: `${item.source_lot_id || "lot"}-${item.material_item_id || "material"}-${index}`
  }))
);
const visibleOperations = computed(() => activeWorkOrder.value?.operations || []);
const activeLimits = computed(() => activeWorkOrder.value?.limits || {});
const limitCards = computed(() => [
  { key: "finished", label: "可入库成品", value: formatQty(activeLimits.value.max_finished_inbound_qty) },
  { key: "scrap", label: "可入库废料", value: formatWeight(activeLimits.value.max_scrap_inbound_weight_kg) },
  { key: "surplus", label: "可归还余料", value: formatWeight(activeLimits.value.max_surplus_inbound_weight_kg) }
]);

const workOrderControls = useTableControls(workOrders, {
  searchFields: ["work_order_no", "product_code", "product_name", "material_summary", "source_lot_summary", "status"],
  sortOptions: [
    { key: "work_order_no", label: "生产工单" },
    { key: "product_name", label: "产品" },
    { key: "material_summary", label: "原材料" },
    { key: "source_lot_summary", label: "来源库存批次号" },
    { key: "planned_qty", label: "计划生产数" },
    { key: "issued_weight_kg", label: "领料重量" },
    { key: "used_material_weight_kg", label: "已用领料重量" },
    { key: "returned_material_weight_kg", label: "归还原料重量" },
    { key: "finished_received_qty", label: "已入库成品" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "work_order_no",
  defaultSortDirection: "desc"
});
const materialControls = useTableControls(visibleMaterials, {
  searchFields: ["material_code", "material_name", "source_lot_no"],
  sortOptions: [
    { key: "material_name", label: "原材料" },
    { key: "source_lot_no", label: "来源库存批次号" },
    { key: "issued_weight_kg", label: "领料重量" },
    { key: "returned_weight_kg", label: "归还重量" },
    { key: "amount", label: "领料金额" }
  ],
  defaultSortKey: "material_name",
  defaultSortDirection: "asc"
});
const operationControls = useTableControls(visibleOperations, {
  searchFields: ["operation_name", "status"],
  sortOptions: [
    { key: "seq_no", label: "序号" },
    { key: "operation_name", label: "工序" },
    { key: "report_qty", label: "已报工" },
    { key: "good_qty", label: "良品数" },
    { key: "scrap_qty", label: "报废数" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "seq_no",
  defaultSortDirection: "asc"
});
const filteredWorkOrders = workOrderControls.rows;
const filteredMaterials = materialControls.rows;
const filteredOperations = operationControls.rows;
const workOrderMaterialDrawerColumns = computed(() => [
  { key: "material_name", label: "原材料", type: "longText", width: "25%" },
  { key: "source_lot_no", label: "来源库存批次号", compactLabel: "库存批次", type: "code", width: "30%" },
  { key: "issued_weight_kg", label: "领料重量", type: "number", width: "96px", format: (value) => formatWeight(value) },
  { key: "returned_weight_kg", label: "归还重量", type: "number", width: "96px", format: (value) => formatWeight(value) },
  { key: "amount", label: "领料金额", type: "number", width: "104px", format: (value) => `¥${formatAmount(value)}` },
  { key: "material_detail", label: "批次详情", detailOnly: true }
]);
const workOrderOperationDrawerColumns = computed(() => [
  { key: "seq_no", label: "序号", type: "number", width: "64px" },
  { key: "operation_name", label: "工序", type: "longText", width: "28%" },
  { key: "report_qty", label: "已报工", type: "number", width: "96px", format: (value) => formatQty(value) },
  { key: "good_qty", label: "良品数", type: "number", width: "96px", format: (value) => formatQty(value) },
  { key: "scrap_qty", label: "报废数", type: "number", width: "96px", format: (value) => formatQty(value) },
  { key: "status", label: "状态", type: "status", width: "88px", format: (value) => formatStatusLabel(value) },
  { key: "operation_detail", label: "工序详情", detailOnly: true }
]);
const {
  page: workOrderPage,
  pageSize: workOrderPageSize,
  rows: paginatedWorkOrders
} = usePagination(filteredWorkOrders);
const {
  page: materialPage,
  pageSize: materialPageSize,
  rows: paginatedMaterials
} = usePagination(filteredMaterials);
const {
  page: operationPage,
  pageSize: operationPageSize,
  rows: paginatedOperations
} = usePagination(filteredOperations);

useBodyScrollLock(computed(() => detailDrawerOpen.value));

function formatProductName(workOrder) {
  const code = workOrder?.product_code ? `${workOrder.product_code} · ` : "";
  return `${code}${workOrder?.product_name || "-"}`;
}

function openDetailDrawer(workOrder) {
  selectedWorkOrderId.value = workOrder.work_order_id;
  expandedWorkOrderMaterialRows.value = [];
  expandedWorkOrderOperationRows.value = [];
  detailDrawerOpen.value = true;
}

function closeDetailDrawer() {
  detailDrawerOpen.value = false;
}

async function loadAll() {
  errorMessage.value = "";
  try {
    workOrders.value = await fetchResource("/production/work-order-ledger?limit=500", []);
  } catch (error) {
    errorMessage.value = error.message || "工单台账加载失败";
    workOrders.value = [];
  }
}

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