<template>
  <div class="choice-statistics-panel">
    <div v-if="isChoiceQuestion && statistics" class="statistics-content">
      <div class="statistics-title">{{ lang.ssChoiceStat }}</div>
      <div class="statistics-summary">
        {{ lang.ssTotalSub.replace(/\*/g, String(statistics.totalSubmissions)) }}
      </div>
    </div>
    <div v-else class="statistics-empty">
      <div v-if="!isChoiceQuestion">{{ lang.ssNotChoice }}</div>
      <div v-else-if="!statistics">{{ lang.ssNoStat }}</div>
    </div>

		<div class="statistics-chart">
				<div class="tool45" v-if="statistics && statistics.tool=='45'">
					<div v-for="(item,index) in statistics.titles" :key="index">
						<div class="t45_title">
							<span>{{ index+1 }}、</span>
							<div>{{ item.title }}</div>
						</div>
            <div class="t45_btn">
              <span @click="lookStudent(item.checkList)">{{ lang.ssViewStu }}</span>
            </div>
						<div class="t45_list">
							<div class="t45_l_item" v-for="(i,index2) in item.checkList" :key="index+'_'+index2">
								<div class="t45_l_i_option">
									<span>{{ i.index }}</span>
                  <span>:</span>
									<div>
										<div :style="{width:i.proportion}"></div>
									</div>
									<span>{{ i.proportion }}</span>
								</div>
								<!-- <div class="t45_l_i_user">
									<template v-for="(j,index3) in i.user" :key="index+'_'+index2+'_'+index3">
										<div  v-if="item.showAllUser || (!item.showAllUser && index3 < 3)">
											<span>{{ j }}</span>
										</div>
									</template>
									<span class="t45_o_btn" v-if="i.user.length > 3 && !item.showAllUser" @click="()=>{item.showAllUser = true,$forceUpdate()}">
										<svg t="1756278651830" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7545" width="200" height="200"><path d="M293.546667 253.013333l264.533333 266.666667-264.106667 266.24 70.4 70.826667 334.506667-337.066667-334.933333-337.066667z" p-id="7546"></path></svg>
									</span>
									<span class="t45_o_btn" v-if="i.user.length > 3 && item.showAllUser" @click="()=>{item.showAllUser = false,$forceUpdate()}">
										<svg style="transform: rotate(180deg);" t="1756278651830" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7545" width="200" height="200"><path d="M293.546667 253.013333l264.533333 266.666667-264.106667 266.24 70.4 70.826667 334.506667-337.066667-334.933333-337.066667z" p-id="7546"></path></svg>
									</span>
								</div> -->
							</div>
						</div>
					</div>
				</div>
      </div>
  </div>

  <Modal :visible="visible" :width="720" :closeButton="true" @update:visible="visible = false">
    <div class="userBox">
			<div class="ub_item" v-for="(item,index) in userCheckList" :key="index">
				<div class="ub_i_options">{{ item.options }}</div>
        <div class="ub_i_user">
          <span>{{ lang.ssSelStu }}</span>
          <div class="ub_i_u_item" v-for="(item2,index2) in item.user" :key="index+'_'+index2">{{ item2 }}</div>
        </div>
			</div>
		</div>
  </Modal>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { ElementTypes } from '@/types/slides'
import Modal from '@/components/Modal.vue'
import { lang } from '@/main'

interface Props {
  workArray: any[]
  elementList: any[]
}

const props = defineProps<Props>()

const visible = ref<boolean>(false)

let userCheckList = reactive<any[]>([])

// 检查当前是否为选择题（toolType为45）
const isChoiceQuestion = computed(() => {
  const frame = props.elementList.find(element => element.type === ElementTypes.FRAME)
  return frame?.toolType === 45
})

const optionList: Array<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 lookStudent = (checkList:any) => {
  userCheckList = checkList
  visible.value = true

}

// 选择题统计信息
const statistics = computed(() => {
  if (!isChoiceQuestion.value || !props.workArray || props.workArray.length === 0) return null

  // 统计信息结构优化
  let titles: Array<{
    title: string,
		showAllUser: boolean,
    checkList: Array<{ options: string, num: number, proportion: string, index :string, user: Array<[]>}>
  }> = []
  let totalSubmissions = 0

  let tool: string = ''

  // 只初始化一次题目结构
  let isTitleInitialized = false

  props.workArray.forEach((work) => {
    if (!work.content) return
    try {
      if (work.atool === '45') {
        const content = JSON.parse(decodeURIComponent(work.content))
        const testJson = content.testJson

        // 初始化题目结构
        if (!isTitleInitialized && Array.isArray(testJson)) {
          tool = work.atool
          titles = testJson.map((item: any) => ({
            title: item.teststitle || '',
            showAllUser: false,
            checkList: Array.isArray(item.checkList)
              ? item.checkList.map((i: any) => ({ options: i, num: 0, user: [], proportion: '', index: '' }))
              : []
          }))
          isTitleInitialized = true
        }

        // 统计每道题的选项被选择次数
        if (Array.isArray(titles) && Array.isArray(testJson)) {
          testJson.forEach((item: any, index: number) => {
            const answer = item.userAnswer
            if (typeof answer === 'number') {
              if (titles[index] && titles[index].checkList[answer]) {
                titles[index].checkList[answer].num += 1
                titles[index].checkList[answer].user.push(work.name)
              }
            } 
            else if (Array.isArray(answer) && answer.length > 0) {
              answer.forEach((i: number) => {
                if (titles[index] && titles[index].checkList[i]) {
                  titles[index].checkList[i].num += 1
                  titles[index].checkList[i].user.push(work.name)
                }
              })
            }
          })
        }
        totalSubmissions++
      }
    } 
    catch (e) {
      // eslint-disable-next-line no-console
      console.log('解析选择题答案失败:', e, work.content)
    }
  })

  titles.forEach((item: any) => {
    const total = item.checkList.reduce((sum: number, cur: any) => sum + cur.num, 0)
    item.checkList.forEach((option: any, index :number) => {
      option.proportion = total > 0 ? ((option.num / total) * 100).toFixed(1) + '%' : '0.0%'
      option.index = optionList[index]
    })
  })

  // 返回结构优化，便于前端展示
  return {
    totalSubmissions,
    titles,
    tool
  }
})
</script>

<style lang="scss" scoped>
.choice-statistics-panel {
  height: 100%;
  padding: 16px;
}

.statistics-content {
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  padding: 16px;
}

.statistics-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  text-align: center;
}

.statistics-summary {
  text-align: center;
  color: #666;
  font-size: 13px;
  margin-bottom: 16px;
  padding: 8px;
  background: #fff;
  border-radius: 6px;
}

.statistics-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.statistics-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-label {
  min-width: 40px;
  font-size: 12px;
  color: #333;
  font-weight: 500;
}

.option-bar {
  flex: 1;
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
}

.option-fill {
  height: 100%;
  background: linear-gradient(90deg, #1890ff, #40a9ff);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.option-count {
  min-width: 35px;
  font-size: 11px;
  color: #666;
  text-align: right;
}

.statistics-empty {
  padding: 40px 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.tool45{
	width: 100%;
	height: auto;
	&>div{
		width: 100%;
		height: auto;
		margin: 10px 0;
		background-color: #F8F9FA;
		border-radius: 8px;
		border: 1px solid #e9ecef;
		box-sizing: border-box;
		padding: 15px;
    position: relative;
    padding-bottom: 21px;
		.t45_title{
			width: 100%;
			display: flex;
			// align-items: center;
      margin-top: 25px;
			margin-bottom: 5px;
			span{
				font-size: 16px;
				color: #1890ff;
			}
		}

    .t45_btn{
      position: absolute;
      right: 18px;
      top: 15px;
      
      span{
        font-size: 12px;
        cursor: pointer;
        color: #409EFF;
      }
    }
	}
	.t45_list{
		width: 100%;
		height: auto;
		.t45_l_item{
			margin-top: 5px;
			.t45_l_i_option{
				display: flex;
				align-items: center;
				height: auto;
				width: 100%;
				justify-content: space-between;
				span{
					display: flex;
					width: 50px;
          &:nth-child(1){
            width: 20px;
          }
					&:nth-of-type(2){
						width: 10px;
					}
				}
				&>div{
					margin: 0 5px;
					width: calc(100% - 10px - 20px - 50px - 10px);
					height: 15px;
					background-color: #FFFFFF;
					// box-sizing: border-box;
					border: solid 1px #E9ECEF;
					border-radius: 4px;
					overflow: hidden;
					&>div{
						height: 100%;
						background-color: #3681FC;
					}
				}
			}
			.t45_l_i_user{
				width: 100%;
				height: auto;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				margin-top: 8px;
				margin-bottom: 8px;
				&>div{
					align-items: center;
					flex-wrap: wrap;
					height: 35px;
					span{
						width: auto;
						height: auto;
						padding: 4px 10px;
						background-color: #fff;
						border: solid 1px #2f80ed;
						border-radius: 6px;
						margin-right:8px ;
						margin-bottom: 5px;
						color: #2f80ed;
					}
				}
				&>span{
					width: auto;
					height: auto;
					padding: 4px 10px;
					background-color: #fff;
					border: solid 1px #E9ECEF;
					border-radius: 6px;
					margin-right:8px;
					cursor: pointer;
					transition: .2s;
					&:hover{
						background-color: #f1f1f1;
					}
					svg{
						width: 15px;
						height: 15px;
					}
				}
			}
		}
	}
}

.userBox{
  width: 100%;
  height: auto;
  .ub_item{
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    border-bottom: solid 1px #D8D8D8;
    .ub_i_options{
      font-size: 20px;
    }
    .ub_i_user{
      display: flex;
      margin: 10px 0;
      align-items: center;
      flex-wrap: wrap;
      &>span{
        color: #ADADAD;
      }
      .ub_i_u_item{
        padding: 5px 10px;
        border: solid 1px #0061FF;
        border-radius: 4px;
        background-color: #fff;
        margin-left: 10px;
        margin-top: 10px;
        color: #0061FF;
      }
    }
  }

}
</style> 