<script setup lang="ts">
import SingleChoice from '@c/question/answer/SingleChoice.vue'
import Judgment from '@c/question/answer/Judgment.vue'
import JudgmentCloze from '@c/question/answer/JudgmentCloze.vue'
import MultipleChoice from '@c/question/answer/MultipleChoice.vue'
import ClozeTest from '@c/question/answer/ClozeTest.vue'
import Other from '@c/question/answer/Other.vue'
import HandDrawn from '@c/question/answer/HandDrawn.vue'
import Input from '@c/question/answer/Input.vue'
import { useAudio, TypeSet } from '@/hooks'
import homeWorkApi from '@/api/system/homeWork'
import EchartsBar from '@/page/system/homework/reports/components/EchartsBar.vue'
import { useRoute } from 'vue-router'

const props = defineProps<{
  data: any
  idx: number
  reportFlag: number
  uploadFile: any
  beforeUpload: any
  isDeadline: boolean
}>()

const emit = defineEmits(['submit', 'handleTime', 'showPic', 'beforeUpload', 'uploadError'])

const route = useRoute()

const component = computed(() => {
  console.log(props.data)
  if (props.data?.autoMarkFlag === 0) {
    // 不可自动批改
    if (props.data?.titleChannelTypeName === '填空题') {
      // 不可自动批改的填空题
      return HandDrawn
    }
    if (props.data?.subjectId === 3 && props.data?.titleChannelTypeName === '解答题') {
      // 数学解答题
      return HandDrawn
    }
    return Other
  }
  if (props.data?.fillBlankNum) {
    // 填空题
    return Input
  }
  // 选项为多个选项组时完形填空
  if (props.data?.optionList?.length > 1) {
    if (['判断', '判断题'].includes(props.data?.titleChannelTypeName)) {
      return JudgmentCloze
    }
    return ClozeTest
  }

  if (props.data?.titleChannelTypeName === '多选题') {
    return MultipleChoice
  }

  if (['判断', '判断题'].includes(props.data?.titleChannelTypeName)) {
    return Judgment
  }

  // 其他题型有optionList时为单选题，否则是应用题
  return props.data?.optionList?.[0]?.length ? SingleChoice : Other
})

// 图片预览
const imgDia = reactive({
  show: false,
  url: '',
})
function handleShow(url: string) {
  if (url) {
    imgDia.show = true
    imgDia.url = url
  }
}

const resultClass = computed(() => {
  return (data: any) => {
    if (!data)
      return {
        class: 'info',
        text: 0 + '分',
        // icon: 'emoji_info',
      }
    if (data.titleStatus === 2) {
      return {
        class: 'wait',
        text: '待批改',
        // icon: 'emoji_info',
      }
    } else if (!data.markFlag && !data.submitAnswer && !data.submitAnswerPic) {
      return {
        class: 'empty',
        text: '未作答',
        icon: 'emoji_empty',
      }
    } else if (data.markFlag) {
      return {
        class: 'success',
        text: '答对啦',
        icon: 'emoji_success',
      }
    } else if (!data.markFlag && data.answerScore === 0) {
      return {
        class: 'error',
        text: '答错了',
        icon: 'emoji_fail',
      }
    } else {
      return {
        class: 'info',
        text: data.answerScore + '分',
        // icon: 'emoji_info',
      }
    }
  }
})

// 给子题目添加序号
const filterTitle = computed(() => {
  return (title: string | undefined, cidx?: number) => {
    if (title) {
      const t = title.replace(/http:\/\//gi, 'https://')
      // .replace(/contenteditable/g, 'no-contenteditable');
      if (cidx !== undefined) {
        return `(${cidx + 1})` + t
      } else {
        return t
      }
    }
    return undefined
  }
})

/**
 * @description: 音频
 */
// 音频是否正在播放
const isAudioPlay = ref(false)
// 音频播放器
let audioPlayer: anyObj = {}
// 播放音频
function playAudio() {
  if (isAudioPlay.value) {
    audioPlayer.pause()
  } else {
    audioPlayer.src = props.data?.voiceUrl
    audioPlayer.play()
  }
}

// 填空题 同步答案
const quizList = ref<anyObj[]>([])
function inputChange(val: string, idx: number) {
  quizList.value[idx].innerText = val
}

const jobStuStatistics = ref<anyObj>([])

const rightRef = ref()
const echartsRef = ref()
const echartsData = reactive<{ xData: string[]; seriesVal: anyObj[] }>({
  xData: [],
  seriesVal: [],
})
watch(
  () => props.data?.jobStuTittleId,
  async nv => {
    if (nv) {
      // 切换题目时初始化音频 初始化右边区域滑动条
      audioPlayer?.pause?.()
      rightRef.value && (rightRef.value.scrollTop = 0)
      await nextTick()
      TypeSet([document.querySelector('.question-item')])
      // 题目里所有图片添加点击放大查看事件
      document.querySelectorAll('.dowork .left-title img').forEach((i: anyObj) => {
        i?.addEventListener('click', () => {
          handleShow(i?.src)
        })
      })
      document.querySelectorAll('.dowork .choice-box img').forEach((i: anyObj) => {
        i?.addEventListener('click', (e: any) => {
          handleShow(i?.src)
          e?.stopPropagation?.()
        })
      })
      document.querySelectorAll('.dowork .answer-box-main img').forEach((i: anyObj) => {
        i?.addEventListener('click', () => {
          handleShow(i?.src)
        })
      })
      document.querySelectorAll('.dowork .analyze-title img').forEach((i: anyObj) => {
        i?.addEventListener('click', () => {
          handleShow(i?.src)
        })
      })

      if (props.reportFlag) {
        const { data: res } = await homeWorkApi.getJobStatistics({
          titleId: props.data.id,
          jobId: props.data.jobId,
          stuId: route.query.stuId || '',
        })

        jobStuStatistics.value = res.data?.map((i: anyObj) => i.scStuList) || []
        echartsData.xData = []
        echartsData.seriesVal = []
        res.data?.forEach((i: anyObj) => {
          echartsData.xData.push(i.intervalValue + '分')
          echartsData.seriesVal.push({
            value: i.num,
            itemStyle: {
              color: i.curFlag ? '#FE8200' : '#7FADFF',
            },
          })
        })
        nextTick(() => {
          echartsRef.value?.drawGraph()
        })
      }

      // 填空题 同步答案
      if (props.data?.fillBlankNum) {
        quizList.value = []
        document
          .querySelectorAll('.quizPutTag[contenteditable]')
          .forEach((i: anyObj, idx: number) => {
            i.setAttribute('contenteditable', false)
            i.innerText = props.data.submitAnswer?.split(',')?.[idx] || ''
            quizList.value.push(i)
          })
      }
    }
  },
  { immediate: true },
)
const xlDia = reactive<{ show: boolean; data: anyObj[] }>({
  show: false,
  data: [],
})

function handleBarClick(params: anyObj) {
  const arr = jobStuStatistics.value[params.dataIndex]
  if (arr?.length) {
    xlDia.show = true
    xlDia.data = arr.map((i: anyObj) => ({
      id: i.id,
      name: i.stuName,
    }))
  }
}

;(() => {
  nextTick(() => {
    audioPlayer = useAudio({
      autoplay: false,
    })
    audioPlayer.on('play', () => {
      isAudioPlay.value = true
    })
    audioPlayer.on('pause', () => {
      isAudioPlay.value = false
    })
    audioPlayer.on('ended', () => {
      isAudioPlay.value = false
    })
  })
})()

onUnmounted(() => {
  audioPlayer?.destroy?.()
  isAudioPlay.value = false
})
</script>
<template>
  <div class="question-item">
    <div class="left hidden_scroll">
      <div class="left-subType">{{ idx }}. ({{ data?.score }}分) {{ data?.channelTypeName }}</div>
      <div v-if="data?.title" class="left-title" v-html="filterTitle(data?.title)"></div>
      <div v-if="data?.voiceUrl" class="left-voice">
        <Horn :active="isAudioPlay" @click="playAudio"></Horn>
      </div>
      <div v-if="data?.children?.length" class="left-children">
        <template v-for="(c, idx) in data?.children" :key="c.id">
          <div class="left-title" v-html="filterTitle(c?.title, idx)"></div>
        </template>
      </div>
    </div>
    <div ref="rightRef" class="right hidden_scroll">
      <!-- 批改结构 -->
      <div class="result-box">
        <div v-if="isDeadline && reportFlag" :class="['result', resultClass(data).class]">
          <div>我的答案</div>
          <div class="emoji-box">
            <div class="emoji">
              <Icon
                v-if="resultClass(data).icon"
                :name="resultClass(data).icon || ''"
                width="48"
              ></Icon>
            </div>
            {{ resultClass(data).text }}
          </div>
        </div>
      </div>
      <!-- 答题区域 -->

      <component
        :is="component"
        :reportFlag="Number(reportFlag)"
        class="answer-com"
        :titleId="data?.id"
        :optionList="data?.optionList || undefined"
        :answer="data?.answer"
        :submitAnswer="data?.submitAnswer"
        :submitAnswerPic="data?.submitAnswerPic"
        :submitAnswerPicOriginal="data?.submitAnswerPicOriginal"
        :isAndroid="data?.isAndroid"
        :markAnswerPic="data?.markAnswerPic"
        :markAnswer="data?.markAnswer"
        :fillBlankNum="data?.fillBlankNum"
        :isDeadline="isDeadline"
        :uploadLoading="data?.uploadLoading"
        :uploadFile="uploadFile"
        :beforeUpload="beforeUpload"
        @submit="
          emit('submit', {
            ...$event,
            id: data?.jobStuTittleId,
          })
        "
        @handleTime="emit('handleTime', $event)"
        @showPic="handleShow"
        @inputChange="inputChange"
      >
        <template #markAnswer>
          <div v-if="isDeadline && reportFlag && data?.markAnswer" class="markAnswerPic">
            <div class="answer-box">
              <div class="answer-box-title">批改说明</div>
            </div>
            <div class="text-box">
              {{ data?.markAnswer }}
            </div>
          </div>
        </template>
      </component>

      <!-- 答案与解析 -->
      <template v-if="isDeadline && reportFlag">
        <div v-if="echartsData.xData.length" class="answer-box">
          <div class="answer-box-title">答题统计</div>
          <div class="answer-box-echarts">
            <EchartsBar
              ref="echartsRef"
              :data="echartsData"
              yName="（人）"
              @handleBarClick="handleBarClick"
            ></EchartsBar>
          </div>
        </div>
        <div v-if="data?.answer" class="answer-box">
          <div class="answer-box-title">参考答案</div>
          <div class="answer-box-main" v-html="data?.answer"></div>
        </div>
        <!-- 暂时隐藏 data.titleAnalyzeJson -->
        <div
          v-if="data?.titleAnalyze || data?.titleAnalyzePicture"
          class="answer-box"
          style="margin-top: 60px"
        >
          <div class="answer-box-title">解析</div>
          <div v-if="data?.titleAnalyze" class="answer-box-main analyze analyze-title">
            <div class="titleAnalyze" v-html="data?.titleAnalyze"></div>
          </div>
          <div v-if="data?.titleAnalyzePicture" class="answer-box-main analyze analyze-pic">
            <div
              v-for="i in data.titleAnalyzePicture.split(',')"
              :key="i"
              class="titleAnalyzePicture"
              @click="handleShow(i)"
            >
              <img :src="i" />
            </div>
          </div>
        </div>
      </template>
    </div>
    <ImgView v-model="imgDia.show" :url="imgDia.url"></ImgView>
    <XLDia v-model="xlDia.show" title="对应学员">
      <div class="stu_list">
        <div v-for="i in xlDia.data" :key="i.id" class="stu_list-item">
          {{ i.name }}
        </div>
      </div>
    </XLDia>
  </div>
</template>
<style scoped lang="scss">
.question-item {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 2.67vh;
  display: flex;
  align-items: center;
  &::before {
    position: absolute;
    left: 50%;
    bottom: 2.67vh;
    transform: translate(-50%);
    content: '';
    display: block;
    width: 6px;
    height: calc(100% - 64px);
    border-radius: 0.5vh;
    background: repeating-linear-gradient(
      to bottom,
      #cdd5ff,
      #cdd5ff 8px,
      transparent 10px,
      transparent 20px /* 线条间隔 */
    );
  }

  .left {
    width: calc(50% - 3px);
    height: 100%;
    padding-right: 48px;

    // word-break: break-all;
    word-break: normal;
    word-wrap: break-word;
    overflow-y: auto;

    &-subType {
      color: #666;
      font-family: 'OPPO Sans';
      font-size: 2.67vh;
      font-style: normal;
      font-weight: 400;
      line-height: 4vh; /* 150% */
      margin-bottom: 2vh;
    }
    &-title {
      padding-left: 40px;
      color: $font-color;
      font-family: 'OPPO Sans';
      font-size: 2.67vh;
      font-style: normal;
      font-weight: 400;
      // line-height: 48px; /* 150% */
      line-height: 1.8em;
      // overflow-x: hidden;
    }
    &-voice {
      padding-left: 40px;
      margin-top: 2vh;
    }
    &-children {
      padding-left: 40px;
      color: $font-color;
      font-family: 'OPPO Sans';
      font-size: 2.67vh;
      font-style: normal;
      font-weight: 400;
      line-height: 4vh; /* 150% */
      // &-item {
      //     display: flex;
      //     flex-wrap: wrap;
      // }
      margin-top: 1.33vh;
      .left-title {
        padding-left: 0;
      }
    }
  }
  .right {
    width: calc(50% - 3px);
    height: 100%;
    padding-left: 48px;
    padding-right: 40px;
    padding-top: 1.33vh;
    .result-box {
      width: 100%;
      height: 4vh;
      margin-bottom: 2vh;
    }
    .result {
      padding: 0 20px 0 32px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      color: $font-color;
      font-family: $font-special;
      font-size: 2.67vh;
      font-style: normal;
      font-weight: 400;
      line-height: 4vh; /* 150% */
      border-radius: 0.33vh;
      &::before {
        content: '';
        width: 12px;
        height: 100%;
        flex-shrink: 0;
        position: absolute;
        top: 0;
        left: 0;
        background-color: #669cfe;
        border-radius: 0 1vh 1vh 0;
      }
      &.error {
        background: linear-gradient(90deg, rgba(255, 191, 191, 0) 0%, #ffbfbf 100%);
      }
      &.success {
        background: linear-gradient(90deg, rgba(221, 255, 140, 0) 0%, #ddff8c 100%);
      }
      &.empty {
        background: linear-gradient(90deg, rgba(255, 191, 191, 0) 0%, #ffbfbf 100%);
      }
      &.wait {
        background: linear-gradient(90deg, rgba(190, 213, 254, 0) 0%, #bed5fe 100%);
      }
      &.info {
        background: linear-gradient(90deg, rgba(190, 213, 254, 0) 0%, #bed5fe 100%);
      }
      .emoji-box {
        display: flex;
        align-items: center;
        .emoji {
          width: 48px;
          height: 4vh;
          margin-right: 16px;
        }
      }
    }
    .answer-com {
      // max-height: calc(100% - 100px);
    }
    .answer-box {
      margin-top: 4vh;
      &-title {
        padding: 0 20px 0 32px;
        position: relative;
        color: $font-color;
        // font-family: $font-special;
        font-family: 'OPPO Sans';
        font-size: 2.67vh;
        font-style: normal;
        font-weight: 400;
        line-height: 4vh; /* 150% */
        border-radius: 0.33vh;
        margin-bottom: 2vh;
        &::before {
          content: '';
          width: 12px;
          height: 100%;
          flex-shrink: 0;
          position: absolute;
          top: 0;
          left: 0;
          background-color: #669cfe;
          border-radius: 0 1vh 1vh 0;
        }
      }
      &-echarts {
        height: 28.33vh;
      }
      &-main {
        color: $font-color;
        font-family: 'OPPO Sans';
        font-size: 2.67vh;
        font-style: normal;
        font-weight: 400;
        line-height: 4vh; /* 150% */
        padding-left: 32px;
        box-sizing: border-box;
        width: 100%;
        &.analyze {
          // padding-left: 0;
          width: 100%;
          &.analyze-pic {
            margin-top: 2vh;
            img {
              max-width: 100%;
              max-height: 66.67vh;
              object-fit: contain;
            }
            .titleAnalyzePicture {
              margin-bottom: 1vh;
              &:last-child {
                margin-bottom: 0;
              }
            }
          }
          &.analyze-title {
            margin-top: 2vh;

            .titleAnalyze {
              color: $font-color;
              font-family: 'OPPO Sans';
              font-size: 2.67vh;
              font-style: normal;
              font-weight: 400;
              line-height: 4vh; /* 150% */
            }
          }
        }
      }
    }
    .text-box {
      // color: $font-color;
      // font-family: $font-special;
      font-size: 2.67vh;
      font-style: normal;
      font-weight: 400;
      line-height: 4vh; /* 150% */
      padding-left: 48px;
    }
  }
}
.xl-dia {
  :deep(.xl-dia-main) {
    padding: 2.33vh;
  }
  .stu_list {
    display: flex;
    align-items: start;
    flex-wrap: wrap;
    height: 100%;
    @include hidden_scroll;
    &-item {
      border-radius: 3.5vh;
      border: 0.17vh solid $font-color;
      padding: 1.33vh 32px;
      color: $font-color;
      text-align: center;
      font-family: OPPOSans;
      font-size: 2.67vh;
      margin: 1vh;
    }
  }
}
</style>
