<template>
  <el-dialog 
    title="" 
    v-model="showDialog" 
    class="preview_dialog" 
    :modal-append-to-body="false"
    append-to-body
    fullscreen 
    height="100%"
  >
    <div class="preview_image">
      <div v-if="showDraw && showDialog" class="preview_canvas">
        <ActionImage 
          ref="ActionCanvasRef" 
          :isDrag="true" 
          :paperImgUrl="currenImageUrl" 
          :drawData="currentDrawData"
        ></ActionImage>
      </div>
      <div v-else>
        <img 
          :src="currenImageUrl" 
          alt="" 
          :style="{ 
            transform: `scale(${zoomLevel}) rotate(${rotateAngle}deg)`, 
            transition: 'transform 0.2s' 
          }"
        />
      </div>
      
      <div class="preview_close" @click="CloseDialog()">
        <el-icon><Close /></el-icon>
      </div>
      <div 
        class="preview_last" 
        :class="currentIndex == 0 ? 'button_diasble' : ''" 
        v-if="imageList.length > 1" 
        @click="LastImage()"
      >
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div 
        class="preview_next" 
        :class="currentIndex == imageList.length - 1 ? 'button_diasble' : ''" 
        v-if="imageList.length > 1" 
        @click="NextImage()"
      >
        <el-icon><ArrowRight /></el-icon>
      </div>
    </div>
    <div class="preview_tool" v-if="showTool">
      <div 
        class="tool_item" 
        v-for="(item, index) in toolList" 
        :key="'tool_' + index" 
        @click="ToolClick(item)"
      >
        <div class="item_icon">
          <i class="iconfont" :class="item.icon"></i>
        </div>
        <div class="item_title">
          {{ item.title }}
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onBeforeUnmount } from 'vue'
import { Close, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import ActionImage from '@/components/ActionImage.vue'

// 定义 Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  imageList: {
    type: Array,
    default: () => [],
  },
  index: {
    type: Number,
    default: 0,
  },
  showTool: {
    type: Boolean,
    default: false,
  },
  showDraw: {
    type: Boolean,
    default: false,
  },
  answerData: {
    type: Object,
    default: () => ({}),
  },
})

// 定义 Emits
const emit = defineEmits(['update:modelValue', 'GetRotateAngle'])

// 响应式数据
const currenImageUrl = ref('')
const currentPageNo = ref(1)
const currentIndex = ref(0)

const toolList = ref([
  {
    title: '放大',
    icon: 'icon_fangda',
    value: '1',
  },
  {
    title: '缩小',
    icon: 'icon_suoxiao',
    value: '2',
  },
  {
    title: '逆时针1°',
    icon: 'icon_nishizhen1',
    value: '3',
  },
  {
    title: '顺时针1°',
    icon: 'icon_shunshizhen1',
    value: '4',
  },
  {
    title: '逆时针90°',
    icon: 'icon_nishizhen90',
    value: '5',
  },
  {
    title: '顺时针90°',
    icon: 'icon_shunshizhen90',
    value: '6',
  },
])

const zoomLevel = ref(1)
const maxZoom = ref(3)
const minZoom = ref(0.5)
const zoomStep = ref(0.1)
const rotateAngle = ref(0)

const currentPageInfo = ref({})
const currentDrawData = ref([])

// Ref 引用
const ActionCanvasRef = ref(null)

// 计算属性：showDialog
const showDialog = ref(props.modelValue)

// 监听 props.modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    showDialog.value = newVal
    if (newVal) {
      currentIndex.value = props.index
      LoadPaperInfo()
    }
  }
)

// 监听 showDialog 内部变化同步回父组件
watch(showDialog, (newVal) => {
  emit('update:modelValue', newVal)
})

// 关闭弹窗
const CloseDialog = () => {
  showDialog.value = false
  const obj = {
    currentIndex: currentIndex.value,
    rotateAngle: rotateAngle.value,
  }
  emit('GetRotateAngle', obj)
}

// 返回角度信息
const GetReturn = () => {
  const obj = {
    currentIndex: currentIndex.value,
    rotateAngle: rotateAngle.value,
  }
  emit('GetRotateAngle', obj)
}

// 加载页面相关信息
const LoadPaperInfo = () => {

    console.log('打印当前图片列表', props.imageList)
  if (!props.imageList || props.imageList.length === 0) return
  
  const currentItem = props.imageList[currentIndex.value]
  if (!currentItem) return

  currenImageUrl.value = currentItem.url
  currentPageNo.value = currentItem.pageNo
  rotateAngle.value = currentItem.rotateAngle || 0
  console.log('打印当前图片信息', currentItem)
  
  if (props.showDraw) {
    LoadDrawData()
  }
}

// 上一个图片
const LastImage = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
    LoadPaperInfo()
  }
}

// 下一个图片
const NextImage = () => {
  if (currentIndex.value < props.imageList.length - 1) {
    currentIndex.value++
    LoadPaperInfo()
  }
}

// 工具栏点击事件
const ToolClick = (item) => {
  switch (item.value) {
    case '1':
      ZoomIn()
      break
    case '2':
      ZoomOut()
      break
    case '3':
      RotateCounterClockwiseOne()
      break
    case '4':
      RotateClockwiseOne()
      break
    case '5':
      RotateCounterClockwise90()
      break
    case '6':
      RotateClockwise90()
      break
  }
}

// 放大图片
const ZoomIn = () => {
  if (zoomLevel.value < maxZoom.value) {
    zoomLevel.value += zoomStep.value
  }
  console.log('打印当前缩放的级别', zoomLevel.value)
}

// 缩小图片
const ZoomOut = () => {
  if (zoomLevel.value > minZoom.value) {
    zoomLevel.value -= zoomStep.value
  }
}

// 逆时针旋转1度
const RotateCounterClockwiseOne = () => {
  rotateAngle.value -= 1
  GetReturn()
}

// 顺时针旋转1度
const RotateClockwiseOne = () => {
  rotateAngle.value += 1
  GetReturn()
}

// 逆时针旋转90度
const RotateCounterClockwise90 = () => {
  rotateAngle.value -= 90
  GetReturn()
}

// 顺时针旋转90度
const RotateClockwise90 = () => {
  rotateAngle.value += 90
  GetReturn()
}

// 加载绘图数据
const LoadDrawData = () => {

  console.log("加载模板绘图数据");
  try {

    
    const templateDataStr = localStorage.getItem('templateData')
    
    // const usedCardTypeStr = localStorage.getItem('usedCardType')
    
    if (!templateDataStr) return
    
    const templateData = JSON.parse(templateDataStr);

    const usedCardType = 2;//默认三方卡
    
    console.log('打印templateData模板信息', templateData)
    console.log('打印currentPageNo', currentPageNo)
    console.log('打印answerData', props.answerData)
    const currentTemplateItem = templateData.find(
      (item) => item.pageNum == currentPageNo.value
    )
    
    if (!currentTemplateItem) {
      console.warn('未找到当前页码对应的模板信息', currentPageNo.value)
      return
    }

    console.log('打印当前页的模板信息', currentTemplateItem)
    
    let drawList = []
    currentDrawData.value = []
    
    let paperInfo = {}
    try {
      paperInfo = JSON.parse(currentTemplateItem.paperInfo)
    } catch (e) {
      console.error('解析 paperInfo 失败', e)
    }

    //选择题判分暂时没有系统卡 注释掉
    // if (usedCardType == 1) {
    //   currentPageInfo.value = {
    //     width: paperInfo.width - 30,
    //     height: paperInfo.height - 25,
    //   }
    // }

    if (currentTemplateItem.examCardGroupVOS) {
      // const list = currentTemplateItem.examCardGroupVOS.filter(
      //   (item) => item.blockArea == 8
      // )
      const list = currentTemplateItem.examCardGroupVOS;//无需过滤 都是客观题的数据
      
      list.forEach((item) => {
        if (item.position) {
          let position = {}
          try {
            position = JSON.parse(item.position)
          } catch (e) {
            console.error('解析 position 失败', e)
            return
          }
          
          const unit = 'px'
          let topiclist = []
          
          if (item.groupTopicList) {
            item.groupTopicList.forEach((topic) => {
              const answerValue = props.answerData[topic.topicName];//答案
              console.log('answerValue',answerValue)
              // 关键修改：使用深拷贝确保是纯JavaScript对象
              let answerList = JSON.parse(JSON.stringify(JSON.parse(topic.optionJsons)));
             
              // 为每个答案项显式添加 isCheck 属性
              answerList.forEach(answer => {
                answer.isCheck = false;
              });
              console.log("打印answerList",answerList);
              if (answerValue) {
                const answerLetters = answerValue.match(/[A-Za-z]/g) || []
                console.log('answerLetters',answerLetters)
                answerLetters.forEach((letter) => {
                  let answerIndex = GetAnswerIndexToLetter(letter)
                
                  if (answerIndex !== -1 && answerList[answerIndex]) {
                    answerList[answerIndex].isCheck = true;
                   
                  } else {
                    console.log("❌ 设置失败! answerIndex:", answerIndex, "answerList长度:", answerList.length);
                  }
                
                 
                  
                })
              }
              let topiclistObj={
                answerList:answerList,
                index:topic.index,
                topicName:topic.topicName,
                topicType:1,//1单选 2多选 3判断
              };
              topiclist.push(topiclistObj);
            })
            
          }

          const obj = {
            x: position.x,
            y: position.y,
            w: position.w,
            h: position.h,
            position: item.position,
            blockArea: item.blockArea,
            page: currentPageNo.value,
            blockName: item.name,
            id: item.groupId,
            unit: unit,
            usedCardType: usedCardType,
            areaOption: item.groupConfig,
            topiclist: topiclist,
          }
          drawList.push(obj)
        }
      })
    }
    
    currentDrawData.value = drawList
  } catch (error) {
    console.error('LoadDrawData 错误:', error)
  }
}

// 根据字母转换成索引
const GetAnswerIndexToLetter = (value) => {
  const letters = [
    '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',
  ]
  return letters.findIndex((letter) => letter == value)
}

// 判断题的
const GetAnswerIndexToLetterTF = (value) => {
  const letters = ['T', 'F']
  return letters.findIndex((letter) => letter == value)
}

// 生命周期
onBeforeUnmount(() => {
  // 清理工作
})
</script>

<style lang="scss" scoped>
.preview_image {
  width: 100%;
  height: calc(100% - 20px);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 0;
  position: relative;
}

.preview_canvas {
  width: 100%;
  height: 100%;
  
  .main_container {
    width: calc(100% - 240px);
    margin: auto;
    height: 100%;
    position: relative;
    background: transparent;
    user-select: none;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;

    .paper_template {
      position: absolute;
    }
  }
}
</style>