<template>
  <div class="HuoQingDetailModal" @click="clickFrame">
    <div class="frame">
      <Frame :w="frameWidth" :h="frameHeight" :dataStyle="option.dataStyle" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import {
    computed,
    PropType,
    toRefs,
    watch,
    reactive,
    ref,
    onMounted,
    onBeforeUnmount,
  } from 'vue';
  import { CreateComponentType } from '@/packages/index.d';
  import { icon } from '@/plugins';
  import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore';
  import { useChartDataFetch } from '@/hooks';
  import Frame from './svg/frame.vue';
  import cloneDeep from 'lodash/cloneDeep';

  const chartEditStore = useChartEditStore();
  const props = defineProps({
    chartConfig: {
      type: Object as PropType<CreateComponentType>,
      required: true,
    },
  });

  const { w, h, x, y } = toRefs(props.chartConfig.attr);

  const option = reactive({
    dataStyle: props.chartConfig.option.dataStyle,
  });
  watch(
    () => option.dataStyle.onlyShowLeftFrame,
    () => {
      if (option.dataStyle.onlyShowLeftFrame) {
        w.value = (h.value / 891) * 417;
      } else {
        w.value = (h.value / 891) * 1343;
      }
    },
  ),
    {
      immediate: true,
    };

  // 弹窗样式
  const frameWidth = computed(() => {
    if (option.dataStyle.mask) {
      return option.dataStyle.maskFrameW;
    } else {
      return w.value;
    }
  });
  const frameHeight = computed(() => {
    if (option.dataStyle.mask) {
      return option.dataStyle.maskFrameH;
    } else {
      return h.value;
    }
  });
  const frameTop = computed(() => {
    if (option.dataStyle.mask) {
      return option.dataStyle.maskFrameY;
    } else {
      return 0;
    }
  });
  const frameLeft = computed(() => {
    if (option.dataStyle.mask) {
      return option.dataStyle.maskFrameX;
    } else {
      return 0;
    }
  });
  // 监听遮罩
  watch(
    () => option.dataStyle.mask,
    () => {
      if (option.dataStyle.mask) {
        option.dataStyle.maskFrameX = cloneDeep(x.value);
        option.dataStyle.maskFrameY = cloneDeep(y.value);
        option.dataStyle.maskFrameW = cloneDeep(w.value);
        option.dataStyle.maskFrameH = cloneDeep(h.value);
        x.value = 0;
        y.value = 0;
        w.value = chartEditStore.getEditCanvasConfig.width;
        h.value = chartEditStore.getEditCanvasConfig.height;
        option.dataStyle.maskColor = option.dataStyle.maskFrameColor;
      } else {
        x.value = option.dataStyle.maskFrameX;
        y.value = option.dataStyle.maskFrameY;
        w.value = option.dataStyle.maskFrameW;
        h.value = option.dataStyle.maskFrameH;
        option.dataStyle.maskFrameColor = option.dataStyle.maskColor;
        option.dataStyle.maskColor = '#FFFFFF00';
      }
    },
  );

  watch(
    () => option.dataStyle.maskFrameW,
    () => {
      if (option.dataStyle.onlyShowLeftFrame) {
        option.dataStyle.maskFrameH = (option.dataStyle.maskFrameW * 891) / 417;
      } else {
        option.dataStyle.maskFrameH = (option.dataStyle.maskFrameW * 891) / 1343;
      }
    },
  );

  // 有遮罩的情况点击
  function clickFrame(event) {
    if (!window.location.href.includes('/chart/home/')) {
      if (option.dataStyle.mask && option.dataStyle.maskClickClose) {
        chartEditStore.getComponentList.forEach((element) => {
          if (
            element.key == props.chartConfig.key ||
            (element.isGroup && element?.groupList.some((li) => li.key == props.chartConfig.key))
          ) {
            if (
              !(
                element.option.maskFrameX <= event.x &&
                event.x <= element.option.maskFrameX + element.option.maskFrameW &&
                element.option.maskFrameY <= event.y &&
                event.y <= element.option.maskFrameY + element.option.maskFrameH
              )
            ) {
              if (!element.status.hide) {
                element.status.hide = true;
              }
            }
          }
        });
      }
    }
  }

  const num = ref(0);
  function getHuoQingDetailModalIsNum() {
    chartEditStore.getComponentList.forEach((element, index) => {
      if (
        element.key == props.chartConfig.key ||
        (element.isGroup && element?.groupList.some((li) => li.key == props.chartConfig.key))
      ) {
        num.value = index;
      }
    });
  }

  let isClickUpdate = false;
  watch(
    () => chartEditStore.getComponentList[num.value]?.status?.hide,
    () => {
      // if (!chartEditStore.getComponentList[num.value]?.status?.hide) {
      isClickUpdate = true;
      // }
    },
    {
      deep: true,
    },
  );

  // 处理无遮罩的情况下的鼠标点击事件
  const handleKeydown = (event: MouseEvent) => {
    if (!window.location.href.includes('/chart/home/')) {
      if (!option.dataStyle.mask && option.dataStyle.maskClickClose) {
        chartEditStore.getComponentList.forEach((element) => {
          // 单个
          if (
            element.key == props.chartConfig.key ||
            (element.isGroup && element?.groupList.some((li) => li.key == props.chartConfig.key))
          ) {
            if (
              !(
                element.attr.x <= event.x &&
                event.x <= element.attr.x + element.attr.w &&
                element.attr.y <= event.y &&
                event.y <= element.attr.y + element.attr.h
              )
            ) {
              if (!element.status.hide && !isClickUpdate) {
                element.status.hide = true;
              } else {
                isClickUpdate = false;
              }
            }
          }
        });
      }
    }
  };

  // 在组件挂载时添加监听器
  onMounted(() => {
    getHuoQingDetailModalIsNum();
    window.addEventListener('click', handleKeydown);
  });
  // 在组件卸载时移除监听器
  onBeforeUnmount(() => {
    window.removeEventListener('click', handleKeydown);
  });

  // 添加鼠标拖动监听器
  let isGroup = 0;
  addListener();
  // 监听器-参数
  let isDragging = false;
  let initialMouseX;
  let initialMouseY;
  let initialDocumentX;
  let initialDocumentY;

  // 添加鼠标拖动监听器
  function addListener() {
    if (option.dataStyle.mouseListener) {
      chartEditStore.getComponentList.forEach((element) => {
        // 未分组
        if (isGroup == 1 || element.key == 'HuoQingDetailModal') {
          isGroup = 1;
          setTimeout(() => {
            const dragDocument: any = document.querySelector('.HuoQingDetailModal');
            if (dragDocument) {
              // 鼠标按下
              dragDocument.addEventListener('mousedown', function (event) {
                isDragging = true;
                initialMouseX = event.clientX;
                initialMouseY = event.clientY;
                initialDocumentX = cloneDeep(x.value);
                initialDocumentY = cloneDeep(y.value);
                dragDocument.style.cursor = 'grabbing';
              });
              // 鼠标移动
              dragDocument.addEventListener('mousemove', function (event) {
                if (isDragging) {
                  const deltaX = event.clientX - initialMouseX;
                  const deltaY = event.clientY - initialMouseY;
                  x.value = initialDocumentX + deltaX;
                  y.value = initialMouseY + deltaY;
                }
              });
              // 鼠标放开
              dragDocument.addEventListener('mouseup', function (event) {
                isDragging = false;
                dragDocument.style.cursor = 'default';
              });
            }
          }, 1000);
        }
        // 分组
        if (
          isGroup == 2 ||
          (element.isGroup && element?.groupList?.some((li) => li.key == 'HuoQingDetailModal'))
        ) {
          isGroup = 2;
          setTimeout(() => {
            const dragDocument = document.getElementById(element.id); // 使用 id 获取元素
            if (dragDocument) {
              // 鼠标按下
              dragDocument.addEventListener('mousedown', function (event) {
                isDragging = true;
                initialMouseX = event.clientX;
                initialMouseY = event.clientY;
                initialDocumentX = dragDocument.offsetLeft;
                initialDocumentY = dragDocument.offsetTop;
                dragDocument.style.cursor = 'grabbing';
              });
              // 鼠标移动
              dragDocument.addEventListener('mousemove', function (event) {
                if (isDragging) {
                  const deltaX = event.clientX - initialMouseX;
                  const deltaY = event.clientY - initialMouseY;
                  dragDocument.style.left = initialDocumentX + deltaX + 'px';
                  dragDocument.style.top = initialDocumentY + deltaY + 'px';
                }
              });
              // 鼠标放开
              dragDocument.addEventListener('mouseup', function (event) {
                isDragging = false;
                dragDocument.style.cursor = 'default';
              });
            }
          }, 1000);
        }
      });
    }
  }
</script>

<style lang="scss" scoped>
  .HuoQingDetailModal {
    display: flex;
    justify-content: center;
    text-align: center;
    width: v-bind('`${w}px`');
    height: v-bind('`${h}px`');
    background: v-bind('`${option.dataStyle.maskColor}`');
  }
  .frame {
    position: absolute;
    top: v-bind('`${frameTop}px`');
    left: v-bind('`${frameLeft}px`');
  }
</style>
