<template>
  <div
    :style="getStyle(borderRadius)"
    @click="clickBtn"
    @dblclick="dblclickBtn"
    @contextmenu="rightclickBtn"
    @mouseenter="mouseenterBtn"
    @mouseleave="mouseleaveBtn"
  >
    <n-image
      :object-fit="fit"
      preview-disabled
      :src="option.dataset"
      :fallback-src="requireErrorImg()"
      :width="w"
      :height="h"
      lazy
    />
  </div>
</template>

<script setup lang="ts">
  import { PropType, shallowReactive, watch, toRefs, onMounted } from 'vue';
  import { requireErrorImg } from '@/utils';
  import { useChartDataFetch } from '@/hooks';
  import { CreateComponentType } from '@/packages/index.d';
  import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore';
  import { eventHandlerHook } from '@/hooks/eventHandler.hook';
  import { EventBus } from '@/utils/eventBus';

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

  const { w, h } = toRefs(props.chartConfig.attr);
  const { dataset, fit, borderRadius } = toRefs(props.chartConfig.option);

  const option = shallowReactive({
    dataset: '',
  });

  const getStyle = (radius: number) => {
    return {
      borderRadius: `${radius}px`,
      overflow: 'hidden',
      cursor: 'pointer',
    };
  };

  // 编辑更新
  watch(
    () => props.chartConfig.option.dataset,
    (newData: any) => {
      option.dataset = newData;
    },
    {
      immediate: true,
    },
  );

  // 预览更新
  useChartDataFetch(props.chartConfig, useChartEditStore, (newData: any) => {
    option.dataset = newData;
  });
  const clickBtn = (val) => {
    eventHandlerHook(
      chartEditStore.getComponentList,
      props.chartConfig.events.interactConfigEvents,
      'click',
      val,
    );
  };
  const dblclickBtn = (val) => {
    eventHandlerHook(
      chartEditStore.getComponentList,
      props.chartConfig.events.interactConfigEvents,
      'dblclick',
      val,
    );
  };
  const rightclickBtn = (event) => {
    event.preventDefault(); // 阻止默认的右键菜单
    eventHandlerHook(
      chartEditStore.getComponentList,
      props.chartConfig.events.interactConfigEvents,
      'rightclick',
    );
  };
  const mouseenterBtn = (val) => {
    eventHandlerHook(
      chartEditStore.getComponentList,
      props.chartConfig.events.interactConfigEvents,
      'mousein',
      val,
    );
  };
  const mouseleaveBtn = (val) => {
    eventHandlerHook(
      chartEditStore.getComponentList,
      props.chartConfig.events.interactConfigEvents,
      'mouseout',
      val,
    );
  };
  onMounted(() => {
    // 获取eventBus传过来的值
    EventBus.on(props.chartConfig.id + 'dataupdate', (data) => {
      console.log('data', data);
    });
    // websocket传过来的值
    EventBus.on(props.chartConfig.id + 'websocket', (data) => {
      console.log('data', data);
    });
  });
</script>
