<script setup lang="ts">
import { Delete, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, reactive, ref } from 'vue';

import {
  batchSave,
  deleteById,
  listForManagement,
  saveOrUpdate,
  type SysEnum,
  type SysEnumBatchSaveItem,
  type SysEnumManageQuery,
} from '@/api/sysEnums';

const loading = ref(false);
const saving = ref(false);
const dialogVisible = ref(false);
const batchDialogVisible = ref(false);
const enumRows = ref<SysEnum[]>([]);

const queryForm = reactive<Required<SysEnumManageQuery>>({
  catalog: '',
  type: '',
  keyword: '',
});

const editForm = reactive<SysEnum>({
  catalog: '',
  type: '',
  name: '',
  value: null,
  strvalue: '',
  sort: 0,
  remark: '',
});

const batchForm = reactive<{
  catalog: string;
  type: string;
  items: SysEnumBatchSaveItem[];
}>({
  catalog: '',
  type: '',
  items: [],
});

const dialogTitle = computed(() => (editForm.id ? '编辑枚举' : '新增枚举'));

function createBatchItem(sort = 0): SysEnumBatchSaveItem {
  return {
    name: '',
    value: null,
    strvalue: '',
    sort,
    remark: '',
  };
}

function resetEditForm(row?: SysEnum) {
  editForm.id = row?.id;
  editForm.catalog = row?.catalog ?? '';
  editForm.type = row?.type ?? '';
  editForm.name = row?.name ?? '';
  editForm.value = row?.value ?? null;
  editForm.strvalue = row?.strvalue ?? '';
  editForm.sort = row?.sort ?? 0;
  editForm.remark = row?.remark ?? '';
}

async function loadEnums() {
  loading.value = true;
  try {
    const response = await listForManagement({ ...queryForm });
    enumRows.value = response.data ?? [];
  } finally {
    loading.value = false;
  }
}

function resetQuery() {
  queryForm.catalog = '';
  queryForm.type = '';
  queryForm.keyword = '';
  loadEnums();
}

function openCreateDialog() {
  resetEditForm();
  dialogVisible.value = true;
}

function openBatchCreateDialog() {
  batchForm.catalog = '';
  batchForm.type = '';
  batchForm.items = [createBatchItem(1), createBatchItem(2)];
  batchDialogVisible.value = true;
}

function openEditDialog(row: SysEnum) {
  resetEditForm(row);
  dialogVisible.value = true;
}

function addBatchItem() {
  batchForm.items.push(createBatchItem(batchForm.items.length + 1));
}

function removeBatchItem(index: number) {
  batchForm.items.splice(index, 1);
  if (batchForm.items.length === 0) {
    addBatchItem();
  }
}

async function submitEnum() {
  if (!editForm.catalog || !editForm.type || !editForm.name) {
    ElMessage.warning('请填写模块目录、枚举类型和名称');
    return;
  }

  saving.value = true;
  try {
    await saveOrUpdate({ ...editForm });
    ElMessage.success('保存成功');
    dialogVisible.value = false;
    await loadEnums();
  } finally {
    saving.value = false;
  }
}

function validateBatchForm() {
  if (!batchForm.catalog || !batchForm.type) {
    ElMessage.warning('请填写模块目录和枚举类型');
    return false;
  }
  if (batchForm.items.length === 0) {
    ElMessage.warning('请至少添加一个枚举项');
    return false;
  }

  const requestValues = new Set<number>();
  const existingValues = new Set(
    enumRows.value
      .filter((row) => row.catalog === batchForm.catalog && row.type === batchForm.type)
      .map((row) => row.value)
      .filter((value): value is number => value !== null && value !== undefined),
  );

  for (const item of batchForm.items) {
    if (!item.name) {
      ElMessage.warning('请填写每个枚举项的名称');
      return false;
    }
    if (item.value === null || item.value === undefined) {
      ElMessage.warning('请填写每个枚举项的整型值');
      return false;
    }
    if (requestValues.has(item.value)) {
      ElMessage.warning(`批量新增中存在重复整型值：${item.value}`);
      return false;
    }
    if (existingValues.has(item.value)) {
      ElMessage.warning(`整型值已存在：${item.value}`);
      return false;
    }
    requestValues.add(item.value);
  }

  return true;
}

async function submitBatchEnums() {
  if (!validateBatchForm()) {
    return;
  }

  saving.value = true;
  try {
    await batchSave({
      catalog: batchForm.catalog,
      type: batchForm.type,
      items: batchForm.items,
    });
    ElMessage.success('批量保存成功');
    batchDialogVisible.value = false;
    await loadEnums();
  } finally {
    saving.value = false;
  }
}

async function removeEnum(row: SysEnum) {
  if (!row.id) {
    return;
  }
  await ElMessageBox.confirm(`确认删除枚举「${row.name}」？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
  });
  await deleteById(row.id);
  ElMessage.success('删除成功');
  await loadEnums();
}

onMounted(loadEnums);
</script>

<template>
  <section class="page-panel enum-page">
    <div class="page-panel__header">
      <h2>系统枚举</h2>
      <span>System</span>
    </div>

    <div class="enum-toolbar">
      <el-form :model="queryForm" inline>
        <el-form-item label="模块目录">
          <el-input
            v-model="queryForm.catalog"
            data-test="catalog-input"
            clearable
            placeholder="如 common"
          />
        </el-form-item>
        <el-form-item label="枚举类型">
          <el-input v-model="queryForm.type" clearable placeholder="如 enable_status" />
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="queryForm.keyword" clearable placeholder="名称/值/备注" />
        </el-form-item>
        <el-form-item>
          <el-button data-test="enum-search" type="primary" :icon="Search" @click="loadEnums">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="enum-actions">
        <el-button data-test="enum-batch-create" :icon="Plus" @click="openBatchCreateDialog">
          批量新增
        </el-button>
        <el-button type="primary" :icon="Plus" @click="openCreateDialog">新增</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="enumRows" row-key="id" class="enum-table">
      <el-table-column prop="catalog" label="模块目录" min-width="120" />
      <el-table-column prop="type" label="枚举类型" min-width="160" />
      <el-table-column prop="name" label="名称" min-width="120" />
      <el-table-column prop="value" label="整型值" width="90" />
      <el-table-column prop="strvalue" label="字符串值" min-width="120" show-overflow-tooltip />
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column prop="remark" label="注释" min-width="180" show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" :icon="Edit" @click="openEditDialog(row)">编辑</el-button>
          <el-button link type="danger" :icon="Delete" @click="removeEnum(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="560px">
      <el-form :model="editForm" label-width="96px">
        <el-form-item label="模块目录" required>
          <el-input v-model="editForm.catalog" placeholder="如 common" />
        </el-form-item>
        <el-form-item label="枚举类型" required>
          <el-input v-model="editForm.type" placeholder="如 enable_status" />
        </el-form-item>
        <el-form-item label="名称" required>
          <el-input v-model="editForm.name" placeholder="如 启用" />
        </el-form-item>
        <el-form-item label="整型值">
          <el-input-number v-model="editForm.value" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="字符串值">
          <el-input v-model="editForm.strvalue" placeholder="可选" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editForm.sort" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="注释">
          <el-input v-model="editForm.remark" type="textarea" :rows="3" placeholder="可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitEnum">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="batchDialogVisible" title="批量新增枚举" width="920px">
      <el-form :model="batchForm" label-width="96px">
        <div class="batch-base">
          <el-form-item label="模块目录" required>
            <el-input v-model="batchForm.catalog" placeholder="如 common" />
          </el-form-item>
          <el-form-item label="枚举类型" required>
            <el-input v-model="batchForm.type" placeholder="如 enable_status" />
          </el-form-item>
        </div>

        <div class="batch-header">
          <span>枚举项</span>
          <el-button :icon="Plus" @click="addBatchItem">添加一行</el-button>
        </div>

        <el-table :data="batchForm.items" class="batch-table" row-key="sort">
          <el-table-column label="名称" min-width="140">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="如 启用" />
            </template>
          </el-table-column>
          <el-table-column label="整型值" width="130">
            <template #default="{ row }">
              <el-input-number v-model="row.value" :min="0" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="字符串值" min-width="140">
            <template #default="{ row }">
              <el-input v-model="row.strvalue" placeholder="可选" />
            </template>
          </el-table-column>
          <el-table-column label="排序" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.sort" :min="0" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="注释" min-width="180">
            <template #default="{ row }">
              <el-input v-model="row.remark" placeholder="可选" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90">
            <template #default="{ $index }">
              <el-button link type="danger" :icon="Delete" @click="removeBatchItem($index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitBatchEnums">保存整组</el-button>
      </template>
    </el-dialog>
  </section>
</template>

<style scoped>
.enum-page {
  overflow: hidden;
}

.enum-toolbar {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  align-items: start;
  gap: 16px;
  padding: 18px 22px 8px;
  border-bottom: 1px solid #eef2f7;
  background: #ffffff;
}

.enum-toolbar :deep(.el-form) {
  display: flex;
  flex-wrap: wrap;
  gap: 0 14px;
}

.enum-toolbar :deep(.el-form-item) {
  margin-right: 0;
  margin-bottom: 10px;
}

.enum-toolbar :deep(.el-form-item__label) {
  color: #475467;
  font-weight: 600;
}

.enum-toolbar :deep(.el-input) {
  width: 196px;
}

.enum-table {
  width: 100%;
}

.enum-table :deep(.el-table__header-wrapper th) {
  background: #f8fafc;
  color: #667085;
  font-weight: 700;
}

.enum-table :deep(.el-table__row td) {
  color: #344054;
}

.enum-table :deep(.el-table__row:hover td) {
  background: #f8fbff;
}

.enum-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 1px;
}

.batch-base {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.batch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 4px 0 12px;
  color: #1f2937;
  font-size: 14px;
  font-weight: 700;
}

.batch-table {
  width: 100%;
}

@media (max-width: 1080px) {
  .enum-toolbar {
    grid-template-columns: 1fr;
  }

  .enum-actions {
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .enum-toolbar {
    padding: 14px 16px 8px;
  }

  .enum-toolbar :deep(.el-form) {
    display: grid;
    grid-template-columns: 1fr;
  }

  .enum-toolbar :deep(.el-input) {
    width: 100%;
  }

  .enum-actions {
    flex-wrap: wrap;
  }

  .batch-base {
    grid-template-columns: 1fr;
  }
}
</style>
