<template>
  <div class="dictionaries-container">
    <el-card class="panel-card">
      <template #header>
        <div class="panel-head">
          <div>
            <div class="panel-title">医学选项字典</div>
            <div class="panel-subtitle">
              系统管理员维护患者手术表单中的标准选项，停用后不会再出现在录入页
            </div>
          </div>
        </div>
      </template>

      <el-alert
        type="info"
        :closable="false"
        class="page-alert"
        title="当前字典为系统级公共配置，所有医院患者录入表单共享同一套选项。"
      />

      <div class="toolbar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="字典类型">
            <el-select
              v-model="searchForm.type"
              clearable
              filterable
              placeholder="全部类型"
              style="width: 220px"
            >
              <el-option
                v-for="option in MEDICAL_DICTIONARY_TYPE_OPTIONS"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              clearable
              placeholder="按字典项名称筛选"
              style="width: 260px"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="fetchData" icon="Search">
              查询
            </el-button>
            <el-button @click="resetSearch" icon="Refresh">重置</el-button>
            <el-button type="success" @click="openCreateDialog" icon="Plus">
              新增字典项
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-empty
        v-if="!groupedTableData.length"
        description="当前筛选条件下暂无字典项"
      />

      <el-collapse
        v-else
        v-model="activeCollapseNames"
        class="dictionary-collapse"
      >
        <el-collapse-item
          v-for="group in groupedTableData"
          :key="group.type"
          :name="group.type"
          class="dictionary-panel"
        >
          <template #title>
            <div class="collapse-title">
              <span>{{ group.label }}</span>
              <el-tag size="small" type="primary">{{
                group.items.length
              }}</el-tag>
            </div>
          </template>

          <el-table :data="group.items" border stripe style="width: 100%">
            <el-table-column prop="id" label="ID" width="90" align="center" />
            <el-table-column prop="label" label="字典项名称" min-width="240" />
            <el-table-column
              prop="sortOrder"
              label="排序"
              width="110"
              align="center"
            />
            <el-table-column label="状态" width="110" align="center">
              <template #default="{ row }">
                <el-tag :type="row.enabled ? 'success' : 'info'">
                  {{ row.enabled ? '启用' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" min-width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.updatedAt) }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="180"
              fixed="right"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  @click="openEditDialog(row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>

    <el-dialog
      :title="isEdit ? '编辑字典项' : '新增字典项'"
      v-model="dialogVisible"
      width="560px"
      destroy-on-close
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
        <el-form-item label="字典类型" prop="type">
          <el-select
            v-model="form.type"
            filterable
            placeholder="请选择字典类型"
            style="width: 100%"
          >
            <el-option
              v-for="option in MEDICAL_DICTIONARY_TYPE_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="字典项名称" prop="label">
          <el-input
            v-model="form.label"
            maxlength="50"
            show-word-limit
            placeholder="请输入字典项名称"
          />
        </el-form-item>

        <el-form-item label="排序值" prop="sortOrder">
          <el-input-number
            v-model="form.sortOrder"
            :controls="false"
            :step="10"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="是否启用" prop="enabled">
          <el-switch
            v-model="form.enabled"
            active-text="启用"
            inactive-text="停用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            {{ isEdit ? '保存修改' : '创建字典项' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  createDictionaryItem,
  deleteDictionaryItem,
  getDictionaries,
  updateDictionaryItem,
} from '../../api/dictionaries';
import { MEDICAL_DICTIONARY_TYPE_OPTIONS } from '../../constants/medical-dictionaries';

const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const currentId = ref(null);
const tableData = ref([]);
const activeCollapseNames = ref([]);

const searchForm = reactive({
  type: '',
  keyword: '',
});

const form = reactive({
  type: MEDICAL_DICTIONARY_TYPE_OPTIONS[0]?.value || '',
  label: '',
  sortOrder: 0,
  enabled: true,
});

const rules = {
  type: [{ required: true, message: '请选择字典类型', trigger: 'change' }],
  label: [{ required: true, message: '请输入字典项名称', trigger: 'blur' }],
};

const groupedTableData = computed(() => {
  const keyword = String(searchForm.keyword || '').trim();
  const filteredItems = tableData.value.filter((item) => {
    if (searchForm.type && item.type !== searchForm.type) {
      return false;
    }

    if (keyword && !String(item.label || '').includes(keyword)) {
      return false;
    }

    return true;
  });

  return MEDICAL_DICTIONARY_TYPE_OPTIONS.map((option) => ({
    type: option.value,
    label: option.label,
    items: filteredItems.filter((item) => item.type === option.value),
  })).filter((group) => group.items.length > 0);
});

watch(
  groupedTableData,
  (groups) => {
    const visibleNames = groups.map((group) => group.type);
    const preservedNames = activeCollapseNames.value.filter((name) =>
      visibleNames.includes(name),
    );
    activeCollapseNames.value =
      preservedNames.length > 0 ? preservedNames : visibleNames;
  },
  { immediate: true },
);

const getTypeLabel = (type) => {
  return (
    MEDICAL_DICTIONARY_TYPE_OPTIONS.find((option) => option.value === type)
      ?.label || type
  );
};

const formatDateTime = (value) => {
  if (!value) {
    return '-';
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return '-';
  }

  return date.toLocaleString('zh-CN', { hour12: false });
};

const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      includeDisabled: true,
      type: searchForm.type || undefined,
    };
    const res = await getDictionaries(params);
    tableData.value = Array.isArray(res) ? res : [];
  } finally {
    loading.value = false;
  }
};

const resetSearch = async () => {
  searchForm.type = '';
  searchForm.keyword = '';
  await fetchData();
};

const resetForm = () => {
  formRef.value?.clearValidate?.();
  form.type = MEDICAL_DICTIONARY_TYPE_OPTIONS[0]?.value || '';
  form.label = '';
  form.sortOrder = 0;
  form.enabled = true;
  currentId.value = null;
};

const openCreateDialog = () => {
  isEdit.value = false;
  resetForm();
  if (searchForm.type) {
    form.type = searchForm.type;
  }
  dialogVisible.value = true;
};

const openEditDialog = (row) => {
  isEdit.value = true;
  formRef.value?.clearValidate?.();
  currentId.value = row.id;
  form.type = row.type;
  form.label = row.label;
  form.sortOrder = row.sortOrder ?? 0;
  form.enabled = Boolean(row.enabled);
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  if (!formRef.value) {
    return;
  }

  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  submitLoading.value = true;
  try {
    const payload = {
      type: form.type,
      label: form.label,
      sortOrder: form.sortOrder,
      enabled: form.enabled,
    };

    if (isEdit.value) {
      await updateDictionaryItem(currentId.value, payload);
      ElMessage.success('字典项已更新');
    } else {
      await createDictionaryItem(payload);
      ElMessage.success('字典项已创建');
    }

    dialogVisible.value = false;
    await fetchData();
  } finally {
    submitLoading.value = false;
  }
};

const handleDelete = async (row) => {
  await ElMessageBox.confirm(
    `确认删除字典项「${row.label}」吗？删除后将无法继续在表单中选择该值。`,
    '删除确认',
    {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
    },
  );

  await deleteDictionaryItem(row.id);
  ElMessage.success('字典项已删除');
  await fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.panel-card {
  border-radius: 18px;
}

.panel-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.panel-title {
  font-size: 18px;
  font-weight: 700;
  color: #1f2937;
}

.panel-subtitle {
  margin-top: 6px;
  font-size: 13px;
  color: #6b7280;
}

.page-alert {
  margin-bottom: 16px;
}

.toolbar {
  margin-bottom: 16px;
}

.dictionary-collapse {
  display: grid;
  gap: 12px;
}

.dictionary-panel {
  border: 1px solid #d8e5f3;
  border-radius: 16px;
  overflow: hidden;
  background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
}

.collapse-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  color: #1f2937;
}
</style>
