<template>
  <el-dialog
    title=""
    :visible.sync="showDialog"
    class="preview_dialog"
    :modal-append-to-body="false"
    append-to-body
    fullscreen
    height="100%"
  >
    <div class="preview_image">
      <div v-if="showDraw" class="preview_canvas">
        <!-- Vue3中 ref 绑定到变量 -->
        <!-- <ActionImage
          ref="ActionCanvasRef"
          :isDrag="true"
          :paperImgUrl="currenImageUrl"
          :drawData="currentDrawData"
        ></ActionImage> -->
        <div>
            <image
              :src="currenImageUrl"
              alt=""></image>
        </div>
      </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()">
        <i class="el-icon-close"></i>
      </div>
      <div
        class="preview_last"
        :class="currentIndex == 0 ? 'button_diasble' : ''"
        v-if="imageList.length > 1"
        @click="LastImage()"
      >
        <i class="el-icon-arrow-left"></i>
      </div>
      <div
        class="preview_next"
        :class="currentIndex == imageList.length - 1 ? 'button_diasble' : ''"
        v-if="imageList.length > 1"
        @click="NextImage()"
      >
        <i class="el-icon-arrow-right"></i>
      </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 ActionImage from '@/components/ActionImage.vue' // 制作模板画布组件

// 定义 Props
const props = defineProps({
  value: {
    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(['input', 'GetRotateAngle'])

// 响应式数据
const currenImageUrl = ref('') // 当前图片url
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)

// Computed: showDialog
// 在 Vue3 script setup 中，通常通过 watch props.value 或直接在使用处判断
// 由于 el-dialog 使用 :visible.sync，我们需要一个内部状态或计算属性来双向绑定
// 这里为了保持逻辑清晰，我们直接使用 props.value 作为显示依据，并通过 emit 更新
// 注意：el-dialog 的 visible.sync 在 Vue3 + Element Plus 中通常改为 v-model
// 如果使用的是 Element UI (Vue2版本库)，则保持 :visible.sync 并手动处理 input 事件

const showDialog = ref(props.value)

// 监听 props.value 变化同步内部状态
watch(
  () => props.value,
  (newVal) => {
    showDialog.value = newVal
    if (newVal) {
      currentIndex.value = props.index
      LoadPaperInfo() // 加载页面相关数据
    }
  }
)

// 监听 showDialog 内部变化（如点击遮罩关闭）同步回父组件
watch(showDialog, (newVal) => {
  emit('input', 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 = () => {
  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
  
  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 = () => {
  try {
    const templateDataStr = localStorage.getItem('templateData')
    const usedCardTypeStr = localStorage.getItem('usedCardType') // 卡类型
    
    if (!templateDataStr) return
    
    const templateData = JSON.parse(templateDataStr)
    const usedCardType = usedCardTypeStr ? parseInt(usedCardTypeStr) : null
    
    console.log('打印templateData模板信息', templateData)
    
    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) {
      // 找到客观题的切块数据 (blockArea == 8)
      const list = currentTemplateItem.examCardGroupVOS.filter(
        (item) => item.blockArea == 8
      )
      
      list.forEach((item) => {
        if (item.position) {
          let position = {}
          try {
            position = JSON.parse(item.position)
          } catch (e) {
            console.error('解析 position 失败', e)
            return
          }
          
          const unit = 'px' // 默认px单位
          let topiclist = []
          
          if (item.groupTopicList) {
            // 处理答案数据
            item.groupTopicList.forEach((topic) => {
              const answerValue = props.answerData[topic.topicName]
              
              if (answerValue) {
                // 将多个字母拆分成数组（兼容多种分隔符）
                const answerLetters = answerValue.match(/[A-Za-z]/g) || []
                
                answerLetters.forEach((letter) => {
                  let answerIndex = GetAnswerIndexToLetter(letter)

                  if (topic.topicType == 3) {
                    // 判断题
                    answerIndex = GetAnswerIndexToLetterTF(letter)
                  }
                  
                  if (answerIndex !== -1 && topic.answerList[answerIndex]) {
                    topic.answerList[answerIndex].isCheck = true
                  }
                })
              }
            })
            topiclist = item.groupTopicList
          }

          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)
        }
      })

      // 找到选做题的切块数据 (blockArea == 9)
      const list2 = currentTemplateItem.examCardGroupVOS.filter(
        (item) => item.blockArea == 9
      )
      
      list2.forEach((item) => {
        if (item.position) {
          let position = {}
          try {
            position = JSON.parse(item.position)
          } catch (e) {
            console.error('解析 position 失败', e)
            return
          }
          
          const unit = 'px' // 默认px单位
          let topiclist = []
          
          if (item.groupTopicList) {
            // 处理答案数据
            item.groupTopicList.forEach((topic) => {
              const answerValue = props.answerData[topic.topicName]
              
              // 对于选做题，只需要检查值是否存在且不是null或undefined
              if (answerValue !== undefined && answerValue !== null) {
                // 检查answerValue是否为有效数字
                if (!isNaN(answerValue) && answerValue !== '') {
                  const answerIndex = answerValue - 1
                  if (answerIndex >= 0 && topic.answerList[answerIndex]) {
                    topic.answerList[answerIndex].isCheck = true
                  }
                }
              }
            })
            topiclist = item.groupTopicList
          }

          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)
        }
      })
      
      console.log('打印选做题drawList', drawList)
    }
    
    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)
}

// 生命周期
// mounted 逻辑已在 watch(props.value) 中处理初始加载
// 如果需要初始加载且 value 默认为 true，可以在这里调用
// onMounted(() => {
//   if (props.value) {
//     currentIndex.value = props.index
//     LoadPaperInfo()
//   }
// })

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;
  background-color: red;
}
.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;
    // border:1px solid red;

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