<template>
  <div>
    <div v-show="showX" class="fp-line fp-x-line" :style="xStyle"></div>
    <div v-show="showY" class="fp-line fp-y-line" :style="yStyle"></div>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { getComponentRotatedStyle } from './utils'

export default {
  data() {
    return {
      diff: 3, // 相距 dff 像素将自动吸附
      showX: false,
      showY: false,
      xStyle:{
        top:'0px'
      },
      yStyle:{
        left:'0px'
      }
    }
  },
  computed: {
    ...mapState({
      'p': state => state.poster.p
    }),
    ...mapGetters({
      'w': 'poster/w',
      'h': 'poster/h',
      'scale': 'poster/scale',
      'ai': 'poster/ai',
    }),
  },
  methods: {
    hideLine() {
      this.showX = false
      this.showY = false
    },
    showLine() {
      const components = this.p.items
      const curStyle = getComponentRotatedStyle(this.ai)
      const curHalfWidth = curStyle.w / 2
      const curHalfHeight = curStyle.h / 2

      this.hideLine()
      components.forEach(component => {
        if (component.uuid == this.ai.uuid) return
        const componentStyle = getComponentRotatedStyle(component)
        const { x, y, bottom, right } = componentStyle
        const halfWidth = componentStyle.w / 2
        const halfHeight = componentStyle.h / 2

        if (this.isNearly(curStyle.y, y) || this.isNearly(curStyle.bottom, y)) {
          //横向 上线
          this.showX = true
          this.xStyle.top = `${y*this.scale}px`
        } else if (this.isNearly(curStyle.y + curHalfHeight, y + halfHeight)) {
          //横向 中线
          this.showX = true
          this.xStyle.top = `${(y + halfHeight)*this.scale}px`
        } else if (this.isNearly(curStyle.y, bottom) || this.isNearly(curStyle.bottom, bottom)) {
          // 横向 下线
          this.showX = true
          this.xStyle.top = `${bottom*this.scale}px`
        }

        if (this.isNearly(curStyle.x, x)||  this.isNearly(curStyle.right, x)) {
          //纵向 上
          this.showY = true
          this.yStyle.left = `${x*this.scale}px`
        } else if (this.isNearly(curStyle.x + curHalfWidth, x + halfWidth)) {
          //纵向 中线
          this.showY = true
          this.yStyle.left = `${(x + halfWidth)*this.scale}px`
        } else if (this.isNearly(curStyle.x, right) ||this.isNearly(curStyle.right, right)) {
          //纵向 下
          this.showY = true
          this.yStyle.left = `${right*this.scale}px`
        }
      })
    },

    isNearly(dragValue, targetValue) {
      return Math.abs(dragValue - targetValue) <= this.diff
    },
  },
}
</script>

<style  scoped>
.fp-line {
  background: #2c8ef8;
  position: absolute;
  top:0px;
  left:0px;
  z-index: 998;
}

.fp-x-line {
  width: 100%;
  height: 1px;
}

.fp-y-line {
  width: 1px;
  height: 100%;
}
</style>
