<template>
  <PageContainer title="平台字典管理">
    <QueryToolbar>
      <el-button v-if="canManage" type="primary" plain @click="openCreateTypeDialog">新增字典类型</el-button>
      <el-button v-if="canRead" @click="loadTypes">刷新类型列表</el-button>
    </QueryToolbar>

    <el-table :data="typeOptions" class="mt-md" empty-text="暂无数据">
      <el-table-column prop="dictType" label="类型编码" width="220" />
      <el-table-column prop="dictName" label="名称" />
      <el-table-column prop="sortNo" label="排序" width="100" />
      <el-table-column prop="status" label="状态" width="110" :formatter="statusFormatter" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button v-if="canRead" size="small" type="primary" @click="openItems(row)">打开字典项</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
      v-model="itemsDrawerVisible"
      :title="currentType ? `${currentType.dictName}（${currentType.dictType}）字典项` : '字典项'"
      size="70%"
      destroy-on-close
    >
      <QueryToolbar>
        <el-button v-if="canManage" type="primary" :disabled="!dictType" @click="openCreateDrawer">新增字典项</el-button>
        <el-button v-if="canRead" :disabled="!dictType" @click="load">刷新</el-button>
      </QueryToolbar>

      <el-table :data="rows" empty-text="暂无数据">
        <el-table-column prop="dictCode" label="编码" width="220" />
        <el-table-column prop="dictName" label="名称" />
        <el-table-column prop="sortNo" label="排序" width="100" />
        <el-table-column prop="status" label="状态" width="110" :formatter="statusFormatter" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="260">
          <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"
              @click="handleDisable(row)"
            >
              停用
            </el-button>
            <el-button v-else-if="canManage" size="small" @click="handleEnable(row)">启用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <el-drawer v-model="createVisible" title="新增字典项" :size="DRAWER_SIZE.sm" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="字典类型"><el-input :value="dictType" disabled /></el-form-item>
        <el-form-item label="编码" prop="dictCode"><el-input v-model="form.dictCode" placeholder="例如 CHIEF_PHYSICIAN" /></el-form-item>
        <el-form-item label="名称" prop="dictName"><el-input v-model="form.dictName" /></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="form.sortNo" :min="1" /></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.sm">
      <el-form ref="editFormRef" :model="editForm" label-position="left" :label-width="LABEL_WIDTH.md" :rules="editFormRules">
        <el-form-item label="名称" prop="dictName"><el-input v-model="editForm.dictName" /></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="editForm.sortNo" :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-item label="备注"><el-input v-model="editForm.remark" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleUpdate">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="createTypeVisible" title="新增字典类型" :width="DIALOG_WIDTH.sm">
      <el-form ref="typeFormRef" :model="typeForm" label-position="left" :label-width="LABEL_WIDTH.md" :rules="typeFormRules">
        <el-form-item label="类型编码" prop="dictType">
          <el-input v-model="typeForm.dictType" placeholder="例如 MEETING_CATEGORY" />
        </el-form-item>
        <el-form-item label="类型名称" prop="dictName">
          <el-input v-model="typeForm.dictName" placeholder="例如 会议类别" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="typeForm.sortNo" :min="1" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="typeForm.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createTypeVisible = false">取消</el-button>
        <el-button v-if="canManage" type="primary" @click="handleCreateType">创建</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 {
  createPlatformDictionaryType,
  createPlatformDictionary,
  disablePlatformDictionary,
  enablePlatformDictionary,
  fetchPlatformDictionaries,
  fetchPlatformDictionaryTypes,
  updatePlatformDictionary,
} 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.platform.dictionaryRead));
const canManage = computed(() => authStore.hasPermission(PERMS.platform.dictionaryManage));

const dictType = ref("");
const typeOptions = ref<Array<{ dictType: string; dictName: string; sortNo?: number; status?: string; remark?: string }>>([]);
const rows = ref<any[]>([]);
const currentType = ref<{ dictType: string; dictName: string } | null>(null);
const itemsDrawerVisible = ref(false);
const createVisible = ref(false);
const form = ref({
  dictCode: "",
  dictName: "",
  sortNo: 100,
});
const createTypeVisible = ref(false);
const typeForm = ref({
  dictType: "",
  dictName: "",
  sortNo: 100,
  remark: "",
});

const editVisible = ref(false);
const editId = ref<number | null>(null);
const editForm = ref({
  dictName: "",
  sortNo: 100,
  status: "ENABLED" as "ENABLED" | "DISABLED",
  remark: "",
});

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

const formRules = ref<FormRules>({
  dictCode: [{ required: true, message: "请输入编码", trigger: "blur" }],
  dictName: [{ required: true, message: "请输入名称", trigger: "blur" }],
});

const editFormRules = ref<FormRules>({
  dictName: [{ required: true, message: "请输入名称", trigger: "blur" }],
});

const typeFormRules = ref<FormRules>({
  dictType: [{ required: true, message: "请输入类型编码", trigger: "blur" }],
  dictName: [{ required: true, message: "请输入类型名称", trigger: "blur" }],
});

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

const openCreateDrawer = () => {
  if (!dictType.value) {
    ElMessage.warning("请先新增并选择字典类型");
    return;
  }
  form.value = {
    dictCode: "",
    dictName: "",
    sortNo: 100,
  };
  createVisible.value = true;
};

const openItems = async (row: { dictType: string; dictName: string }) => {
  dictType.value = row.dictType;
  currentType.value = row;
  itemsDrawerVisible.value = true;
  await load();
};

const openCreateTypeDialog = () => {
  typeForm.value = {
    dictType: "",
    dictName: "",
    sortNo: 100,
    remark: "",
  };
  createTypeVisible.value = true;
};

const loadTypes = async () => {
  if (!canRead.value) {
    typeOptions.value = [];
    dictType.value = "";
    return;
  }
  const resp = await fetchPlatformDictionaryTypes();
  typeOptions.value = resp?.data || [];
  if (dictType.value && !typeOptions.value.some((item) => item.dictType === dictType.value)) {
    dictType.value = "";
    currentType.value = null;
  }
};

const load = async () => {
  if (!canRead.value || !dictType.value) {
    rows.value = [];
    return;
  }
  const resp = await fetchPlatformDictionaries({ dictType: dictType.value });
  rows.value = resp?.data || [];
};

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

  await createPlatformDictionaryType(typeForm.value);
  ElMessage.success("字典类型创建成功");
  createTypeVisible.value = false;
  await loadTypes();
};

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

  await createPlatformDictionary({
    dictType: dictType.value,
    dictCode: form.value.dictCode,
    dictName: form.value.dictName,
    sortNo: form.value.sortNo,
  });
  ElMessage.success("字典项创建成功");
  createVisible.value = false;
  form.value = { dictCode: "", dictName: "", sortNo: 100 };
  await load();
};

const openEdit = (row: any) => {
  editId.value = row.id;
  editForm.value = {
    dictName: row.dictName || "",
    sortNo: row.sortNo || 100,
    status: row.status || "ENABLED",
    remark: row.remark || "",
  };
  editVisible.value = true;
};

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

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

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

const handleEnable = async (row: any) => {
  await enablePlatformDictionary(row.id);
  ElMessage.success("已启用");
  await load();
};

const handleDisable = async (row: any) => {
  await disablePlatformDictionary(row.id);
  ElMessage.success("已停用");
  await load();
};

onMounted(async () => {
  await loadTypes();
});
</script>
