// Creo API服务 - MVP版本，只实现连接测试功能
// 严格遵循开发规范：核心需求优先，杜绝过度工程

import apiClient from './apiClient'
import { buildApiUrl } from '@/config/cad'

// 重复使用的常量
const SOFTWARE_TYPE = "creo"
const DEFAULT_MAX_RESULTS = 20

// Creo API服务类
class CreoApiService {
  constructor() {
    this.softwareName = 'creo'
  }

  /**
   * 测试Creo连接
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async testConnection() {
    // 构建连接测试URL
    const url = buildApiUrl(this.softwareName, 'connect')

    // 调用统一API客户端（错误处理和通知由apiClient统一管理）
    return await apiClient.get(url, {
      operationContext: {
        software: 'Creo',
        operation: '连接测试'
      }
    })
  }

  /**
   * 获取当前模型状态
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async getCurrentModel() {
    const url = buildApiUrl(this.softwareName, 'status')

    return await apiClient.get(url, {
      operationContext: {
        software: 'Creo',
        operation: '获取当前模型'
      }
    })
  }

  /**
   * 打开模型文件
   * @param {string} filePath - 模型文件路径
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async openModelFile(filePath) {
    const url = buildApiUrl(this.softwareName, 'open')

    return await apiClient.post(url, {
      "software_type": "creo",
      "file_path": filePath,
      "open_mode": "active"
    }, {
      operationContext: {
        software: 'Creo',
        operation: '打开模型文件'
      }
    })
  }

  /**
   * 开始智能薄壳化分析
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async startShellAnalysis() {
    const url = buildApiUrl(this.softwareName, 'shellAnalysis')

    return await apiClient.post(url, {
      "software_type": SOFTWARE_TYPE,
      "projectName": "current_model",
      "analysisType": "surface_shell",
      "preserveExternalSurfaces": true,
      "minWallThickness": 1.0,
      "confidenceThreshold": 0.7
    }, {
      operationContext: {
        software: 'Creo',
        operation: '智能薄壳化分析'
      }
    })
  }

  /**
   * 开始按层级删除优化分析
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async startHierarchyAnalysis() {
    const url = buildApiUrl(this.softwareName, 'hierarchy')

    return await apiClient.post(url, {
      "software_type": SOFTWARE_TYPE,
      "project_name": "overall_top_design.asm",
      "max_depth": DEFAULT_MAX_RESULTS,
      "include_geometry": true,
      "target_level": 0
    }, {
      operationContext: {
        software: 'Creo',
        operation: '按层级删除优化分析'
      }
    })
  }

  /**
   * 开始几何复杂度分析
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async startGeometryComplexityAnalysis() {
    const url = buildApiUrl(this.softwareName, 'geometryComplexity')

    return await apiClient.post(url, {
      "software_type": SOFTWARE_TYPE,
      "project_name": "Geometry Analysis",
      "max_results": 30,
      "sort_order": "desc",
      "complexity_threshold": 0.0,
      "include_details": true
    }, {
      operationContext: {
        software: 'Creo',
        operation: '几何复杂度分析'
      }
    })
  }

  /**
   * 删除指定路径的组件
   * @param {Array<string>} componentPaths - 要删除的组件路径数组
   * @param {boolean} forceDelete - 是否强制删除，默认false
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async deleteComponentsByPath(componentPaths, forceDelete = false) {
    const url = buildApiUrl(this.softwareName, 'deleteComponent')

    return await apiClient.post(url, {
      "software_type": SOFTWARE_TYPE,
      "component_paths": componentPaths,
      "force_delete": forceDelete
    }, {
      operationContext: {
        software: 'Creo',
        operation: '删除组件'
      }
    })
  }

  /**
   * 获取层级统计信息
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async getHierarchyStatistics() {
    const url = buildApiUrl(this.softwareName, 'hierarchyStatistics')

    return await apiClient.post(url, {}, {
      operationContext: {
        software: 'Creo',
        operation: '获取层级统计'
      }
    })
  }

  /**
   * 删除指定层级及以下的所有组件
   * @param {number} targetLevel - 目标层级
   * @param {string} projectName - 项目名称
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async deleteHierarchy(targetLevel, projectName) {
    if (!projectName) {
      throw new Error('项目名称不能为空')
    }

    const url = buildApiUrl(this.softwareName, 'hierarchyDelete')

    return await apiClient.post(url, {
      "software_type": SOFTWARE_TYPE,
      "project_name": projectName,
      "target_level": targetLevel
    }, {
      operationContext: {
        software: 'Creo',
        operation: `层级删除 - 层级${targetLevel + 1}`
      }
    })
  }

  /**
   * 执行薄壳化分析 (Shrinkwrap Shell Analysis)
   * @param {Object} params - 分析参数
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async startShrinkwrapShell(params) {
    const url = buildApiUrl(this.softwareName, 'optimization')

    return await apiClient.post(url, params, {
      operationContext: {
        software: 'Creo',
        operation: '薄壳化分析'
      }
    })
  }

  /**
   * 导出模型到指定格式
   * @param {string} formatType - 导出格式类型 (step, iges, stl, pdf, dwg)
   * @param {string} exportPath - 导出文件路径
   * @param {Object} options - 导出选项
   * @param {string} options.geom_flags - 几何类型 (solids, surfaces, wireframe, quilts)
   * @param {boolean} options.advanced - 是否启用高级模式
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async exportModel(formatType, exportPath, options = {}) {
    if (!formatType) {
      throw new Error('导出格式不能为空')
    }
    if (!exportPath) {
      throw new Error('导出路径不能为空')
    }

    const url = buildApiUrl(this.softwareName, 'export')

    return await apiClient.post(url, {
      "software_type": SOFTWARE_TYPE,
      "format_type": formatType,
      "export_path": exportPath,
      "options": {
        "geom_flags": options.geom_flags || "solids",
        "advanced": options.advanced || false
      }
    }, {
      operationContext: {
        software: 'Creo',
        operation: `模型导出 - ${formatType.toUpperCase()}`
      }
    })
  }

  /**
   * 获取指定组件的子组件
   * @param {string} componentPath - 组件路径
   * @param {number} componentId - 组件ID (Creo Feature ID)
   * @returns {Promise<{success: boolean, data?: any, error?: string}>}
   */
  async getChildrenComponents(componentPath, componentId = null) {
    if (!componentPath) {
      throw new Error('组件路径不能为空')
    }

    const url = buildApiUrl(this.softwareName, 'componentChildren')

    const requestData = {
      "component_path": componentPath
    }

    // 只有当componentId存在时才添加到请求中
    if (componentId) {
      requestData.component_id = componentId
    }

    return await apiClient.post(url, requestData, {
      operationContext: {
        software: 'Creo',
        operation: '获取子组件'
      }
    })
  }
}

// 导出单例实例
export const creoApi = new CreoApiService()

// 默认导出
export default creoApi