<template>
  <el-dialog title="编辑问题" v-model="showQuestionDialog" width="500px" :close-on-click-modal="false"
    class="question-dialog" @close="resetForm">
    <div class="question-form">
      <div class="form-item">
        <div class="form-label">
          题目内容<span class="required">*</span>
        </div>
        <el-input v-model="questionForm.content" type="textarea" rows="4" placeholder="请描述一次你如何在紧迫的时间内完成一个复杂的后端开发任务的经历"
          maxlength="300" show-word-limit />
      </div>

      <div class="form-item">
        <div class="form-label">胜任力标签</div>
        <el-select v-model="competencyTagsValue" placeholder="请选择胜任力标签" class="full-width" multiple>
          <el-option v-for="tag in competencyTagOptions" :key="tag.id" :label="tag.name" :value="tag.id" />
        </el-select>
        <div class="form-tip">选择胜任力标签和胜任力标签，可多选</div>
      </div>

      <div class="form-item">
        <div class="form-label">
          胜任力配置
        </div>
        <div class="competency-config">
          <div class="config-row">
            <span class="config-label">标签</span>
            <span class="config-label">权重</span>
          </div>
          <div class="config-row" v-for="(tag, index) in questionForm.competency_tags" :key="tag.id">
            <span class="tag-name">{{ tag.name }}</span>
            <el-input-number v-model="tag.weight" :min="0" :max="100" :step="1" controls-position="right"
              @change="(value: number) => handleWeightChange(index, value)" /> %
          </div>
        </div>
        <div class="form-tip">
          配置各个胜任力标签的权重，总和需要100%
          <span class="weight-sum" :class="{ 'weight-error': getTotalWeight() !== 100 }">
            (当前总计: {{ getTotalWeight() }}%)
          </span>
          <br />
          <el-icon style="color: #409eff; margin-right: 4px; margin-top: 4px;">
            <InfoFilled />
          </el-icon>
          <span style="color: #909399; font-size: 11px;">
            修改任意权重时，其他权重会自动按比例调整以保持总和为100%。点击"平均分配"可快速平均分配所有权重。
          </span>
        </div>
      </div>

      <div class="form-item">
        <div class="form-label">题目形式</div>
        <el-select v-model="questionForm.type" placeholder="开放问题" class="full-width" @change="handleQuestionTypeChange">
          <el-option label="开放问题" value="open" />
          <el-option label="单选题" value="single" />
          <el-option label="多选题" value="multiple" />
          <el-option label="填空题" value="fill" />
          <el-option label="自言语" value="self" />
        </el-select>
        <div class="form-tip">选择题目的形式：开放问题、单选题、多选题、填空题、自言语</div>
      </div>

      <!-- 追问次数 - 仅在开放问题时显示 -->
      <div class="form-item" v-if="questionForm.question_form === 0">
        <div class="form-label">追问次数</div>
        <el-input-number
          v-model="questionForm.follow_up_count"
          :min="1"
          :max="2"
          :step="1"
          :precision="0"
          placeholder="请输入追问次数"
          class="full-width"
        />
        <div class="form-tip">设置开放问题的追问次数，范围为1-2次</div>
      </div>

      <!-- <div class="form-item">
        <div class="form-label">适用职位</div>
        <el-select
          v-model="questionForm.position"
          placeholder="请选择适用职位类型"
          class="full-width"
          multiple
        >
          <el-option 
            v-for="pos in positionOptions" 
            :key="pos.value"
            :label="pos.label"
            :value="pos.value"
          />
        </el-select>
        <div class="form-tip">选择题目适用的职位类型，可多选</div>
      </div> -->

      <div class="form-item" v-if="questionForm.question_form === 1 || questionForm.question_form === 2">
        <div class="form-label">选项</div>
        <div>
          <div class="option-header" style="display: flex; margin-bottom: 10px; font-weight: bold;">
            <span style="flex: 1;">选项内容</span>
            <span style="width: 80px; text-align: center;">是否正确</span>
          </div>
          <div v-for="(option, index) in questionForm.options" :key="index" class="option-item"
            style="display: flex; align-items: center; margin-bottom: 10px;">
            <el-input v-model="option.text" placeholder="请输入选项内容" style="flex: 1; margin-right: 10px;" />
            <el-tooltip content="设置为正确答案" placement="top" effect="light">
              <div @click="() => handleOptionCorrectChange(index)"
                style="cursor: pointer; width: 80px; text-align: center;">
                <template v-if="questionForm.question_form === 1">
                  <el-radio v-model="option.is_correct" :label="true" />
                </template>
                <template v-else>
                  <el-checkbox v-model="option.is_correct" />
                </template>
              </div>
            </el-tooltip>
          </div>
          <div style="display: flex; justify-content: space-between; margin-top: 10px;">
            <el-button type="primary" @click="addOption">
              添加选项
            </el-button>

            <el-button v-if="questionForm.options && questionForm.options.length > 2" type="danger"
              @click="removeLastOption">
              删除最后一项
            </el-button>
          </div>
        </div>
        <div class="form-tip">添加选项并设置正确答案，单选题只能有一个正确答案，多选题可以有多个正确答案</div>
      </div>
      <!--  {{ questionForm.question_form==6 }} -->
      <!-- 填空答案模板 -->
      <!--   <div class="form-item"
        v-if="questionForm.question_form === 6"
      >
       <div class="form-label">填空答案模板</div>
        <BlankAnswerEditor
          v-model="questionForm.blank_answer_template"
          :question="questionForm.content"
        />
      </div> -->

      <div class="form-item">
        <div class="form-label">分类</div>
        <el-select v-model="questionForm.category" placeholder="请选择题目分类" class="full-width">
          <el-option v-for="cat in categoryOptions" :key="cat.value" :label="cat.label" :value="cat.value" />
        </el-select>
        <div class="form-tip">选择题目所属分类</div>
      </div>

      <div class="form-item">
        <div class="form-label">标签</div>
        <el-select v-model="questionForm.tags" placeholder="请选择标签" class="full-width" multiple>
          <el-option v-for="tag in tagOptions" :key="tag.value" :label="tag.label" :value="tag.value" />
        </el-select>
        <div class="form-tip">选择题目相关标签，可多选</div>
      </div>
      <div class="form-item" v-if="questionForm.question_form === 1">
        <div class="form-label">是否为红线题</div>
        <el-select v-model="questionForm.is_required_correct" placeholder="请选择是否为红线问题" style="width: 100%;">
          <el-option label="否" :value="false" />
          <el-option label="是" :value="true" />
        </el-select>
      </div>
      <div class="form-item">
        <div class="form-label">建议时长(秒)</div>
        <el-input-number v-model="questionForm.suggestedDuration" :min="0" :step="1" controls-position="right"
          placeholder="请输入建议回答时长" class="full-width" />
        <div class="form-tip">建议回答题目的时长，单位为秒</div>
      </div>

      <div class="form-item">
        <div class="form-label">评价标准</div>
        <el-input v-model="questionForm.scoring_reference" type="textarea" rows="4"
          placeholder="评分标准说明，例如：【团队协作能力】1.优秀：xxxxxx。2.xxxx。3.一般：xxxxx。" class="full-width" />
        <div class="form-tip">评分标准说明，例如：【团队协作能力】1.优秀：xxxxxx。2.xxxx。3.一般：xxxxx。</div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAddQuestion">取消</el-button>
        <el-button type="primary" @click="confirmAddQuestion">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import { getBaseURL } from '/@/utils/baseUrl';
import * as api from '../../list/api';
import BlankAnswerEditor from '../../list/components/BlankAnswerEditor.vue'//'@/BlankAnswerEditor.vue';

// 添加 props 定义
const props = defineProps({
  questionId: {
    type: [String, Number],
    default: ''
  }
});

// 类型定义
interface CompetencyTag {
  id: number
  name: string
  weight: number
}

interface QuestionOption {
  text: string
  is_correct: boolean
  sort: number
}
interface BlankAnswer {
  blank_index: number;
  correct_answer: string;
  score: number;
}


interface QuestionForm {
  content: string
  type: string
  position: string[]
  category: string
  tags: string[]
  competency_tags: CompetencyTag[]
  options: QuestionOption[]
  question_form: number
  suggestedDuration: number
  scoring_reference: string
  is_required_correct: Boolean
  blank_answer_template: BlankAnswer[]
  follow_up_count: number
}

// 对话框显示状态
const showQuestionDialog = ref(false)

// 监听对话框显示状态
watch(() => showQuestionDialog.value, (newVal) => {
  if (newVal && props.questionId) {
    fetchQuestionDetail(props.questionId);
  }
});

// 获取问题详情的函数
const fetchQuestionDetail = async (id: string | number) => {
  if (!id) return;

  try {
    const response = await api.GetObj({ question_id: id });

    if (response?.code === 2000 && response.data) {
      const questionData = response.data;
      // 更新表单数据
      questionForm.content = questionData.question || '';
      questionForm.type = questionData.question_form === 1 ? 'single' :
        questionData.question_form === 2 ? 'multiple' : questionData.question_form === 6 ? 'fill' : 'open';
      questionForm.position = questionData.position_types || [];
      questionForm.category = questionData.category_id || '';
      questionForm.tags = questionData.tags || [];
      const competencyTags = questionData.competency_tags || [];
      questionForm.competency_tags = competencyTags;
      questionForm.question_form = questionData.question_form;
      questionForm.suggestedDuration = questionData.recommended_duration || 0;
      questionForm.scoring_reference = questionData.scoring_reference || '';
      questionForm.is_required_correct = questionData.is_required_correct
      questionForm.follow_up_count = questionData.follow_up_count || 1;
      // 更新胜任力标签选择
      competencyTagsValue.value = competencyTags.map((tag: any) => tag.id);
       questionForm.options = questionData.options?.map((el: any) => {
        if (el) { // 检查 el 是否存在
          el.text = el.option_text;
        }
        return el; // 确保返回元素
      })|| []; // 可选：过滤掉 undefined/null 
    } else {
      ElMessage.warning('未找到问题详情数据');
    }
  } catch (error: any) {
    console.error('获取问题详情失败:', error);
    ElMessage.error(error.message || '获取问题详情失败');
  }
};

// 监听 questionId 变化
watch(() => props.questionId, (newVal) => {
  console.log(newVal)
  fetchQuestionDetail(newVal);
}, { immediate: true });



// 加载初始数据
onMounted(async () => {
  try {
    // 加载胜任力标签选项
    const competencyResponse = await api.GetCompetencyList({ page: 1, limit: 1000 })
    console.log(competencyResponse)
    if (competencyResponse && competencyResponse.code === 2000 && competencyResponse.data) {
      competencyTagOptions.value = competencyResponse.data.items.map((item: any) => ({
        id: item.id,
        name: item.name,
        weight: 0
      }));
    }

    // 加载职位选项
    const positionResponse = await api.GetPositionList({ page: 1, limit: 50, tenant_id: Session.get('tenant_id') });

    if (positionResponse && positionResponse.code === 2000 && positionResponse.data) {
      positionOptions.value = positionResponse.data.map((item: any) => ({
        value: item.id,
        label: item.title
      }));
    }

    // 加载分类选项
    const categoryResponse = await api.GetcategoryList({ page: 1, limit: 50, tenant_id: Session.get('tenant_id') })
    if (categoryResponse && categoryResponse.code === 2000 && categoryResponse.data.items) {
      categoryOptions.value = categoryResponse.data.items.map((item: any) => ({
        value: item.id,
        label: item.name
      }));
    }


    // 加载标签选项
    const tagResponse = await api.GetTagList({ page: 1, limit: 50, tenant_id: Session.get('tenant_id') });

    if (tagResponse && tagResponse.code === 2000 && tagResponse.data.items) {
      tagOptions.value = tagResponse.data.items.map((item: any) => ({
        value: item.id,
        label: item.name
      }));
    }
  } catch (error) {
    console.error('加载选项数据失败:', error);
    ElMessage.error('加载选项数据失败');
  }
});

// 表单数据
const questionForm = reactive<QuestionForm>({
  content: '',
  type: 'open',
  position: [],
  category: '',
  tags: [],
  competency_tags: [],
  options: [],
  question_form: 0,
  suggestedDuration: 0,
  scoring_reference: '',
  is_required_correct: false,
  follow_up_count: 1,
  blank_answer_template: []
})

// 胜任力标签相关
const competencyTagsValue = ref<number[]>([])
const competencyTagOptions = ref<CompetencyTag[]>([])

// 监听胜任力标签选择变化
watch(() => competencyTagsValue.value, (newVal) => {
  if (!newVal) return;

  // 根据选中的ID更新competency_tags
  questionForm.competency_tags = newVal.map(id => {
    const tag = competencyTagOptions.value.find(t => t.id === id);
    return {
      id: tag?.id || 0,
      name: tag?.name || '',
      weight: tag?.weight || 0
    };
  });

  // 如果有标签，自动平均分配权重
  if (questionForm.competency_tags.length > 0) {
    const averageWeight = Math.floor(100 / questionForm.competency_tags.length);
    const remainder = 100 - (averageWeight * questionForm.competency_tags.length);

    questionForm.competency_tags.forEach((tag, index) => {
      tag.weight = averageWeight + (index === 0 ? remainder : 0);
    });
  }
});

// 职位选项
interface PositionOption {
  value: string
  label: string
}
const positionOptions = ref<PositionOption[]>([])

// 分类选项
interface CategoryOption {
  value: string
  label: string
}
const categoryOptions = ref<CategoryOption[]>([])

// 标签选项
interface TagOption {
  value: string
  label: string
}
const tagOptions = ref<TagOption[]>([])

// 方法定义
const getTotalWeight = () => {
  return questionForm.competency_tags.reduce((sum, tag) => sum + (tag.weight || 0), 0)
}

const handleWeightChange = (index: number, value: number): void => {
  const tags = questionForm.competency_tags;
  if (!tags || tags.length <= 1) return;

  const oldWeight = tags[index].weight;
  const weightDiff = value - oldWeight;

  // 如果权重差为0，不需要调整
  if (weightDiff === 0) return;

  // 计算其他标签的总权重
  const otherTotalWeight = tags.reduce((sum, tag, i) => i !== index ? sum + tag.weight : sum, 0);

  // 如果其他标签总权重为0，平均分配剩余权重
  if (otherTotalWeight === 0) {
    const remainingWeight = 100 - value;
    const averageWeight = Math.floor(remainingWeight / (tags.length - 1));
    const remainder = remainingWeight - (averageWeight * (tags.length - 1));

    tags.forEach((tag, i) => {
      if (i !== index) {
        tag.weight = averageWeight + (i === 0 ? remainder : 0);
      }
    });
  } else {
    // 按比例调整其他标签的权重
    tags.forEach((tag, i) => {
      if (i !== index) {
        const proportion = tag.weight / otherTotalWeight;
        tag.weight = Math.max(0, Math.round(tag.weight - (weightDiff * proportion)));
      }
    });
  }
}

const handleQuestionTypeChange = (value: string) => {
  questionForm.question_form = value === 'single' ? 1 : value === 'multiple' ? 2 : 0
  if (value === 'single' || value === 'multiple') {
    if (!questionForm.options || questionForm.options.length === 0) {
      questionForm.options = [
        { text: '', is_correct: false, sort: 1 },
        { text: '', is_correct: false, sort: 2 }
      ]
    }
  } else if (value === 'open') {
    // 开放问题 - 初始化追问次数
    questionForm.question_form = 0;
    if (questionForm.follow_up_count === undefined) {
      questionForm.follow_up_count = 1;
    }
  } else {
    questionForm.blank_answer_template = [
      {
        blank_index: 1,
        correct_answer: '',
        score: 5
      }
    ]
  }
}

const handleOptionCorrectChange = (index: number) => {
  if (questionForm.question_form === 1) {
    // 单选题：只能有一个正确答案
    questionForm.options.forEach((item, idx) => {
      item.is_correct = (idx === index)
    })
  }
  // 多选题不需要特殊处理，直接使用checkbox的值
}

const addOption = () => {
  const sort = questionForm.options.length > 0 ?
    Math.max(...questionForm.options.map(o => o.sort || 0)) + 1 : 1
  questionForm.options.push({ text: '', is_correct: false, sort })
}

const removeLastOption = () => {
  if (questionForm.options && questionForm.options.length > 2) {
    questionForm.options.pop()
  }
}

// 重置表单数据
const resetForm = () => {
  questionForm.content = ''
  questionForm.type = 'open'
  questionForm.position = []
  questionForm.category = ''
  questionForm.tags = []
  questionForm.competency_tags = []
  questionForm.options = []
  questionForm.suggestedDuration = 0
  questionForm.scoring_reference = ''
  questionForm.is_required_correct = false
  questionForm.follow_up_count = 1
  questionForm.blank_answer_template = []
  competencyTagsValue.value = []
}

const cancelAddQuestion = () => {
  resetForm()
  showQuestionDialog.value = false
}

// 修改确认添加/编辑方法
const confirmAddQuestion = async () => {
  try {
    // 构建请求数据
    const requestData = {
      id: props.questionId,
      question: questionForm.content,
      question_form: questionForm.question_form,
      position_types: questionForm.position,
      category_id: questionForm.category,
      tags: questionForm.tags,
      competency_tags: questionForm.competency_tags,
      recommended_duration: questionForm.suggestedDuration,
      scoring_reference: questionForm.scoring_reference,
      is_required_correct: questionForm.is_required_correct,
      follow_up_count: questionForm.follow_up_count,
      options: questionForm.options?.map((el: any) => {
        if (el) { // 检查 el 是否存在
          el.option_text = el.text;
        }
        return el; // 确保返回元素
      }),
    };
    /*     console.log(questionForm)
    return */
    // 发送请求
    try {
      const response = await api.UpdateObj(requestData);

      if (response && response.code === 2000) {
        ElMessage.success(props.questionId ? '编辑成功' : '添加成功');
        showQuestionDialog.value = false;
        // 触发刷新事件
        window.dispatchEvent(new CustomEvent('refreshQuestionList'));
      } else {
        throw new Error(response.msg || '保存失败');
      }
    } catch (error: any) {
      throw new Error(error.message || '保存失败');
    }
  } catch (error: any) {
    console.error('保存问题失败:', error);
    ElMessage.error(error.message || '保存失败');
  }
};

// 导出方法供父组件使用
defineExpose({
  showQuestionDialog
})
</script>

<style scoped>
.question-dialog {
  .question-form {
    max-height: 60vh;
    overflow-y: auto;
    padding: 0 20px;
  }

  .form-item {
    margin-bottom: 20px;
  }

  .form-label {
    margin-bottom: 8px;
    font-weight: bold;
  }

  .form-tip {
    margin-top: 4px;
    color: #909399;
    font-size: 12px;
  }

  .required {
    color: #f56c6c;
    margin-left: 4px;
  }

  .full-width {
    width: 100%;
  }

  .competency-config {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 8px;
  }

  .config-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

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

  .config-label {
    width: 105px;
    margin-right: 10px;
  }

  .tag-name {
    flex: 1;
    margin-right: 10px;
  }

  .weight-sum {
    &.weight-error {
      color: #f56c6c;
    }
  }
}
</style>
