/**
 * 连接配置 Mock API
 * 模拟后端接口，用于开发阶段
 * @author 前端架构师
 */

// 模拟延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟配置数据
const mockConfig = {
  // 基础网络配置
  toolIp: '192.168.1.100',
  serverIp: '192.168.1.200',
  enableProxy: false,
  netProxy: 'http://proxy.company.com:8080',
  
  // MQTT 配置
  mqttBroker: 'mqtt://broker.hivemq.com:1883',
  mqttProductId: 'smart_driving_001',
  mqttDeviceId: 'vehicle_12345',
  mqttSecret: 'mqtt_secret_key_2024',
  
  // HTTP 配置
  httpBase: 'https://api.smartdriving.com',
  httpTimeout: 30000,
  
  // 代理与安全配置
  packetFilter: true,
  certFile: null
}

// 存储当前配置（模拟数据库）
let currentConfig = { ...mockConfig }
let draftConfig = { ...mockConfig }
let configHistory = [
  {
    version: 'v1.2.3',
    timestamp: Date.now() - 86400000, // 1天前
    config: { ...mockConfig }
  }
]

/**
 * 获取当前配置
 */
export async function getConfig() {
  await delay(300)
  
  return {
    code: 200,
    message: 'success',
    data: {
      current: { ...currentConfig },
      draft: { ...draftConfig },
      lastModified: Date.now() - 3600000, // 1小时前
      version: 'v1.2.4-draft'
    }
  }
}

/**
 * 保存草稿
 */
export async function saveDraft(config) {
  await delay(500)
  
  // 模拟保存失败（10%概率）
  if (Math.random() < 0.1) {
    return {
      code: 500,
      message: '保存失败：网络连接超时',
      data: null
    }
  }
  
  draftConfig = { ...config }
  
  return {
    code: 200,
    message: '草稿保存成功',
    data: {
      savedAt: Date.now(),
      version: 'v1.2.4-draft'
    }
  }
}

/**
 * 发布配置
 */
export async function publishConfig(selectedFields) {
  await delay(1000)
  
  // 模拟发布失败（5%概率）
  if (Math.random() < 0.05) {
    return {
      code: 500,
      message: '发布失败：配置验证不通过',
      data: null
    }
  }
  
  // 只更新选中的字段
  selectedFields.forEach(field => {
    if (draftConfig.hasOwnProperty(field)) {
      currentConfig[field] = draftConfig[field]
    }
  })
  
  // 添加到历史记录
  configHistory.unshift({
    version: `v1.2.${configHistory.length + 4}`,
    timestamp: Date.now(),
    config: { ...currentConfig },
    publishedFields: selectedFields
  })
  
  return {
    code: 200,
    message: `成功发布 ${selectedFields.length} 项配置`,
    data: {
      publishedAt: Date.now(),
      version: configHistory[0].version,
      affectedFields: selectedFields
    }
  }
}

/**
 * 回滚配置
 */
export async function rollbackConfig(targetVersion) {
  await delay(800)
  
  const targetHistory = configHistory.find(h => h.version === targetVersion)
  if (!targetHistory) {
    return {
      code: 404,
      message: '目标版本不存在',
      data: null
    }
  }
  
  // 模拟回滚失败（3%概率）
  if (Math.random() < 0.03) {
    return {
      code: 500,
      message: '回滚失败：系统正在维护中',
      data: null
    }
  }
  
  currentConfig = { ...targetHistory.config }
  draftConfig = { ...targetHistory.config }
  
  return {
    code: 200,
    message: `成功回滚到版本 ${targetVersion}`,
    data: {
      rolledBackAt: Date.now(),
      version: targetVersion
    }
  }
}

/**
 * 测试连接配置
 */
export async function testConnection(groupName, config) {
  const logs = []
  const startTime = Date.now()
  
  // 根据不同组生成不同的测试步骤
  const testSteps = getTestSteps(groupName)
  
  for (let i = 0; i < testSteps.length; i++) {
    const step = testSteps[i]
    const stepStartTime = Date.now()
    
    // 模拟异步测试
    const duration = Math.random() * 700 + 800 // 800ms - 1500ms
    await delay(duration)
    
    const cost = Date.now() - stepStartTime
    const status = getRandomStatus(i, testSteps.length)
    
    logs.push({
      ts: Date.now(),
      step: step.name,
      status: status,
      cost: cost,
      tip: step.getTip(status, config),
      details: step.getDetails ? step.getDetails(status, config) : null
    })
    
    // 如果某步失败，后续步骤标记为跳过
    if (status === 'fail' && i < testSteps.length - 1) {
      for (let j = i + 1; j < testSteps.length; j++) {
        logs.push({
          ts: Date.now(),
          step: testSteps[j].name,
          status: 'pending',
          cost: 0,
          tip: '由于前置步骤失败，跳过此步骤',
          details: null
        })
      }
      break
    }
  }
  
  const totalCost = Date.now() - startTime
  const hasFailure = logs.some(log => log.status === 'fail')
  
  return {
    code: 200,
    message: hasFailure ? '测试完成，发现问题' : '测试完成',
    data: {
      groupName,
      logs,
      totalCost,
      summary: {
        total: logs.length,
        passed: logs.filter(log => log.status === 'ok').length,
        warning: logs.filter(log => log.status === 'warn').length,
        failed: logs.filter(log => log.status === 'fail').length
      }
    }
  }
}

/**
 * 获取配置历史
 */
export async function getConfigHistory() {
  await delay(200)
  
  return {
    code: 200,
    message: 'success',
    data: configHistory
  }
}

/**
 * 获取配置差异
 */
export function getConfigDiffs(currentConfig, draftConfig) {
  const diffs = []
  const fieldNames = {
    toolIp: '工具机IP',
    serverIp: '服务器IP',
    enableProxy: '启用代理',
    netProxy: '网络代理',
    mqttBroker: 'MQTT代理',
    mqttProductId: 'MQTT产品ID',
    mqttDeviceId: 'MQTT设备ID',
    mqttSecret: 'MQTT密钥',
    httpBase: 'HTTP基础地址',
    httpTimeout: 'HTTP超时时间',
    packetFilter: '数据包过滤',
    certFile: '证书文件'
  }
  
  const fieldPaths = {
    toolIp: 'config.network.basic',
    serverIp: 'config.network.basic',
    enableProxy: 'config.network.basic',
    netProxy: 'config.network.basic',
    mqttBroker: 'config.mqtt',
    mqttProductId: 'config.mqtt',
    mqttDeviceId: 'config.mqtt',
    mqttSecret: 'config.mqtt',
    httpBase: 'config.http',
    httpTimeout: 'config.http',
    packetFilter: 'config.security',
    certFile: 'config.security'
  }
  
  Object.keys(fieldNames).forEach(key => {
    const oldValue = currentConfig[key]
    const newValue = draftConfig[key]
    const isChanged = JSON.stringify(oldValue) !== JSON.stringify(newValue)
    
    diffs.push({
      key,
      name: fieldNames[key],
      path: fieldPaths[key],
      oldValue,
      newValue,
      isChanged,
      isNew: false,
      isDeleted: false,
      description: isChanged ? getChangeDescription(key, oldValue, newValue) : null
    })
  })
  
  return diffs
}

// 辅助函数：获取测试步骤
function getTestSteps(groupName) {
  const stepMap = {
    '基础网络': [
      {
        name: '检查工具机IP连通性',
        getTip: (status, config) => {
          if (status === 'ok') return `工具机 ${config.toolIp} 连接正常`
          if (status === 'warn') return `工具机连接延迟较高`
          return `无法连接到工具机 ${config.toolIp}`
        },
        getDetails: (status, config) => {
          if (status === 'fail') {
            return `Ping ${config.toolIp} 失败\n请检查：\n1. IP地址是否正确\n2. 网络连接是否正常\n3. 防火墙设置`
          }
          return null
        }
      },
      {
        name: '检查服务器IP连通性',
        getTip: (status, config) => {
          if (status === 'ok') return `服务器 ${config.serverIp} 连接正常`
          if (status === 'warn') return `服务器连接不稳定`
          return `无法连接到服务器 ${config.serverIp}`
        }
      },
      {
        name: '验证代理配置',
        getTip: (status, config) => {
          if (!config.enableProxy) return '代理功能已禁用'
          if (status === 'ok') return '代理配置验证通过'
          if (status === 'warn') return '代理配置可能有问题'
          return '代理配置验证失败'
        }
      }
    ],
    'MQTT': [
      {
        name: '解析MQTT代理地址',
        getTip: (status, config) => {
          if (status === 'ok') return `代理地址解析成功: ${config.mqttBroker}`
          return `代理地址解析失败: ${config.mqttBroker}`
        }
      },
      {
        name: '建立MQTT连接',
        getTip: (status) => {
          if (status === 'ok') return 'MQTT连接建立成功'
          if (status === 'warn') return 'MQTT连接不稳定'
          return 'MQTT连接失败'
        }
      },
      {
        name: '验证设备认证',
        getTip: (status, config) => {
          if (status === 'ok') return `设备 ${config.mqttDeviceId} 认证成功`
          return `设备认证失败，请检查产品ID和设备ID`
        }
      },
      {
        name: '测试消息发布',
        getTip: (status) => {
          if (status === 'ok') return '消息发布测试成功'
          return '消息发布失败'
        }
      }
    ],
    'HTTP/回调': [
      {
        name: '检查HTTP基础地址',
        getTip: (status, config) => {
          if (status === 'ok') return `HTTP地址可访问: ${config.httpBase}`
          return `HTTP地址无法访问: ${config.httpBase}`
        }
      },
      {
        name: '测试HTTP连接',
        getTip: (status) => {
          if (status === 'ok') return 'HTTP连接正常'
          if (status === 'warn') return 'HTTP连接超时'
          return 'HTTP连接失败'
        }
      },
      {
        name: '验证超时配置',
        getTip: (status, config) => {
          if (status === 'ok') return `超时设置合理: ${config.httpTimeout}ms`
          if (status === 'warn') return `超时时间可能过短: ${config.httpTimeout}ms`
          return '超时配置有问题'
        }
      }
    ],
    '代理与安全': [
      {
        name: '检查数据包过滤规则',
        getTip: (status, config) => {
          if (config.packetFilter) {
            return status === 'ok' ? '数据包过滤规则正常' : '数据包过滤规则有问题'
          }
          return '数据包过滤已禁用'
        }
      },
      {
        name: '验证证书文件',
        getTip: (status, config) => {
          if (!config.certFile) return '未配置证书文件'
          if (status === 'ok') return '证书文件验证通过'
          if (status === 'warn') return '证书即将过期'
          return '证书文件无效'
        }
      },
      {
        name: '安全策略检查',
        getTip: (status) => {
          if (status === 'ok') return '安全策略配置正确'
          if (status === 'warn') return '安全策略需要优化'
          return '安全策略存在风险'
        }
      }
    ]
  }
  
  return stepMap[groupName] || []
}

// 辅助函数：获取随机状态
function getRandomStatus(stepIndex, totalSteps) {
  // 前面的步骤更容易成功
  const successRate = Math.max(0.7, 1 - stepIndex * 0.1)
  const rand = Math.random()
  
  if (rand < successRate) return 'ok'
  if (rand < successRate + 0.2) return 'warn'
  return 'fail'
}

// 辅助函数：获取变更描述
function getChangeDescription(key, oldValue, newValue) {
  if (key.includes('Ip')) {
    return `IP地址从 ${oldValue} 变更为 ${newValue}`
  }
  if (key.includes('mqtt')) {
    return `MQTT配置更新`
  }
  if (key.includes('http')) {
    return `HTTP配置更新`
  }
  if (key === 'enableProxy') {
    return newValue ? '启用代理功能' : '禁用代理功能'
  }
  if (key === 'packetFilter') {
    return newValue ? '启用数据包过滤' : '禁用数据包过滤'
  }
  return `配置项已更新`
}
