<template>
  <PageContainer title="发票管理">
    <QueryToolbar>
      <el-button v-if="canManage" type="primary" @click="openCreateDrawer">新增抬头</el-button>
      <el-button v-if="canRead" @click="load">刷新</el-button>
    </QueryToolbar>

    <el-table :data="rows">
      <el-table-column prop="companyName" label="企业名称" width="160" />
      <el-table-column prop="taxNo" label="税号" width="170" />
      <el-table-column prop="bankName" label="开户行" width="150" />
      <el-table-column prop="accountNo" label="账号" width="170" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="phone" label="电话" width="130" />
      <el-table-column prop="defaultProjectId" label="默认项目" width="100" />
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button v-if="canManage" size="small" @click="openEdit(row)">编辑</el-button>
          <el-button v-if="canManage && row.status !== 'ENABLED'" size="small" type="success" @click="handleEnable(row.id)">启用</el-button>
          <el-button v-else-if="canManage" size="small" type="warning" @click="handleDisable(row.id)">停用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer v-model="createVisible" title="新增发票抬头" :size="DRAWER_SIZE.md" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="企业名称" prop="companyName"><el-input v-model="form.companyName" /></el-form-item>
        <el-form-item label="税号" prop="taxNo"><el-input v-model="form.taxNo" /></el-form-item>
        <el-form-item label="开户行" prop="bankName"><el-input v-model="form.bankName" /></el-form-item>
        <el-form-item label="账号" prop="accountNo"><el-input v-model="form.accountNo" /></el-form-item>
        <el-form-item label="地址"><el-input v-model="form.address" /></el-form-item>
        <el-form-item label="电话"><el-input v-model="form.phone" /></el-form-item>
        <el-form-item label="默认项目"><el-input-number v-model="form.defaultProjectId" :min="1" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="启用" value="ENABLED" />
            <el-option label="停用" value="DISABLED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="editVisible" title="编辑发票抬头" :width="DIALOG_WIDTH.md">
      <el-form ref="editFormRef" :model="editForm" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="企业名称" prop="companyName"><el-input v-model="editForm.companyName" /></el-form-item>
        <el-form-item label="税号" prop="taxNo"><el-input v-model="editForm.taxNo" /></el-form-item>
        <el-form-item label="开户行" prop="bankName"><el-input v-model="editForm.bankName" /></el-form-item>
        <el-form-item label="账号" prop="accountNo"><el-input v-model="editForm.accountNo" /></el-form-item>
        <el-form-item label="地址"><el-input v-model="editForm.address" /></el-form-item>
        <el-form-item label="电话"><el-input v-model="editForm.phone" /></el-form-item>
        <el-form-item label="默认项目"><el-input-number v-model="editForm.defaultProjectId" :min="1" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="启用" value="ENABLED" />
            <el-option label="停用" value="DISABLED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import { DRAWER_SIZE, DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  createInvoiceProfile,
  disableInvoiceProfile,
  enableInvoiceProfile,
  fetchInvoiceProfiles,
  updateInvoiceProfile,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const canRead = computed(() => authStore.hasPermission(PERMS.invoiceProfile.read));
const canManage = computed(() => authStore.hasPermission(PERMS.invoiceProfile.manage));
const rows = ref<any[]>([]);
const createVisible = ref(false);
const form = ref({
  companyName: "",
  taxNo: "",
  bankName: "",
  accountNo: "",
  address: "",
  phone: "",
  defaultProjectId: 1001,
  status: "ENABLED" as "ENABLED" | "DISABLED",
});
const editVisible = ref(false);
const editId = ref<number | null>(null);
const editForm = ref<any>({});

const formRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const formRules = ref<FormRules>({
  companyName: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  taxNo: [{ required: true, message: "请输入税号", trigger: "blur" }],
  bankName: [{ required: true, message: "请输入开户行", trigger: "blur" }],
  accountNo: [{ required: true, message: "请输入账号", trigger: "blur" }],
});

const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);

const openCreateDrawer = () => {
  form.value = {
    companyName: "",
    taxNo: "",
    bankName: "",
    accountNo: "",
    address: "",
    phone: "",
    defaultProjectId: 1001,
    status: "ENABLED",
  };
  createVisible.value = true;
};

const load = async () => {
  const resp = await fetchInvoiceProfiles();
  rows.value = resp?.data?.list || [];
};

const handleCreate = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  await createInvoiceProfile(form.value);
  ElMessage.success("新增成功");
  createVisible.value = false;
  await load();
};

const openEdit = (row: any) => {
  editId.value = row.id;
  editForm.value = { ...row };
  editVisible.value = true;
};

const handleSave = async () => {
  if (!editId.value) return;

  if (!editFormRef.value) return;
  const valid = await editFormRef.value.validate().catch(() => false);
  if (!valid) return;

  await updateInvoiceProfile(editId.value, editForm.value);
  ElMessage.success("更新成功");
  editVisible.value = false;
  await load();
};

const handleEnable = async (id: number) => {
  await enableInvoiceProfile(id);
  ElMessage.success("抬头已启用");
  await load();
};

const handleDisable = async (id: number) => {
  await disableInvoiceProfile(id);
  ElMessage.success("抬头已停用");
  await load();
};

onMounted(async () => {
  if (canRead.value) {
    await load();
  }
});
</script>
