<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="楼层管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <icon-plus />
          </template>
          新建楼层
        </a-button>
      </template>
      
      <!-- 序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>
      
      <!-- 所属中心 -->
      <template #datacenter="{ record }">
        {{ record.datacenter?.name || '-' }}
      </template>
      
      <!-- 状态 -->
      <template #status="{ record }">
        <a-tag :color="statusMap[record.status]?.color || 'gray'">
          {{ statusMap[record.status]?.text || record.status }}
        </a-tag>
      </template>
      
      <!-- 操作 -->
      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">
          详情
        </a-button>
        <a-button type="text" size="small" @click="handleEdit(record)">
          编辑
        </a-button>
        <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
          删除
        </a-button>
      </template>
    </search-table>
    
    <!-- 楼层表单对话框（新建/编辑） -->
    <floor-form-dialog
      v-model:visible="formVisible"
      :floor="editingFloor"
      @success="handleFormSuccess"
    />
    
    <!-- 楼层详情对话框 -->
    <floor-detail-dialog
      v-model:visible="detailVisible"
      :floor-id="currentFloorId"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { searchFormConfig } from './config/search-form'
import { columns as columnsConfig } from './config/columns'
import {
  fetchFloorList,
  fetchDatacenterList,
  deleteFloor,
} from '@/api/ops/floor'
import FloorDetailDialog from './components/FloorDetailDialog.vue'
import FloorFormDialog from './components/FloorFormDialog.vue'

// 状态映射
const statusMap: Record<string, { text: string; color: string }> = {
  planning: { text: '规划中', color: 'blue' },
  construction: { text: '建设中', color: 'orange' },
  operating: { text: '运营中', color: 'green' },
  maintenance: { text: '维护中', color: 'gold' },
  offline: { text: '已下线', color: 'red' },
}

// 状态管理
const loading = ref(false)
const tableData = ref<any[]>([])
const formModel = ref({
  keyword: '',
  status: '',
  datacenter_id: undefined as number | undefined,
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 表单项配置
const datacenterSelectOptions = ref<{ label: string; value: number }[]>([])
let datacenterSearchTimer: number | undefined

const formItems = computed<FormItem[]>(() =>
  searchFormConfig.map((item) => {
    if (item.field === 'datacenter_id') {
      return {
        ...item,
        options: datacenterSelectOptions.value,
        allowSearch: true,
        onSearch: handleDatacenterSearch,
      }
    }
    return item
  }),
)

// 表格列配置
const columns = computed(() => columnsConfig)

// 当前选中的楼层
const currentFloorId = ref<number | undefined>(undefined)
const editingFloor = ref<any>(null)

// 对话框可见性
const formVisible = ref(false)
const detailVisible = ref(false)

// 获取数据中心下拉选项
const loadDatacenterOptions = async (keyword?: string) => {
  try {
    const res: any = await fetchDatacenterList({ keyword })
    if (res.code === 0) {
      const list = res.details || []
      datacenterSelectOptions.value = Array.isArray(list)
        ? list.map((d: any) => ({
          label: d.name || d.code || String(d.id),
          value: d.id,
        }))
        : []
    }
  } catch (error) {
    console.error('获取数据中心列表失败:', error)
    Message.error('获取数据中心列表失败')
    datacenterSelectOptions.value = []
  }
}

const handleDatacenterSearch = (keyword: string) => {
  if (datacenterSearchTimer) {
    window.clearTimeout(datacenterSearchTimer)
  }
  datacenterSearchTimer = window.setTimeout(() => {
    loadDatacenterOptions(keyword?.trim() || undefined)
  }, 300)
}

// 获取楼层列表
const fetchFloors = async () => {
  loading.value = true
  
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      datacenter_id: formModel.value.datacenter_id ?? undefined,
      status: formModel.value.status || undefined,
    }

    const res = await fetchFloorList(params)
    
    tableData.value = res.details?.data || []
    pagination.total = res.details?.total || 0
  } catch (error) {
    console.error('获取楼层列表失败:', error)
    Message.error('获取楼层列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchFloors()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    status: '',
    datacenter_id: undefined,
  }
  pagination.current = 1
  fetchFloors()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchFloors()
}

// 刷新
const handleRefresh = () => {
  fetchFloors()
  Message.success('数据已刷新')
}

// 新建楼层
const handleCreate = () => {
  editingFloor.value = null
  formVisible.value = true
}

// 编辑楼层
const handleEdit = (record: any) => {
  console.log('编辑楼层:', record)
  editingFloor.value = record
  formVisible.value = true
}

// 详情
const handleDetail = (record: any) => {
  console.log('查看详情:', record)
  currentFloorId.value = record.id
  detailVisible.value = true
}

// 删除楼层
const handleDelete = async (record: any) => {
  console.log('删除楼层:', record)
  try {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除楼层 ${record.name} 吗？`,
      onOk: async () => {
        const res = await deleteFloor(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchFloors()
        } else {
          Message.error(res.message || '删除失败')
        }
      },
    })
  } catch (error) {
    console.error('删除楼层失败:', error)
  }
}

// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  fetchFloors()
}

// 初始化加载数据
onMounted(() => {
  loadDatacenterOptions()
  fetchFloors()
})
</script>

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

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>
