<template>
  <div class="defect-details-panel">
    <!-- 头部 -->
    <div class="panel-header">
      <h3>缺陷详情</h3>
    </div>

    <!-- 缺陷详情表单 -->
    <div v-if="selectedDefect" class="defect-detail-form">
      <div class="form-container">
        <!-- 编号和缺陷名称 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">编号</label>
            <a-input :model-value="defectForm.defectCode" readonly />
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label class="form-label">缺陷名称</label>
            <a-input v-model="defectForm.defectName" />
          </div>
        </div>

        <!-- 部位 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">部位</label>
            <a-input v-model="defectForm.defectPosition" />
          </div>
        </div>

        <!-- 缺陷类型 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">缺陷类型</label>
            <a-select v-model="defectForm.defectType">
              <a-option value="crack">裂纹</a-option>
              <a-option value="erosion">截蚀</a-option>
              <a-option value="wear">磨损</a-option>
              <a-option value="corrosion">腐蚀</a-option>
              <a-option value="deformation">变形</a-option>
              <a-option value="damage">损伤</a-option>
            </a-select>
          </div>
        </div>

        <!-- 严重程度 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">严重程度</label>
            <a-select v-model="defectForm.defectLevel">
              <a-option value="low">轻微</a-option>
              <a-option value="medium">中等</a-option>
              <a-option value="high">严重</a-option>
              <a-option value="critical">危急</a-option>
            </a-select>
          </div>
        </div>

        <!-- 维修状态 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">维修状态</label>
            <a-select v-model="defectForm.repairStatus">
              <a-option value="pending">未处理</a-option>
              <a-option value="processing">处理中</a-option>
              <a-option value="completed">已完成</a-option>
            </a-select>
          </div>
        </div>

        <!-- 轴向尺寸和弦向尺寸 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">轴向尺寸</label>
            <div class="size-input-group">
              <a-button 
                size="small" 
                @click="defectForm.axial = Math.max(0, (defectForm.axial || 0) - 1)"
              >
                −
              </a-button>
              <a-input-number 
                v-model="defectForm.axial" 
                :min="0" 
                size="small"
                style="width: 70px"
              />
              <a-button 
                size="small" 
                @click="defectForm.axial = (defectForm.axial || 0) + 1"
              >
                +
              </a-button>
              <span class="unit">(mm)</span>
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">弦向尺寸</label>
            <div class="size-input-group">
              <a-button 
                size="small" 
                @click="defectForm.chordwise = Math.max(0, (defectForm.chordwise || 0) - 1)"
              >
                −
              </a-button>
              <a-input-number 
                v-model="defectForm.chordwise" 
                :min="0" 
                size="small"
                style="width: 70px"
              />
              <a-button 
                size="small" 
                @click="defectForm.chordwise = (defectForm.chordwise || 0) + 1"
              >
                +
              </a-button>
              <span class="unit">(mm)</span>
            </div>
          </div>
        </div>

        <!-- 面积 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">面积(mm²)</label>
            <div class="size-input-group">
              <a-button 
                size="small" 
                @click="defectForm.area = Math.max(0, (defectForm.area || 0) - 1)"
              >
                −
              </a-button>
              <a-input-number 
                v-model="defectForm.area" 
                :min="0" 
                size="small"
                style="width: 70px"
              />
              <a-button 
                size="small" 
                @click="defectForm.area = (defectForm.area || 0) + 1"
              >
                +
              </a-button>
            </div>
          </div>
        </div>

        <!-- 描述 -->
        <div class="form-row">
          <div class="form-group full-width">
            <label class="form-label">描述</label>
            <a-textarea 
              v-model="defectForm.description" 
              :rows="3"
              placeholder="叶片前缘纵向裂纹，长度约15mm，宽度约2mm"
            />
            <div class="action-button-container">
              <a-button 
                size="small" 
                @click="handleSelectFromStandardDescription"
                class="standard-library-btn"
              >
                从标准描述库选择
              </a-button>
            </div>
          </div>
        </div>

        <!-- 维修建议 -->
        <div class="form-row">
          <div class="form-group full-width">
            <label class="form-label">维修建议</label>
            <a-textarea 
              v-model="defectForm.repairIdea" 
              :rows="3"
              placeholder="建议进行表面修复处理，防止裂纹扩散"
            />
            <div class="action-button-container">
              <a-button 
                size="small" 
                @click="handleSelectFromStandardInfo"
                class="standard-library-btn"
              >
                从标准信息库选择
              </a-button>
            </div>
          </div>
        </div>

        <!-- 其他信息 (用于测试滚动) -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">检测方法</label>
            <a-select v-model="defectForm.detectionMethod" placeholder="选择检测方法">
              <a-option value="visual">目视检测</a-option>
              <a-option value="ultrasonic">超声波检测</a-option>
              <a-option value="magnetic">磁粉检测</a-option>
              <a-option value="penetrant">渗透检测</a-option>
            </a-select>
          </div>
          <div class="form-group">
            <label class="form-label">检测日期</label>
            <a-date-picker v-model="defectForm.inspectionDate" style="width: 100%" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label class="form-label">检测人员</label>
            <a-input v-model="defectForm.inspector" placeholder="请输入检测人员姓名" />
          </div>
          <div class="form-group">
            <label class="form-label">复检状态</label>
            <a-select v-model="defectForm.recheckStatus" placeholder="选择复检状态">
              <a-option value="not_required">无需复检</a-option>
              <a-option value="pending">待复检</a-option>
              <a-option value="passed">复检通过</a-option>
              <a-option value="failed">复检未通过</a-option>
            </a-select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group full-width">
            <label class="form-label">技术备注</label>
            <a-textarea 
              v-model="defectForm.technicalNotes" 
              :rows="4"
              placeholder="记录技术细节、处理方案、注意事项等"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-group full-width">
            <label class="form-label">修复记录</label>
            <a-textarea 
              v-model="defectForm.repairRecord" 
              :rows="3"
              placeholder="记录修复过程、使用材料、处理结果等"
            />
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <a-button type="primary" @click="handleSave">保存</a-button>
        <a-button status="danger" @click="handleDelete">删除</a-button>
      </div>
    </div>

    <!-- 无缺陷选中状态 -->
    <div v-else class="no-defect-selected">
      <icon-file class="empty-icon" />
      <p>请从左侧选择缺陷进行编辑</p>
    </div>

    <!-- 标准描述库选择模态框 -->
    <a-modal
      v-model:visible="standardDescriptionModalVisible"
      title="选择标准描述"
      width="600px"
      @ok="handleConfirmStandardDescription"
      @cancel="handleCancelStandardDescription"
    >
      <div class="standard-library-content">
        <a-list :data="standardDescriptions" :bordered="false">
          <template #item="{ item }">
            <a-list-item 
              :class="{ 'selected': selectedStandardDescription === item }"
              @click="selectedStandardDescription = item"
              class="clickable-item"
            >
              <div class="description-item">
                <div class="description-title">{{ item.title }}</div>
                <div class="description-content">{{ item.content }}</div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </a-modal>

    <!-- 标准信息库选择模态框 -->
    <a-modal
      v-model:visible="standardInfoModalVisible"
      title="选择标准维修建议"
      width="600px"
      @ok="handleConfirmStandardInfo"
      @cancel="handleCancelStandardInfo"
    >
      <div class="standard-library-content">
        <a-list :data="standardRepairIdeas" :bordered="false">
          <template #item="{ item }">
            <a-list-item 
              :class="{ 'selected': selectedStandardInfo === item }"
              @click="selectedStandardInfo = item"
              class="clickable-item"
            >
              <div class="description-item">
                <div class="description-title">{{ item.title }}</div>
                <div class="description-content">{{ item.content }}</div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import { IconFile } from '@arco-design/web-vue/es/icon'
import { Message, Modal } from '@arco-design/web-vue'
import type { DefectDetectionResult } from '@/apis/industrial-image/defect'

const props = defineProps<{
  selectedDefect: DefectDetectionResult | null
}>()

const emit = defineEmits<{
  'edit-defect': [defect: DefectDetectionResult]
  'delete-defect': [defectId: string]
}>()

// 缺陷表单数据
const defectForm = reactive({
  defectCode: '',
  defectName: '',
  defectType: '',
  defectPosition: '',
  defectLevel: '',
  repairStatus: '',
  axial: 0,
  chordwise: 0,
  area: 0,
  description: '',
  repairIdea: '',
  detectionMethod: '',
  inspectionDate: '',
  inspector: '',
  recheckStatus: '',
  technicalNotes: '',
  repairRecord: ''
})

// 标准描述库相关
const standardDescriptionModalVisible = ref(false)
const selectedStandardDescription = ref<any>(null)
const standardDescriptions = ref([
  {
    title: '前缘裂纹模板',
    content: '叶片前缘纵向裂纹，长度约15mm，宽度约2mm'
  },
  {
    title: '表面磨损模板',
    content: '叶片表面出现明显磨损痕迹，影响空气动力学性能'
  },
  {
    title: '截蚀损伤模板', 
    content: '叶片前缘截蚀损伤，表面粗糙度增加，深度约1-3mm'
  },
  {
    title: '腐蚀斑点模板',
    content: '叶片表面出现腐蚀斑点，直径约5-10mm，深度轻微'
  }
])

// 标准信息库相关
const standardInfoModalVisible = ref(false)
const selectedStandardInfo = ref<any>(null)
const standardRepairIdeas = ref([
  {
    title: '裂纹修复建议',
    content: '建议进行表面修复处理，防止裂纹扩散'
  },
  {
    title: '磨损处理建议',
    content: '定期监测磨损程度，必要时进行表面打磨和重新涂层'
  },
  {
    title: '截蚀修复建议',
    content: '建议进行前缘修复，使用专用胶泥填补并重新整形'
  },
  {
    title: '腐蚀处理建议',
    content: '清理腐蚀区域，涂抹防腐涂层，定期检查'
  },
  {
    title: '严重损伤建议',
    content: '建议立即停机检修，更换受损部件，避免安全隐患'
  }
])

// 监听选中缺陷变化，更新表单数据
watch(() => props.selectedDefect, (newDefect) => {
  if (newDefect) {
    Object.assign(defectForm, {
      defectCode: newDefect.defectCode || '',
      defectName: newDefect.defectName || '',
      defectType: newDefect.defectType || '',
      defectPosition: newDefect.defectPosition || '',
      defectLevel: newDefect.defectLevel || '',
      repairStatus: newDefect.repairStatus || '',
      axial: newDefect.axial || 0,
      chordwise: newDefect.chordwise || 0,
      area: calculateArea(newDefect.axial || 0, newDefect.chordwise || 0),
      description: newDefect.description || '',
      repairIdea: newDefect.repairIdea || ''
    })
  }
}, { immediate: true })

// 计算面积
const calculateArea = (axial: number, chordwise: number) => {
  return Math.round(axial * chordwise)
}

// 监听尺寸变化，自动计算面积
watch([() => defectForm.axial, () => defectForm.chordwise], ([newAxial, newChordwise]) => {
  defectForm.area = calculateArea(newAxial || 0, newChordwise || 0)
})

// 保存缺陷
const handleSave = () => {
  if (!props.selectedDefect?.defectId) {
    Message.warning('请先选择要编辑的缺陷')
    return
  }

  const updatedDefect = {
    ...props.selectedDefect,
    ...defectForm
  }

  emit('edit-defect', updatedDefect)
  Message.success('缺陷信息已保存')
}

// 删除缺陷
const handleDelete = () => {
  if (!props.selectedDefect?.defectId) {
    Message.warning('请先选择要删除的缺陷')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: '确定要删除此缺陷记录吗？删除后无法恢复。',
    onOk: () => {
      emit('delete-defect', props.selectedDefect!.defectId)
      Message.success('缺陷已删除')
    }
  })
}

// 取消编辑
const handleCancel = () => {
  if (props.selectedDefect) {
    // 重置表单到原始状态
    Object.assign(defectForm, {
      defectCode: props.selectedDefect.defectCode || '',
      defectName: props.selectedDefect.defectName || '',
      defectType: props.selectedDefect.defectType || '',
      defectPosition: props.selectedDefect.defectPosition || '',
      defectLevel: props.selectedDefect.defectLevel || '',
      repairStatus: props.selectedDefect.repairStatus || '',
      axial: props.selectedDefect.axial || 0,
      chordwise: props.selectedDefect.chordwise || 0,
      area: calculateArea(props.selectedDefect.axial || 0, props.selectedDefect.chordwise || 0),
      description: props.selectedDefect.description || '',
      repairIdea: props.selectedDefect.repairIdea || ''
    })
  }
}

// 标准描述库选择
const handleSelectFromStandardDescription = () => {
  standardDescriptionModalVisible.value = true
  selectedStandardDescription.value = null
}

const handleConfirmStandardDescription = () => {
  if (selectedStandardDescription.value) {
    defectForm.description = selectedStandardDescription.value.content
    Message.success('已选择标准描述')
  }
  standardDescriptionModalVisible.value = false
}

const handleCancelStandardDescription = () => {
  standardDescriptionModalVisible.value = false
  selectedStandardDescription.value = null
}

// 标准信息库选择
const handleSelectFromStandardInfo = () => {
  standardInfoModalVisible.value = true
  selectedStandardInfo.value = null
}

const handleConfirmStandardInfo = () => {
  if (selectedStandardInfo.value) {
    defectForm.repairIdea = selectedStandardInfo.value.content
    Message.success('已选择标准维修建议')
  }
  standardInfoModalVisible.value = false
}

const handleCancelStandardInfo = () => {
  standardInfoModalVisible.value = false
  selectedStandardInfo.value = null
}
</script>

<style scoped lang="scss">
.defect-details-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0; /* 确保flex子项可以收缩 */
  background: #f8f9fa;
}

.panel-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
  background: white;

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

.defect-detail-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.form-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: white;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-group {
  flex: 1;

  &.full-width {
    flex: none;
    width: 100%;
  }

  .form-label {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: #374151;
    margin-bottom: 8px;
  }
}

.size-input-group {
  display: flex;
  align-items: center;
  gap: 4px;

  .unit {
    font-size: 12px;
    color: #6b7280;
    margin-left: 4px;
  }
}

.action-button-container {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;

  .standard-library-btn {
    font-size: 12px;
    height: 28px;
    border: 1px solid #d1d5db;
    background: #f9fafb;
    color: #6b7280;

    &:hover {
      background: #f3f4f6;
      border-color: #9ca3af;
    }
  }
}

.form-actions {
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background: white;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.no-defect-selected {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  background: white;
  margin: 20px;
  border-radius: 8px;
  border: 2px dashed #d1d5db;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    color: #9ca3af;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

.standard-library-content {
  max-height: 400px;
  overflow-y: auto;

  .clickable-item {
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f9fafb;
    }

    &.selected {
      background-color: #eff6ff;
      border-left: 3px solid #3b82f6;
    }
  }

  .description-item {
    width: 100%;

    .description-title {
      font-weight: 500;
      color: #1f2937;
      margin-bottom: 4px;
    }

    .description-content {
      font-size: 14px;
      color: #6b7280;
      line-height: 1.4;
    }
  }
}

// Arco Design样式覆盖
:deep(.arco-input-number) {
  .arco-input-inner {
    text-align: center;
  }
}

:deep(.arco-select) {
  width: 100%;
}

:deep(.arco-input),
:deep(.arco-textarea) {
  width: 100%;
}

:deep(.arco-list-item) {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}
</style> 