<template>
  <section class="page-grid">
    <section class="panel">
      <div class="panel-header">
        <div>
          <p class="eyebrow">基础资料导入导出</p>
          <span
            class="title-with-help"
            title="使用小程序“产品清单”导入导出的同一份模板。导入后会先写入小程序产品清单，再同步更新产品需规清单。"
          >
            <h3>小程序产品清单 Excel 导入导出</h3>
          </span>
        </div>
        <div class="workflow-inline-actions import-header-actions">
          <button class="ghost-button" type="button" :disabled="exportingTemplate" @click="exportTemplate">
            {{ exportingTemplate ? "导出中..." : "导出模版" }}
          </button>
          <button class="ghost-button" type="button" :disabled="exportingData" @click="exportMasterData">
            {{ exportingData ? "导出中..." : "导出基础资料" }}
          </button>
        </div>
      </div>

      <div class="import-layout">
        <form class="import-card" @submit.prevent="submitImport">
          <label class="import-dropzone" title="支持 .xlsx / .xlsm，字段按小程序模板列名识别。">
            <input ref="fileInputRef" class="hidden-file-input" type="file" accept=".xlsx,.xlsm" @change="handleFileChange" />
            <span class="import-icon" aria-hidden="true">XLSX</span>
            <strong>{{ selectedFile?.name || "选择小程序产品清单 Excel" }}</strong>
          </label>

          <div class="workflow-inline-actions">
            <button class="primary-button" type="submit" :disabled="importing || !selectedFile">
              {{ importing ? "导入中..." : "开始导入" }}
            </button>
            <button class="ghost-button" type="button" :disabled="importing || !selectedFile" @click="clearFile">清空文件</button>
          </div>
        </form>

        <section class="import-card import-guide-card">
          <div class="subsection-head">
            <strong>模板字段</strong>
          </div>
          <div class="table-wrap">
            <table class="data-table compact-table">
              <thead>
                <tr>
                  <th>字段</th>
                  <th>同步去向</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="field in templateFields" :key="field.name">
                  <td>{{ field.name }}</td>
                  <td>{{ field.target }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>
      </div>

      <section v-if="importResult" class="import-result-card">
        <div class="subsection-head">
          <strong>导入结果</strong>
          <span class="panel-tag">{{ importResult.message }}</span>
        </div>
        <div class="summary-grid compact-summary-grid">
          <article class="summary-card">
            <span>新增产品清单</span>
            <strong>{{ importResult.imported }}</strong>
          </article>
          <article class="summary-card">
            <span>更新产品清单</span>
            <strong>{{ importResult.updated }}</strong>
          </article>
          <article class="summary-card">
            <span>跳过行</span>
            <strong>{{ importResult.skipped }}</strong>
          </article>
          <article class="summary-card">
            <span>产品需规匹配</span>
            <strong>{{ importResult.product_specs?.matched || 0 }}</strong>
          </article>
        </div>
        <div v-if="importResult.errors?.length" class="feedback-banner error-banner">
          {{ importResult.errors.join("；") }}
        </div>
      </section>
    </section>
  </section>
</template>

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

import { downloadResource, uploadResource } from "../services/api";
import { notifyError, notifySuccess } from "../utils/notifications";

const fileInputRef = ref(null);
const selectedFile = ref(null);
const importing = ref(false);
const exportingTemplate = ref(false);
const exportingData = ref(false);
const importResult = ref(null);

const templateFields = [
  { name: "考勤点", target: "小程序产品清单 / 产品需规清单" },
  { name: "项目号", target: "产品需规清单产品编码来源" },
  { name: "型材号", target: "产品需规清单型材号" },
  { name: "产品名称", target: "产品需规清单产品资料" },
  { name: "物料编码", target: "产品需规清单默认用料匹配信息" },
  { name: "物料名称", target: "产品需规清单默认用料匹配信息" },
  { name: "供应商", target: "小程序产品清单供应商字段" },
  { name: "产品净重(kg)", target: "产品需规清单产品净重" },
  { name: "产品毛重(kg)", target: "产品需规清单产品毛重" },
  { name: "允许报废率", target: "产品需规清单允许报废率" },
  { name: "废料单价(元/kg)", target: "小程序产品清单 / 产品需规展示参考" },
  { name: "工序", target: "产品需规清单工序行" },
  { name: "冲压方式", target: "产品需规清单小程序报工字段" },
  { name: "操作人数", target: "产品需规清单小程序报工字段" },
  { name: "标准节拍", target: "产品需规清单小程序报工字段" }
];

function handleFileChange(event) {
  selectedFile.value = event.target.files?.[0] || null;
  importResult.value = null;
}

function clearFile() {
  clearSelectedFile();
  importResult.value = null;
}

function clearSelectedFile() {
  selectedFile.value = null;
  if (fileInputRef.value) {
    fileInputRef.value.value = "";
  }
}

async function submitImport() {
  if (!selectedFile.value) {
    notifyError("请先选择 Excel 文件");
    return;
  }

  importing.value = true;
  try {
    const formData = new FormData();
    formData.append("file", selectedFile.value);
    importResult.value = await uploadResource("/master-data/miniapp-products/import", formData);
    notifySuccess(importResult.value.message || "基础资料导入完成");
    clearSelectedFile();
  } catch (error) {
    notifyError(error.message || "基础资料导入失败");
  } finally {
    importing.value = false;
  }
}

async function exportTemplate() {
  exportingTemplate.value = true;
  try {
    await downloadResource("/master-data/miniapp-products/export-template", "基础资料导入模版.xlsx");
    notifySuccess("基础资料模版已导出");
  } catch (error) {
    notifyError(error.message || "基础资料模版导出失败");
  } finally {
    exportingTemplate.value = false;
  }
}

async function exportMasterData() {
  exportingData.value = true;
  try {
    await downloadResource("/master-data/miniapp-products/export", "基础资料.xlsx");
    notifySuccess("基础资料已导出");
  } catch (error) {
    notifyError(error.message || "基础资料导出失败");
  } finally {
    exportingData.value = false;
  }
}
</script>
