<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑数据中心' : '新建数据中心'"
    width="800px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :confirm-loading="submitting"
  >
    <a-form :model="form" layout="vertical" ref="formRef">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="数据中心名称" field="name" :rules="[{ required: true, message: '请输入数据中心名称' }]">
            <a-input v-model="form.name" placeholder="请输入数据中心名称" :max-length="200" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="数据中心编码" field="code" :rules="[{ required: true, message: '请输入数据中心编码' }]">
            <a-input v-model="form.code" placeholder="请输入数据中心编码" :max-length="100" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="简称" field="short_name">
            <a-input v-model="form.short_name" placeholder="请输入简称" :max-length="50" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <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-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="联系人" field="contact_person">
            <a-input v-model="form.contact_person" placeholder="请输入联系人" :max-length="50" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系电话" field="contact_phone">
            <a-input v-model="form.contact_phone" placeholder="请输入联系电话" :max-length="20" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="联系邮箱" field="contact_email">
        <a-input v-model="form.contact_email" placeholder="请输入联系邮箱" :max-length="100" />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="所属省份" field="province_id" :rules="[{ required: true, message: '请选择所属省份' }]">
            <a-select
              v-model="form.province_id"
              placeholder="请选择省份"
              allow-search
              :filter-option="false"
              :loading="provinceLoading"
              @change="handleProvinceChange"
              @search="handleProvinceSearch"
            >
              <a-option v-for="item in provinceOptions" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属城市" field="city_id" :rules="[{ required: true, message: '请选择所属城市' }]">
            <a-select
              v-model="form.city_id"
              placeholder="请选择城市"
              :disabled="!form.province_id"
              allow-search
              :filter-option="false"
              :loading="cityLoading"
              @search="handleCitySearch"
            >
              <a-option v-for="item in cityOptions" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="详细地址" field="address">
        <a-input v-model="form.address" placeholder="请输入详细地址" :max-length="200" />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="总面积（平方米）" field="total_area">
            <a-input-number v-model="form.total_area" placeholder="请输入总面积" :min="0" :precision="2" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="IT区域面积（平方米）" field="it_area">
            <a-input-number v-model="form.it_area" placeholder="请输入IT区域面积" :min="0" :precision="2" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="总电力（KW）" field="total_power">
            <a-input-number v-model="form.total_power" placeholder="请输入总电力" :min="0" :precision="2" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="可容纳机柜数" field="max_rack_capacity">
        <a-input-number v-model="form.max_rack_capacity" placeholder="请输入可容纳机柜数" :min="0" :precision="0" style="width: 100%" />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="是否通过ISO27001认证" field="iso27001">
            <a-switch v-model="form.iso27001" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="是否通过ISO9001认证" field="iso9001">
            <a-switch v-model="form.iso9001" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="是否启用" field="enabled">
            <a-switch v-model="form.enabled" />
          </a-form-item>
        </a-col>
      </a-row>

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

      <a-form-item label="备注" field="remarks">
        <a-textarea v-model="form.remarks" placeholder="请输入备注" :auto-size="{ minRows: 3, maxRows: 6 }" :max-length="500" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { createDatacenter, updateDatacenter, fetchProvinceList, fetchCityList } from '@/api/ops/datacenter'

interface Datacenter {
  id?: number
  name?: string
  code?: string
  short_name?: string
  contact_person?: string
  contact_phone?: string
  contact_email?: string
  status?: string
  province_id?: number
  city_id?: number
  address?: string
  total_area?: number
  it_area?: number
  total_power?: number
  max_rack_capacity?: number
  iso27001?: boolean
  iso9001?: boolean
  enabled?: boolean
  description?: string
  remarks?: string
}

interface Props {
  visible: boolean
  datacenter: Datacenter | null
  provinces?: any[]
}

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

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

const formRef = ref()
const submitting = ref(false)

// 表单数据
const form = ref({
  name: '',
  code: '',
  short_name: '',
  contact_person: '',
  contact_phone: '',
  contact_email: '',
  status: 'planning',
  province_id: undefined as number | undefined,
  city_id: undefined as number | undefined,
  address: '',
  total_area: undefined as number | undefined,
  it_area: undefined as number | undefined,
  total_power: undefined as number | undefined,
  max_rack_capacity: undefined as number | undefined,
  iso27001: false,
  iso9001: false,
  enabled: true,
  description: '',
  remarks: '',
})

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

const provinceOptions = ref<any[]>([])
const cityOptions = ref<any[]>([])
const provinceLoading = ref(false)
const cityLoading = ref(false)
const provinceKeyword = ref('')
const cityKeyword = ref('')
let provinceSearchTimer: ReturnType<typeof setTimeout> | null = null
let citySearchTimer: ReturnType<typeof setTimeout> | null = null

// 省份变化时清空城市选择
const handleProvinceChange = (value?: number) => {
  form.value.city_id = undefined
  cityOptions.value = []
  cityKeyword.value = ''
  if (value) {
    fetchCitiesByProvince(value)
  }
}

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

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

const handleProvinceSearch = (keyword: string) => {
  provinceKeyword.value = keyword
  if (provinceSearchTimer) {
    clearTimeout(provinceSearchTimer)
  }
  provinceSearchTimer = setTimeout(() => {
    if (!keyword.trim()) return
    fetchProvinces(keyword.trim())
  }, 300)
}

const handleCitySearch = (keyword: string) => {
  cityKeyword.value = keyword
  if (!form.value.province_id) return
  if (citySearchTimer) {
    clearTimeout(citySearchTimer)
  }
  citySearchTimer = setTimeout(() => {
    if (!keyword.trim()) return
    fetchCitiesByProvince(form.value.province_id as number, keyword.trim())
  }, 300)
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      provinceOptions.value = props.provinces || []
      provinceKeyword.value = ''
      cityKeyword.value = ''
      if (props.datacenter && isEdit.value) {
        // 编辑模式：填充表单
        form.value = {
          name: props.datacenter.name || '',
          code: props.datacenter.code || '',
          short_name: props.datacenter.short_name || '',
          contact_person: props.datacenter.contact_person || '',
          contact_phone: props.datacenter.contact_phone || '',
          contact_email: props.datacenter.contact_email || '',
          status: props.datacenter.status || 'planning',
          province_id: props.datacenter.province_id,
          city_id: props.datacenter.city_id,
          address: props.datacenter.address || '',
          total_area: props.datacenter.total_area,
          it_area: props.datacenter.it_area,
          total_power: props.datacenter.total_power,
          max_rack_capacity: props.datacenter.max_rack_capacity,
          iso27001: props.datacenter.iso27001 !== undefined ? props.datacenter.iso27001 : false,
          iso9001: props.datacenter.iso9001 !== undefined ? props.datacenter.iso9001 : false,
          enabled: props.datacenter.enabled !== undefined ? props.datacenter.enabled : true,
          description: props.datacenter.description || '',
          remarks: props.datacenter.remarks || '',
        }
        fetchProvinces()
        if (form.value.province_id) {
          fetchCitiesByProvince(form.value.province_id)
        }
      } else {
        // 新建模式：重置表单
        form.value = {
          name: '',
          code: '',
          short_name: '',
          contact_person: '',
          contact_phone: '',
          contact_email: '',
          status: 'planning',
          province_id: undefined,
          city_id: undefined,
          address: '',
          total_area: undefined,
          it_area: undefined,
          total_power: undefined,
          max_rack_capacity: undefined,
          iso27001: false,
          iso9001: false,
          enabled: true,
          description: '',
          remarks: '',
        }
        fetchProvinces()
        cityOptions.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,
      short_name: form.value.short_name,
      contact_person: form.value.contact_person,
      contact_phone: form.value.contact_phone,
      contact_email: form.value.contact_email,
      status: form.value.status,
      province_id: form.value.province_id,
      city_id: form.value.city_id,
      address: form.value.address,
      total_area: form.value.total_area,
      it_area: form.value.it_area,
      total_power: form.value.total_power,
      max_rack_capacity: form.value.max_rack_capacity,
      iso27001: form.value.iso27001,
      iso9001: form.value.iso9001,
      enabled: form.value.enabled,
      description: form.value.description,
      remarks: form.value.remarks,
    }

    let res
    if (isEdit.value && props.datacenter?.id) {
      // 编辑数据中心
      data.id = props.datacenter.id
      res = await updateDatacenter(data)
    } else {
      // 新建数据中心
      res = await createDatacenter(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)
}
</script>

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