<template>
  <div class="auto-recognition-panel">
    <div class="panel-header">
      <h3>自动识别设置</h3>
      <a-button type="text" @click="$emit('close')">
        <template #icon><icon-close /></template>
      </a-button>
    </div>

    <div class="panel-content">
      <div class="panel-section">
        <div class="section-header">
          <h4>识别算法</h4>
          <!-- <a-link @click="goToModelManagement">管理模型</a-link> -->
        </div>
        <a-select v-model:model-value="selectedAlgorithm" placeholder="请选择识别算法" loading-tip="加载中...">
          <template v-if="loadingModels">
            <a-option value="" disabled>加载中...</a-option>
          </template>
          <template v-else>
            <a-option v-for="model in modelList" :key="model.modelId" :value="model.modelId">
              {{ model.modelName }}
            </a-option>
            <a-empty v-if="modelList.length === 0" description="暂无可用模型" />
          </template>
        </a-select>
      </div>

      <div class="panel-section">
        <div class="section-header">
          <h4>置信度</h4>
        </div>
        <a-slider 
          v-model:model-value="confidence" 
          :min="0" 
          :max="100" 
          :step="10"
          show-tooltip
          :format-tooltip="(value) => `${value}%`"
        />
      </div>

      <div class="panel-section">
        <div class="section-header">
          <h4>缺陷类型</h4>
        </div>
        <div class="defect-types">
          <div v-if="loadingDefectTypes" class="loading-defect-types">
            <a-spin />
            <span>加载缺陷类型...</span>
          </div>
          <a-checkbox-group v-else v-model:model-value="selectedDefectTypes">
            <div 
              v-for="defectType in defectTypes" 
              :key="defectType.value"
              class="defect-item"
            >
              <a-checkbox :value="defectType.value">
                <span class="defect-label">{{ defectType.label }}</span>
              </a-checkbox>
            </div>
          </a-checkbox-group>
        </div>
      </div>

      <div class="panel-actions">
        <a-button type="primary" @click="handleStartRecognition" :loading="isRecognizing" block>
          开始识别
        </a-button>
        <a-button @click="handleResetSettings" block>
          重置设置
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconClose } from '@arco-design/web-vue/es/icon'
import { listDefectType } from '@/apis/common/common'
import { getModelConfigList } from '@/apis/model-config'
import type { DefectTypeResp, DefectTypeOption } from '@/apis/common/type'
import type { ModelConfigResponse } from '@/apis/model-config/type'
import { useRouter } from 'vue-router'

const props = defineProps<{
  currentImage?: {
    url: string
    name: string
    partName?: string
    componentType?: string
  }
}>()

const emit = defineEmits<{
  close: []
  startRecognition: [settings: {
    algorithm: string
    confidence: number
    defectTypes: string[]
  }]
}>()

// 设置状态
const selectedAlgorithm = ref('')
const confidence = ref(100)
const selectedDefectTypes = ref<string[]>([])
const isRecognizing = ref(false)

// 模型数据
const modelList = ref<ModelConfigResponse[]>([])
const loadingModels = ref(false)

// 缺陷类型数据
const defectTypes = ref<DefectTypeOption[]>([])
const loadingDefectTypes = ref(false)

// 获取模型列表
const loadModelList = async () => {
  try {
    loadingModels.value = true
    const response = await getModelConfigList()
    
    if (response && response.rows) {
      // 处理返回的数据结构
      if (Array.isArray(response.rows)) {
        modelList.value = response.rows;
      } else {
        // 检查是否有嵌套数据结构
        const responseData = response.rows;
        modelList.value = [];
        
        // 根据API返回的实际数据结构处理
        if (responseData && Array.isArray(responseData)) {
          modelList.value = responseData.map((item: any) => ({
            modelId: item.modelId || '',
            modelName: item.modelName || item.modelId || '',
            attachId: item.attachId || '',
            confThreshold: item.confThreshold || 0.5,
            nmsThreshold: item.nmsThreshold || 0.5,
            modelPath: item.modelPath || ''
          }));
        }
      }
      
      // 如果有模型，默认选择第一个
      if (modelList.value.length > 0) {
        selectedAlgorithm.value = modelList.value[0].modelId
      }
    }
  } catch (error) {
    console.error('获取模型列表失败:', error)
    Message.error('获取模型列表失败')
    modelList.value = []
  } finally {
    loadingModels.value = false
  }
}

// 获取缺陷类型列表
const loadDefectTypes = async () => {
  try {
    loadingDefectTypes.value = true
    const response = await listDefectType()
    
    // 转换数据格式 - 处理实际API返回的数据结构
    const defectTypeOptions: DefectTypeOption[] = []
    
    // 遍历返回的数组，每个元素是一个对象，包含一个键值对
    response.data.forEach((item: DefectTypeResp) => {
      // 获取对象的所有键值对
      Object.entries(item).forEach(([code, name]) => {
        defectTypeOptions.push({
          value: code,
          label: name,
          code: code
        })
      })
    })
    
    defectTypes.value = defectTypeOptions
    
    // 设置默认选中的缺陷类型（选择前几个）
    if (defectTypes.value.length > 0) {
      selectedDefectTypes.value = defectTypes.value.slice(0, 3).map(item => item.value)
    }
  } catch (error) {
    console.error('获取缺陷类型失败:', error)
    Message.error('获取缺陷类型失败')
    defectTypes.value = []
    selectedDefectTypes.value = []
  } finally {
    loadingDefectTypes.value = false
  }
}

// 开始识别
const handleStartRecognition = async () => {
  if (!props.currentImage) {
    Message.error('请先选择图像')
    return
  }

  if (!selectedAlgorithm.value) {
    Message.error('请选择识别算法')
    return
  }

  if (selectedDefectTypes.value.length === 0) {
    Message.error('请选择至少一种缺陷类型')
    return
  }

  const settings = {
    algorithm: selectedAlgorithm.value,
    confidence: confidence.value,
    defectTypes: selectedDefectTypes.value
  }

  try {
    isRecognizing.value = true
    Message.success('识别设置已保存，开始识别...')
    emit('startRecognition', settings)
  } catch (error) {
    console.error('识别失败:', error)
    Message.error('识别失败，请重试')
  } finally {
    isRecognizing.value = false
  }
}

// 重置设置
const handleResetSettings = () => {
  selectedAlgorithm.value = modelList.value.length > 0 ? modelList.value[0].modelId : ''
  confidence.value = 80
  selectedDefectTypes.value = defectTypes.value.length > 0 ? defectTypes.value.slice(0, 3).map(item => item.value) : []
}

// 设置识别状态
const setRecognizing = (status: boolean) => {
  isRecognizing.value = status
}

// 组件挂载时加载数据
onMounted(() => {
  loadModelList()
  loadDefectTypes()
})

// 路由相关
const router = useRouter()

// 跳转到模型管理页面
const goToModelManagement = () => {
  router.push('/construction-operation-platform/implementation-workflow/data-processing/model-config')
}

defineExpose({
  setRecognizing
})
</script>

<style scoped lang="scss">
.auto-recognition-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #e5e7eb;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #1f2937;
    }
  }

  .panel-content {
    // flex: 1;
    display: flex;
    flex-direction: column;
    overflow-y: scroll;
    height: 600px;
    
    .panel-section {
      padding: 16px 20px;
      border-bottom: 1px solid #f3f4f6;
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        h4 {
          margin: 0;
          font-size: 14px;
          font-weight: 600;
          color: #1f2937;
        }
      }

      .arco-select {
        width: 100%;
      }

      .defect-types {
        .loading-defect-types {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 12px;
          color: #666;
        }

        .arco-checkbox-group {
          display: flex;
          flex-direction: column;
          gap: 6px;

          .defect-item {
            padding: 4px 0;

            .arco-checkbox {
              font-size: 13px;
            }

            .defect-label {
              margin-right: 8px;
            }
          }
        }
      }
    }

    .panel-actions {
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 12px;
      margin-top: auto;
    }
  }
}
</style> 