<template>
  <div class="HuoQingDetailPie">
    <div class="pie">
      <v-chart
        ref="vChartRef"
        autoresize
        :init-options="initOptions"
        :theme="themeColor"
        :option="option"
        :manual-update="isPreview()"
        @mouseover="handleHighlight"
        @mouseout="handleDownplay"
      >
      </v-chart>
      <div class="sum" v-if="showSum">
        <div class="sumSpan1" v-if="!mouseFlag">{{ totalData }}</div>
        <div class="sumSpan2" v-if="!mouseFlag">{{ sumName }}</div>
        <div class="container" v-if="mouseFlag">
          <div class="sumSpan3">
            {{ sumName }}
          </div>
          <div class="sumSpan3">
            {{ totalData }}
          </div>
        </div>
      </div>
    </div>
    <div class="list">
      <div class="li" v-for="item in nowData" :key="item.key" @click="clickLi(item)">
        <div
          class="fontDivColor"
          :style="{ background: item.visible ? item.background : '#CCCCCC' }"
        />
        <span
          class="fontSpan1"
          :style="{ color: item.visible ? optionData.dataStyle.liFontSpanColor1 : '#CCCCCC' }"
        >
          {{ item.product }}
        </span>
        <span
          class="fontSpan2"
          :style="{ color: item.visible ? optionData.dataStyle.liFontSpanColor2 : '#CCCCCC' }"
        >
          {{ item.data }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, PropType, toRefs, ref, reactive, onMounted, watch } from 'vue';
  import VChart from 'vue-echarts';
  import { useCanvasInitOptions } from '@/hooks/useCanvasInitOptions.hook';
  import { use } from 'echarts/core';
  import { CanvasRenderer } from 'echarts/renderers';
  import { PieChart } from 'echarts/charts';
  import { mergeTheme } from '@/packages/public/chart';
  import config, { includes } from './config';
  import { useChartDataFetch } from '@/hooks';
  import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore';
  import { isPreview } from '@/utils';
  import {
    DatasetComponent,
    GridComponent,
    TooltipComponent,
    LegendComponent,
  } from 'echarts/components';
  import dataJson from './data.json';
  import { cloneDeep } from 'lodash-es';
  import { EventBus } from '@/utils/eventBus';
  import { replaceSqlParams } from '@/utils/sqlHandler';

  const props = defineProps({
    themeSetting: {
      type: Object,
      required: true,
    },
    themeColor: {
      type: Object,
      required: true,
    },
    chartConfig: {
      type: Object as PropType<config>,
      required: true,
    },
  });
  const { w, h } = toRefs(props.chartConfig.attr);

  const initOptions = useCanvasInitOptions(
    getDataset(props.chartConfig.option),
    props.themeSetting,
  );

  use([
    DatasetComponent,
    CanvasRenderer,
    PieChart,
    GridComponent,
    TooltipComponent,
    LegendComponent,
  ]);

  const { vChartRef } = useChartDataFetch(props.chartConfig, useChartEditStore);

  const option = computed(() => {
    return mergeTheme(getDataset(props.chartConfig.option), props.themeSetting, includes);
  });

  const optionData = reactive({
    dataStyle: props.chartConfig.option.dataStyle,
    status: props.chartConfig.status,
  });

  watch(
    () => optionData.status.hide,
    () => {
      if (!optionData.status.hide) {
        initialization();
      }
    },
  );

  // 鼠标浮动-计算总数据
  const showSum = ref(true);
  const sumName = ref('总受损面积');
  const totalData = ref(0);
  const mouseFlag = ref(false);

  // function mouseEnter(item) {
  //   mouseFlag.value = true;
  //   sumName.value = item.product;
  //   totalData.value = item.data;
  // }
  // function mouseLeave(item) {
  //   mouseFlag.value = false;
  //   sumName.value = '总受损面积';
  //   totalData.value = option.value.dataset.reduce(
  //     (sum, item) => sum + (item.visible ? item[option.value.dimensions[1]] : 0),
  //     0,
  //   );
  // }

  // 点击列表项
  function clickLi(item) {
    item.visible = !item.visible;
    // option.value.series.data = option.value.dataset.source
    //   .filter((item) => item.visible)
    //   .map((item) => ({
    //     name: item.product,
    //     value: item.data,
    //   }));
  }

  const nowData = computed(() => {
    // return option.value.dataset.source.filter((item) => {
    //   return item.visible;
    // });
    return option.value.dataset.source;
  });

  // 初始化列表
  watch(
    () => props.themeColor.color,
    () => {
      initialization();
    },
    {
      immediate: true,
      deep: true,
    },
  );

  function initialization() {
    option.value.dataset.source = option.value.dataset.source.map((item, index) => {
      return {
        ...item,
        key: index,
        visible: true,
        background: props.themeColor.color[index],
      };
    });
  }

  function getDataset(option) {
    let combinationData = cloneDeep(option);
    let dimensions = cloneDeep(option.dimensions);
    let dataset = cloneDeep(option.dataset);
    combinationData.dataset = {
      dimensions: dimensions,
      source: dataset,
    };
    return combinationData;
  }

  // 处理鼠标聚焦高亮内容
  const handleHighlight = () => {
    showSum.value = false;
  };

  // 处理鼠标取消悬浮
  const handleDownplay = () => {
    showSum.value = true;
  };

  onMounted(() => {
    totalData.value = option.value.dataset.source.reduce(
      (sum, item) => sum + item[option.value.dataset.dimensions[1]],
      0,
    );

    // 组件通信
    const sql = props.chartConfig.request?.requestSQLContent?.sql;
    EventBus.on(props.chartConfig.id + 'dataupdate', (data) => {
      props.chartConfig.request.requestSQLContent.sql = replaceSqlParams(sql, { Id: data.id });
      // 数据callback处理（预览时触发）
      useChartDataFetch(props.chartConfig, useChartEditStore, (resData: any[]) => {
        console.log(resData);
        props.chartConfig.option.dataset = resData;
        getDataset(props.chartConfig.option);
      });
    });
  });

  // 数据callback处理（预览时触发）
  useChartDataFetch(props.chartConfig, useChartEditStore, (resData: any[]) => {
    props.chartConfig.option.dataset = resData;
    getDataset(props.chartConfig.option);
  });
</script>

<style lang="scss" scoped>
  .HuoQingDetailPie {
    width: v-bind('`${w}px`');
    height: v-bind('`${h}px`');

    // 页面不能被选中
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE/Edge */
    user-select: none;
  }
  .pie {
    position: relative;
    width: 100%;
    height: 60%;

    .sum {
      position: absolute;
      display: block;
      align-items: center;
      justify-content: center;
      top: 50%;
      left: 50%;
      transform: translate(-60%, -50%);

      .sumSpan1 {
        display: flex;
        align-items: center;
        justify-content: center;
        color: v-bind('`${optionData.dataStyle.sumSpanColor1}`');
        font-size: v-bind('`${optionData.dataStyle.sumSpanFontSize1}px`');
      }
      .sumSpan2 {
        display: flex;
        align-items: center;
        justify-content: center;
        color: v-bind('`${optionData.dataStyle.sumSpanColor2}`');
        font-size: v-bind('`${optionData.dataStyle.sumSpanFontSize2}px`');
      }

      .container {
        display: block;
        text-align: center;
        justify-content: center;
        white-space: nowrap;
      }
      .sumSpan3 {
        line-height: v-bind('`${option.series[0].emphasis.label.fontSize}px`');
        font-weight: v-bind('`${option.series[0].emphasis.label.fontWeight}`');
        font-size: v-bind('`${option.series[0].emphasis.label.fontSize}px`');
        color: v-bind('`${option.series[0].label.color}`');
        text-shadow:
          v-bind('`${-option.series[0].label.textBorderWidth}px`')
            v-bind('`${-option.series[0].label.textBorderWidth}px`')
            v-bind('`${ option.series[0].label.textBorderWidth* 2}px`')
            v-bind('`${option.series[0].label.textBorderColor}`'),
          v-bind('`${option.series[0].label.textBorderWidth}px`')
            v-bind('`${-option.series[0].label.textBorderWidth}px`')
            v-bind('`${option.series[0].label.textBorderWidth* 2}px`')
            v-bind('`${option.series[0].label.textBorderColor}`'),
          v-bind('`${-option.series[0].label.textBorderWidth}px`')
            v-bind('`${option.series[0].label.textBorderWidth}px`')
            v-bind('`${ option.series[0].label.textBorderWidth* 2}px`')
            v-bind('`${option.series[0].label.textBorderColor}`'),
          v-bind('`${option.series[0].label.textBorderWidth}px`')
            v-bind('`${option.series[0].label.textBorderWidth}px`')
            v-bind('`${option.series[0].label.textBorderWidth* 2}px`')
            v-bind('`${option.series[0].label.textBorderColor}`');
      }
    }
  }
  .list {
    width: 100%;
    height: 40%;
    margin-left: v-bind('`${optionData.dataStyle.listMarginLeft}px`');
    margin-right: v-bind('`${optionData.dataStyle.listMarginLeft}px`');
    overflow-y: auto;

    .li {
      background-image: url('@/assets/images/chart/zhiku/component/pielist.png');
      background-size: 100% 100%;
      background-repeat: no-repeat;
      width: v-bind('`${w - optionData.dataStyle.listMarginLeft * 2}px`');
      margin-bottom: v-bind('`${optionData.dataStyle.liMarginBottom}px`');

      position: relative;
      display: flex;
      align-items: center;

      .fontDivColor {
        margin-left: 10px;
        width: 10px;
        height: 10px;
        border-radius: 10px;
      }
      .fontSpan1 {
        position: relative;
        margin-left: 10px;
        color: v-bind('`${optionData.dataStyle.liFontSpanColor1}`');
        font-size: v-bind('`${optionData.dataStyle.liFontSpanFontSize1}px`');
      }
      .fontSpan2 {
        position: absolute;
        right: 20px;
        color: v-bind('`${optionData.dataStyle.liFontSpanColor2}`');
        font-size: v-bind('`${optionData.dataStyle.liFontSpanFontSize2}px`');
      }
    }
  }

  .list::-webkit-scrollbar {
    display: none;
  }

  .list {
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
</style>
