<template>
  <!-- 搜索工作栏 -->
  <el-form :model="queryParams" ref="queryFormRef" inline label-width="0">
    <el-form-item>
      <el-input
        v-model="queryParams.name"
        placeholder="请输入部门名称"
        clearable
        class="!w-240px"
      />
    </el-form-item>
    <el-form-item>
      <el-button @click="handleQuery"> 搜索</el-button>
      <el-button @click="resetQuery"> 重置</el-button>
      <el-button type="primary" plain @click="openForm('create')"> 新增 </el-button>
    </el-form-item>
  </el-form>

  <!-- 列表 -->
  <el-table v-loading="loading" :data="list" row-key="id" default-expand-all border>
    <el-table-column prop="name" label="部门名称" />
    <el-table-column prop="leader" label="负责人" width="120" />
    <el-table-column prop="sort" label="排序" width="200" />
    <el-table-column prop="status" label="状态" width="100" />
    <el-table-column label="创建时间" prop="createTime" width="180" :formatter="dateFormatter" />
    <el-table-column label="操作" class-name="fixed-width" width="160">
      <template #default="scope">
        <el-button link type="primary" @click="openForm('update', scope.row.id)"> 修改 </el-button>
        <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 表单弹窗：添加/修改 -->
  <DeptForm ref="formRef" @success="getList" />
</template>
<script setup lang="ts" name="SystemDept">
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import DeptForm from './DeptForm.vue'
import { dateFormatter } from '@/utils/formatTime'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  name: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeptApi.getDeptPage(queryParams)
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

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

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

/** 初始化 **/
onMounted(async () => {
  await getList()
})
</script>
