<template>
  <section class="page-grid">
    <section class="panel panel-hero master-compact-hero">
      <div class="hero-copy">
        <p class="eyebrow">产品管理</p>
        <span
          class="title-with-help"
          title="02-1 只保留产品列表，新增或编辑时再进入流程抽屉，按产品资料、供应商、原材料、BOM、工艺路线逐步配置。"
        >
          <h3>产品列表与流程化建档入口</h3>
        </span>
      </div>
    </section>

    <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="productControls.search.value"
        v-model:sort-key="productControls.sortKey.value"
        v-model:sort-direction="productControls.sortDirection.value"
        :sort-options="productControls.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>
            </tr>
          </thead>
          <tbody>
            <tr v-for="product in paginatedProducts" :key="product.item_code">
              <td>
                <button class="link-button" type="button" @click="openDetailDrawer(product)">
                  {{ product.item_code }}
                </button>
              </td>
              <td>{{ product.item_name }}</td>
              <td>{{ product.product_family || "-" }}</td>
              <td>
                <select v-model.number="versionSelections[product.item_code]" @change="applyProductVersion(product.item_code)">
                  <option v-for="option in product.version_options" :key="option.item_id" :value="option.item_id">
                    {{ option.version_no }}
                  </option>
                </select>
              </td>
              <td>{{ product.specification || "-" }}</td>
              <td>{{ Number(product.unit_weight_kg || 0).toFixed(3) }}</td>
              <td>{{ formatRate(product.allowed_scrap_rate) }}</td>
              <td>{{ formatStatusLabel(product.status) }}</td>
              <td class="action-row">
                <button class="ghost-button" type="button" @click="openEditDrawer(product)">编辑</button>
                <button class="ghost-button danger-ghost" type="button" @click="removeProduct(product)">删除</button>
              </td>
            </tr>
            <tr v-if="!filteredProducts.length">
              <td colspan="9" class="empty-row">暂无产品主档</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="productPage" v-model:page-size="productPageSize" :total="filteredProducts.length" />
    </section>

    <ProductWorkflowDrawer
      :open="drawerOpen"
      :mode="drawerMode"
      :product="drawerProduct"
      @close="closeDrawer"
      @saved="handleDrawerSaved"
    />

    <FormDrawer
      :open="detailDrawerOpen"
      eyebrow="产品详情"
      :title="detailProduct ? `${detailProduct.item_code} · ${detailProduct.item_name}` : '产品详情'"
      tag="只读详情"
      @close="closeDetailDrawer"
    >
      <div v-if="detailProduct" class="detail-grid">
        <div class="detail-item">
          <span>产品编码</span>
          <strong>{{ detailProduct.item_code }}</strong>
        </div>
        <div class="detail-item">
          <span>版本号</span>
          <strong>{{ detailProduct.version_no }}</strong>
        </div>
        <div class="detail-item">
          <span>产品名称</span>
          <strong>{{ detailProduct.item_name }}</strong>
        </div>
        <div class="detail-item">
          <span>产品系列</span>
          <strong>{{ detailProduct.product_family || "-" }}</strong>
        </div>
        <div class="detail-item">
          <span>规格</span>
          <strong>{{ detailProduct.specification || "-" }}</strong>
        </div>
        <div class="detail-item">
          <span>图号</span>
          <strong>{{ detailProduct.drawing_no || "-" }}</strong>
        </div>
        <div class="detail-item">
          <span>单重(kg)</span>
          <strong>{{ Number(detailProduct.unit_weight_kg || 0).toFixed(3) }}</strong>
        </div>
        <div class="detail-item">
          <span>允许报废率</span>
          <strong>{{ formatRate(detailProduct.allowed_scrap_rate) }}</strong>
        </div>
        <div class="detail-item">
          <span>安全库存重量</span>
          <strong>{{ Number(detailProduct.safety_stock_weight_kg || 0).toFixed(3) }} kg</strong>
        </div>
        <div class="detail-item">
          <span>状态</span>
          <strong>{{ formatStatusLabel(detailProduct.status) }}</strong>
        </div>
        <div class="detail-block">
          <span>质量标准</span>
          <strong>{{ detailProduct.quality_standard || "-" }}</strong>
        </div>
      </div>
    </FormDrawer>
  </section>
</template>

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

import FormDrawer from "../components/FormDrawer.vue";
import PaginationBar from "../components/PaginationBar.vue";
import ProductWorkflowDrawer from "../components/ProductWorkflowDrawer.vue";
import TableControls from "../components/TableControls.vue";
import { deleteResource, fetchResource } from "../services/api";
import { buildVersionedRows, formatStatusLabel } from "../utils/dictionaries";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const products = ref([]);
const feedbackMessage = ref("");
const errorMessage = ref("");
const versionSelections = reactive({});

const drawerOpen = ref(false);
const drawerMode = ref("create");
const drawerProduct = ref(null);
const detailDrawerOpen = ref(false);
const detailProduct = ref(null);

const productGroups = computed(() => buildVersionedRows(products.value, { codeKey: "item_code", idKey: "item_id" }));
const visibleProducts = computed(() =>
  productGroups.value.map((group) => {
    const selectedId = Number(versionSelections[group.code] || group.active_id);
    const activeRow = group.rows.find((row) => row.item_id === selectedId) || group.rows[0];
    return {
      ...activeRow,
      version_options: group.rows.map((row) => ({
        item_id: row.item_id,
        version_no: row.version_no
      }))
    };
  })
);
const productControls = useTableControls(visibleProducts, {
  searchFields: ["item_code", "item_name", "product_family", "version_no", "specification", "status"],
  sortOptions: [
    { key: "item_code", label: "产品编码" },
    { key: "item_name", label: "产品名称" },
    { key: "product_family", label: "产品系列" },
    { key: "version_no", label: "版本" },
    { key: "unit_weight_kg", label: "单重" },
    { key: "allowed_scrap_rate", label: "报废率" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "item_code",
  defaultSortDirection: "asc"
});
const filteredProducts = productControls.rows;
const {
  page: productPage,
  pageSize: productPageSize,
  rows: paginatedProducts
} = usePagination(filteredProducts);

function formatRate(rate) {
  const numeric = Number(rate || 0);
  return `${(numeric * 100).toFixed(2)}%`;
}

function syncVersionSelections(rows) {
  const groups = buildVersionedRows(rows, { codeKey: "item_code", idKey: "item_id" });
  const validCodes = new Set(groups.map((group) => group.code));
  Object.keys(versionSelections).forEach((code) => {
    if (!validCodes.has(code)) {
      delete versionSelections[code];
    }
  });
  groups.forEach((group) => {
    const currentSelection = Number(versionSelections[group.code] || 0);
    if (!group.rows.some((row) => row.item_id === currentSelection)) {
      versionSelections[group.code] = group.active_id;
    }
  });
}

async function loadProducts() {
  const rows = await fetchResource("/master-data/products", []);
  products.value = rows;
  syncVersionSelections(rows);
}

function applyProductVersion(itemCode) {
  const currentProduct = products.value.find((item) => item.item_id === Number(versionSelections[itemCode] || 0));
  if (currentProduct) {
    versionSelections[itemCode] = currentProduct.item_id;
  }
}

function openCreateDrawer() {
  errorMessage.value = "";
  drawerMode.value = "create";
  drawerProduct.value = null;
  drawerOpen.value = true;
}

function openEditDrawer(product) {
  errorMessage.value = "";
  drawerMode.value = "edit";
  drawerProduct.value = { ...product };
  drawerOpen.value = true;
}

function openDetailDrawer(product) {
  detailProduct.value = { ...product };
  detailDrawerOpen.value = true;
}

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

function closeDrawer() {
  drawerOpen.value = false;
}

async function handleDrawerSaved({ product, message }) {
  feedbackMessage.value = message || "产品已保存";
  errorMessage.value = "";
  await loadProducts();
  if (product?.item_code && product?.item_id) {
    versionSelections[product.item_code] = product.item_id;
  }
}

async function removeProduct(product) {
  feedbackMessage.value = "";
  errorMessage.value = "";

  if (!window.confirm(`确认删除产品“${product.item_name} ${product.version_no}”吗？`)) {
    return;
  }

  try {
    const result = await deleteResource(`/master-data/products/${product.item_id}`);
    feedbackMessage.value = result.message || `产品 ${product.item_name} 已删除`;
    await loadProducts();
  } catch (error) {
    errorMessage.value = error.message || "删除产品失败";
  }
}

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