<template>
  <section class="page-grid">
    <section class="panel">
      <div class="panel-header">
        <div>
          <p class="eyebrow">原材料名录</p>
          <h3>维护采购和生产使用的原材料基础信息</h3>
        </div>
        <div class="supplier-action-bar">
          <button class="supplier-action-button supplier-action-primary no-auto-icon" type="button" @click="openCreateDrawer">
            <span class="supplier-action-icon supplier-action-icon-add" aria-hidden="true">+</span>
            <span>新增原材料</span>
          </button>
          <div class="supplier-exchange-group" aria-label="原材料名录导入导出">
            <button class="supplier-action-button supplier-action-import no-auto-icon" type="button" :disabled="importing" @click="triggerImport">
              <span class="supplier-action-icon" aria-hidden="true">
                <svg viewBox="0 0 24 24">
                  <path d="M12 21V9" />
                  <path d="m7 16 5 5 5-5" />
                  <path d="M5 8V5h14v3" />
                </svg>
              </span>
              <span>{{ importing ? "导入中..." : "导入" }}</span>
            </button>
            <button class="supplier-action-button supplier-action-export no-auto-icon" type="button" :disabled="exporting" @click="exportMaterials">
              <span class="supplier-action-icon" aria-hidden="true">
                <svg viewBox="0 0 24 24">
                  <path d="M12 3v12" />
                  <path d="m7 8 5-5 5 5" />
                  <path d="M5 16v3h14v-3" />
                </svg>
              </span>
              <span>{{ exporting ? "导出中..." : "导出" }}</span>
            </button>
          </div>
          <input ref="importInputRef" class="hidden-file-input" type="file" accept=".xlsx,.xlsm" @change="importMaterials" />
        </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="controls.search.value"
        v-model:sort-key="controls.sortKey.value"
        v-model:sort-direction="controls.sortDirection.value"
        :sort-options="controls.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>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in paginatedRows" :key="row.item_id">
              <td>
                <button class="link-button" type="button" @click="openEditDrawer(row)">
                  {{ row.item_code }}
                </button>
              </td>
              <td>{{ row.item_name }}</td>
              <td>{{ row.material_grade }}</td>
              <td>{{ row.specification }}</td>
              <td>¥{{ formatAmount(row.scrap_sale_price) }}</td>
              <td class="muted-cell">{{ row.remark || "-" }}</td>
              <td>{{ formatStatusLabel(row.status) }}</td>
              <td class="action-row">
                <button class="ghost-button" type="button" @click="openEditDrawer(row)">编辑</button>
                <button class="ghost-button danger-ghost" type="button" @click="removeMaterial(row)">删除</button>
              </td>
            </tr>
            <tr v-if="!filteredRows.length">
              <td colspan="8" class="empty-row">暂无原材料</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="filteredRows.length" />
    </section>

    <FormDrawer
      :open="drawerOpen"
      eyebrow="原材料名录"
      :title="editingRow ? '编辑原材料' : '新增原材料'"
      tag="独立维护"
      wide
      @close="drawerOpen = false"
    >
      <form class="stack-form" @submit.prevent="submitForm">
        <div class="triple-field">
          <label class="form-field">
            <span>原材料编码</span>
            <input :value="materialCodePreview" type="text" disabled readonly />
          </label>
          <label class="form-field">
            <span>原材料名称</span>
            <input v-model.trim="form.item_name" type="text" required />
          </label>
          <label class="form-field">
            <span>材质</span>
            <input v-model.trim="form.material_grade" type="text" required />
          </label>
        </div>

        <div class="triple-field">
          <label class="form-field">
            <span>规格</span>
            <input v-model.trim="form.specification" type="text" required />
          </label>
          <label class="form-field">
            <span>性能要求</span>
            <input v-model.trim="form.remark" type="text" />
          </label>
        </div>

        <div class="double-field">
          <label class="form-field">
            <span>废料单价(元/kg)</span>
            <input v-model.number="form.scrap_sale_price" type="number" min="0" step="0.0001" />
          </label>
          <label class="form-field">
            <span>状态</span>
            <select v-model="form.status">
              <option value="ACTIVE">启用</option>
              <option value="INACTIVE">停用</option>
            </select>
          </label>
        </div>

        <button class="primary-button" type="submit" :disabled="submitting">
          {{ submitting ? "保存中..." : "保存原材料" }}
        </button>
      </form>
    </FormDrawer>
  </section>
</template>

<script setup>
import { computed, onActivated, 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, downloadResource, fetchResource, postResource, putResource, uploadResource } from "../services/api";
import { buildMaterialCodePreview, buildNextMaterialCode } from "../utils/codeRules";
import { formatStatusLabel } from "../utils/dictionaries";
import { formatAmount } from "../utils/formatters";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const materials = ref([]);
const drawerOpen = ref(false);
const editingRow = ref(null);
const submitting = ref(false);
const importing = ref(false);
const exporting = ref(false);
const importInputRef = ref(null);
const hasLoaded = ref(false);
const feedbackMessage = ref("");
const errorMessage = ref("");

const form = reactive(buildEmptyForm());
const nextMaterialCode = computed(() => buildNextMaterialCode(materials.value));
const materialCodePreview = computed(() =>
  buildMaterialCodePreview(form, editingRow.value?.item_code || "", nextMaterialCode.value)
);

const controls = useTableControls(materials, {
  searchFields: ["item_code", "item_name", "material_grade", "specification", "remark", "status"],
  sortOptions: [
    { key: "item_code", label: "原材料编码" },
    { key: "item_name", label: "原材料名称" },
    { key: "material_grade", label: "材质" },
    { key: "specification", label: "规格" },
    { key: "scrap_sale_price", label: "废料单价" },
    { key: "remark", label: "性能要求" },
    { key: "status", label: "状态" }
  ],
  defaultSortKey: "item_code",
  defaultSortDirection: "asc"
});
const filteredRows = controls.rows;
const { page, pageSize, rows: paginatedRows } = usePagination(filteredRows);

function buildEmptyForm() {
  return {
    item_name: "",
    specification: "",
    material_grade: "",
    scrap_sale_price: 0,
    remark: "",
    status: "ACTIVE"
  };
}

function resetForms() {
  Object.assign(form, buildEmptyForm());
  editingRow.value = null;
}

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

function openEditDrawer(row) {
  resetForms();
  editingRow.value = row;
  Object.assign(form, {
    item_name: row.item_name,
    specification: row.specification,
    material_grade: row.material_grade,
    scrap_sale_price: Number(row.scrap_sale_price || 0),
    remark: row.remark || row.quality_rule || "",
    status: row.status || "ACTIVE"
  });
  drawerOpen.value = true;
}

async function fetchPageData() {
  materials.value = await fetchResource("/master-data/materials?limit=200", []);
}

async function loadAll() {
  await fetchPageData();
}

function triggerImport() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  if (importInputRef.value) {
    importInputRef.value.value = "";
    importInputRef.value.click();
  }
}

async function importMaterials(event) {
  const file = event.target.files?.[0];
  if (!file) {
    return;
  }

  importing.value = true;
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    const formData = new FormData();
    formData.append("file", file);
    const result = await uploadResource("/master-data/materials/import", formData);
    feedbackMessage.value = result.message || "原材料名录导入完成";
    if (result.errors?.length) {
      errorMessage.value = result.errors.join("；");
    }
    await loadAll();
  } catch (error) {
    errorMessage.value = error.message || "原材料名录导入失败";
  } finally {
    importing.value = false;
    if (importInputRef.value) {
      importInputRef.value.value = "";
    }
  }
}

async function exportMaterials() {
  exporting.value = true;
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    await downloadResource("/master-data/materials/export", "原材料名录.xlsx");
    feedbackMessage.value = "原材料名录已导出";
  } catch (error) {
    errorMessage.value = error.message || "原材料名录导出失败";
  } finally {
    exporting.value = false;
  }
}

async function submitForm() {
  feedbackMessage.value = "";
  errorMessage.value = "";
  submitting.value = true;
  try {
    const payload = {
      item_name: form.item_name,
      specification: form.specification,
      material_grade: form.material_grade,
      unit_weight_kg: 1,
      safety_stock_weight_kg: 0,
      scrap_sale_price: Number(form.scrap_sale_price || 0),
      default_supplier_id: null,
      purchase_calc_mode: "BY_WEIGHT",
      min_purchase_qty: 0,
      purchase_multiple_qty: 0,
      purchase_multiple_weight_kg: 0,
      lead_time_days: 0,
      quality_rule: form.remark || null,
      remark: form.remark || null,
      status: form.status
    };
    const result = editingRow.value
      ? await putResource(`/master-data/materials/${editingRow.value.item_id}`, payload)
      : await postResource("/master-data/materials", payload);
    feedbackMessage.value = `原材料 ${result.item_code} 已保存`;
    drawerOpen.value = false;
    await loadAll();
  } catch (error) {
    errorMessage.value = error.message || "原材料保存失败";
  } finally {
    submitting.value = false;
  }
}

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

  if (!window.confirm(`确认删除原材料“${row.item_code} · ${row.item_name}”吗？已被业务引用的原材料不能删除。`)) {
    return;
  }

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

onMounted(async () => {
  await loadAll();
  hasLoaded.value = true;
});

onActivated(async () => {
  if (!hasLoaded.value) {
    return;
  }
  await fetchPageData();
});
</script>
