<template>
  <div class="preliminary-diagnosis">
    <!-- 初步诊断区域 -->
    <div class="preliminary-diagnosis-section">
      <div class="diagnosis-header">
        <span class="diagnosis-key">病历信息：</span>
        <span class="diagnosis-value">{{ preliminaryDiagnosis || '病历信息' }}</span>
      </div>

      <!-- AI建议问题补充 -->
      <div v-if="preliminaryDiagnosis && aiSuggestions.length > 0" class="ai-suggestions-content">
        <div class="section-divider"></div>
        <div class="section-title">
          AI建议问题补充
        </div>
        <div class="suggestions-list">
          <div
            v-for="suggestion in aiSuggestions"
            :key="suggestion.question"
            class="suggestion-item"
          >
            <div class="question-text">{{ suggestion.question }}</div>
            <div class="option-blocks">
              <div
                v-for="(option, optionIndex) in suggestion.options"
                :key="option.value"
                class="option-block"
                :class="{ 'selected': suggestion.selectedAnswer === `${option.value}_${optionIndex}` }"
                @click="handleAnswerSelect(suggestion, option.value, optionIndex)"
              >
                {{ option.label }}
              </div>
              <a-input
                v-model="suggestion.customAnswer"
                placeholder="请输入"
                @input="handleCustomInput(suggestion)"
                :class="['option-block', 'custom-input', { 'selected': suggestion.customAnswer.trim() }]"
              />
            </div>
          </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons-section">
          <a-button
            type="default"
            @click="insertToRecord"
            :disabled="!hasSelectedAnswers"
            class="action-button"
          >
            插入病历
          </a-button>
          <a-button
            type="primary"
            @click="submitAndAnalyze"
            :disabled="!hasSelectedAnswers"
            class="action-button"
          >
            提交并分析
          </a-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'

// AI 服务配置 - 暂时使用完整地址（代理配置待修复）
const AI_API_URL = 'http://192.168.50.67:30556/predict'

// Props
const props = defineProps({
  patientComplaint: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['question-asked', 'proceed-to-next', 'set-patient-complaint', 'action1'])

// 响应式数据
const aiSuggestions = ref([])
const preliminaryDiagnosis = ref('')

// 计算属性
const hasSelectedAnswers = computed(() => {
  return aiSuggestions.value.some(suggestion =>
    suggestion.selectedAnswer || suggestion.customAnswer.trim()
  )
})


// 监听病人主诉变化，生成AI建议问题和初步诊断
watch(() => props.patientComplaint, (newComplaint) => {
  if (newComplaint) {
    generateAISuggestions(newComplaint)
    generatePreliminaryDiagnosis(newComplaint)
  }
}, { immediate: true })

// 生成AI建议问题
const generateAISuggestions = (complaint) => {
  // 调用实际的AI接口，不再使用模拟数据
  fetchAISuggestions()
}

// 生成初步诊断
const generatePreliminaryDiagnosis = (complaint) => {
  // 使用传入的complaint参数作为初步诊断内容
  preliminaryDiagnosis.value = complaint || '暂无病历信息'

  // 调用AI接口获取建议问题
  fetchAISuggestions()
}

// 调用AI接口获取建议问题
const fetchAISuggestions = async () => {
  try {
    const requestData = {
      'known_facts': props.patientComplaint ? [props.patientComplaint] : [],
      'top_n': 5,
      'step_id': 0,
      'asked_count': 0
    }

    const response = await fetch(AI_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    })

    const result = await response.json()
    console.log('AI接口返回结果:', result)

    // 解析API返回数据为组件所需的格式
    if (result.success && result.results && result.results.length > 0) {
      const suggestions = result.results.map(item => ({
        question: item.question_text,
        questionCategory: item.question_category, // 保留问题分类
        selectedAnswer: '',
        selectedAnswerLabel: '',
        customAnswer: '',
        options: item.options.map((option, optionIndex) => ({
          label: option.text,
          value: option.fact,
          id: `${item.action_id}_${optionIndex}` // 添加唯一ID
        }))
      }))

      aiSuggestions.value = suggestions
    } else {
      // 如果没有返回结果，设置为空数组
      aiSuggestions.value = []
    }

  } catch (error) {
    console.error('调用AI接口失败:', error)
    // 接口失败时设置为空数组
    aiSuggestions.value = []
  }
}


// 处理答案选择
const handleAnswerSelect = (suggestion, selectedValue, optionIndex) => {
  const selectedOption = suggestion.options[optionIndex]
  if (selectedOption) {
    suggestion.selectedAnswer = `${selectedValue}_${optionIndex}`
    suggestion.selectedAnswerLabel = selectedOption.label
    suggestion.customAnswer = '' // 清除自定义输入

    // 通知父组件时仍然使用原始的fact值
    emit('question-asked', {
      question: suggestion.question,
      answer: selectedValue, // 使用原始的fact值
      answerLabel: selectedOption.label,
      time: new Date().toLocaleTimeString()
    })
  }
}

// 处理自定义输入
const handleCustomInput = (suggestion) => {
  if (suggestion.customAnswer.trim()) {
    // 如果有自定义输入，清除选项选择
    suggestion.selectedAnswer = 'custom'
    suggestion.selectedAnswerLabel = suggestion.customAnswer.trim()

    // 通知父组件
    emit('question-asked', {
      question: suggestion.question,
      answer: 'custom',
      answerLabel: suggestion.customAnswer.trim(),
      time: new Date().toLocaleTimeString()
    })
  } else {
    // 如果自定义输入为空，清除选择状态
    suggestion.selectedAnswer = ''
    suggestion.selectedAnswerLabel = ''
  }
}

// 设置病历信息的方法
// eslint-disable-next-line no-unused-vars
const setPatientComplaint = (complaint) => {
  emit('set-patient-complaint', complaint)
}

// 插入病历
const insertToRecord = () => {
  if (!hasSelectedAnswers.value) return

  // 获取原始的病历信息
  const baseContent = props.patientComplaint || ''

  // 获取所有已回答的问题
  const answeredQuestions = aiSuggestions.value.filter(s => s.selectedAnswer)

  // 生成完整的病历信息句子
  let fullDiagnosis = baseContent

  if (answeredQuestions.length > 0) {
    // 将所有回答拼接成一个句子
    const answersText = answeredQuestions
      .map(suggestion => `${suggestion.questionCategory}${suggestion.selectedAnswerLabel}`)
      .join('，')

    fullDiagnosis += `，${answersText}`
  }

  // 直接替换整个病历信息
  preliminaryDiagnosis.value = fullDiagnosis.trim()

  console.log('已插入病历：', fullDiagnosis)

  // 触发action1事件，传递病历信息
  emit('action1', {
    patientComplaint: fullDiagnosis.trim()
  })
}

// 提交并分析
const submitAndAnalyze = () => {
  if (!hasSelectedAnswers.value) return

  const answeredQuestions = aiSuggestions.value
    .filter(s => s.selectedAnswer || s.customAnswer.trim())
    .map(s => ({
      question: s.question,
      answer: s.customAnswer.trim() ? 'custom' : s.selectedAnswer,
      answerLabel: s.customAnswer.trim() || s.selectedAnswerLabel,
      time: new Date().toLocaleTimeString()
    }))

  emit('proceed-to-next', {
    stage: 'examination',
    patientComplaint: props.patientComplaint,
    preliminaryDiagnosis: preliminaryDiagnosis.value,
    answeredQuestions: answeredQuestions
  })

  console.log('提交并分析，进入检查检验阶段')
}


// 初始化
onMounted(() => {
  if (props.patientComplaint) {
    generateAISuggestions(props.patientComplaint)
    generatePreliminaryDiagnosis(props.patientComplaint)
  }
})
</script>

<style scoped>
.preliminary-diagnosis {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 16px;
  overflow-y: auto;
}


/* 章节样式 */
.section-title {
  font-family: 'Source Han Sans';
  font-weight: 700;
  font-size: 16px;
  color: #313131;
  margin-bottom: 16px;
}

.section-icon {
  color: #999;
  font-size: 14px;
}

/* 初步诊断区域 */
.preliminary-diagnosis-section {
  background: #FFFFFF;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.diagnosis-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.diagnosis-key {
  font-family: 'Source Han Sans';
  font-size: 16px;
  font-weight: bold;
  line-height: normal;
  text-align: justify;
  letter-spacing: 0em;
  font-feature-settings: "kern" on;
  color: #313131;
  flex-shrink: 0;
}

.diagnosis-value {
  font-family: 'Source Han Sans';
  font-size: 16px;
  font-weight: normal;
  line-height: normal;
  letter-spacing: 0em;
  font-variation-settings: "opsz" auto;
  font-feature-settings: "kern" on;
  color: #313131;
  white-space: pre-line;
  word-break: break-word;
}


.section-divider {
  margin: 16px 0;
  border: 1px solid #E5E9F0;
}

/* AI建议问题内容 */
.ai-suggestions-content {
  margin-top: 16px;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggestion-item {
  margin-bottom: 12px;
}

.suggestion-item:last-child {
  margin-bottom: 0;
}


.question-text {
  font-family: 'Source Han Sans';
  font-weight: 700;
  font-size: 16px;
  color: #313131;
  margin-bottom: 12px;
}

.option-blocks {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 8px;
  margin-bottom: 8px;
  width: 100%;
}

.option-block {
  height: 32px;
  border-radius: 6px;
  opacity: 1;
  background: #FFFFFF;
  box-sizing: border-box;
  border: 1px solid #D8D8D8;
  padding: 8px 12px;
  color: #313131;
  font-size: 14px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  word-break: break-word;
  overflow-wrap: break-word;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.option-block:hover {
  border-color: #1890ff;
  background: #f0f8ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
}

.option-block.selected {
  background: #1890ff;
  color: #FFFFFF;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}


.custom-input {
  height: 32px;
  border-radius: 7px;
  background: #FFFFFF;
  box-sizing: border-box;
  border: 1px solid #D8D8D8;
}

.custom-input :deep(.ant-input) {
  border: none !important;
  background: transparent !important;
  padding: 0 8px !important;
  height: 100% !important;
  font-family: 'Source Han Sans';
  font-size: 16px;
  font-weight: normal;
  line-height: normal;
  text-align: center;
  color: #313131;
}

.custom-input :deep(.ant-input:focus) {
  box-shadow: none !important;
}

.custom-input :deep(.ant-input::placeholder) {
  color: #999;
}


/* 操作按钮区域 */
.action-buttons-section {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.action-button {
  width: 173px;
  height: 32px;
  border-radius: 6px;
  opacity: 1;
  background: #FFFFFF;
  box-sizing: border-box;
  border: 1px solid #9499A0;
  font-family: 'Source Han Sans';
  font-size: 16px;
  font-weight: normal;
  line-height: normal;
  text-align: center;
  color: #313131;
}


</style>
