<template>
  <div class="venue-preview">
    <!-- v-show="currentMarkData && currentMarkData.signPoint" -->
    <div v-show="currentMarkData && currentMarkData.signPoint">
      <canvas :id="`canvasPreview${currentMarkData && currentMarkData.id}`" :width="width" :height="height" />
    </div>
    <img v-if="currentMarkData &&!currentMarkData.signPoint" :src="imageUrl" :onerror="defaultImg" alt="">
    <div id="tooltip" class="tooltip-style">
      <!-- <div class="tooltip-top">
        <h4>区域名称</h4>
        <span class="update-time">2024-11-28 09:46</span>
      </div>
      <ul>
        <li><p>在架</p><span><i>15000</i>册</span></li>
        <li><p>错架</p><span><i>300</i>层</span> <span class="percentage">（2.00%）</span></li>
        <li><p>错序</p><span><i>0</i>层</span><span class="percentage">（0.00%）</span></li>
      </ul> -->
    </div>
  </div>
</template>

<script>
// import { dataScreeningCrud } from '@/views/visualCheck/mixins/index'
import defaultImg from '@/assets/images/default-img-bg.jpg'
import { fabric } from 'fabric'
import { mapGetters } from 'vuex'
export default {
  name: 'Mark',
  mixins: [],
  props: {
    currentMarkData: {
      type: Object,
      require: true,
      default: function() {
        return {}
      }
    },
    imageUrl: {
      type: String,
      default: ''
    },
    pagePreview: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      defaultImg: defaultImg,
      canvasPreview: {},
      width: 1200,
      height: 600,
      drawWidth: 2,
      tooltipInfo: null,
      initialDistance: 0,
      initialZoom: 0
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'
    ])
  },
  watch: {
    width() {
      this.canvasPreview.setWidth(this.width)
    },
    height() {
      this.canvasPreview.setHeight(this.height)
    },
    currentMarkData: {
      handler(newVal, oldVal) {
        // 检查 newVal 是否为 null 或 undefined
        if (!newVal) {
          console.log('newVal - null')
          return
        }
      },
      deep: true
    },
    imageUrl(newVal, oldVal) {
      if (newVal !== oldVal) {
        console.log('imageUrl', newVal)
      }
    }
  },
  mounted() {
    if (this.canvasPreview.lowerCanvasEl) {
      this.canvasPreview.getCanvas().el.addEventListener('touchstart', this.handleTouchStart.bind(this))
      this.canvasPreview.getCanvas().el.addEventListener('touchmove', this.handleTouchMove.bind(this))
      this.canvasPreview.getCanvas().el.addEventListener('touchend', this.handleTouchEnd.bind(this))
    }
  },
  beforeDestroy() {
    // if (this.canvasPreview) {
    //   this.canvasPreview.clear()
    //   this.canvasPreview.dispose()
    // }
  },
  methods: {
    initCanvasPreview(drawinfo, tabIndex) {
      if (!this.currentMarkData) {
        console.error('currentMarkData - null')
        return
      }

      const canvasId = `canvasPreview${this.currentMarkData.id}`
      this.canvasPreview = new fabric.Canvas(canvasId, {
        skipTargetFind: false,
        selectable: false,
        selection: false
      })

      this.$nextTick(() => {
        this.canvasPreview.selectionColor = 'rgba(0,0,0,0.05)'
        this.loadDrawPreview(drawinfo, tabIndex)
        // this.canvasPreview.on('mouse:wheel', this.mouse)
      })
    },
    // 触摸事件处理函数
    handleTouchStart(e) {
      if (e.touches.length === 2) {
        const touch1 = e.touches[0]
        const touch2 = e.touches[1]
        this.initialDistance = Math.sqrt((touch2.clientX - touch1.clientX) * (touch2.clientX - touch1.clientX) + (touch2.clientY - touch1.clientY) * (touch2.clientY - touch1.clientY))
        this.initialZoom = this.canvasPreview.getZoom()
      }
    },
    handleTouchMove(e) {
      if (e.touches.length === 2) {
        const touch1 = e.touches[0]
        const touch2 = e.touches[1]
        const currentDistance = Math.sqrt((touch2.clientX - touch1.clientX) * (touch2.clientX - touch1.clientX) + (touch2.clientY - touch1.clientY) * (touch2.clientY - touch1.clientY))
        let newZoom = this.initialZoom * (currentDistance / this.initialDistance)
        newZoom = Math.max(0.8, newZoom)
        newZoom = Math.min(3, newZoom)
        const centerX = (touch1.clientX + touch2.clientX) / 2
        const centerY = (touch1.clientY + touch2.clientY) / 2
        const zoomPoint = new fabric.Point(centerX, centerY)
        this.canvasPreview.zoomToPoint(zoomPoint, newZoom)
      }
    },
    handleTouchEnd() {
      // 触摸结束时可以做一些清理操作，这里暂未用到
    },
    // 回显详情信息
    loadDrawPreview(drawinfo, tabIndex) {
      const self = this
      const pointGroup = drawinfo.pointInfo
      const imgInfo = drawinfo.imgInfo
      imgInfo.src = self.imageUrl

      // 加载底图
      fabric.util.enlivenObjects([imgInfo], objects => {
        objects.forEach(o => {
          o.selectable = false
          o.hasControls = false
          o.centeredScaling = false
          self.canvasPreview.add(o)
        })
        // 处理多边形绘制回显操作
        pointGroup.forEach(async(item, index) => {
          console.log('item', item)
          if (item.pointInfo !== '') {
            const polygon = new fabric.Polygon(item.pointInfo, {
              id: item.id,
              name: item.name,
              floorId: item.floorId,
              regionId: item.regionId,
              rowType: item.rowType,
              toward: item.toward,
              floorName: item.floorName,
              regionName: item.regionName,
              shelfFloor: item.shelfFloor,
              shelfShelf: item.shelfShelf,
              errorOrderNum: item.errorOrderNum,
              errorOrderProbo: item.errorOrderProbo,
              errorShelfNum: item.errorShelfNum,
              errorShelfProbo: item.errorShelfProbo,
              onShelfNum: item.onShelfNum,
              stroke: 'rgba(196,43, 1, 1)',
              strokeWidth: self.drawWidth,
              fill: 'rgba(196,43, 1, 1)',
              opacity: 0.5,
              selectable: false,
              hasBorders: false,
              hasControls: false,
              originX: 'left', // 设置原点为左上角
              originY: 'top' // 设置原点为左上角
            })
            self.canvasPreview.add(polygon)

            // const lastClickTime = 0
            // const doubleClickInterval = 300
            polygon.on('mousedown', function(e) {
              // const currentTime = new Date().getTime()
              // const timeDiff = currentTime - lastClickTime

              const toReigonsData = {
                id: e.target.id,
                name: e.target.name,
                floorId: e.target.floorId,
                regionId: e.target.regionId,
                rowType: e.target.rowType,
                toward: e.target.toward,
                regionName: e.target.regionName,
                floorName: e.target.floorName
              }
              console.log('toReigonsData', toReigonsData)
              if (self.pagePreview === 'floor') {
                console.log('toReigonsData', toReigonsData)
                self.handleToRegions(toReigonsData, tabIndex)
              } else if (self.pagePreview === 'region') {
                self.handleToShelfs(toReigonsData, tabIndex)
              }

              // if (timeDiff <= doubleClickInterval) {
              //   console.log('双击事件', e)
              //   lastClickTime = 0
              //   const toReigonsData = {
              //     id: e.target.id,
              //     name: e.target.name,
              //     floorId: e.target.floorId,
              //     regionId: e.target.regionId,
              //     rowType: e.target.rowType,
              //     toward: e.target.toward,
              //     regionName: e.target.regionName,
              //     floorName: e.target.floorName
              //   }
              //   console.log('toReigonsData', toReigonsData)
              //   if (self.pagePreview === 'floor') {
              //     self.handleToRegions(toReigonsData, tabIndex)
              //   } else if (self.pagePreview === 'region') {
              //     self.handleToShelfs(toReigonsData, tabIndex)
              //   }
              // } else {
              //   lastClickTime = currentTime
              // }
            })

            // polygon.on('mouseover', function(e) {
            //   this.tooltipInfo = {
            //     'id': e.target.id,
            //     'name': e.target.name,
            //     'rowType': e.target.rowType,
            //     'shelfFloor': e.target.shelfFloor,
            //     'shelfShelf': e.target.shelfShelf,
            //     'floorId': e.target.floorId,
            //     'regionId': e.target.regionId,
            //     'errorOrderNum': e.target.errorOrderNum,
            //     'errorOrderProbo': e.target.errorOrderProbo,
            //     'errorShelfNum': e.target.errorShelfNum,
            //     'errorShelfProbo': e.target.errorShelfProbo,
            //     'onShelfNum': e.target.onShelfNum
            //   }
            //   this.set({ opacity: 0.8, hoverCursor: 'pointer' })
            //   // <span class="update-time">2024-11-28 09:46</span>

            //   if (self.pagePreview === 'floor') {
            //     document.getElementById('tooltip').innerHTML =
            //     `<div class="tooltip-top">
            //       <h4>${this.tooltipInfo.name}</h4>
            //     </div>
            //     <ul>
            //       <li><p>在架</p><span><i>${this.tooltipInfo.onShelfNum}</i>册</span></li>
            //       <li><p>错架</p><span><i>${this.tooltipInfo.errorShelfNum}</i>册</span> <span class="percentage">（${this.tooltipInfo.errorShelfProbo}）</span></li>
            //       <li><p>错序</p><span><i>${this.tooltipInfo.errorOrderNum}</i>册</span><span class="percentage">（${this.tooltipInfo.errorOrderProbo}）</span></li>
            //     </ul>`
            //   } else if (self.pagePreview === 'region') {
            //     document.getElementById('tooltip').innerHTML =
            //     `<div class="tooltip-top">
            //       <h4>书架概况</h4>
            //     </div>
            //     <ul>
            //       <li><p>书架</p><span><i>${this.tooltipInfo.name}</i></span></li>
            //       <li><p>规则</p><span><i>${this.tooltipInfo.rowType === 1 ? '单面' : '双面'}${this.tooltipInfo.shelfFloor}*${this.tooltipInfo.shelfShelf}</i></span></li>
            //       <li><p>在架</p><span><i>${this.tooltipInfo.onShelfNum}</i>册</span></li>
            //       <li><p>错架</p><span><i>${this.tooltipInfo.errorShelfNum}</i>册</span> <span class="percentage">（${this.tooltipInfo.errorShelfProbo}）</span></li>
            //       <li><p>错序</p><span><i>${this.tooltipInfo.errorOrderNum}</i>册</span><span class="percentage">（${this.tooltipInfo.errorOrderProbo}）</span></li>
            //     </ul>`
            //   }

            //   // var rectLeft = e.target.left + e.target.width - 100
            //   var rectLeft = e.target.left + e.target.width
            //   var rectTop = e.target.top + e.target.height - 40
            //   document.getElementById('tooltip').style.left = rectLeft + 'px'
            //   document.getElementById('tooltip').style.top = rectTop + 'px'
            //   document.getElementById('tooltip').style.display = 'block'
            //   self.canvasPreview.renderAll()
            // })

            // polygon.on('mouseout', function() {
            //   this.set({ opacity: 0.5 })
            //   document.getElementById('tooltip').style.display = 'none'
            //   self.canvasPreview.renderAll()
            // })
          }
        })
        // 计算画布的中心点
        const centerX = self.canvasPreview.width / 2
        const centerY = self.canvasPreview.height / 2
        const centerPoint = new fabric.Point(centerX, centerY)

        // 设置画布的缩放比例为最小值并居中显示
        self.canvasPreview.zoomToPoint(centerPoint, 1)
        self.canvasPreview.renderAll()

        setTimeout(() => {
          self.$parent.prewLoading = false
        }, 500)
      })
    },
    handleToRegions(data, tabIndex) {
      this.$router.push({ path: '/regions' })
      localStorage.setItem('dataScreenFloor', JSON.stringify(data))
      localStorage.setItem('dataScreenFloorTableIndex', tabIndex)
    },
    handleToShelfs(data, tabIndex) {
      this.$router.push({ path: '/shelf' })
      localStorage.setItem('dataScreenRegion', JSON.stringify(data))
      localStorage.setItem('dataScreenRegionTableIndex', tabIndex)
    }
  }
}
</script>
<style lang="scss" scoped>
#expImg{
  display: none;
}
.venue-preview{
  width: 100%;
  background-color: #fff;
  overflow: hidden;
  margin-top: -30px;
}
</style>
