<template>
  <el-dialog
    v-model="dialogVisible"
    title="调监操作"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" v-loading="loading">
      <!-- 罪犯信息展示 -->
      <el-form-item label="罪犯信息">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="罪犯编号">{{ prisoner.prisonerNo }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ prisoner.name }}</el-descriptions-item>
          <el-descriptions-item label="当前监区">{{ prisoner.areaName }}</el-descriptions-item>
          <el-descriptions-item label="当前监室">{{ prisoner.cellName }}</el-descriptions-item>
        </el-descriptions>
      </el-form-item>

      <el-form-item label="目标监区" prop="targetAreaId">
        <el-select
          v-model="formData.targetAreaId"
          placeholder="请选择目标监区"
          clearable
          style="width: 100%"
          @change="handleTargetAreaChange"
        >
          <el-option
            v-for="area in areaList"
            :key="area.id"
            :label="area.name"
            :value="area.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="目标分监区" prop="targetSubAreaId">
        <el-select
          v-model="formData.targetSubAreaId"
          placeholder="请选择目标分监区"
          clearable
          style="width: 100%"
          @change="handleTargetSubAreaChange"
        >
          <el-option
            v-for="subArea in subAreaList"
            :key="subArea.id"
            :label="subArea.name"
            :value="subArea.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="目标监室" prop="targetCellId">
        <el-select
          v-model="formData.targetCellId"
          placeholder="请选择目标监室"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="cell in cellList"
            :key="cell.id"
            :label="`${cell.name} (${cell.currentCount}/${cell.capacity})`"
            :value="cell.id"
            :disabled="cell.currentCount >= cell.capacity"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="调监原因" prop="reason">
        <el-input v-model="formData.reason" type="textarea" :rows="3" placeholder="请输入调监原因" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import * as PrisonerApi from '@/api/prison/prisoner'
import { AreaApi } from '@/api/prison/area'
import { CellApi } from '@/api/prison/cell'

defineOptions({ name: 'PrisonTransferForm' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()
const prisoner = ref<any>({})
const areaList = ref([])
const subAreaList = ref([])
const cellList = ref([])

const formData = reactive({
  prisonerId: undefined as number | undefined,
  targetAreaId: undefined as number | undefined,
  targetSubAreaId: undefined as number | undefined,
  targetCellId: undefined as number | undefined,
  reason: ''
})

const rules = {
  targetAreaId: [{ required: true, message: '请选择目标监区', trigger: 'change' }],
  targetSubAreaId: [{ required: true, message: '请选择目标分监区', trigger: 'change' }],
  targetCellId: [{ required: true, message: '请选择目标监室', trigger: 'change' }]
}

/** 打开弹窗 */
const open = async (prisonerId: number) => {
  dialogVisible.value = true
  loading.value = true
  resetForm()
  try {
    // 获取罪犯信息
    prisoner.value = await PrisonerApi.getPrisoner(prisonerId)
    formData.prisonerId = prisonerId
    // 加载监区列表
    const treeData = await AreaApi.getAreaTree()
    areaList.value = treeData.filter((item: any) => item.level === 1 || item.parentId === 0)
  } finally {
    loading.value = false
  }
}

/** 目标监区变化 */
const handleTargetAreaChange = async (areaId: number) => {
  formData.targetSubAreaId = undefined
  formData.targetCellId = undefined
  subAreaList.value = []
  cellList.value = []
  if (areaId) {
    const treeData = await AreaApi.getAreaTree()
    const area = findArea(treeData, areaId)
    if (area && area.children) {
      subAreaList.value = area.children
    }
  }
}

/** 目标分监区变化 */
const handleTargetSubAreaChange = async (subAreaId: number) => {
  formData.targetCellId = undefined
  cellList.value = []
  if (subAreaId) {
    cellList.value = await CellApi.getCellPage({ areaId: subAreaId, pageNo: 1, pageSize: 200 }).then((res: any) => res.list || [])
  }
}

/** 递归查找监区 */
const findArea = (areas: any[], id: number): any => {
  for (const area of areas) {
    if (area.id === id) return area
    if (area.children) {
      const found = findArea(area.children, id)
      if (found) return found
    }
  }
  return null
}

/** 重置表单 */
const resetForm = () => {
  formData.prisonerId = undefined
  formData.targetAreaId = undefined
  formData.targetSubAreaId = undefined
  formData.targetCellId = undefined
  formData.reason = ''
  prisoner.value = {}
  subAreaList.value = []
  cellList.value = []
  formRef.value?.resetFields()
}

/** 提交 */
const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  loading.value = true
  try {
    await PrisonerApi.doTransfer({
      prisonerId: formData.prisonerId!,
      targetCellId: formData.targetCellId!,
      reason: formData.reason
    })
    ElMessage.success('调监成功')
    dialogVisible.value = false
    emit('success')
  } catch {
  } finally {
    loading.value = false
  }
}

defineExpose({ open })
</script>
