<template>
  <div class="network-config">
    <a-card title="系统网络配置">
      <!-- 网络配置表单 -->
      <a-form
        :model="networkConfig"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        @submit.prevent="handleSubmit"
      >
        <!-- IP获取方式选择 -->
        <a-form-item label="IP获取方式">
          <a-radio-group v-model:value="networkConfig.ipMethod" @change="onIpMethodChange">
            <a-radio value="dhcp">DHCP自动获取</a-radio>
            <a-radio value="static">静态IP配置</a-radio>
          </a-radio-group>
        </a-form-item>

        <!-- 自动获取的IP信息 (DHCP模式下显示) -->
        <template v-if="networkConfig.ipMethod === 'dhcp'">
          <a-form-item label="获取的IP地址">
            <a-input v-model:value="networkConfig.dhcpIp" disabled placeholder="自动获取的IP地址" />
          </a-form-item>
          <a-form-item label="获取的子网掩码">
            <a-input v-model:value="networkConfig.dhcpSubnetMask" disabled placeholder="自动获取的子网掩码" />
          </a-form-item>
          <a-form-item label="获取的网关">
            <a-input v-model:value="networkConfig.dhcpGateway" disabled placeholder="自动获取的网关" />
          </a-form-item>
        </template>

        <!-- 静态IP配置 (静态IP模式下显示) -->
        <template v-if="networkConfig.ipMethod === 'static'">
          <a-form-item label="IP地址" name="staticIp" :rules="[{ required: true, message: '请输入IP地址' }]">
            <a-input v-model:value="networkConfig.staticIp" placeholder="请输入IP地址" />
          </a-form-item>
          <a-form-item label="子网掩码" name="staticSubnetMask" :rules="[{ required: true, message: '请输入子网掩码' }]">
            <a-input v-model:value="networkConfig.staticSubnetMask" placeholder="请输入子网掩码" />
          </a-form-item>
          <a-form-item label="默认网关" name="staticGateway" :rules="[{ required: true, message: '请输入默认网关' }]">
            <a-input v-model:value="networkConfig.staticGateway" placeholder="请输入默认网关" />
          </a-form-item>
        </template>

        <!-- DNS配置 (两种模式都可配置) -->
        <a-form-item label="首选DNS服务器">
          <a-input v-model:value="networkConfig.primaryDns" placeholder="请输入首选DNS服务器" />
        </a-form-item>
        <a-form-item label="备用DNS服务器">
          <a-input v-model:value="networkConfig.secondaryDns" placeholder="请输入备用DNS服务器" />
        </a-form-item>

        <!-- 操作按钮 -->
        <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
          <a-button type="primary" html-type="submit" :loading="submitting">
            保存配置
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            重置
          </a-button>
          <a-button style="margin-left: 8px" type="default" @click="refreshConfig">
            刷新配置
          </a-button>
        </a-form-item>
      </a-form>

      <!-- 网络状态信息 -->
      <a-divider>网络状态</a-divider>
      <a-descriptions column="1" bordered>
        <a-descriptions-item label="网络接口状态">
          <a-tag :color="networkStatus.connected ? 'green' : 'red'">
            {{ networkStatus.connected ? '已连接' : '未连接' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="MAC地址">{{ networkStatus.macAddress || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="网络接口">{{ networkStatus.interfaceName || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="连接速度">{{ networkStatus.speed || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="配置应用状态">
          <a-tag :color="configStatus === 'applied' ? 'green' : configStatus === 'pending' ? 'orange' : 'default'">
            {{ configStatusText }}
          </a-tag>
        </a-descriptions-item>
      </a-descriptions>

      <!-- 重启提示 -->
      <a-alert
        v-if="configStatus === 'pending'"
        message="配置已保存，需要重启网络服务才能生效"
        type="warning"
        show-icon
        action
      >
        <template #action>
          <a-button type="primary" size="small" @click="restartNetwork">
            立即重启
          </a-button>
        </template>
      </a-alert>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { getNetworkConfig, updateNetworkConfig, restartNetworkService, getNetworkStatus } from '../api/network'

// 网络配置数据
const networkConfig = reactive({
  ipMethod: 'dhcp', // 'dhcp' 或 'static'
  // DHCP模式下获取的信息
  dhcpIp: '',
  dhcpSubnetMask: '',
  dhcpGateway: '',
  // 静态IP配置
  staticIp: '',
  staticSubnetMask: '',
  staticGateway: '',
  // DNS配置
  primaryDns: '',
  secondaryDns: ''
})

// 网络状态信息
const networkStatus = reactive({
  connected: false,
  macAddress: '',
  interfaceName: '',
  speed: ''
})

// 配置状态
const configStatus = ref('applied') // 'applied', 'pending', 'error'
const submitting = ref(false)

// 配置状态文本
const configStatusText = computed(() => {
  switch (configStatus.value) {
    case 'applied':
      return '已应用'
    case 'pending':
      return '待应用'
    case 'error':
      return '应用失败'
    default:
      return '未知'
  }
})

// IP获取方式改变处理
const onIpMethodChange = () => {
  // 重置表单校验状态
  // 如果需要，可以在这里添加一些额外的处理逻辑
}

// 提交表单处理
const handleSubmit = async () => {
  submitting.value = true
  try {
    // 构建符合后端要求的数据结构
    const configData = {
      config_mode: networkConfig.ipMethod,
      interface: 'eth0', // 默认接口
      static_config: {
        ip_address: networkConfig.staticIp,
        subnet_mask: networkConfig.staticSubnetMask,
        gateway: networkConfig.staticGateway,
        dns_servers: [
          networkConfig.primaryDns || '8.8.8.8',
          networkConfig.secondaryDns || '8.8.4.4'
        ].filter(Boolean)
      }
    }
    
    const response = await updateNetworkConfig(configData)
    if (response && response.success) {
      message.success('网络配置保存成功')
      configStatus.value = 'pending' // 标记为待应用状态
    } else {
      message.error('保存失败: ' + (response?.message || '未知错误'))
      configStatus.value = 'error'
    }
  } catch (error) {
    console.error('保存网络配置失败:', error)
    message.error('保存失败，请检查网络连接')
    configStatus.value = 'error'
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  // 重置为当前获取的配置
  fetchNetworkConfig()
  message.success('已重置为当前配置')
}

// 刷新配置
const refreshConfig = () => {
  fetchNetworkConfig()
  fetchNetworkStatus()
  message.success('配置已刷新')
}

// 重启网络服务
const restartNetwork = async () => {
  try {
    const response = await restartNetworkService()
    if (response.success) {
      message.success('网络服务正在重启，请等待...')
      // 重启后检查状态
      setTimeout(() => {
        fetchNetworkConfig()
        fetchNetworkStatus()
        configStatus.value = 'applied'
      }, 5001)
    } else {
      message.error('重启失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('重启网络服务失败:', error)
    message.error('重启失败，请检查系统权限')
  }
}

// 获取网络配置
const fetchNetworkConfig = async () => {
  try {
    const response = await getNetworkConfig()
    if (response && response.success) {
      // 根据后端返回的数据结构更新配置
      // 配置模式
      networkConfig.ipMethod = response.config_mode || 'dhcp'
      
      // 静态配置信息
      if (response.static_config) {
        networkConfig.staticIp = response.static_config.ip_address || ''
        networkConfig.staticSubnetMask = response.static_config.subnet_mask || ''
        networkConfig.staticGateway = response.static_config.gateway || ''
        
        // DNS配置
        if (response.static_config.dns_servers && Array.isArray(response.static_config.dns_servers)) {
          networkConfig.primaryDns = response.static_config.dns_servers[0] || ''
          networkConfig.secondaryDns = response.static_config.dns_servers[1] || ''
        }
      }
      
      // 如果是DHCP模式，尝试从静态配置中获取当前IP信息（开发环境）
      if (networkConfig.ipMethod === 'dhcp' && response.static_config) {
        networkConfig.dhcpIp = response.static_config.ip_address || ''
        networkConfig.dhcpSubnetMask = response.static_config.subnet_mask || ''
        networkConfig.dhcpGateway = response.static_config.gateway || ''
      }
    } else {
      message.error('获取配置失败: ' + (response?.message || '未知错误'))
      // 即使失败也设置一些默认值，避免界面空白
      setDefaultConfig()
    }
  } catch (error) {
    console.error('获取网络配置失败:', error)
    message.error('获取配置时发生错误')
    // 设置默认值
    setDefaultConfig()
  }
}

// 获取网络状态
const fetchNetworkStatus = async () => {
  try {
    const response = await getNetworkStatus()
    if (response && response.success) {
      const ifs = response.interfaces || {}
      const activeIface = Object.entries(ifs).find(([name, v]) =>
        v.status === 'UP'
        && !name.startsWith('docker') && !name.startsWith('br-') && !name.startsWith('veth') && name !== 'lo'
        && v.ip_addresses?.some(ip => !ip.startsWith('127.'))
      )
      const iface = activeIface ? activeIface[1] : {}
      const ifaceName = activeIface ? activeIface[0] : '未知'
      networkStatus.connected = !!activeIface
      networkStatus.macAddress = iface.mac_address || iface.macAddress || '未知'
      networkStatus.interfaceName = ifaceName
      networkStatus.speed = '100Mbps'
    } else {
      message.error('获取网络状态失败: ' + (response?.message || '未知错误'))
      setDefaultStatus()
    }
  } catch (error) {
    console.error('获取网络状态失败:', error)
    message.error('获取网络状态时发生错误')
    setDefaultStatus()
  }
}

// 设置默认配置
const setDefaultConfig = () => {
  networkConfig.ipMethod = 'dhcp'
  networkConfig.dhcpIp = '192.168.1.100'
  networkConfig.dhcpSubnetMask = '255.255.255.0'
  networkConfig.dhcpGateway = '192.168.1.1'
  networkConfig.staticIp = '192.168.1.100'
  networkConfig.staticSubnetMask = '255.255.255.0'
  networkConfig.staticGateway = '192.168.1.1'
  networkConfig.primaryDns = '8.8.8.8'
  networkConfig.secondaryDns = '8.8.4.4'
}

// 设置默认状态
const setDefaultStatus = () => {
  networkStatus.connected = true
  networkStatus.macAddress = '00:11:22:33:44:55'
  networkStatus.interfaceName = 'eth0'
  networkStatus.speed = '100Mbps'
}

// 组件挂载时获取配置和状态
onMounted(() => {
  fetchNetworkConfig()
  fetchNetworkStatus()
})
</script>

<style scoped>
.network-config {
  width: 100%;
  padding: 20px;
}

/* 确保表单元素间距合适 */
.ant-form-item {
  margin-bottom: 20px;
}

/* 确保描述信息显示清晰 */
.ant-descriptions-item-label {
  font-weight: 600;
}

/* 确保警告提示显示合理 */
.ant-alert {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .network-config {
    padding: 10px;
  }
  
  .ant-form-horizontal .ant-form-item-label {
    text-align: left;
  }
}
</style>