<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="datacenter_id"
        :rules="[{ required: true, message: '请选择所属中心' }]"
      >
        <a-select
          v-model="form.datacenter_id"
          placeholder="请选择所属中心"
          :loading="loadingDatacenters"
          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="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/*"
        >
          <!-- <template #upload-button>
            <div class="upload-btn">
              <icon-plus />
              <div class="upload-text">上传图片</div>
            </div>
          </template> -->
        </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 { ref, watch, onMounted } from 'vue'
import { computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import { createFloor, updateFloor } from '@/api/ops/floor'
import { fetchDatacenterList } from '@/api/ops/floor'
import FtsUpload from '@/api/common/fts'

interface Floor {
  id?: number
  name?: string
  datacenter_id?: number
  floor_number?: number
  area?: number
  height?: number
  load_bearing?: number
  enabled?: boolean
  layout_plan?: string
  description?: string
}

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 form = ref({
  name: '',
  datacenter_id: undefined as number | undefined,
  floor_number: 1,
  area: undefined as number | undefined,
  height: undefined as number | undefined,
  load_bearing: undefined as number | undefined,
  enabled: true,
  layout_plan: '',
  description: '',
})

// 是否为编辑模式
const isEdit = computed(() => !!props.floor?.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 handleUpload = async (option: any) => {
  try {
    const file = option.fileItem.file
    const formData = new FormData()
    formData.append('file', file)
    
    // 使用fts接口上传文件
    const res: any = await FtsUpload(formData)
    
    if (res.code === 0) {
      // 上传成功，设置文件URL
      form.value.layout_plan = res.data?.result_url || ''
      option.onSuccess(res)
      Message.success('上传成功')
    } else {
      option.onError(new Error('上传失败'))
      Message.error('上传失败')
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    option.onError(error)
    Message.error('文件上传失败')
  }
}

// 处理文件变化
const handleFileChange = (files: any[]) => {
  fileList.value = files
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.floor && isEdit.value) {
        // 编辑模式：填充表单
        form.value = {
          name: props.floor.name || '',
          datacenter_id: props.floor.datacenter_id,
          floor_number: props.floor.floor_number || 1,
          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 || '',
          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: '',
          datacenter_id: undefined,
          floor_number: 1,
          area: undefined,
          height: undefined,
          load_bearing: undefined,
          enabled: true,
          layout_plan: '',
          description: '',
        }
        fileList.value = []
      }
    }
  }
)

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

  submitting.value = true
  try {
    const data: any = {
      name: form.value.name,
      datacenter_id: form.value.datacenter_id,
      floor_number: form.value.floor_number,
      area: form.value.area,
      height: form.value.height,
      load_bearing: form.value.load_bearing,
      enabled: form.value.enabled,
      layout_plan: form.value.layout_plan,
      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) {
      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)
}

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

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

<style scoped lang="less">
.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.upload-text {
  margin-top: 8px;
  font-size: 12px;
  color: var(--color-text-2);
}
</style>
