<template>
  <div style="position: absolute;z-index: 39;left: 0;top:0;right: 0;bottom: 0;" @mousemove="updateLinePathHandler" @click.stop="endDrawHandler" ref="drawPanel">
    <v-stage :config="configKonva">
      <v-layer>
        <v-line ref="line" :config="configLine"></v-line>
      </v-layer>
    </v-stage>
  </div>
</template>

<script setup lang="ts">
import { PropType, ref } from 'vue';
import { useMapStore } from '@/store/index'
import { storeToRefs } from 'pinia';
import { injectKeyMapOperaIndex } from '@/types/injectKey';

const props = defineProps({
  position:{
    type: Object as PropType<{x:number,y:number}>,
    require: true
  },
  parent:{
    type: Object as PropType<HTMLElement>,
    require: true
  }
})

const emit = defineEmits<{
  (event: 'success'): void
}>()

const mapStore = useMapStore()
const { fillColor,newLine } = storeToRefs(mapStore)
const configKonva = ref({
  width: props.parent?.offsetWidth,
  height: props.parent?.offsetHeight,
})
const configLine = ref({
  points: [props.position?.x??0,props.position?.y??0, props.position?.x??0, props.position?.y??0],
  stroke: `#${fillColor.value.color.toString(16).padStart(6, '0')}`,
  strokeWidth: 2,
  lineCap: 'round',
  opacity: fillColor.value.opacity
})
const drawPanel = ref()
const canMove = ref(true)
const line = ref()

const updateLinePathHandler = (e:MouseEvent)=>{
  if(!canMove.value) return
  
  configLine.value.points[2] = e.offsetX
  configLine.value.points[3] = e.offsetY
  line.value.getNode().parent.batchDraw();
}
const endDrawHandler = () => {
  canMove.value=false
  let t = configLine.value.points
  newLine.value = [t[0],t[1],t[2],t[3]]
  mapStore.setOperaIndex(0)
  emit('success')
}
</script>

<style scoped>
/* Add any necessary styles */
</style>
