<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="所属监区" prop="areaId">
        <el-tree-select
          v-model="queryParams.areaId"
          :data="areaTreeData"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          :render-after-expand="false"
          default-expand-all
          check-strictly
          placeholder="请选择监区"
          clearable
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="监室名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入监室名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-160px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          class="!w-100px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['prison:cell:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['prison:cell:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="checkedIds.length === 0"
          @click="handleDeleteBatch"
          v-hasPermi="['prison:cell:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="监室ID" align="center" prop="id" width="80" />
      <el-table-column label="所属监区" align="center" prop="areaName" width="120" />
      <el-table-column label="监室名称" align="center" prop="name" width="120" />
      <el-table-column label="监室编码" align="center" prop="code" width="120" />
      <el-table-column label="床位数量" align="center" prop="capacity" width="90" />
      <el-table-column label="当前人数" align="center" prop="currentCount" width="90" />
      <el-table-column label="排序" align="center" prop="sort" width="70" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PRISON_CELL_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          {{ dateFormatter(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['prison:cell:update']"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            link
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['prison:cell:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CellForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CellApi } from '@/api/prison/cell'
import { AreaApi } from '@/api/prison/area'
import CellForm from './CellForm.vue'
import type { CellVO, CellPageReqVO } from '@/api/prison/cell'

defineOptions({ name: 'Cell' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<CellVO[]>([])
const total = ref(0)
const queryParams = reactive<CellPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  areaId: undefined,
  name: undefined,
  status: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

// 监区树形数据
const areaTreeData = ref<any[]>([])

// 使用字典获取选项
const statusOptions = getIntDictOptions(DICT_TYPE.PRISON_CELL_STATUS)

const loadAreaTree = async () => {
  try {
    areaTreeData.value = await AreaApi.getAreaTree()
  } catch {
    areaTreeData.value = []
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CellApi.getCellPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  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 CellApi.deleteCell(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 批量删除按钮操作 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (rows: CellVO[]) => {
  checkedIds.value = rows.map((row) => row.id!)
}

const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await CellApi.deleteCellList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await CellApi.exportCell(queryParams)
    download.excel(data, '监室信息.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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