<template>
  <div class="adjust-apply-container">
    <vab-card>
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form :inline="true" :model="queryForm" @submit.prevent>
            <el-form-item label="申请人">
              <el-input v-model="queryForm.keyword" placeholder="姓名/学号" clearable />
            </el-form-item>
            <el-form-item label="调宿类型">
              <el-select v-model="queryForm.type" placeholder="全部" clearable style="width: 120px">
                <el-option label="单人换房" value="single" />
                <el-option label="双人互换" value="exchange" />
              </el-select>
            </el-form-item>
            <el-form-item label="审批状态">
              <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                <el-option label="待审批" value="pending" />
                <el-option label="已通过" value="approved" />
                <el-option label="已驳回" value="rejected" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"> <vab-icon icon="search-line" /> 查询</el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
        <vab-query-form-right-panel>
          <el-button type="primary" @click="handleApply"> <vab-icon icon="add-line" /> 发起调宿</el-button>
        </vab-query-form-right-panel>
      </vab-query-form>

      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="applyNo" label="申请单号" width="160" fixed />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'single' ? '' : 'warning'">{{ row.type === 'single' ? '单人换房' : '双人互换' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请详情" min-width="300">
          <template #default="{ row }">
            <div class="apply-detail">
              <div class="student-a">
                <span class="font-bold">{{ row.studentName }}</span>
                <span class="text-gray text-xs ml-5">({{ row.currentRoom }})</span>
              </div>
              <div class="arrow">
                <vab-icon icon="arrow-right-line" />
                <span class="action-text">{{ row.type === 'single' ? '调至' : '互换' }}</span>
              </div>
              <div class="target">
                <template v-if="row.type === 'single'">
                  <span class="text-primary">{{ row.targetRoom }}</span>
                </template>
                <template v-else>
                  <span class="font-bold">{{ row.targetStudentName }}</span>
                  <span class="text-gray text-xs ml-5">({{ row.targetRoom }})</span>
                </template>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="调宿原因" show-overflow-tooltip />
        <el-table-column prop="applyTime" label="申请时间" width="160" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div v-if="row.status === 'pending'">
              <el-button type="success" size="small" @click="handleApprove(row)"> <vab-icon icon="check-line" /> 同意</el-button>
              <el-button type="danger" size="small" @click="handleReject(row)"> <vab-icon icon="close-line" /> 驳回</el-button>
            </div>
            <el-button v-else size="small" @click="handleDetail(row)"> <vab-icon icon="info-line" /> 查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <vab-pagination
        :current-page="queryForm.pageNo"
        :page-size="queryForm.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </vab-card>

    <adjust-apply-dialog ref="applyDialogRef" @success="handleQuery" />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdjustApplyDialog from './components/AdjustApplyDialog.vue'

defineOptions({
  name: 'AdjustApply',
})

// --- Data ---
const queryForm = reactive({
  keyword: '',
  type: '',
  status: '',
  pageNo: 1,
  pageSize: 10,
})

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const applyDialogRef = ref()

// --- Helpers ---
const getStatusLabel = (status) => {
  const map = { pending: '待审批', approved: '已通过', rejected: '已驳回' }
  return map[status]
}
const getStatusType = (status) => {
  const map = { pending: 'warning', approved: 'success', rejected: 'danger' }
  return map[status]
}

// --- Methods ---
const generateMockData = () => {
  return [
    {
      applyNo: 'TS20260124001',
      type: 'single',
      studentName: '梁健',
      currentRoom: '一号书院 302-1',
      targetRoom: '一号书院 305-2',
      reason: '因生活习惯差异，申请调至空寝室',
      applyTime: '2026-01-24 10:00:00',
      status: 'pending'
    },
    {
      applyNo: 'TS20260124002',
      type: 'exchange',
      studentName: '鲁永波',
      currentRoom: '三号书院 501-1',
      targetStudentName: '王应哲',
      targetRoom: '三号书院 502-1',
      reason: '双方协商一致互换寝室',
      applyTime: '2026-01-23 15:30:00',
      status: 'approved'
    }
  ]
}

const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = generateMockData()
    loading.value = false
  }, 500)
}

const handleApply = () => {
  applyDialogRef.value.open()
}

const handleApprove = (row) => {
  ElMessageBox.confirm(
    `确认同意该调宿申请吗？系统将自动变更${row.type === 'exchange' ? '双方' : ''}床位信息及门禁权限。`,
    '审批通过',
    { confirmButtonText: '确认并执行', cancelButtonText: '取消', type: 'warning' }
  ).then(() => {
    row.status = 'approved'
    ElMessage.success('审批通过，数据已更新')
  })
}

const handleReject = (row) => {
  ElMessageBox.prompt('请输入驳回理由', '驳回申请', {
    confirmButtonText: '驳回',
    cancelButtonText: '取消',
  }).then(({ value }) => {
    row.status = 'rejected'
    ElMessage.info('申请已驳回')
  })
}

const handleDetail = (row) => {
  ElMessage.info('查看详情')
}

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

handleQuery()
</script>

<style lang="scss" scoped>
.adjust-apply-container {
  .text-gray { color: #909399; }
  .text-primary { color: var(--el-color-primary); }
  .text-xs { font-size: 12px; }
  .font-bold { font-weight: bold; }
  .ml-5 { margin-left: 5px; }

  .apply-detail {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .arrow {
      color: #909399;
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 12px;
      
      .action-text { transform: scale(0.8); }
    }
  }
}
</style>