<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>
          <button class="primary-button" type="button" @click="openCreateDrawer">新增入库</button>
        </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="receiptControls.search.value"
        v-model:sort-key="receiptControls.sortKey.value"
        v-model:sort-direction="receiptControls.sortDirection.value"
        :sort-options="receiptControls.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>
            </tr>
          </thead>
          <tbody>
            <tr v-for="receipt in paginatedReceipts" :key="receipt.completion_receipt_id" :class="{ 'row-selected': selectedReceiptId === receipt.completion_receipt_id }">
              <td>
                <button class="link-button" type="button" @click="openDetailDrawer(receipt)">
                  {{ receipt.receipt_no }}
                </button>
              </td>
              <td>{{ receipt.work_order_no }}</td>
              <td>{{ receipt.product_name }}</td>
              <td>{{ formatQty(receipt.total_receipt_qty) }}</td>
              <td>{{ formatWeight(receipt.total_receipt_weight_kg) }}</td>
              <td>{{ formatStatusLabel(receipt.status) }}</td>
            </tr>
            <tr v-if="!filteredReceipts.length">
              <td colspan="6" class="empty-row">暂无成品入库单</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="receiptPage" v-model:page-size="receiptPageSize" :total="filteredReceipts.length" />
    </section>

    <FormDrawer
      :open="drawerOpen"
      eyebrow="完工入库"
      title="新增成品入库"
      description="只允许已完成全部工序报工且仍有可入库数量的库存批次号过账。"
      tag="成品过账"
      wide
      @close="drawerOpen = false"
    >
      <form class="stack-form" @submit.prevent="submitReceipt">
        <div class="double-field">
          <label class="form-field">
            <span>库存批次号</span>
            <select v-model.number="form.work_order_id" @change="applyWorkOrder" required>
              <option disabled value="">请选择库存批次号</option>
              <option v-for="workOrder in receivableWorkOrders" :key="workOrder.work_order_id" :value="workOrder.work_order_id">
                {{ workOrder.work_order_no }} · {{ workOrder.product_name }} · 可入库 {{ formatQty(workOrder.max_receivable_qty) }}
              </option>
            </select>
          </label>
          <label class="form-field">
            <span>成品仓</span>
            <select v-model.number="form.warehouse_id" required>
              <option disabled value="">请选择仓库</option>
              <option v-for="warehouse in finishedWarehouses" :key="warehouse.id" :value="warehouse.id">
                {{ warehouse.warehouse_name }}
              </option>
            </select>
          </label>
        </div>

        <div class="triple-field">
          <label class="form-field">
            <span>接收人</span>
            <select v-model.number="form.receiver_employee_id">
              <option value="">请选择</option>
              <option v-for="employee in employees" :key="employee.id" :value="employee.id">
                {{ employeeOptionLabel(employee) }}
              </option>
            </select>
          </label>
          <label class="form-field">
            <span>产品</span>
            <input :value="currentProductLabel" type="text" disabled />
          </label>
          <label class="form-field">
            <span>库位</span>
            <select v-model.number="form.location_id">
              <option value="">默认库位</option>
              <option v-for="location in currentLocations" :key="location.id" :value="location.id">
                {{ location.location_name }}
              </option>
            </select>
          </label>
        </div>

        <div class="triple-field">
          <label class="form-field">
            <span>最大可入库数量</span>
            <input :value="formatQty(form.max_receivable_qty)" type="text" disabled />
          </label>
          <label class="form-field">
            <span>入库数量</span>
            <input
              v-model.number="form.receipt_qty"
              type="number"
              min="1"
              step="1"
              :max="form.max_receivable_qty || undefined"
              required
              @input="recalculateReceiptWeight"
            />
          </label>
          <label class="form-field">
            <span>入库重量(kg)</span>
            <input v-model.number="form.receipt_weight_kg" type="number" min="0" step="0.001" readonly />
          </label>
        </div>

        <label class="form-field">
          <span>备注</span>
          <textarea v-model.trim="form.remark" rows="3"></textarea>
        </label>

        <button class="primary-button" type="submit" :disabled="submitting">
          {{ submitting ? "过账中..." : "创建成品入库单" }}
        </button>
      </form>
    </FormDrawer>

    <FormDrawer
      :open="detailDrawerOpen"
      eyebrow="入库明细"
      :title="activeReceipt ? `${activeReceipt.receipt_no} · ${activeReceipt.product_name}` : '入库明细'"
      tag="成品批次"
      size="xl"
      @close="detailDrawerOpen = false"
    >
      <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="expandedCompletionItemRows"
        :rows="paginatedItems"
        :columns="completionItemDrawerColumns"
        row-key="completion_receipt_item_id"
        empty-text="暂无成品入库明细"
      >
        <template #cell-lot_no="{ row }">
          <span class="drawer-cell-code" :title="row.lot_no || ''">{{ row.lot_no || "-" }}</span>
        </template>
        <template #cell-source_inventory_lot_no="{ row }">
          <span class="drawer-cell-code" :title="sourceInventoryLotNo(row)">{{ sourceInventoryLotNo(row) }}</span>
        </template>
        <template #detail="{ row }">
          <div class="drawer-row-detail-grid">
            <article><span>来源库存批次号</span><strong>{{ sourceInventoryLotNo(row) }}</strong></article>
            <article><span>来源材料摘要</span><strong>{{ row.source_material_summary || "-" }}</strong></article>
            <article><span>库位</span><strong>{{ row.location_name || "-" }}</strong></article>
            <article><span>入库材料成本(毛重；元/件)</span><strong>¥{{ formatAmount(row.unit_cost) }}/件</strong></article>
          </div>
        </template>
      </DrawerDataTable>
      <PaginationBar v-model:page="itemPage" v-model:page-size="itemPageSize" :total="filteredItems.length" />
    </FormDrawer>
  </section>
</template>

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

import DrawerDataTable from "../components/DrawerDataTable.vue";
import FormDrawer from "../components/FormDrawer.vue";
import PaginationBar from "../components/PaginationBar.vue";
import TableControls from "../components/TableControls.vue";
import { fetchResource, postResource } from "../services/api";
import { PERSONNEL_PERMISSION_CODES, employeeOptionLabel, fetchPermissionEmployeeOptions } from "../services/employeeOptions";
import { formatProductLabel, formatStatusLabel } from "../utils/dictionaries";
import { formatAmount, formatQty, formatWeight } from "../utils/formatters";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const workOrders = ref([]);
const products = ref([]);
const warehouses = ref([]);
const locations = ref([]);
const employees = ref([]);
const receipts = ref([]);
const receiptItems = ref([]);
const feedbackMessage = ref("");
const errorMessage = ref("");
const submitting = ref(false);
const selectedReceiptId = ref(null);
const drawerOpen = ref(false);
const detailDrawerOpen = ref(false);
const expandedCompletionItemRows = ref([]);

const form = reactive(buildEmptyForm());

const receivableWorkOrders = computed(() =>
  workOrders.value.filter((item) => Boolean(item.all_operations_done) && Number(item.max_receivable_qty || 0) > 0)
);
const finishedWarehouses = computed(() => warehouses.value.filter((item) => normalizeWarehouseType(item) === "FINISHED"));
const currentLocations = computed(() => locations.value.filter((item) => item.warehouse_id === Number(form.warehouse_id)));
const currentProduct = computed(() => products.value.find((item) => item.item_id === Number(form.product_item_id)) || null);
const currentProductLabel = computed(() => formatProductLabel(currentProduct.value));
const activeReceipt = computed(() => receipts.value.find((item) => item.completion_receipt_id === selectedReceiptId.value) || null);
const visibleItems = computed(() => {
  if (!selectedReceiptId.value) {
    return receiptItems.value;
  }
  return receiptItems.value.filter((item) => item.completion_receipt_id === selectedReceiptId.value);
});
const receiptControls = useTableControls(receipts, {
  searchFields: ["receipt_no", "work_order_no", "product_name", "status"],
  sortOptions: [
    { key: "receipt_no", label: "入库单号" },
    { key: "work_order_no", label: "库存批次号" },
    { key: "product_name", label: "产品" },
    { key: "total_receipt_qty", label: "数量" },
    { key: "total_receipt_weight_kg", label: "重量" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "receipt_no",
  defaultSortDirection: "desc"
});
const itemControls = useTableControls(visibleItems, {
  searchFields: ["product_name", "lot_no", "location_name", "source_material_lot_no", "source_material_sub_batch_no", "source_material_summary"],
  sortOptions: [
    { key: "product_name", label: "产品" },
    { key: "lot_no", label: "批次" },
    { key: "receipt_qty", label: "数量" },
    { key: "receipt_weight_kg", label: "重量" },
    { key: "source_material_lot_no", label: "来源库存批次号", field: (row) => sourceInventoryLotNo(row) },
    { key: "unit_cost", label: "入库材料成本" }
  ],
  defaultSortKey: "lot_no",
  defaultSortDirection: "desc"
});
const filteredReceipts = receiptControls.rows;
const filteredItems = itemControls.rows;
const completionItemDrawerColumns = computed(() => [
  { key: "product_name", label: "产品", type: "longText", width: "24%" },
  { key: "lot_no", label: "成品批次", type: "code", width: "22%" },
  { key: "receipt_qty", label: "数量", type: "number", width: "88px", format: (value) => formatQty(value) },
  { key: "receipt_weight_kg", label: "重量", type: "number", width: "96px", format: (value) => formatWeight(value) },
  { key: "source_inventory_lot_no", label: "来源库存批次号", compactLabel: "来源批次", type: "code", width: "22%" },
  { key: "unit_cost", label: "材料成本", type: "number", width: "116px", format: (value) => `¥${formatAmount(value)}/件` },
  { key: "location_name", label: "库位", detailOnly: true },
  { key: "source_material_summary", label: "来源材料摘要", detailOnly: true }
]);
const {
  page: receiptPage,
  pageSize: receiptPageSize,
  rows: paginatedReceipts
} = usePagination(filteredReceipts);
const {
  page: itemPage,
  pageSize: itemPageSize,
  rows: paginatedItems
} = usePagination(filteredItems);

function buildEmptyForm() {
  return {
    work_order_id: "",
    warehouse_id: "",
    receiver_employee_id: "",
    product_item_id: "",
    location_id: "",
    max_receivable_qty: 0,
    unit_weight_kg: 0,
    receipt_qty: 0,
    receipt_weight_kg: 0,
    remark: ""
  };
}

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

function resetForm() {
  Object.assign(form, buildEmptyForm());
  form.warehouse_id = finishedWarehouses.value[0]?.id || "";
}

function normalizeWarehouseType(item) {
  return String(item?.warehouse_type || "").toUpperCase();
}

function openCreateDrawer() {
  resetForm();
  feedbackMessage.value = "";
  errorMessage.value = "";
  drawerOpen.value = true;
}

function openDetailDrawer(receipt) {
  selectedReceiptId.value = receipt.completion_receipt_id;
  expandedCompletionItemRows.value = [];
  detailDrawerOpen.value = true;
}

function recalculateReceiptWeight() {
  if (Number(form.receipt_qty || 0) > Number(form.max_receivable_qty || 0)) {
    form.receipt_qty = Number(form.max_receivable_qty || 0);
  }
  form.receipt_weight_kg = Number((Number(form.receipt_qty || 0) * Number(form.unit_weight_kg || 0)).toFixed(3));
}

function applyWorkOrder() {
  const workOrder = workOrders.value.find((item) => item.work_order_id === Number(form.work_order_id));
  if (!workOrder) {
    return;
  }
  const product = products.value.find((item) => item.item_id === Number(workOrder.product_item_id));
  form.product_item_id = workOrder.product_item_id;
  form.max_receivable_qty = Number(workOrder.max_receivable_qty || 0);
  form.unit_weight_kg = Number(product?.unit_weight_kg || 0);
  form.receipt_qty = Number(workOrder.max_receivable_qty || 0);
  recalculateReceiptWeight();
}

async function loadAll() {
  const [workOrderRows, productRows, warehouseRows, locationRows, employeeRows, receiptRows, itemRows] = await Promise.all([
    fetchResource("/production/work-orders", []),
    fetchResource("/master-data/products", []),
    fetchResource("/master-data/warehouses", []),
    fetchResource("/master-data/locations", []),
    fetchPermissionEmployeeOptions(PERSONNEL_PERMISSION_CODES.INVENTORY_LEDGER),
    fetchResource("/production/completion-receipts", []),
    fetchResource("/production/completion-items", [])
  ]);
  workOrders.value = workOrderRows;
  products.value = productRows;
  warehouses.value = warehouseRows;
  locations.value = locationRows;
  employees.value = employeeRows;
  receipts.value = receiptRows;
  receiptItems.value = itemRows;
}

async function submitReceipt() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  submitting.value = true;
  try {
    const result = await postResource("/production/completion-receipts", {
      work_order_id: Number(form.work_order_id),
      warehouse_id: Number(form.warehouse_id),
      receiver_employee_id: form.receiver_employee_id ? Number(form.receiver_employee_id) : null,
      remark: form.remark || null,
      items: [
        {
          product_item_id: Number(form.product_item_id),
          location_id: form.location_id ? Number(form.location_id) : null,
          receipt_qty: Number(form.receipt_qty || 0),
          receipt_weight_kg: Number(form.receipt_weight_kg || 0)
        }
      ]
    });
    feedbackMessage.value = `成品入库单 ${result.receipt_no} 已创建`;
    selectedReceiptId.value = result.completion_receipt_id;
    drawerOpen.value = false;
    detailDrawerOpen.value = true;
    await loadAll();
    resetForm();
  } catch (error) {
    errorMessage.value = error.message || "成品入库失败";
  } finally {
    submitting.value = false;
  }
}

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