<template>
  <div class="dict-data-drawer">
    <el-drawer
      v-model="isShowDrawer"
      :title="title"
      direction="rtl"
      size="75%"
      @close="
        () => {
          isShowDrawer = false
        }
      "
    >
      <div class="dict-data-wrap">
        <EdfsWrap class="dict-data-from-wrap">
          <div class="from">
            <div class="from-input">
              <div class="from-row">
                <el-select v-model="queryParams.dictType">
                  <el-option
                    v-for="item in dictTypeList"
                    :key="item.type"
                    :label="item.name"
                    :value="item.type"
                  />
                </el-select>
              </div>
              <div class="from-row">
                <el-input
                  v-model="queryParams.label"
                  placeholder="请输入字典标签"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </div>

              <div class="from-row">
                <el-select v-model="queryParams.status" placeholder="数据状态" clearable>
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </div>
              <div class="btn-group">
                <el-button @click="handleQuery"><Icon icon="ep:search" /> 搜索</el-button>
                <el-button @click="resetQuery"><Icon icon="ep:refresh" /> 重置</el-button>
                <el-button
                  type="primary"
                  plain
                  @click="openForm('create')"
                  v-hasPermi="['system:dict:create']"
                >
                  <Icon icon="ep:plus" /> 新增
                </el-button>
                <el-button
                  type="primary"
                  plain
                  @click="handleExport"
                  :loading="exportLoading"
                  v-hasPermi="['system:dict:export']"
                >
                  <Icon icon="ep:download" /> 导出
                </el-button>
              </div>
            </div>
          </div>
        </EdfsWrap>

        <!-- 列表 -->
        <EdfsWrap class="dict-data-table" title="数据列表">
          <EdfsTable
            v-loading="loading"
            :data="list"
            class="table"
            :highlight-current-row="true"
            :page-total="total"
            :current-page="queryParams.pageNo"
            :page-size="queryParams.pageSize"
            row-class-name="row"
            ref="tableRef"
            @pageCurrentChange="handleJump"
          >
            <el-table-column label="字典编码" align="center" prop="id" />
            <el-table-column label="字典标签" align="center" prop="label" />
            <el-table-column label="字典键值" align="center" prop="value" />
            <el-table-column label="字典排序" align="center" prop="sort" />
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column label="颜色类型" align="center" prop="colorType" />
            <el-table-column label="CSS Class" align="center" prop="cssClass" />
            <el-table-column
              label="备注"
              align="center"
              prop="remark"
              show-overflow-tooltip
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              width="180"
              :formatter="dateFormatter"
            />
            <el-table-column label="操作" align="center" min-width="100%">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['system:dict:update']"
                >
                  修改
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['system:dict:delete']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </EdfsTable>
        </EdfsWrap>
      </div>
    </el-drawer>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <DictDataForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as DictDataApi from '@/api/module/system/dict/dict.data'
import * as DictTypeApi from '@/api/module/system/dict/dict.type'
import DictDataForm from './DictDataForm.vue'
import EdfsWrap from '@/components/dashboard/Edfs-wrap.vue'
import EdfsTable from '@/components/dashboard/Edfs-table/index.vue'
import { isResError, useMessage } from '@/hooks/useMessage'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
defineOptions({ name: 'SystemDictData' })
const isShowDrawer = defineModel<boolean>()
const props = defineProps<{
  dictType: string
}>()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute() // 路由

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const tableRef = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  label: '',
  status: undefined,
  dictType: props.dictType,
})
const exportLoading = ref(false) // 导出的加载中
const dictTypeList = ref<DictTypeApi.DictTypeVO[]>() // 字典类型的列表

const title = computed(() => {
  if (!dictTypeList.value || !queryParams.dictType) return '字典数据列表'
  const name =
    dictTypeList.value.find(item => item.type === queryParams.dictType)?.name ?? ''
  return `${name}-字典数据`
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  if (!queryParams.pageSize) {
    queryParams.pageSize = tableRef.value.getSize()
  }
  const res = await DictDataApi.getDictDataPage(queryParams)
  if (!isResError(res)) {
    list.value = res.data.list
    total.value = res.data.total
  }
  loading.value = false
}

function handleJump(page: number) {
  queryParams.pageNo = page
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.label = ''
  queryParams.status = undefined
  queryParams.dictType = props.dictType
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, queryParams.dictType)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const res = await DictDataApi.deleteDictData(id)
    if (isResError(res)) return
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const res = await DictDataApi.exportDictData(queryParams)

    download.excel(res.data, '字典数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 查询字典（精简)列表
  const res = await DictTypeApi.getSimpleDictTypeList()
  if (!isResError(res)) {
    dictTypeList.value = res.data
  }
})
</script>
<style lang="scss" scoped>
.dict-data-drawer {
  :deep(.el-drawer__body){
    padding: 10px;
  }
  .dict-data-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    row-gap: 10px;
    .dict-data-from-wrap {
      height: auto;
      width: 100%;
      .from {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        height: 100%;
        width: 100%;
        .from-input {
          display: flex;
          width: 100%;
          column-gap: 20px;
          row-gap: 10px;
          flex-wrap: wrap;
          .from-row {
            min-width: 270px;
          }
        }
      }
    }
    .dict-data-table {
      flex: 1;
      box-shadow: none;
      .table {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
