<template>
  <div class="defect-details-form">
    <div class="form-header">
      <h3>缺陷详情</h3>
      <a-button type="text" @click="$emit('close')">
        <template #icon><icon-close /></template>
      </a-button>
    </div>
    
    <div class="form-body">
      <a-form :model="form" layout="vertical">
        <a-form-item label="缺陷名称" field="defectName">
          <a-input v-model="form.defectName" placeholder="请输入缺陷名称" />
        </a-form-item>

        <!-- 缺陷位置 -->
        <a-form-item
            field="defectPosition"
            label="缺陷位置"
        >
          <a-input v-model="form.defectPosition" placeholder="请输入缺陷位置" />
        </a-form-item>
        
        <!-- 缺陷类型 -->
        <a-form-item
          field="defectType"
          label="缺陷类型"
          :rules="[{ required: true, message: '请选择缺陷类型' }]"
        >
          <a-select
            v-model="form.defectType"
            placeholder="请选择缺陷类型"
            :loading="loadingDefectTypes"
          >
            <a-option v-for="type in defectTypes" :key="type.code" :value="type.code">{{ type.label }}</a-option>
          </a-select>
        </a-form-item>

        <!--轴向尺寸-->
        <div class="dimension-fields">
          <a-form-item
              field="axialDimension"
              label="轴向尺寸 (mm)"
              :rules="[{ type: 'number', min: 0, message: '必须大于等于0' }]"
          >
            <a-input-number
                v-model="form.axialDimension"
                :min="0"
                :step="1"
                placeholder="请输入轴向尺寸"
                mode="button"
                size="large"
            >
            </a-input-number>
          </a-form-item>

          <!--弦向尺寸 -->
          <a-form-item
              field="chordDimension"
              label="弦向尺寸 (mm)"
              :rules="[{ type: 'number', min: 0, message: '必须大于等于0' }]"
          >
            <a-input-number
                v-model="form.chordDimension"
                :min="0"
                :step="1"
                placeholder="请输入弦向尺寸"
                mode="button"
                size="large"
            >
            </a-input-number>
          </a-form-item>
        </div>
        
        <!-- 缺陷等级 -->
        <a-form-item
          field="defectLevel"
          label="严重程度"
          :rules="[{ required: true, message: '请选择缺陷等级' }]"
        >
          <a-select
            v-model="form.defectLevel"
            placeholder="请选择缺陷等级"
            :loading="loadingDefectLevels"
            @change="handleDefectLevelChange"
          >
            <a-option v-for="level in defectLevels" :key="level.code" :value="level.code">{{ level.name }}</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="描述" field="description">
          <a-textarea 
            v-model="form.description" 
            placeholder="请输入缺陷描述"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="维修建议" field="repairIdea">
          <a-textarea 
            v-model="form.repairIdea" 
            placeholder="请输入维修建议"
            :rows="3"
          />
        </a-form-item>
        <div class="form-footer">
      <a-button @click="$emit('close')" size="large">取消</a-button>
      <a-button 
        type="primary" 
        size="large"
        @click="handleSubmit"
        :loading="submitting"
      >
        <template #icon><icon-save /></template>
        保存缺陷
      </a-button>
    </div>
      </a-form>
    </div>
    
   
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { IconClose, IconSave } from '@arco-design/web-vue/es/icon'
import { Message } from '@arco-design/web-vue'
import type { Annotation } from '@/views/project-operation-platform/data-processing/industrial-image/components/ImageCanvas.vue'
import { getDefectLevels, getDefectTypes, type DefectLevelType, type DefectType } from '@/apis/industrial-image/defect'
import { listDefectType } from '@/apis/common/common'
import type { DefectTypeResp, DefectTypeOption } from '@/apis/common/type'

interface DefectFormData {
  defectName: string
  defectType: string
  defectTypeLabel: string
  defectLevel: string
  defectLevelLabel: string
  defectPosition: string
  description: string
  repairIdea: string
  axialDimension: number | 0
  chordDimension: number | 0
}

const props = defineProps<{
  annotation: ExtendedAnnotation | null
}>()

const emit = defineEmits<{
  close: []
  submit: [formData: DefectFormData, annotation: ExtendedAnnotation]
}>()

// 提交状态
const submitting = ref(false)

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

// 缺陷等级列表
const defectLevels = ref<DefectTypeOption[]>([])
const loadingDefectLevels = ref(false)

// 表单数据
const form = reactive<DefectFormData>({
  defectName: '',
  defectType: '', 
  defectTypeLabel: '',
  defectLevel: '', 
  defectLevelLabel: '',
  defectPosition: '',
  description: '',
  repairIdea: '建议进行进一步检查',
  axialDimension: 0,  // 初始为null
  chordDimension: 0   // 初始为null
})

// 获取缺陷类型列表
const loadDefectTypes = async () => {
  try {
    loadingDefectTypes.value = true
    const response = await listDefectType()
    
    // 转换数据格式 - 处理实际API返回的数据结构
    const defectTypeOptions: DefectTypeOption[] = []
    
    // 遍历返回的数组，每个元素是一个对象，包含一个键值对
    if (Array.isArray(response.data)) {
      response.data.forEach((item: any) => {
        // 获取对象的所有键值对
        const entries = Object.entries(item)
        if (entries.length > 0) {
          const [code, name] = entries[0]
          defectTypeOptions.push({
            value: code,
            label: name as string,
            code: code
          })
        }
      })
    }
    
    defectTypes.value = defectTypeOptions
    console.log('缺陷类型选项:', defectTypeOptions)
    
    // 如果有选项且没有设置默认值，则设置第一个为默认值
    if (defectTypeOptions.length > 0 && !form.defectType) {
      form.defectType = defectTypeOptions[0].code
      form.defectTypeLabel = defectTypeOptions[0].label
    }
  } catch (error) {
    console.error('获取缺陷类型失败:', error)
    Message.error('获取缺陷类型失败')
    defectTypes.value = []
  } finally {
    loadingDefectTypes.value = false
  }
}


// 加载缺陷等级
const loadDefectLevels = async () => {
  try {
    loadingDefectLevels.value = true
    const response = await getDefectLevels()
    
    // 转换数据格式
    const defectLevelOptions: DefectTypeOption[] = []
    
    // 检查数据格式并处理
    if (response.data && response.data.code === 0 && Array.isArray(response.data.data)) {
      // 处理标准API返回格式
      response.data.data.forEach(item => {
        defectLevelOptions.push({
          code: item.code,
          label: item.name,  // 使用name作为label
          value: item.value,
          name: item.name,
          sort: item.sort
        })
      })
      defectLevels.value = defectLevelOptions
    } else if (Array.isArray(response.data)) {
      // 直接返回数组格式的处理
      response.data.forEach((item: any) => {
        const entries = Object.entries(item)
        if (entries.length > 0) {
          const [code, name] = entries[0]
          defectLevelOptions.push({
            code: code,
            label: name as string,
            value: code,
            name: name as string
          })
        }
      })
      defectLevels.value = defectLevelOptions
    } else {
      console.error('无法解析缺陷等级数据格式:', response)
      // 设置默认等级
      defectLevels.value = [
        { code: 'low', label: '轻微', value: 'low', name: '轻微' },
        { code: 'medium', label: '中等', value: 'medium', name: '中等' },
        { code: 'high', label: '严重', value: 'high', name: '严重' }
      ]
    }
    
    console.log('缺陷等级选项:', defectLevels.value)
    
    // 如果有选项且没有设置默认值，则设置默认值
    if (defectLevels.value.length > 0 && !form.defectLevel) {
      const mediumLevel = defectLevels.value.find(l => 
        l.code.toLowerCase().includes('medium') || 
        (l.name && l.name.includes('中'))
      )
      form.defectLevel = mediumLevel?.code || defectLevels.value[0].code
      form.defectLevelLabel = mediumLevel?.name || mediumLevel?.label || defectLevels.value[0].label
    }
  } catch (error) {
    console.error('加载缺陷等级失败:', error)
    // 设置默认等级
    defectLevels.value = [
      { code: 'low', label: '轻微', value: 'low', name: '轻微' },
      { code: 'medium', label: '中等', value: 'medium', name: '中等' },
      { code: 'high', label: '严重', value: 'high', name: '严重' }
    ]
  } finally {
    loadingDefectLevels.value = false
  }
}

// 监听标注变化，重置表单
watch(() => props.annotation, (newAnnotation) => {
  if (newAnnotation) {
    // 检查是否是虚拟标注（从按钮添加）
    const isVirtualAnnotation = newAnnotation.id.startsWith('virtual-')
    // 检查是否是多区域标注
    const isMultiAnnotation = newAnnotation.metadata?.isMultiAnnotation
    
    if (isVirtualAnnotation) {
      // 从按钮添加的缺陷，不显示坐标信息
      form.description = '手动添加的缺陷，请填写详细描述'
    } else if (isMultiAnnotation) {
      // 多区域标注
      const annotationCount = newAnnotation.metadata?.allAnnotations?.length || 0
      form.description = `包含${annotationCount}个标注区域的缺陷，请填写详细描述`
    } else {
      // 从Canvas绘制的单个缺陷，显示坐标信息
      const rect = newAnnotation.points
      if (rect && rect.length >= 2) {
        const width = Math.abs(rect[1].x - rect[0].x)
        const height = Math.abs(rect[1].y - rect[0].y)
        form.description = `标注区域大小: ${Math.round(width)}x${Math.round(height)} 像素`
      }
    }
    
    // 如果有标签信息，设置为缺陷名称
    if (newAnnotation.label) {
      form.defectName = newAnnotation.label
    }
  }
}, { immediate: true })

const handleSubmit = async () => {
  if (!props.annotation) {
    Message.warning('没有标注数据')
    return
  }
  
  // 基础验证
  if (!form.defectName.trim()) {
    Message.warning('请输入缺陷名称')
    return
  }
  
  if (!form.defectType) {
    Message.warning('请选择缺陷类型')
    return
  }
  
  if (!form.defectLevel) {
    Message.warning('请选择严重程度')
    return
  }
  
  try {
    submitting.value = true
    
    // 检查是否是多区域标注
    const isMultiAnnotation = props.annotation.metadata?.isMultiAnnotation
    const annotationCount = props.annotation.metadata?.allAnnotations?.length || 0
    
    if (isMultiAnnotation && annotationCount > 0) {
      Message.loading({
        content: `正在保存包含${annotationCount}个标注区域的缺陷信息...`,
        duration: 0
      })
    } else {
      Message.loading({
        content: '正在保存缺陷信息...',
        duration: 0
      })
    }
    
    // 触发提交事件
    console.log("form:",form);
    emit('submit', form, props.annotation)
    
  } catch (error) {
    console.error('提交缺陷失败:', error)
    Message.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 处理缺陷类型变化
const handleDefectTypeChange = (value: string) => {
  const selectedType = defectTypes.value.find(type => type.code === value)
  if (selectedType) {
    form.defectTypeLabel = selectedType.name
  }
}

// 处理缺陷等级变化
const handleDefectLevelChange = (value: string) => {
  const selectedLevel = defectLevels.value.find(level => level.code === value)
  if (selectedLevel) {
    form.defectLevelLabel = selectedLevel.name
  }
}

// 组件挂载时加载缺陷类型
onMounted(() => {
  // 可以通过标注信息预设部分表单值
  if (props.annotation) {
    if (props.annotation.label) {
      form.defectName = props.annotation.label
    }
    
    // 如果标注有position属性，可以设置位置
    if ('position' in props.annotation && typeof props.annotation.position === 'string') {
      form.defectPosition = props.annotation.position
    }
  }
  
  // 加载缺陷等级和类型
  loadDefectLevels()
  loadDefectTypes()
})
</script>

<style scoped lang="scss">
.defect-details-form {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-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;
  }
}

.form-body {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.form-footer {
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #f8f9fa;
  
  .arco-btn {
    min-width: 80px;
    font-weight: 500;
    
    &.arco-btn-primary {
      background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
      border-color: #1890ff;
      box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
      
      &:hover {
        background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
        box-shadow: 0 4px 8px rgba(24, 144, 255, 0.4);
        transform: translateY(-1px);
      }
      
      &:active {
        transform: translateY(0);
        box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
      }
    }
  }
}

.dimension-fields {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;

  :deep(.arco-input-number) {
    width: 100%;

    .arco-input-number-step {
      width: 32px;
    }

    .arco-input-number-input {
      text-align: center;
    }
  }
}

:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
  color: #374151;
}
</style>