<template>
  <div class="connection-config-simple">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-main">
          <h1 class="page-title">连接配置</h1>
          <p class="page-desc">配置系统连接参数，逐项编辑保存</p>
        </div>
      </div>
      
      <!-- 搜索框 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索配置参数..."
          clearable
          prefix-icon="el-icon-search"
          class="search-input"
        />
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="page-content">
      <div class="config-cards" :class="{ 'two-columns': isLargeScreen }">
        <!-- IP配置卡片 -->
        <div class="config-card" v-show="hasVisibleItems('ip')">
          <div class="card-header">
            <h2 class="card-title">IP 配置</h2>
            <p class="card-desc">网络地址和服务连接配置</p>
          </div>
          <div class="card-content">
            <XtParamItem
              v-for="item in ipConfigItems"
              :key="item.key"
              v-show="isItemVisible(item)"
              :label="item.label"
              :value="config[item.key]"
              :type="item.type"
              :placeholder="item.placeholder"
              :search-keyword="searchKeyword"
              @save="(value) => handleParamSave(item.key, value)"
              @cancel="handleParamCancel"
            />
            <div v-if="!hasVisibleItems('ip')" class="empty-state">
              <i class="el-icon-search"></i>
              <p>无匹配的配置参数</p>
            </div>
          </div>
        </div>

        <!-- 硬件接口卡片 -->
        <div class="config-card" v-show="hasVisibleItems('hardware')">
          <div class="card-header">
            <h2 class="card-title">硬件接口</h2>
            <p class="card-desc">硬件设备和数据过滤配置</p>
          </div>
          <div class="card-content">
            <XtParamItem
              v-for="item in hardwareConfigItems"
              :key="item.key"
              v-show="isItemVisible(item)"
              :label="item.label"
              :value="config[item.key]"
              :type="item.type"
              :placeholder="item.placeholder"
              :search-keyword="searchKeyword"
              @save="(value) => handleParamSave(item.key, value)"
              @cancel="handleParamCancel"
            />
            <div v-if="!hasVisibleItems('hardware')" class="empty-state">
              <i class="el-icon-search"></i>
              <p>无匹配的配置参数</p>
            </div>
          </div>
        </div>

        <!-- 网络代理卡片 -->
        <div class="config-card" v-show="hasVisibleItems('proxy')">
          <div class="card-header">
            <h2 class="card-title">网络代理</h2>
            <p class="card-desc">代理服务和端口映射配置</p>
          </div>
          <div class="card-content">
            <XtParamItem
              v-for="item in proxyConfigItems"
              :key="item.key"
              v-show="isItemVisible(item)"
              :label="item.label"
              :value="config[item.key]"
              :type="item.type"
              :placeholder="item.placeholder"
              :search-keyword="searchKeyword"
              :disabled="item.key === 'netProxyAddr' && !config.netProxyEnabled"
              @save="(value) => handleParamSave(item.key, value)"
              @cancel="handleParamCancel"
            />
            <div v-if="!hasVisibleItems('proxy')" class="empty-state">
              <i class="el-icon-search"></i>
              <p>无匹配的配置参数</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 导入参数组件
import XtParamItem from '@/components/XtParamItem'

// 尝试导入真实 API，失败则使用 Mock
let api
try {
  // 尝试导入真实 API（如果存在）
  api = require('@/api/connection')
} catch (error) {
  // Fallback 到 Mock API
  api = require('@/api/mock/connectionSimple')
}

export default {
  name: 'ConnectionConfigSimple',
  
  components: {
    XtParamItem
  },

  data() {
    return {
      // 配置数据
      config: {
        // IP配置
        serverIp: '',
        mqttBrokerWeb: '',
        mqttBrokerNav: '',
        mqttProductId: '',
        httpBase: '',
        
        // 硬件接口
        lidarNic: '',
        packetFilterEnabled: false,
        packetFilterRule: '',
        
        // 网络代理
        netProxyEnabled: false,
        netProxyAddr: '',
        map8086: '',
        map8088: ''
      },

      // 搜索关键字
      searchKeyword: '',

      // 加载状态
      loading: false,

      // 响应式状态
      windowWidth: window.innerWidth
    }
  },

  computed: {
    // 是否为大屏
    isLargeScreen() {
      return this.windowWidth >= 1440
    },

    // IP配置项
    ipConfigItems() {
      return [
        {
          key: 'serverIp',
          label: '服务器IP',
          type: 'ip',
          placeholder: '请输入服务器IP地址',
          group: 'ip'
        },
        {
          key: 'mqttBrokerWeb',
          label: 'MQTT代理地址（网页）',
          type: 'url',
          placeholder: 'ws://broker.hivemq.com:8000',
          group: 'ip'
        },
        {
          key: 'mqttBrokerNav',
          label: 'MQTT代理地址（导航）',
          type: 'url',
          placeholder: 'mqtt://broker.hivemq.com:1883',
          group: 'ip'
        },
        {
          key: 'mqttProductId',
          label: 'MQTT产品ID',
          type: 'text',
          placeholder: '请输入产品ID',
          group: 'ip'
        },
        {
          key: 'httpBase',
          label: 'HTTP服务地址',
          type: 'url',
          placeholder: 'https://api.smartdriving.com',
          group: 'ip'
        }
      ]
    },

    // 硬件接口配置项
    hardwareConfigItems() {
      return [
        {
          key: 'lidarNic',
          label: '激光网卡',
          type: 'text',
          placeholder: 'enp0s31f6',
          group: 'hardware'
        },
        {
          key: 'packetFilterEnabled',
          label: '网络包过滤使能',
          type: 'switch',
          placeholder: '',
          group: 'hardware'
        },
        {
          key: 'packetFilterRule',
          label: '网络包过滤规则',
          type: 'textarea',
          placeholder: '请输入过滤规则，每行一条',
          group: 'hardware'
        }
      ]
    },

    // 网络代理配置项
    proxyConfigItems() {
      return [
        {
          key: 'netProxyEnabled',
          label: '开启网络代理',
          type: 'switch',
          placeholder: '',
          group: 'proxy'
        },
        {
          key: 'netProxyAddr',
          label: '代理服务地址',
          type: 'text',
          placeholder: 'proxy.company.com:8080',
          group: 'proxy'
        },
        {
          key: 'map8086',
          label: '8086映射参数',
          type: 'text',
          placeholder: 'localhost:8086',
          group: 'proxy'
        },
        {
          key: 'map8088',
          label: '8088映射参数',
          type: 'text',
          placeholder: 'localhost:8088',
          group: 'proxy'
        }
      ]
    },

    // 所有配置项
    allConfigItems() {
      return [
        ...this.ipConfigItems,
        ...this.hardwareConfigItems,
        ...this.proxyConfigItems
      ]
    }
  },

  async mounted() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
    
    // 加载配置数据
    await this.loadConfig()
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },

  methods: {
    // 处理窗口大小变化
    handleResize() {
      this.windowWidth = window.innerWidth
    },

    // 加载配置
    async loadConfig() {
      this.loading = true
      try {
        const response = await api.getConfig()
        if (response.code === 200) {
          this.config = { ...this.config, ...response.data }
        }
      } catch (error) {
        this.$message.error('加载配置失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },

    // 保存单个参数
    async handleParamSave(key, value) {
      try {
        const response = await api.updateParam({ key, value })
        if (response.code === 200) {
          this.config[key] = value
          this.$message.success('参数保存成功')
        } else {
          throw new Error(response.message || '保存失败')
        }
      } catch (error) {
        this.$message.error('保存失败: ' + error.message)
        throw error // 重新抛出错误，让组件显示错误状态
      }
    },

    // 取消参数编辑
    handleParamCancel() {
      // 可以在这里添加取消编辑的逻辑
      console.log('参数编辑已取消')
    },

    // 检查项目是否可见（搜索过滤）
    isItemVisible(item) {
      if (!this.searchKeyword.trim()) {
        return true
      }
      const keyword = this.searchKeyword.toLowerCase().trim()
      return item.label.toLowerCase().includes(keyword)
    },

    // 检查分组是否有可见项目
    hasVisibleItems(groupType) {
      let items = []
      switch (groupType) {
        case 'ip':
          items = this.ipConfigItems
          break
        case 'hardware':
          items = this.hardwareConfigItems
          break
        case 'proxy':
          items = this.proxyConfigItems
          break
        default:
          return false
      }
      
      return items.some(item => this.isItemVisible(item))
    },

    // 刷新配置
    async handleRefresh() {
      await this.loadConfig()
      this.$message.success('配置已刷新')
    }
  }
}
</script>

<style lang="scss" scoped>
.connection-config-simple {
  min-height: 100vh;
  background: var(--color-bg-secondary);
  padding-bottom: var(--spacing-6);

  .page-header {
    background: var(--color-bg-card);
    border-bottom: 1px solid var(--color-border-primary);
    padding: var(--spacing-6);
    margin-bottom: var(--spacing-6);
    box-shadow: 0 6px 18px rgba(2, 6, 23, 0.05);

    .header-content {
      max-width: 1200px;
      margin: 0 auto;

      .header-main {
        .page-title {
          color: var(--color-text-primary);
          font-size: var(--font-size-3xl);
          font-weight: var(--font-weight-bold);
          margin: 0 0 var(--spacing-2) 0;
          line-height: var(--line-height-tight);
        }

        .page-desc {
          color: var(--color-text-secondary);
          font-size: var(--font-size-base);
          margin: 0 0 var(--spacing-4) 0;
          line-height: var(--line-height-relaxed);
        }
      }
    }

    .search-section {
      max-width: 1200px;
      margin: 0 auto;

      .search-input {
        max-width: 400px;

        ::v-deep .el-input__inner {
          border-radius: var(--radius-lg);
          border: 1px solid var(--color-border-primary);
          background: var(--color-bg-card);
          transition: all var(--duration-200) var(--ease-out);

          &:focus {
            border-color: var(--color-primary);
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.15);
          }
        }

        ::v-deep .el-input__prefix {
          color: var(--color-text-tertiary);
        }
      }
    }
  }

  .page-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 var(--spacing-6);

    .config-cards {
      display: grid;
      gap: var(--spacing-6);
      grid-template-columns: 1fr;

      &.two-columns {
        grid-template-columns: repeat(2, 1fr);
      }

      .config-card {
        background: var(--color-bg-card);
        border-radius: 12px;
        box-shadow: 0 6px 18px rgba(2, 6, 23, 0.05);
        overflow: hidden;
        transition: all var(--duration-200) var(--ease-out);
        animation: slideInUp 0.3s ease-out;

        &:hover {
          box-shadow: 0 8px 24px rgba(2, 6, 23, 0.08);
        }

        .card-header {
          padding: 20px 20px 16px 20px;
          border-bottom: 1px solid var(--color-border-secondary);

          .card-title {
            color: var(--color-text-primary);
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            margin: 0 0 var(--spacing-1) 0;
            line-height: var(--line-height-tight);
          }

          .card-desc {
            color: var(--color-text-secondary);
            font-size: var(--font-size-sm);
            margin: 0;
            line-height: var(--line-height-normal);
          }
        }

        .card-content {
          padding: 16px 20px 20px 20px;
          min-height: 200px;

          .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 120px;
            color: var(--color-text-quaternary);
            background: rgba(0, 0, 0, 0.02);
            border-radius: var(--radius-base);
            border: 1px dashed var(--color-border-secondary);

            i {
              font-size: var(--font-size-2xl);
              margin-bottom: var(--spacing-2);
              opacity: 0.5;
            }

            p {
              margin: 0;
              font-size: var(--font-size-sm);
              opacity: 0.8;
            }
          }
        }
      }
    }
  }
}

// 暗色主题适配
html.dark {
  .connection-config-simple {
    .page-header {
      background: var(--color-bg-tertiary);
      box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);

      .search-section {
        .search-input {
          ::v-deep .el-input__inner {
            background: var(--color-bg-quaternary);
            border-color: var(--color-border-tertiary);
            color: var(--color-text-primary);
          }
        }
      }
    }

    .config-cards {
      .config-card {
        background: var(--color-bg-tertiary);
        box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);

        &:hover {
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
        }

        .card-header {
          border-bottom-color: var(--color-border-tertiary);
        }

        .card-content {
          .empty-state {
            background: rgba(255, 255, 255, 0.03);
            border-color: var(--color-border-tertiary);
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1439px) {
  .connection-config-simple {
    .page-content {
      .config-cards {
        &.two-columns {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .connection-config-simple {
    .page-header {
      padding: var(--spacing-4);
      margin-bottom: var(--spacing-4);

      .header-content {
        .header-main {
          .page-title {
            font-size: var(--font-size-2xl);
          }

          .page-desc {
            font-size: var(--font-size-sm);
          }
        }
      }

      .search-section {
        .search-input {
          max-width: 100%;
        }
      }
    }

    .page-content {
      padding: 0 var(--spacing-4);

      .config-cards {
        gap: var(--spacing-4);

        .config-card {
          .card-header {
            padding: 16px;
          }

          .card-content {
            padding: 12px 16px 16px 16px;
            min-height: 150px;

            .empty-state {
              height: 100px;
            }
          }
        }
      }
    }
  }
}

// 动画效果
@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
