<template>
  <el-dialog
    title="宿舍互换"
    v-model="visible"
    :close-on-click-modal="false"
    draggable
    width="520px">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-form-item label="学生一" prop="sourceSutNo">
        <el-select
          v-model="form.sourceSutNo"
          placeholder="请选择学生（学号）"
          clearable
          filterable
          style="width: 100%"
          @change="onSourceChange">
          <el-option
            v-for="item in studentOptions"
            :key="item.stuNo"
            :label="`${item.realName}（${item.stuNo}）${item.roomNo || ''}`"
            :value="item.stuNo" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生二" prop="targetStuNO">
        <el-select
          v-model="form.targetStuNO"
          placeholder="请选择学生（学号）"
          clearable
          filterable
          style="width: 100%"
          @change="onTargetChange">
          <el-option
            v-for="item in studentOptions"
            :key="item.stuNo"
            :label="`${item.realName}（${item.stuNo}）${item.roomNo || ''}`"
            :value="item.stuNo" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="submitting">确 认 互 换</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="DormRoomStudentSwapDialog">
import { ref, reactive } from 'vue'
import { useMessage } from '/@/hooks/message'
import { exchangeRoom } from '/@/api/stuwork/dormroomstudent'
import { fetchList } from '/@/api/stuwork/dormroomstudent'

const emit = defineEmits(['refresh'])

const formRef = ref()
const visible = ref(false)
const loading = ref(false)
const submitting = ref(false)
const studentOptions = ref<any[]>([])

const form = reactive({
  sourceSutNo: '',
  targetStuNO: ''
})

const rules = {
  sourceSutNo: [{ required: true, message: '请选择学生一', trigger: 'change' }],
  targetStuNO: [{ required: true, message: '请选择学生二', trigger: 'change' }]
}

const onSourceChange = () => {
  if (form.sourceSutNo && form.targetStuNO && form.sourceSutNo === form.targetStuNO) {
    form.targetStuNO = ''
  }
}
const onTargetChange = () => {
  if (form.sourceSutNo && form.targetStuNO && form.sourceSutNo === form.targetStuNO) {
    form.sourceSutNo = ''
  }
}

const openDialog = async (queryParams?: any) => {
  visible.value = true
  form.sourceSutNo = ''
  form.targetStuNO = ''
  loading.value = true
  try {
    const res = await fetchList({
      current: 1,
      size: 500,
      ...queryParams
    })
    const list = res?.data?.records ?? res?.records ?? []
    studentOptions.value = Array.isArray(list) ? list : []
  } catch (err) {
    studentOptions.value = []
  } finally {
    loading.value = false
  }
}

const onSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    if (form.sourceSutNo === form.targetStuNO) {
      useMessage().warning('请选择两名不同学生')
      return
    }
    submitting.value = true
    try {
      await exchangeRoom({
        sourceSutNo: form.sourceSutNo,
        targetStuNO: form.targetStuNO
      })
      useMessage().success('互换成功')
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      console.error(err)
    } finally {
      submitting.value = false
    }
  })
}

defineExpose({ openDialog })
</script>
