<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="exportSuppliers">
              <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="importSuppliers" />
        </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="supplierControls.search.value"
        v-model:sort-key="supplierControls.sortKey.value"
        v-model:sort-direction="supplierControls.sortDirection.value"
        :sort-options="supplierControls.sortOptions"
        placeholder="搜索供应商名称、联系人、联系电话、地址"
      />

      <div class="table-wrap">
        <table class="data-table compact-table">
          <thead>
            <tr>
              <th>供应商名称</th>
              <th>联系人</th>
              <th>联系电话</th>
              <th>地址</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="supplier in paginatedSuppliers" :key="supplier.id">
              <td>
                <button class="link-button" type="button" @click="openDetailDrawer(supplier)">
                  {{ supplier.supplier_name }}
                </button>
              </td>
              <td>
                <div v-for="(contact, index) in displayContacts(supplier)" :key="`supplier-name-${supplier.id}-${index}`">
                  {{ contact.contact_name || "-" }}
                </div>
                <span v-if="!displayContacts(supplier).length">-</span>
              </td>
              <td>
                <div v-for="(contact, index) in displayContacts(supplier)" :key="`supplier-phone-${supplier.id}-${index}`">
                  {{ contact.contact_phone || "-" }}
                </div>
                <span v-if="!displayContacts(supplier).length">-</span>
              </td>
              <td>{{ supplier.address || "-" }}</td>
              <td class="action-row">
                <button class="ghost-button" type="button" @click="startEdit(supplier)">编辑</button>
                <button class="ghost-button danger-ghost" type="button" @click="removeSupplier(supplier)">删除</button>
              </td>
            </tr>
            <tr v-if="!filteredSuppliers.length">
              <td colspan="5" class="empty-row">暂无供应商名录</td>
            </tr>
          </tbody>
        </table>
      </div>
      <PaginationBar v-model:page="supplierPage" v-model:page-size="supplierPageSize" :total="filteredSuppliers.length" />
    </section>

    <FormDrawer
      :open="drawerOpen"
      eyebrow="供应商名录"
      :title="editingId ? '编辑供应商' : '新增供应商'"
      :tag="editingId ? '编辑模式' : '新建模式'"
      @close="closeDrawer"
    >
      <form class="stack-form" @submit.prevent="submitSupplier">
        <div class="double-field">
          <label class="form-field">
            <span>供应商名称 <i class="required-mark">*</i></span>
            <input v-model.trim="form.supplier_name" type="text" required />
          </label>
          <label class="form-field">
            <span>地址</span>
            <input v-model.trim="form.address" type="text" />
          </label>
        </div>

        <div class="subsection-head">
          <strong>联系人（最多3位）</strong>
          <button class="ghost-button" type="button" :disabled="form.contacts.length >= 3" @click="addContact">添加联系人</button>
        </div>
        <div v-for="(contact, index) in form.contacts" :key="`supplier-contact-${index}`" class="triple-field">
          <label class="form-field">
            <span>联系人{{ index + 1 }}</span>
            <input v-model.trim="contact.contact_name" type="text" />
          </label>
          <label class="form-field">
            <span>联系电话{{ index + 1 }}</span>
            <input v-model.trim="contact.contact_phone" type="text" />
          </label>
          <div class="form-field form-field-action">
            <span>&nbsp;</span>
            <button class="ghost-button danger-ghost" type="button" @click="removeContact(index)">
              {{ form.contacts.length > 1 ? "删除" : "清空" }}
            </button>
          </div>
        </div>

        <div class="form-toolbar">
          <button class="primary-button" type="submit" :disabled="submitting">
            {{ submitting ? "保存中..." : editingId ? "更新供应商" : "新增供应商" }}
          </button>
        </div>
      </form>
    </FormDrawer>

    <FormDrawer
      :open="detailDrawerOpen"
      eyebrow="供应商详情"
      :title="detailSupplier ? detailSupplier.supplier_name : '供应商详情'"
      tag="只读详情"
      @close="closeDetailDrawer"
    >
      <div v-if="detailSupplier" class="detail-grid">
        <div class="detail-item">
          <span>供应商名称</span>
          <strong>{{ detailSupplier.supplier_name }}</strong>
        </div>
        <div class="detail-item">
          <span>联系人</span>
          <strong>{{ formatContactNames(detailSupplier) }}</strong>
        </div>
        <div class="detail-item">
          <span>联系电话</span>
          <strong>{{ formatContactPhones(detailSupplier) }}</strong>
        </div>
        <div class="detail-block">
          <span>地址</span>
          <strong>{{ detailSupplier.address || "-" }}</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, downloadResource, fetchResource, postResource, putResource, uploadResource } from "../services/api";
import { usePagination } from "../utils/pagination";
import { useTableControls } from "../utils/tableControls";

const suppliers = ref([]);
const editingId = ref(null);
const drawerOpen = ref(false);
const detailDrawerOpen = ref(false);
const detailSupplier = ref(null);
const submitting = ref(false);
const importing = ref(false);
const exporting = ref(false);
const importInputRef = ref(null);
const feedbackMessage = ref("");
const errorMessage = ref("");

const form = reactive(buildEmptyForm());

const supplierControls = useTableControls(suppliers, {
  searchFields: ["supplier_name", "contacts", "contact_name", "contact_phone", "address"],
  sortOptions: [
    { key: "supplier_name", label: "供应商名称" },
    { key: "contact_name", label: "联系人" },
    { key: "contact_phone", label: "联系电话" },
    { key: "address", label: "地址" }
  ],
  defaultSortKey: "supplier_name",
  defaultSortDirection: "asc"
});
const filteredSuppliers = supplierControls.rows;
const {
  page: supplierPage,
  pageSize: supplierPageSize,
  rows: paginatedSuppliers
} = usePagination(filteredSuppliers);
function buildEmptyForm() {
  return {
    supplier_name: "",
    contacts: [buildEmptyContact()],
    address: ""
  };
}

function buildEmptyContact() {
  return {
    contact_name: "",
    contact_phone: ""
  };
}

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

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

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

function openDetailDrawer(supplier) {
  detailSupplier.value = { ...supplier };
  detailDrawerOpen.value = true;
}

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

function startEdit(supplier) {
  feedbackMessage.value = "";
  errorMessage.value = "";
  editingId.value = supplier.id;
  Object.assign(form, {
    supplier_name: supplier.supplier_name,
    contacts: contactsForForm(supplier),
    address: supplier.address || ""
  });
  drawerOpen.value = true;
}

async function loadSuppliers() {
  suppliers.value = await fetchResource("/purchase/suppliers?limit=500", []);
}

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

async function importSuppliers(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("/purchase/suppliers/import", formData);
    feedbackMessage.value = result.message || "供应商名录导入完成";
    if (result.errors?.length) {
      errorMessage.value = result.errors.join("；");
    }
    await loadSuppliers();
  } catch (error) {
    errorMessage.value = error.message || "供应商名录导入失败";
  } finally {
    importing.value = false;
    if (importInputRef.value) {
      importInputRef.value.value = "";
    }
  }
}

async function exportSuppliers() {
  exporting.value = true;
  feedbackMessage.value = "";
  errorMessage.value = "";
  try {
    await downloadResource("/purchase/suppliers/export", "供应商名录.xlsx");
    feedbackMessage.value = "供应商名录已导出";
  } catch (error) {
    errorMessage.value = error.message || "供应商名录导出失败";
  } finally {
    exporting.value = false;
  }
}

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

  try {
    const contacts = normalizedFormContacts();
    const payload = {
      supplier_name: form.supplier_name,
      short_name: form.supplier_name || null,
      contact_name: contacts.map((contact) => contact.contact_name).filter(Boolean).join("、") || null,
      contact_phone: contacts.map((contact) => contact.contact_phone).filter(Boolean).join("、") || null,
      contacts,
      address: form.address || null,
      default_tax_rate: 0,
      status: "ACTIVE",
      remark: null
    };

    const result = editingId.value
      ? await putResource(`/purchase/suppliers/${editingId.value}`, payload)
      : await postResource("/purchase/suppliers", payload);

    feedbackMessage.value = `供应商 ${result.supplier_name} 已保存`;
    await loadSuppliers();
    resetForm();
    drawerOpen.value = false;
  } catch (error) {
    errorMessage.value = error.message || "供应商保存失败";
  } finally {
    submitting.value = false;
  }
}

async function removeSupplier(supplier) {
  feedbackMessage.value = "";
  errorMessage.value = "";

  if (!window.confirm(`确认删除供应商“${supplier.supplier_name}”吗？`)) {
    return;
  }

  try {
    const result = await deleteResource(`/purchase/suppliers/${supplier.id}`);
    feedbackMessage.value = result.message || `供应商 ${supplier.supplier_name} 已删除`;
    await loadSuppliers();
    if (editingId.value === supplier.id) {
      resetForm();
      drawerOpen.value = false;
    }
  } catch (error) {
    errorMessage.value = error.message || "删除供应商失败";
  }
}

onMounted(async () => {
  await loadSuppliers();
});

function splitContactText(value) {
  return String(value || "")
    .split(/[、,，;；\n]+/)
    .map((item) => item.trim())
    .filter(Boolean);
}

function displayContacts(row) {
  const contacts = Array.isArray(row?.contacts)
    ? row.contacts
        .map((contact) => ({
          contact_name: String(contact?.contact_name || "").trim(),
          contact_phone: String(contact?.contact_phone || "").trim()
        }))
        .filter((contact) => contact.contact_name || contact.contact_phone)
    : [];
  if (contacts.length) {
    return contacts.slice(0, 3);
  }
  const names = splitContactText(row?.contact_name);
  const phones = splitContactText(row?.contact_phone);
  const total = Math.min(Math.max(names.length, phones.length), 3);
  return Array.from({ length: total }, (_, index) => ({
    contact_name: names[index] || "",
    contact_phone: phones[index] || ""
  }));
}

function contactsForForm(row) {
  const contacts = displayContacts(row);
  return contacts.length ? contacts.map((contact) => ({ ...contact })) : [buildEmptyContact()];
}

function normalizedFormContacts() {
  return form.contacts
    .map((contact) => ({
      contact_name: String(contact.contact_name || "").trim(),
      contact_phone: String(contact.contact_phone || "").trim()
    }))
    .filter((contact) => contact.contact_name || contact.contact_phone)
    .slice(0, 3);
}

function addContact() {
  if (form.contacts.length < 3) {
    form.contacts.push(buildEmptyContact());
  }
}

function removeContact(index) {
  if (form.contacts.length <= 1) {
    Object.assign(form.contacts[0], buildEmptyContact());
    return;
  }
  form.contacts.splice(index, 1);
}

function formatContactNames(row) {
  const names = displayContacts(row).map((contact) => contact.contact_name).filter(Boolean);
  return names.length ? names.join("、") : "-";
}

function formatContactPhones(row) {
  const phones = displayContacts(row).map((contact) => contact.contact_phone).filter(Boolean);
  return phones.length ? phones.join("、") : "-";
}
</script>
