<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="这里决定 MRP 向上取整、默认供应商、采购提前期、废料单价和来料质检口径，是采购、计划和库存联动的基础页面。"
        >
          <h3>维护钢板、卷料等原材料主档与采购参数</h3>
        </span>
      </div>
    </section>

    <section class="panel">
      <div class="panel-header">
        <div>
          <p class="eyebrow">原材料列表</p>
          <h3>采购与 MRP 基础档案</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="materialControls.search.value"
        v-model:sort-key="materialControls.sortKey.value"
        v-model:sort-direction="materialControls.sortDirection.value"
        :sort-options="materialControls.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="material in paginatedMaterials" :key="material.item_id">
              <td>
                <button class="link-button" type="button" @click="openDetailDrawer(material)">
                  {{ material.item_code }}
                </button>
              </td>
              <td>{{ material.item_name }}</td>
              <td>{{ material.specification || "-" }}</td>
              <td>{{ material.supplier_name || "-" }}</td>
              <td>{{ formatWeight(material.purchase_multiple_weight_kg) }}</td>
              <td>{{ material.lead_time_days }} 天</td>
              <td>¥{{ Number(material.scrap_sale_price || 0).toFixed(4) }}</td>
              <td>{{ material.status === "ACTIVE" ? "启用" : "停用" }}</td>
              <td class="action-row">
                <button class="ghost-button" type="button" @click="startEdit(material)">编辑</button>
                <button class="ghost-button danger-ghost" type="button" @click="removeMaterial(material)">删除</button>
              </td>
            </tr>
            <tr v-if="!filteredMaterials.length">
              <td colspan="9" class="empty-row">暂无原材料主档</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="materialPage" v-model:page-size="materialPageSize" :total="filteredMaterials.length" />
    </section>

    <FormDrawer
      :open="drawerOpen"
      eyebrow="原材料资料"
      :title="editingItemId ? '编辑原材料' : '新增原材料'"
      description="维护钢板、卷料等原材料主档、采购参数、质检规则与废料单价。"
      :tag="editingItemId ? '编辑模式' : '新建模式'"
      @close="closeDrawer"
    >
      <form class="stack-form" @submit.prevent="submitMaterial">
        <div class="double-field">
          <label class="form-field">
            <span>原材料编码</span>
            <input :value="materialCodePreview" type="text" disabled readonly />
          </label>
          <label class="form-field">
            <span>原材料名称 <i class="required-mark">*</i></span>
            <input v-model.trim="form.item_name" type="text" required />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>规格 <i class="required-mark">*</i></span>
            <input v-model.trim="form.specification" type="text" placeholder="500*600*2.5" required />
          </label>
          <label class="form-field">
            <span>材质牌号 <i class="required-mark">*</i></span>
            <input v-model.trim="form.material_grade" type="text" placeholder="SAP440" required />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>默认供应商 <i class="required-mark">*</i></span>
            <select v-model.number="form.default_supplier_id" required>
              <option disabled value="">请选择</option>
              <option v-for="supplier in suppliers" :key="supplier.id" :value="supplier.id">
                {{ supplier.supplier_name }}
              </option>
            </select>
          </label>
          <label class="form-field">
            <span>状态</span>
            <select v-model="form.status">
              <option value="ACTIVE">启用</option>
              <option value="INACTIVE">停用</option>
            </select>
          </label>
        </div>

        <div class="triple-field">
          <label class="form-field">
	            <span>重量基准(kg) <i class="required-mark">*</i></span>
            <input v-model.number="form.unit_weight_kg" type="number" min="0.001" step="0.001" required />
          </label>
          <label class="form-field">
            <span>安全库存重量(kg)</span>
            <input v-model.number="form.safety_stock_weight_kg" type="number" min="0" step="0.001" />
          </label>
          <label class="form-field">
            <span>废料单价(元/kg)</span>
            <input v-model.number="form.scrap_sale_price" type="number" min="0" step="0.0001" />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>最小采购重量(kg)</span>
            <input v-model.number="form.min_purchase_qty" type="number" min="0" step="0.001" />
          </label>
          <label class="form-field">
            <span>采购倍数重量(kg) <i class="required-mark">*</i></span>
            <input v-model.number="form.purchase_multiple_weight_kg" type="number" min="0.001" step="0.001" required />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>采购提前期(天)</span>
            <input v-model.number="form.lead_time_days" type="number" min="0" step="1" />
          </label>
          <label class="form-field">
            <span>来料质检规则</span>
            <input v-model.trim="form.quality_rule" type="text" placeholder="厚度、表面、重量偏差" />
          </label>
        </div>

        <div class="form-toolbar">
          <button class="primary-button" type="submit" :disabled="submitting">
            {{ submitting ? "保存中..." : editingItemId ? "更新原材料" : "新增原材料" }}
          </button>
        </div>
      </form>
    </FormDrawer>

    <FormDrawer
      :open="detailDrawerOpen"
      eyebrow="原材料详情"
      :title="detailMaterial ? `${detailMaterial.item_code} · ${detailMaterial.item_name}` : '原材料详情'"
      tag="只读详情"
      @close="closeDetailDrawer"
    >
      <div v-if="detailMaterial" class="detail-grid">
        <div class="detail-item">
          <span>原材料编码</span>
          <strong>{{ detailMaterial.item_code }}</strong>
        </div>
        <div class="detail-item">
          <span>原材料名称</span>
          <strong>{{ detailMaterial.item_name }}</strong>
        </div>
        <div class="detail-item">
          <span>规格</span>
          <strong>{{ detailMaterial.specification || "-" }}</strong>
        </div>
        <div class="detail-item">
          <span>材质牌号</span>
          <strong>{{ detailMaterial.material_grade || "-" }}</strong>
        </div>
        <div class="detail-item">
          <span>默认供应商</span>
          <strong>{{ detailMaterial.supplier_name || "-" }}</strong>
        </div>
        <div class="detail-item">
	          <span>重量基准</span>
          <strong>{{ formatWeight(detailMaterial.unit_weight_kg) }}</strong>
        </div>
        <div class="detail-item">
          <span>采购倍数重量</span>
          <strong>{{ formatWeight(detailMaterial.purchase_multiple_weight_kg) }}</strong>
        </div>
        <div class="detail-item">
          <span>采购提前期</span>
          <strong>{{ Number(detailMaterial.lead_time_days || 0) }} 天</strong>
        </div>
        <div class="detail-item">
          <span>废料单价</span>
          <strong>¥{{ Number(detailMaterial.scrap_sale_price || 0).toFixed(4) }}</strong>
        </div>
        <div class="detail-item">
          <span>状态</span>
          <strong>{{ detailMaterial.status === "ACTIVE" ? "启用" : "停用" }}</strong>
        </div>
        <div class="detail-block">
          <span>来料质检规则</span>
          <strong>{{ detailMaterial.quality_rule || "-" }}</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 TableControls from "../components/TableControls.vue";
import { deleteResource, fetchResource, postResource, putResource } from "../services/api";
import { buildMaterialCodePreview, buildNextMaterialCode } from "../utils/codeRules";
import { formatWeight } from "../utils/formatters";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const materials = ref([]);
const suppliers = ref([]);
const editingItemId = ref(null);
const drawerOpen = ref(false);
const detailDrawerOpen = ref(false);
const detailMaterial = ref(null);
const submitting = ref(false);
const feedbackMessage = ref("");
const errorMessage = ref("");

const form = reactive(buildEmptyForm());

const materialCodePreview = computed(() =>
  buildMaterialCodePreview(form, form.item_code, buildNextMaterialCode(materials.value))
);
const materialControls = useTableControls(materials, {
  searchFields: ["item_code", "item_name", "specification", "material_grade", "supplier_name", "status"],
  sortOptions: [
    { key: "item_code", label: "原材料编码" },
    { key: "item_name", label: "原材料名称" },
    { key: "material_grade", label: "材质" },
    { key: "supplier_name", label: "默认供应商" },
    { key: "purchase_multiple_weight_kg", label: "采购倍数" },
    { key: "lead_time_days", label: "提前期" },
    { key: "scrap_sale_price", label: "废料单价" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "item_code",
  defaultSortDirection: "asc"
});
const filteredMaterials = materialControls.rows;
const {
  page: materialPage,
  pageSize: materialPageSize,
  rows: paginatedMaterials
} = usePagination(filteredMaterials);

function buildEmptyForm() {
  return {
    item_code: "",
    item_name: "",
    specification: "",
    material_grade: "",
    unit_weight_kg: 0,
    safety_stock_weight_kg: 0,
    scrap_sale_price: 0,
    default_supplier_id: "",
    min_purchase_qty: 0,
    purchase_multiple_weight_kg: 0,
    lead_time_days: 0,
    quality_rule: "",
    status: "ACTIVE"
  };
}

function resetForm() {
  editingItemId.value = null;
  Object.assign(form, buildEmptyForm());
}

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

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

function openDetailDrawer(material) {
  detailMaterial.value = { ...material };
  detailDrawerOpen.value = true;
}

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

function startEdit(material) {
  feedbackMessage.value = "";
  errorMessage.value = "";
  editingItemId.value = material.item_id;
  Object.assign(form, {
    item_code: material.item_code,
    item_name: material.item_name,
    specification: material.specification || "",
    material_grade: material.material_grade || "",
    unit_weight_kg: Number(material.unit_weight_kg || 0),
    safety_stock_weight_kg: Number(material.safety_stock_weight_kg || 0),
    scrap_sale_price: Number(material.scrap_sale_price || 0),
    default_supplier_id: material.default_supplier_id || "",
    min_purchase_qty: Number(material.min_purchase_qty || 0),
    purchase_multiple_weight_kg: Number(material.purchase_multiple_weight_kg || 0),
    lead_time_days: Number(material.lead_time_days || 0),
    quality_rule: material.quality_rule || "",
    status: material.status
  });
  drawerOpen.value = true;
}

async function loadAll() {
  const [materialRows, supplierRows] = await Promise.all([
    fetchResource("/master-data/materials", []),
    fetchResource("/purchase/suppliers", [])
  ]);
  materials.value = materialRows;
  suppliers.value = supplierRows;
}

async function submitMaterial() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  submitting.value = true;

  try {
    const payload = {
      item_code: form.item_code || null,
      item_name: form.item_name,
      specification: form.specification,
      material_grade: form.material_grade,
      unit_weight_kg: Number(form.unit_weight_kg || 0),
      safety_stock_weight_kg: Number(form.safety_stock_weight_kg || 0),
      scrap_sale_price: Number(form.scrap_sale_price || 0),
      default_supplier_id: Number(form.default_supplier_id),
      purchase_calc_mode: "BY_WEIGHT",
      min_purchase_qty: Number(form.min_purchase_qty || 0),
      purchase_multiple_qty: 0,
      purchase_multiple_weight_kg: Number(form.purchase_multiple_weight_kg || 0),
      lead_time_days: Number(form.lead_time_days || 0),
      quality_rule: form.quality_rule || null,
      status: form.status
    };

    const result = editingItemId.value
      ? await putResource(`/master-data/materials/${editingItemId.value}`, payload)
      : await postResource("/master-data/materials", payload);

    feedbackMessage.value = `原材料 ${result.item_name} 已保存`;
    await loadAll();
    resetForm();
    drawerOpen.value = false;
  } catch (error) {
    errorMessage.value = error.message || "保存原材料失败";
  } finally {
    submitting.value = false;
  }
}

async function removeMaterial(material) {
  feedbackMessage.value = "";
  errorMessage.value = "";

  if (!window.confirm(`确认删除原材料“${material.item_name}”吗？`)) {
    return;
  }

  try {
    const result = await deleteResource(`/master-data/materials/${material.item_id}`);
    feedbackMessage.value = result.message || `原材料 ${material.item_name} 已删除`;
    await loadAll();
    if (editingItemId.value === material.item_id) {
      resetForm();
      drawerOpen.value = false;
    }
  } catch (error) {
    errorMessage.value = error.message || "删除原材料失败";
  }
}

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