<template>
  <VerticalFlexLayout>
    <template #static>
      <Breadcrumb />
    </template>
    <div class="dictionary-container">
      <div class="table-operations">
        <el-button type="primary" @click="handleAddDialogShow" :icon="Plus">新增字典项</el-button>
      </div>

      <div class="table-wrapper">
        <el-table v-loading="loading" :data="dataSource" height="100%">
          <el-table-column prop="dictName" label="字典名称" width="360" />
          <el-table-column prop="dictCode" label="字典编码" width="360" />
          <el-table-column prop="description" label="字典描述" />
          <el-table-column prop="dictType" label="分类" width="180">
            <template #default="{ row }">
              {{ typeLabelMap[row.dictType] || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="180">
            <template #default="{ row }">
              {{ statusLabelMap[row.status] || '' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="primary" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="paginationPosition">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="PAGE_SIZE_CONFIG"
          :total="totalRow"
          background
          :layout="DEFAULT_PAGINATION_LAYOUT"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <AddDict
        v-if="dialogVisible"
        ref="addDictRef"
        @close="closeAddDialog"
        @submit="handleSubmit"
        :dictCode="currentDictCode"
      />
    </div>
  </VerticalFlexLayout>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { DEFAULT_PAGINATION_LAYOUT, PAGE_SIZE_CONFIG } from '@/constant/pagination';
  import { Plus } from '@element-plus/icons-vue';
  import AddDict from './components/AddDict.vue';
  import { createDictApi, SaveDictParams, updateDict, deleteDict } from '@/api/dict';
  import { useDataSource } from './useDataSource';
  import { dictionaryStatusOptions, dictionaryTypeOptions } from './constants';
  import Breadcrumb from '@/components/Breadcrumb.vue';
  import VerticalFlexLayout from '@/components/VerticalFlexLayout.vue';
  import { msgConfirm } from '@/utils/element-plus/messageBox';

  // 表格数据
  const loading = ref(false);

  const { dataSource, getDataSource, pageSize, currentPage, totalRow } = useDataSource();

  onMounted(() => {
    getDataSource();
  });

  // 分页相关
  function handleSizeChange(val: number) {
    pageSize.value = val;
    getDataSource();
  }

  function handleCurrentChange(val: number) {
    currentPage.value = val;
    getDataSource();
  }

  // 表单相关
  const dialogVisible = ref(false);
  const dialogTitle = ref('新增字典');
  const addDictRef = ref<InstanceType<typeof AddDict>>();
  const currentDictCode = ref('');

  // 新增字典
  function handleAddDialogShow() {
    dialogVisible.value = true;
    currentDictCode.value = '';
  }

  const closeAddDialog = () => {
    dialogVisible.value = false;
    if (addDictRef.value) {
      addDictRef.value.resetForm();
    }
  };

  // 编辑字典
  function handleEdit(row: any) {
    dialogTitle.value = '编辑字典';
    dialogVisible.value = true;
    currentDictCode.value = row.dictCode;
  }

  // 删除字典
  async function handleDelete(row: any) {
    try {
      await msgConfirm('确定要删除这条字典记录吗？', '提示', {
        type: 'warning',
      });
      await deleteDictionary(row.dictId);
    } catch {
      // 用户取消删除
    }
  }

  // 提交表单
  async function handleSubmit(formData: SaveDictParams) {
    if (!addDictRef.value) return;
    let operate = '';
    if (formData.dictId) {
      await updateDictionary(formData);
      operate = '编辑';
    } else {
      await createDictionary(formData);
      operate = '新增';
    }
    dialogVisible.value = false;
    ElMessage.success(`${operate}字典成功`);
    getDataSource();
  }

  const createDictionary = (formData: SaveDictParams) => {
    createDictApi(formData).then(() => {
      ElMessage.success('保存成功');
    });
  };

  const updateDictionary = (formData: SaveDictParams) => {
    updateDict(formData).then(() => {
      ElMessage.success('编辑成功');
    });
  };

  const deleteDictionary = (id: number) => {
    deleteDict(id).then(() => {
      ElMessage.success('删除成功');
      getDataSource();
    });
  };

  const typeLabelMap = computed(() =>
    Object.fromEntries(dictionaryTypeOptions.map((item) => [item.value, item.label])),
  );

  const statusLabelMap = computed(() =>
    Object.fromEntries(dictionaryStatusOptions.map((item) => [item.value, item.label])),
  );
</script>

<style lang="scss" scoped>
  .dictionary-container {
    padding: 20px;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;

    .table-operations {
      margin-bottom: 20px;
      flex-shrink: 0;
    }
  }

  .table-wrapper {
    flex: 1;
    overflow: hidden;
    min-height: 0;
  }
</style>
