<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 #form-items>
        <a-col :span="8">
          <a-form-item field="province_id" label="所属省份">
            <a-select
              v-model="formModel.province_id"
              placeholder="请选择省份"
              allow-search
              allow-clear
              :filter-option="false"
              :loading="provinceSelectLoading"
              @change="handleFilterProvinceChange"
              @search="handleFilterProvinceSearch"
            >
              <a-option
                v-for="item in provinceSelectOptions"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="city_id" label="所属城市">
            <a-select
              v-model="formModel.city_id"
              placeholder="请选择城市"
              :disabled="!formModel.province_id"
              allow-search
              allow-clear
              :filter-option="false"
              :loading="citySelectLoading"
              @search="handleFilterCitySearch"
            >
              <a-option
                v-for="item in citySelectOptions"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </template>
      <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 #province="{ record }">
        {{ record.province?.name || '-' }}
      </template>
      
      <!-- 所属城市 -->
      <template #city="{ record }">
        {{ record.city?.name || '-' }}
      </template>
      
      <!-- 状态 -->
      <template #status="{ record }">
        <a-tag :color="statusMap[record.status]?.color || 'gray'">
          {{ statusMap[record.status]?.text || record.status }}
        </a-tag>
      </template>
      
      <!-- 是否启用 -->
      <template #enabled="{ record }">
        <a-tag :color="record.enabled ? 'green' : 'red'">
          {{ record.enabled ? '是' : '否' }}
        </a-tag>
      </template>
      
      <!-- ISO27001 -->
      <template #iso27001="{ record }">
        <a-tag :color="record.iso27001 ? 'green' : 'gray'">
          {{ record.iso27001 ? '是' : '否' }}
        </a-tag>
      </template>
      
      <!-- ISO9001 -->
      <template #iso9001="{ record }">
        <a-tag :color="record.iso9001 ? 'green' : 'gray'">
          {{ record.iso9001 ? '是' : '否' }}
        </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>
    
    <!-- 数据中心表单对话框（新建/编辑） -->
    <datacenter-form-dialog
      v-model:visible="formVisible"
      :datacenter="editingDatacenter"
      :provinces="provinces"
      @success="handleFormSuccess"
    />
    
    <!-- 数据中心详情对话框 -->
    <datacenter-detail-dialog
      v-model:visible="detailVisible"
      :datacenter-id="currentDatacenterId"
    />
  </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 {
  fetchDatacenterList,
  deleteDatacenter,
  fetchProvinceList,
  fetchCityList,
} from '@/api/ops/datacenter'
import DatacenterDetailDialog from './components/DatacenterDetailDialog.vue'
import DatacenterFormDialog from './components/DatacenterFormDialog.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: '',
  province_id: '',
  city_id: '',
})

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

// 省份和城市列表
const provinces = ref<any[]>([])
const provinceSelectOptions = ref<any[]>([])
const citySelectOptions = ref<any[]>([])
const provinceSelectLoading = ref(false)
const citySelectLoading = ref(false)
let filterProvinceSearchTimer: ReturnType<typeof setTimeout> | null = null
let filterCitySearchTimer: ReturnType<typeof setTimeout> | null = null

// 表单项配置
const formItems = computed<FormItem[]>(() => searchFormConfig)

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

// 当前选中的数据中心
const currentDatacenterId = ref<number | undefined>(undefined)
const editingDatacenter = ref<any>(null)

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

// 获取省份列表
const fetchProvinces = async (keyword = '') => {
  provinceSelectLoading.value = true
  try {
    const res = await fetchProvinceList({ keyword: keyword || undefined })
    const list = res.details || []
    provinceSelectOptions.value = list
    if (!keyword) {
      provinces.value = list
    }
  } catch (error) {
    console.error('获取省份列表失败:', error)
    provinceSelectOptions.value = []
  } finally {
    provinceSelectLoading.value = false
  }
}

// 根据省份获取城市列表
const fetchCitiesByProvince = async (provinceId: number, keyword = '') => {
  citySelectLoading.value = true
  try {
    const res = await fetchCityList(provinceId, { keyword: keyword || undefined })
    citySelectOptions.value = res.details || []
  } catch (error) {
    console.error('获取城市列表失败:', error)
    citySelectOptions.value = []
  } finally {
    citySelectLoading.value = false
  }
}

const handleFilterProvinceChange = (provinceId?: number) => {
  formModel.value.city_id = ''
  citySelectOptions.value = []
  if (provinceId) {
    fetchCitiesByProvince(provinceId)
  }
}

const handleFilterProvinceSearch = (keyword: string) => {
  if (filterProvinceSearchTimer) {
    clearTimeout(filterProvinceSearchTimer)
  }
  filterProvinceSearchTimer = setTimeout(() => {
    if (!keyword.trim()) return
    fetchProvinces(keyword.trim())
  }, 300)
}

const handleFilterCitySearch = (keyword: string) => {
  if (!formModel.value.province_id) return
  if (filterCitySearchTimer) {
    clearTimeout(filterCitySearchTimer)
  }
  filterCitySearchTimer = setTimeout(() => {
    if (!keyword.trim()) return
    fetchCitiesByProvince(Number(formModel.value.province_id), keyword.trim())
  }, 300)
}

// 获取数据中心列表
const fetchDatacenters = async () => {
  loading.value = true
  
  try {
    const params: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: formModel.value.keyword || undefined,
      status: formModel.value.status || undefined,
      province_id: formModel.value.province_id || undefined,
      city_id: formModel.value.city_id || undefined,
    }

    const res = await fetchDatacenterList(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
  fetchDatacenters()
}

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

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    status: '',
    province_id: '',
    city_id: '',
  }
  citySelectOptions.value = []
  fetchProvinces()
  pagination.current = 1
  fetchDatacenters()
}

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

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

// 新建数据中心
const handleCreate = () => {
  editingDatacenter.value = null
  formVisible.value = true
}

// 编辑数据中心
const handleEdit = (record: any) => {
  console.log('编辑数据中心:', record)
  editingDatacenter.value = record
  formVisible.value = true
}

// 详情
const handleDetail = (record: any) => {
  console.log('查看详情:', record)
  currentDatacenterId.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 deleteDatacenter(record.id)
        if (res.code === 0) {
          Message.success('删除成功')
          fetchDatacenters()
        } else {
          Message.error(res.message || '删除失败')
        }
      },
    })
  } catch (error) {
    console.error('删除数据中心失败:', error)
  }
}

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

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

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

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