<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑机房' : '新建机房'"
    width="700px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :confirm-loading="submitting"
  >
    <a-form :model="form" layout="vertical" ref="formRef">
      <a-form-item label="机房名称" field="name" :rules="[{ required: true, message: '请输入机房名称' }]">
        <a-input v-model="form.name" placeholder="请输入机房名称" :max-length="200" />
      </a-form-item>

      <a-form-item label="机房编码" field="code" :rules="[{ required: true, message: '请输入机房编码' }]">
        <a-input v-model="form.code" placeholder="请输入机房编码" :max-length="100" />
      </a-form-item>

      <a-form-item label="所属中心" field="datacenter_id" :rules="[{ required: true, message: '请选择所属中心' }]">
        <a-select
          v-model="form.datacenter_id"
          placeholder="请选择所属中心"
          :loading="loadingDatacenters"
          allow-search
          @change="handleDatacenterChange"
        >
          <a-option v-for="item in datacenterList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>

      <a-form-item label="所属楼层" field="floor_id" :rules="[{ required: true, message: '请选择所属楼层' }]">
        <a-select
          v-model="form.floor_id"
          placeholder="请选择所属楼层"
          :loading="loadingFloors"
          :disabled="!form.datacenter_id"
          allow-search
          @search="handleFloorSearch"
        >
          <a-option v-for="item in floorList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>

      <a-form-item label="状态" field="status">
        <a-select v-model="form.status" placeholder="请选择状态">
          <a-option value="planning">规划中</a-option>
          <a-option value="construction">建设中</a-option>
          <a-option value="operating">运营中</a-option>
          <a-option value="maintenance">维护中</a-option>
          <a-option value="offline">已下线</a-option>
        </a-select>
      </a-form-item>

      <a-form-item label="描述" field="description">
        <a-textarea v-model="form.description" placeholder="请输入描述" :auto-size="{ minRows: 4, maxRows: 8 }" :max-length="500" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { createRoom, updateRoom } from '@/api/ops/room'
import { fetchDatacenterList } from '@/api/ops/floor'
import { fetchFloorListByDatacenter } from '@/api/ops/floor'

interface Room {
  id?: number
  name?: string
  code?: string
  datacenter_id?: number
  floor_id?: number
  status?: string
  description?: string
}

interface Props {
  visible: boolean
  room: Room | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const loadingDatacenters = ref(false)
const loadingFloors = ref(false)
const submitting = ref(false)
const datacenterList = ref<any[]>([])
const floorList = ref<any[]>([])
let floorSearchTimer: number | undefined

const form = ref({
  name: '',
  code: '',
  datacenter_id: undefined as number | undefined,
  floor_id: undefined as number | undefined,
  status: 'planning',
  description: '',
})

const isEdit = computed(() => !!props.room?.id)

const loadDatacenterList = async () => {
  loadingDatacenters.value = true
  try {
    const res: any = await fetchDatacenterList()
    if (res.code === 0) {
      datacenterList.value = res.details
    }
  } catch (error) {
    console.error('获取数据中心列表失败:', error)
  } finally {
    loadingDatacenters.value = false
  }
}

const loadFloorList = async (datacenterId?: number, keyword?: string) => {
  if (!datacenterId) {
    floorList.value = []
    return
  }
  loadingFloors.value = true
  try {
    const res: any = await fetchFloorListByDatacenter(datacenterId, { name: keyword })
    if (res.code === 0) {
      floorList.value = res.details
    }
  } catch (error) {
    console.error('获取楼层列表失败:', error)
    floorList.value = []
  } finally {
    loadingFloors.value = false
  }
}

const handleDatacenterChange = async (value: number) => {
  form.value.floor_id = undefined
  await loadFloorList(value)
}

const handleFloorSearch = (keyword: string) => {
  if (!form.value.datacenter_id) return
  if (floorSearchTimer) {
    window.clearTimeout(floorSearchTimer)
  }
  floorSearchTimer = window.setTimeout(() => {
    loadFloorList(form.value.datacenter_id, keyword?.trim() || undefined)
  }, 300)
}

watch(
  () => props.visible,
  async (newVal) => {
    if (!newVal) return

    if (props.room && isEdit.value) {
      form.value = {
        name: props.room.name || '',
        code: props.room.code || '',
        datacenter_id: props.room.datacenter_id,
        floor_id: props.room.floor_id,
        status: props.room.status || 'planning',
        description: props.room.description || '',
      }
      if (props.room.datacenter_id) {
        await loadFloorList(props.room.datacenter_id)
      }
    } else {
      form.value = {
        name: '',
        code: '',
        datacenter_id: undefined,
        floor_id: undefined,
        status: 'planning',
        description: '',
      }
      floorList.value = []
    }
  }
)

const handleOk = async () => {
  const valid = await formRef.value?.validate()
  if (valid) return

  submitting.value = true
  try {
    const data: any = {
      name: form.value.name,
      code: form.value.code,
      datacenter_id: form.value.datacenter_id,
      floor_id: form.value.floor_id,
      status: form.value.status,
      description: form.value.description,
    }

    let res
    if (isEdit.value && props.room?.id) {
      data.id = props.room.id
      res = await updateRoom(data)
    } else {
      res = await createRoom(data)
    }

    if (res.code === 0) {
      Message.success(isEdit.value ? '编辑成功' : '创建成功')
      emit('success')
      emit('update:visible', false)
    } else {
      Message.error(res.message || (isEdit.value ? '编辑失败' : '创建失败'))
    }
  } catch (error) {
    Message.error(isEdit.value ? '编辑失败' : '创建失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  emit('update:visible', false)
}

const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}

loadDatacenterList()
</script>

<script lang="ts">
export default {
  name: 'RoomFormDialog',
}
</script>
