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

        <el-table v-loading="loading" :data="dataSource" style="width: 100%; margin-top: 16px">
          <el-table-column prop="dictName" label="字典名称" />
          <el-table-column prop="dictCode" label="字典编码" />
          <el-table-column prop="description" label="字典描述" show-overflow-tooltip />
          <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="200" 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 class="paginationPosition">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalRow"
            background
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <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, ElMessageBox } from 'element-plus';
  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';

  // 表格数据
  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 ElMessageBox.confirm('确定要删除这条字典记录吗？', '提示', {
        type: 'warning',
      });
      await deleteDictionary(row.dictId);
    } catch {
      // 用户取消删除
    }
  }

  // 提交表单
  async function handleSubmit(formData: SaveDictParams) {
    if (!addDictRef.value) return;
    if (formData.dictId) {
      await updateDictionary(formData);
    } else {
      await createDictionary(formData);
    }
    dialogVisible.value = false;
    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 {
    .search-form {
      margin-bottom: 16px;
    }

    .table-operations {
      margin-bottom: 16px;
    }
  }
</style>
