<template>
	<div class="answerTheResult">
		<div class="atr_detail">
			<div class="atr_d_btn" @click="lookDetail()">{{ isShowDialog ? lang.ssViewQ : lang.ssViewRes }}</div>
			<div class="atr_d_msg">
				<div>{{ lang.ssParticipants }}</div>
				<span
					>{{ workArrayLength }}/{{
						workArrayLength + unsubmittedStudentsLength
					}}</span
				>
			</div>

			<div class="atr_d_msg" v-if="workDetail && workDetail.type === '45'">
				<div>{{ lang.ssAccuracy }}</div>
				<span v-if="choiceQuestionListData[workIndex]">{{choiceQuestionListData[workIndex].accuracyRate}}%（{{choiceQuestionListData[workIndex].yes}}/{{choiceQuestionListData[workIndex].all}}）</span>
			</div>

			<div class="atr_d_msg" v-if="choiceQuestionAnswer">
				<div>{{ lang.ssCorrectAns }}</div>
				<span style="color: #03ae2b">{{ choiceQuestionAnswer }}</span>
			</div>
			<span class="atr_d_line" v-if="props.unsubmittedStudents && props.unsubmittedStudents?.length > 0"></span>

			<div class="no_submit" v-if="props.unsubmittedStudents && props.unsubmittedStudents?.length > 0">
				<div>{{ lang.ssUnsubStu }}</div>
				<img
					@click="showNoSubmitDetail = !showNoSubmitDetail"
					:class="{ no_submit_active: !showNoSubmitDetail }"
					src="../../../assets/img/arrow_up.png"
				/>
			</div>

			<div
				class="no_submitList"
				v-if="props.unsubmittedStudents && props.unsubmittedStudents?.length > 0"
				:class="{ no_submitList_active: showNoSubmitDetail }"
			>
				<div
					v-for="(student, idx) in props.unsubmittedStudents"
					:key="student.id ?? idx"
				>
					{{ student.name ?? "" }}
				</div>
			</div>

      <span class="atr_d_line" v-if="props.workArray && props.workArray?.length > 0"></span>

      <div class="is_submit" v-if="props.workArray && props.workArray?.length > 0">
				<div>{{ lang.ssSubStu }}</div>
				<img
					@click="showIsSubmitDetail = !showIsSubmitDetail"
					:class="{ is_submit_active: !showIsSubmitDetail }"
					src="../../../assets/img/arrow_up.png"
				/>
			</div>

			<div
				class="is_submitList"
				v-if="props.workArray && props.workArray?.length > 0"
				:class="{ is_submitList_active: showIsSubmitDetail }"
			>
				<div
					v-for="(student, idx) in props.workArray"
					:key="student.id ?? idx"
          @click="emit('openWorkModal', student)"
				>
					{{ student.name ?? "" }}
				</div>
			</div>
		</div>

		<div
			class="atr_type45Area"
			v-if="
				workDetail &&
				workDetail.type === '45' &&
				choiceQuestionListData[workIndex] &&
				choiceQuestionListData[workIndex].choiceUser
			"
		>

		<!-- <div class="atr_t45a_title" >
			<span>{{ workIndex+1 }}、{{ choiceQuestionListData[workIndex].type=='1'?'单选题':'多选题' }}：</span>
			<span>{{ choiceQuestionListData[workIndex].teststitle }}</span>
      <img @click="previewImage(choiceQuestionListData[workIndex].timuList[0].src)" :src="choiceQuestionListData[workIndex].timuList[0].src" v-if="choiceQuestionListData[workIndex].timuList.length>0">
		</div> -->

			<template
				v-for="(op, idx) in choiceQuestionListData[workIndex].choiceUser"
				:key="`${workIndex}_${idx}`"
			>
				<div class="atr_t45a_item">
					<div class="atr_t45a_i_top">
						<div class="atr_t45a_i_left">
							<span>{{ serialNumber[idx] }}</span>
							<div>
								<img 
									v-if="op.option.imgType" 
									:src="op.option.src"
									@click="previewImage(op.option.src)"
								/>
								<span v-else>{{ op.option }}</span>
								
							</div>
							<span v-if="op.isAnswer">{{ lang.ssCorrectTag }}</span>
						</div>
						<img
							@click="changeShow(op, idx)"
              v-if="op.user.length > 0"
							:class="{ show_active: !op.show }"
							src="../../../assets/img/arrow_up.png"
						/>
					</div>
					<div
						class="atr_t45a_i_bottom"
						v-if="op.user.length > 0 && op.show"
						:class="{ atr_t45a_i_b_active: op.show }"
					>
						<div
              
							v-for="(name, uIdx) in op.user"
							:key="`${workIndex}_${idx}_${uIdx}`"
						>
							{{ name }}
						</div>
					</div>
				</div>
			</template>

			<div class="nextAndUpBtn" v-if="choiceQuestionListData.length>1">
				<span :class="{no_active:workIndex==0}" @click="changeWorkIndex(0)">{{ lang.ssPrevQ }}</span>
				<span :class="{no_active:choiceQuestionListData.length-1<=workIndex}"  @click="changeWorkIndex(1)">{{ lang.ssNextQ }}</span>
			</div>
		</div>
	</div>

	<!-- 预览放大（带缩放/拖拽/旋转/工具栏） -->
  <previewImageTool ref="previewImageToolRef"/>
</template>

<script lang="ts" setup>
import { ref, computed, watch, inject, type Ref } from 'vue'
import previewImageTool from '../../components/tool/previewImageTool.vue'
import api from '../../../services/course'
import { lang } from '@/main'
interface Props {
	workArray?: object[] | null;
	unsubmittedStudents?: object[] | null;
	workId?: string | null;
  slideIndex?:number
  toolType?:number
}

const props = withDefaults(defineProps<Props>(), {
  workArray: () => [],
  unsubmittedStudents: () => [],
  workId: '',
  toolType: 0,
  slideIndex: 0
})

const emit = defineEmits<{
  (e: 'openChoiceQuestionDetail', v: number): void,
  (e: 'openWorkModal', v:any):void
}>()

const choiceQuestionDetailDialogOpenList = inject<Ref<number[]>>('choiceQuestionDetailDialogOpenList', ref<number[]>([]))
const isShowDialog = computed(() => {
  return choiceQuestionDetailDialogOpenList.value.includes(props.slideIndex)
})


// 已提交的作业数量
const workArrayLength = computed(() => {
  let _result = 0
  if (props.workArray) {
    _result = props.workArray.length
  }
  return _result
})
// 未提交的作业数量
const unsubmittedStudentsLength = computed(() => {
  let _result = 0
  if (props.unsubmittedStudents) {
    _result = props.unsubmittedStudents.length
  }
  return _result
})

// 选项序号
const serialNumber = ref<string[]>([
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
])

// 第几题
const workIndex = ref<number>(0)

// 是否显示未提交人员
const showNoSubmitDetail = ref<boolean>(false)
const showIsSubmitDetail = ref<boolean>(false)

// 作业详细
const workDetail = ref<any>({})

// 获取作业详细
const getWorkDetail = async () => {
  if (props.workId) {
    const _res = await api.getWorkDetail({ id: props.workId })
    const _data = _res[0][0]
    if (_data) {
      _data.json = JSON.parse(_data.json)
      workDetail.value = _data
      choiceQuestionListData.value = choiceQuestionList()
    }
  }
}

// 选择题题目数组
const choiceQuestionList = () => {
  let _result: any[] = []
  if (workDetail.value && workDetail.value.type === '45') {
    const _workData = workDetail.value.json.testJson
    _workData.forEach((item: any, index: number) => {
      // 修复 props.workArray 可能为 null 的问题
      item.choiceUser = []
      item.yes = 0
      item.no = 0
      item.checkList.forEach((op: any, oidx: number) =>
        item.choiceUser.push({
          index: serialNumber.value[oidx],
          option: op,
          user: [],
          show: false,
          isAnswer: Array.isArray(item.answer)
            ? item.answer.includes(oidx)
            : item.answer === oidx,
        })
      )
    });
    (props.workArray ?? []).forEach(
      (studentWork: any, studentIndex: number) => {
        const _studentContent: any = JSON.parse(
          decodeURIComponent(studentWork.content)
        ).testJson
        // let _studentContentCorrection = []
        // console.log(_workData)
        // console.log(_studentContent)
        // _studentContentCorrection = _workData.map((i:any) => {
        //   return _studentContent.find((i2:any) => {
        //     return (JSON.stringify({testtitle: i2.testtitle, checkList: i2.checkList, timuList: i2.timuList}) === JSON.stringify({testtitle: i.testtitle, checkList: i.checkList, timuList: i.timuList}))
        //   })
        // })
        // console.log(_studentContentCorrection)
        _studentContent.forEach((test: any, testIndex: number) => {
          if (_workData[testIndex] && JSON.stringify({testtitle: test.testtitle, checkList: test.checkList, timuList: test.timuList}) === JSON.stringify({testtitle: _workData[testIndex].testtitle, checkList: _workData[testIndex].checkList, timuList: _workData[testIndex].timuList}) && (test.userAnswer || test.userAnswer === 0)) {
            if (Array.isArray(test.userAnswer)) {
              test.userAnswer.forEach((ch: number) => {
                _workData[testIndex].choiceUser[ch].user.push(studentWork.name)
              })
              if (
                JSON.stringify(
                  test.userAnswer.sort((a: number, b: number) => a - b)
                ) === JSON.stringify(_workData[testIndex].answer.sort((a: number, b: number) => a - b))
              ) {
                _workData[testIndex].yes += 1
              }
              else {
                _workData[testIndex].no += 1
              }
            }
            else {
              _workData[testIndex].choiceUser[test.userAnswer].user.push(
                studentWork.name
              )
              if (test.userAnswer === _workData[testIndex].answer) {
                _workData[testIndex].yes += 1
              }
              else {
                _workData[testIndex].no += 1
              }
            }
          }
        })
      }
    )

    _workData.forEach((item:any) => {
      item.all = item.yes + item.no
      if (item.all === 0) {
        item.accuracyRate = 0
      }
      else {
        const rate = (item.yes / item.all) * 100
        item.accuracyRate = Number.isInteger(rate) ? rate : Number(rate.toFixed(2))
      }
    })

    _result = _workData
  }

  return _result
}


const choiceQuestionListData = ref<any[]>([])

// 选择题题目正确答案
const choiceQuestionAnswer = computed(() => {
  let _result = ''
  if (
    workDetail.value &&
		workDetail.value.type === '45' &&
		workDetail.value.json.testJson[workIndex.value]
  ) {
    const _answer = workDetail.value.json.testJson[workIndex.value].answer
    if (Array.isArray(_answer)) {
      _result = _answer.map((i: any) => serialNumber.value[i]).join('、')
    }
    else {
      _result = [serialNumber.value[_answer]].join('、')
    }
  }

  return _result
})


// //当前题目正确率
// const choiceQuestionAccuracyRate = computed

// 监听作业Id
watch(
  () => props.workId,
  (newVal, oldVal) => {
    console.log('props.workId变化', { newVal, oldVal })
    if (newVal && newVal !== oldVal) {
      getWorkDetail()
    }
  },
  { immediate: true }
)


// 监听已提交的作业
watch(() => props.workArray, (newVal, oldVal) => {
  if (newVal && newVal !== oldVal) {
    choiceQuestionListData.value = choiceQuestionList()
    // choiceQuestionAnswerData.value = choiceQuestionAnswer()
  }
}, { immediate: true })

// 切换题目
const changeWorkIndex = (type:number) => {
  if (type === 0) {
    if (workIndex.value === 0) return
    workIndex.value -= 1
  }
  else if (type === 1) {
    if (choiceQuestionListData.value.length - 1 <= workIndex.value) return
    workIndex.value += 1
  }
}

// 切换题目展示所有人选项
const changeShow = (op: any, idx: number) => {
  choiceQuestionListData.value[workIndex.value].choiceUser[idx].show = !choiceQuestionListData.value[workIndex.value].choiceUser[idx].show
}

const lookDetail = () => {
  console.log(props.toolType)
  if ([45, 15, 72, 73].includes(props.toolType)) {
    emit('openChoiceQuestionDetail', props.slideIndex)
  }
}

const previewImageToolRef = ref<any>(null)
const previewImage = (url:string) => {
  previewImageToolRef.value.previewImage(url)
}


defineExpose({
  workDetail,
  choiceQuestionListData,
  workIndex,
  workArray: props.workArray,
  unsubmittedStudents: props.unsubmittedStudents,
  toolType: props.toolType,
  changeWorkIndex
})

</script>

<style lang="scss" scoped>
.answerTheResult {
	width: 100%;
	height: auto;
	max-height: 100%;
	overflow: auto;
	box-sizing: border-box;
	padding: 12px;
	.atr_detail {
		width: 100%;
		height: auto;
		border-radius: 4px;
		padding: 10px 15px 10px 15px;
		box-sizing: border-box;
		border: solid 1px rgba(0, 0, 0, 0.1);
		.atr_d_btn {
			width: 100%;
			height: 40px;
			display: flex;
			align-items: center;
			justify-content: center;
			background: rgba(0, 0, 0, 0.9);
			color: #fff;
			font-weight: 500;
			font-size: 14px;
			border-radius: 4px;
			cursor: pointer;
		}

		.atr_d_msg {
			width: 100%;
			display: flex;
			align-items: center;
			margin-top: 15px;
			font-size: 14px;
			color: rgba(0, 0, 0, 0.9);
			& > div {
				width: 4em;
				margin-right: 35px;
				font-weight: 500;
			}
		}

		.atr_d_line {
			width: 100%;
			height: 2px;
			display: block;
			background: rgba(242, 243, 245, 1);
			margin: 20px 0;
			border-radius: 2px;
		}

		.no_submit {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 14px;
			font-weight: 500;
			margin-bottom: 20px;
			.no_submit_active {
				transform: rotate(180deg);
			}
			& > img {
				cursor: pointer;
			}
		}

		.no_submitList {
			width: 100%;
			display: flex;
			align-items: center;
			flex-wrap: nowrap;
			overflow: hidden;
			gap: 10px;
			& > div {
				padding: 5px 10px;
				background: rgba(255, 236, 232, 1);
				color: rgba(245, 63, 63, 1);
				font-size: 14px;
				font-weight: 500;
				border-radius: 10px;
        white-space: nowrap;
			}
		}
		.no_submitList_active {
			flex-wrap: wrap;
		}

    .is_submit {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 14px;
			font-weight: 500;
			margin-bottom: 20px;
			.is_submit_active {
				transform: rotate(180deg);
			}
			& > img {
				cursor: pointer;
			}
		}

		.is_submitList {
			width: 100%;
			display: flex;
			align-items: center;
			flex-wrap: nowrap;
			overflow: hidden;
			gap: 10px;
			& > div {
				padding: 5px 10px;
				background: #fff;
				color: #2F80ED;
				font-size: 14px;
				font-weight: 500;
				border-radius: 10px;
        white-space: nowrap;
        box-sizing: border-box;
        border: solid 1px #2F80ED;
        cursor: pointer;
			}
		}
		.is_submitList_active {
			flex-wrap: wrap;
		}
	}

	.atr_type45Area {
		width: 100%;
		height: auto;
		.atr_t45a_title{
			width: 100%;
			height: auto;
			box-sizing: border-box;
			padding: 10px 15px 10px 15px;
			border: solid 1px #0000001a;
			border-radius: 4px;
			margin-top: 20px;
			font-size: 14px;
			font-weight: 600;
      img{
        width: auto;
        max-width: 100%;
        height: auto;
        object-fit: cover;
        cursor: pointer;
        display: block;
      }
		}
		.atr_t45a_item {
			width: 100%;
			height: auto;
			box-sizing: border-box;
			padding: 10px 15px 10px 15px;
			border: solid 1px #0000001a;
			border-radius: 4px;
			margin-top: 20px;
			.atr_t45a_i_top {
				width: 100%;
				height: auto;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.atr_t45a_i_left {
					width: calc(100% - 50px);
					height: auto;
					display: flex;
					align-items: center;
					& > span:nth-child(1) {
						display: block;
						width: 20px;
						height: 20px;
						background: #fccf00;
						border-radius: 50%;
						padding: auto;
						box-sizing: border-box;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 14px;
						font-weight: 500;
						color: #fff;
						margin-right: 10px;
					}
					& > div {
						font-size: 14px;
						font-weight: bold;
						max-width: calc(100% - 20px - 10px - 45px);
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						display: block;
						position: relative;
						&>img{
							width: 20px;
							height: 20px;
							object-fit: cover;
							cursor: pointer;
						}
					}
					& > span:nth-of-type(2) {
						display: block;
						padding: 2px 4px;
						border-radius: 2px;
						background: #aff0b580;
						color: #03ae2b;
						font-size: 12px;
						font-weight: 400;
						margin-left: 10px;
					}
				}
				& > img {
					width: 16px;
					height: 16px;
					margin-left: 20px;
					cursor: pointer;
				}
				.show_active {
					transform: rotate(180deg);
				}
			}
			.atr_t45a_i_bottom {
				width: 100%;
				display: flex;
				align-items: center;
				flex-wrap: nowrap;
				overflow: hidden;
				gap: 10px;
				margin-top: 10px;
				& > div {
					padding: 5px 10px;
					background: #0000000f;
					color: #222222;
					font-size: 14px;
					font-weight: 500;
					border-radius: 10px;
				}
			}
			.atr_t45a_i_b_active {
				flex-wrap: wrap !important;
			}
		}
		.nextAndUpBtn{
			width: 100%;
			height: auto;
			display: grid;
			grid-template-columns: 1fr 1fr;
			margin-top: 20px;
			gap: 15px;
			&>span{
				display: flex;
				justify-content: center;
				align-items: center;
				width: 100%;
				height: 40px;
				border-radius: 5px;
				font-size: 14px;
				font-weight: 500;
				color: #fff;
				background: #3681FC;
				cursor: pointer;
			}
			&>.no_active{
				background: #cccccc !important;
				color: #999999 !important;
				cursor: not-allowed !important;
				pointer-events: none !important;
			}
		}
	}
}
</style>
