<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" :disabled="isEdit" allow-search>
          <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_number" :rules="[{ required: true, message: '请输入楼层号' }]">
        <a-input-number v-model="form.floor_number" placeholder="请输入楼层号" :min="-10" :max="100" style="width: 100%" />
      </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="area">
        <a-input-number v-model="form.area" placeholder="请输入面积" :min="0" :precision="2" style="width: 100%" />
      </a-form-item>

      <a-form-item label="楼高（米）" field="height">
        <a-input-number v-model="form.height" placeholder="请输入楼高" :min="0" :precision="2" style="width: 100%" />
      </a-form-item>

      <a-form-item label="承重（kg/m²）" field="load_bearing">
        <a-input-number v-model="form.load_bearing" placeholder="请输入承重" :min="0" :precision="2" style="width: 100%" />
      </a-form-item>

      <a-form-item label="启用" field="enabled">
        <a-switch v-model="form.enabled" />
      </a-form-item>

      <a-form-item label="楼层布局" field="layout_plan">
        <a-upload
          :limit="1"
          :custom-request="handleUpload"
          @change="handleFileChange"
          :file-list="fileList"
          list-type="picture-card"
          accept="image/*"
        ></a-upload>
      </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, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { createFloor, fetchDatacenterList, updateFloor } from '@/api/ops/floor'
import type { Floor, SaveFloorPayload } from '@/api/ops/floor'
import { uploadFloorLayout } from '@/api/ops/floorFile'

interface Props {
  visible: boolean
  floor: Floor | 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 submitting = ref(false)
const datacenterList = ref<any[]>([])
const fileList = ref<any[]>([])
const localPreviewURL = ref('')

// 表单数据
const form = ref({
  name: '',
  code: '',
  datacenter_id: undefined as number | undefined,
  floor_number: 1,
  status: 'planning',
  area: undefined as number | undefined,
  height: undefined as number | undefined,
  load_bearing: undefined as number | undefined,
  enabled: true,
  layout_plan: '',
  layout_plan_file_id: '',
  description: '',
})

// 是否为编辑模式
const isEdit = computed(() => !!props.floor?.id)

const releaseLocalPreviewURL = () => {
  if (localPreviewURL.value) {
    URL.revokeObjectURL(localPreviewURL.value)
    localPreviewURL.value = ''
  }
}

// 加载数据中心列表
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 handleUpload = async (option: any) => {
  try {
    const file = option.fileItem.file as File
    const pendingUpload = await uploadFloorLayout(file)

    releaseLocalPreviewURL()
    localPreviewURL.value = URL.createObjectURL(file)
    option.fileItem.url = localPreviewURL.value
    form.value.layout_plan = ''
    form.value.layout_plan_file_id = pendingUpload.file_id
    option.onSuccess(pendingUpload)
    Message.success('上传成功')
  } catch (error) {
    console.error('文件上传失败:', error)
    option.onError(error)
    Message.error('文件上传失败')
  }
}

// 处理文件变化
const handleFileChange = (files: any[]) => {
  fileList.value = files
  if (files.length === 0) {
    releaseLocalPreviewURL()
    form.value.layout_plan = ''
    form.value.layout_plan_file_id = ''
  }
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      releaseLocalPreviewURL()
      if (props.floor && isEdit.value) {
        // 编辑模式：填充表单
        form.value = {
          name: props.floor.name || '',
          code: props.floor.code || '',
          datacenter_id: props.floor.datacenter_id,
          floor_number: props.floor.floor_number || 1,
          status: props.floor.status || 'planning',
          area: props.floor.area,
          height: props.floor.height,
          load_bearing: props.floor.load_bearing,
          enabled: props.floor.enabled !== undefined ? props.floor.enabled : true,
          layout_plan: props.floor.layout_plan || '',
          layout_plan_file_id: props.floor.layout_plan_file_id || '',
          description: props.floor.description || '',
        }
        // 如果有布局图，设置文件列表
        if (props.floor.layout_plan) {
          fileList.value = [
            {
              uid: '-1',
              name: 'layout_plan',
              url: props.floor.layout_plan,
            },
          ]
        } else {
          fileList.value = []
        }
      } else {
        // 新建模式：重置表单
        form.value = {
          name: '',
          code: '',
          datacenter_id: undefined,
          floor_number: 1,
          status: 'planning',
          area: undefined,
          height: undefined,
          load_bearing: undefined,
          enabled: true,
          layout_plan: '',
          layout_plan_file_id: '',
          description: '',
        }
        fileList.value = []
      }
    } else releaseLocalPreviewURL()
  }
)

// 确认提交
const handleOk = async () => {
  const valid = await formRef.value?.validate()
  if (valid) return

  submitting.value = true
  try {
    const data: SaveFloorPayload = {
      name: form.value.name,
      code: form.value.code,
      datacenter_id: form.value.datacenter_id,
      floor_number: form.value.floor_number,
      status: form.value.status,
      area: form.value.area,
      height: form.value.height,
      load_bearing: form.value.load_bearing,
      enabled: form.value.enabled,
      layout_plan_file_id: form.value.layout_plan_file_id,
      description: form.value.description,
    }

    let res
    if (isEdit.value && props.floor?.id) {
      // 编辑楼层
      data.id = props.floor.id
      res = await updateFloor(data)
    } else {
      // 新建楼层
      res = await createFloor(data)
    }

    if (res.code === 0) {
      const savedFloor = res.details
      form.value.layout_plan = savedFloor?.layout_plan || ''
      form.value.layout_plan_file_id = savedFloor?.layout_plan_file_id || ''
      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 = () => {
  releaseLocalPreviewURL()
  emit('update:visible', false)
}

// 处理对话框可见性变化
const handleVisibleChange = (visible: boolean) => {
  if (!visible) releaseLocalPreviewURL()
  emit('update:visible', visible)
}

// 组件挂载时加载数据中心列表
onMounted(() => {
  loadDatacenterList()
})

onBeforeUnmount(releaseLocalPreviewURL)
</script>

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