<script setup lang="ts">
import { Ref, defineProps, watchEffect, ref, computed, unref, onMounted, onUnmounted } from "vue";
import type { EChartsOption } from "echarts";
import { bigNumberTransform } from "../../../utils/utils";
import { useECharts } from "../../../hooks/web/useECharts";
import useEchartsAutoTooltip from "../../../components/chart/logic/useEchartsAutoTooltip";
import { useLineXAxisAuto } from "../../../components/chart/logic/useLineXAxisAuto";
import {
  mergeOptions,
  removeExtraCssText,
  getCommonTheme,
} from "../../../components/chart/options/index";
import { getThemeColor } from "../../../components/chart/options/theme";

import { isObject, isTowArray } from "../../../utils/is";
import img1 from "../../../assets/image/monitor.png";

const themeColor = getThemeColor();
const chartRef = ref<HTMLDivElement | null>(null);
const { setOptions, getInstance, echarts, resize } = useECharts(
  chartRef as Ref<HTMLDivElement>
);
const yaTheme = localStorage.getItem("YA_THEME");
/**
 * @author changjun
 * @description 折线图组件
 * @prop { String } title 标题
 * @prop { Array } chartData 图表数据
 * @prop { Boolean } smooth 开启平滑模式
 * @prop { Boolean } manual 手动设置 结合otherOptions
 * @prop { Object } otherOptions 手动设置一些其它的设置 结合manual
 * @prop { Function } legendFormatter 图例自定义显示函数
 * @date 2022/08/29
 */
interface LineChartProps {
  title?: string;
  xAxisData: any[];
  theme?: string;
  autotip?: boolean;
  autoAxis?: boolean;
  colors?: string[];
  /**
   * 图表数据
   */
  chartData: any[];
  /**
   * 是否开启平滑模式
   */
  smooth?: boolean;
  tooltipFormatter?:
  | string
  | ((params: any, ticket: any, callback: any) => string);
  /**
   * 格式化图例显示函数 用于需要显示图例名称之外内容的时候
   */
  legendFormatter?: string | ((name: string) => string);
  /**
   * 是否需要手动设置一些其它的设置，需要结合otherOptions才能起作用
   */
  manual?: boolean;
  /**
   * 手动设置一些其它的设置，需要结合manual才能起作用
   */
  otherOptions?: EChartsOption;
  areaGradientColor?: any[];
  autoXAxis?: boolean;
  autoStartValue?: number;
  autoEndValue?: number;
  xInterval?: number; // 设置X轴间隔
  xFontSize?: number;
  xAxisAxisLineShow?: boolean;
  xAxisSplitLineShow?: boolean;
  yAxisAxisLineShow?: boolean;
  yAxisSplitLineShow?: boolean;
  showSymbol?: boolean;
  gridTop?: number | string; // 布局距离顶部
  gridBottom?: number | string; // 布局距离底部
  gridLeft?: number | string; // 布局距离左侧
  gridRight?: number | string; // 布局距离右侧
  titleLeft?: number | string; // Y轴title距离左侧距离
  tooltipValueFormatter?: any;
  legendRight?: number | string; // 图例距离右边的位置
  isShowSide?: boolean;
  containLabel?: boolean;
  splitLineColor?: number | string; // 图例距离右边的位置
  tooltipBg?: number | string;
  tooltipColor?: number | string;
  lendData?: any[];
  titleTop?: number | string;
  legendTop?: number | string;
  yAxisColor?: string;
  yLineColor?: string;
}

let {
  xAxisData = [],
  title = "",
  chartData = [],
  legendFormatter = (name) => name,
  smooth = true,
  manual = false,
  otherOptions = {},
  tooltipFormatter = "",
  areaGradientColor = getThemeColor().lineGradient,
  theme = "light",
  colors = [],
  autoXAxis = false,
  autoStartValue = 0,
  autoEndValue = 6,
  xInterval = 0,
  xFontSize = 10,
  autotip = false,
  autoAxis = false,
  xAxisAxisLineShow = true,
  xAxisSplitLineShow = false,
  yAxisAxisLineShow = true,
  yAxisSplitLineShow = false,
  showSymbol = true,
  gridTop = 55,
  gridBottom = 0,
  gridLeft = 0,
  gridRight = 5,
  titleLeft = 0,
  legendRight = 0,
  isShowSide = false,
  tooltipValueFormatter = (val) => bigNumberTransform(val),
  containLabel = true,
  splitLineColor = "rgba(154, 239, 255, 0.22)",
  tooltipBg = "",
  tooltipColor = "",
  lendData = [],
  titleTop = 16,
  legendTop = 16,
  yAxisColor = '',
  yLineColor = '',
} = defineProps<LineChartProps>();

const commonChartTheme = computed(() => {
  return getCommonTheme(unref(theme));
}) as any;

let options: EChartsOption = {
  title: {
    show: true,
    text: unref(title),
    top: unref(titleTop),
    left: unref(titleLeft),
    textStyle: {
      fontSize: 12,
      color: yaTheme === "light" ? "rgba(0, 0, 0, 0.4)" : "#8CECFF",
      fontWeight: 400,
    },
  },

  tooltip: {
    trigger: "axis",
    show: true,
    confine: true,
    textStyle: {
      color: tooltipColor
        ? tooltipColor
        : unref(commonChartTheme).tooltip.textStyle.color,
    },
    backgroundColor: tooltipBg
      ? tooltipBg
      : unref(commonChartTheme).tooltip.backgroundColor,
    borderColor: "transparent",
    extraCssText: "border-radius: 4px;",
    formatter: unref(tooltipFormatter) as any,
    valueFormatter: unref(tooltipValueFormatter),
  },

  color: unref(colors).length > 0 ? unref(colors) : themeColor.lineColorList,

  grid: {
    top: unref(gridTop),
    left: unref(gridLeft),
    right: unref(gridRight),
    bottom: isShowSide ? 24 : unref(gridBottom),
    containLabel: unref(containLabel),
    backgroundColor: yAxisColor ? 'none' : "rgba(0,172,236,0.08)",
    show: true,
    borderWidth: 0,
  },

  legend: {
    show: true,
    top: unref(legendTop), // 距离容器上边界的距离
    right: legendRight, // 距离容器右边界的距离
    itemWidth: 6, // 图例宽度
    itemHeight: 6, // 图例高度
    itemGap: 16, // 图例间距
    icon: "circle",
    // 图例文字的样式
    textStyle: {
      fontSize: 12,
      fontWeight: 400,
      color:
        yaTheme === "light"
          ? "rgba(0, 0, 0, 0.4)"
          : yaTheme === "jasper"
            ? "#fff"
            : "#8CECFF",
    },
    formatter: unref(legendFormatter),
  },

  xAxis: [
    {
      data: unref(xAxisData),
      axisLabel: {
        fontSize: xFontSize,
        fontWeight: 400,
        color: yaTheme === "light" ? "rgba(0, 0, 0, 0.4)" : yAxisColor ? yAxisColor : "#8CECFF",
        interval: unref(xInterval),
      },
      axisTick: { show: false },
      splitLine: {
        show: unref(xAxisSplitLineShow),
        lineStyle: {
          color: "#f4f4f4",
          width: 1,
        },
      },
      axisLine: {
        show: unref(xAxisAxisLineShow),
        lineStyle: {
          color: splitLineColor
            ? splitLineColor
            : yaTheme === "light"
              ? "#f4f4f4"
              : "#8CECFF",
          width: 1,
          type: 'solid'
        },
      }, // 坐标轴轴线
      boundaryGap: true,
    },
  ],

  yAxis: [
    {
      type: "value",
      axisLabel: {
        fontSize: 10,
        fontWeight: 400,
        color: yaTheme === "light" ? "rgba(0, 0, 0, 0.4)" : yAxisColor ? yAxisColor : "#8CECFF",
        formatter: function (value) {
          if (value >= 100000000) {
            return value / 100000000 + "亿";
            // } else if (value >= 10000000) {
            //   return value / 10000000 + "千万";
            // } else if (value >= 1000000) {
            //   return value / 1000000 + "百万";
            // } else if (value >= 100000) {
            //   return value / 100000 + "十万";
          } else if (value >= 10000) {
            return value / 10000 + "万";
          } else {
            return value;
          }
        },
      },
      minInterval: 1,
      min: 0,
      max: 5,
      splitLine: {
        // 坐标轴分割线
        show: unref(yAxisSplitLineShow),
        lineStyle: { color: yaTheme === "light" ? "#f4f4f4" : yLineColor ? yLineColor : "#32496D", type: unref(yAxisColor) ? 'dotted' : 'solid' }, // 分割线颜色
      },
      axisLine: {
        show: unref(yAxisAxisLineShow),
        lineStyle: {
          color: splitLineColor ? splitLineColor : "#f4f4f4",
          width: 1,
        },
      },
    },
  ],
  series: [],
};

const getSeriesData = function (list) {
  let yAxios;
  return list.map((item, index) => {
    if (!yAxios) {
      yAxios = item.data?.find((item) => {
        return item > 5;
      });
    }
    options.yAxis![0].max = yAxios ? null : 5;
    const newItem = {
      type: "line",
      showSymbol: unref(showSymbol),
      smooth: unref(smooth),
      lineStyle: { width: 1.5 },
    } as any;

    if (unref(showSymbol)) {
      newItem.symbol = "circle";
      newItem.symbolSize = 6;
    }
    if (unref(areaGradientColor).length > 0) {
      const _isTowArray = isTowArray(unref(areaGradientColor));
      const _startColor = _isTowArray
        ? unref(areaGradientColor)[index][0]
        : unref(areaGradientColor)[0];
      const _endColor = _isTowArray
        ? unref(areaGradientColor)[index][1]
        : unref(areaGradientColor)[1];
      newItem.areaStyle = {
        color: {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: _startColor, // 0% 处的颜色
            },
            {
              offset: 1,
              color: _endColor, // 100% 处的颜色
            },
          ],
          global: false,
        },
      };
    }
    return {
      ...newItem,
      ...item,
    };
  });
};

let stopAutoShowFun = null as any;
let stopAutoSwipeFun = null as any;

async function initChart() {
  options.series = getSeriesData(unref(chartData));
  console.log(options.series);
  options.series.forEach((item) => {
    item.showAllSymbol = false;
  });
  options.xAxis![0].data = unref(xAxisData);
  options.xAxis![0].axisLabel!.interval = unref(xInterval);
  //   unref(xInterval) ||
  //   (xAxisData.length > 20 && xAxisData.length < 35 ? 2 : 0);

  // const xData = (chartData[0] && chartData[0].data) || [];
  // const yAXisValue = xData.find((item) => Number(item) > 0);
  // options.yAxis![0].min = yAXisValue ? 0 : 5;
  // @ts-ignore
  options.title!.text = unref(title);
  // @ts-ignore
  options.legend!.formatter = unref(legendFormatter);
  if (unref(tooltipFormatter)) {
    // @ts-ignore
    options.tooltip!.extraCssText = removeExtraCssText;
    // @ts-ignore
    options.tooltip!.formatter = unref(tooltipFormatter);
  } else {
    // @ts-ignore
    options.tooltip!.extraCssText = "border-radius: 4px;";
    // @ts-ignore
    options.tooltip!.borderColor = "transparent";
    // @ts-ignore
    if (unref(tooltipColor)) {
      options.tooltip!.textStyle.color = unref(tooltipColor);
    } else {
      options.tooltip!.textStyle.color =
        unref(commonChartTheme).tooltip.textStyle.color;
    }

    // @ts-ignore
    options.tooltip!.textStyle.backgroundColor =
      unref(commonChartTheme).tooltip.backgroundColor;
  }
  // 如果是手动设置模式的话
  if (unref(manual) && isObject(unref(otherOptions))) {
    options = mergeOptions(options, unref(otherOptions));
  }
  console.log(options, "-----------");
  if (unref(lendData).length > 0) {
    options.legend.data = unref(lendData);
    options.legend.itemWidth = 14;
    options.legend.itemHeight = 14;
  }
  openAutoTooltip();
  setOptions(options);
  initAutoXAxis();
  if (unref(isShowSide)) {
    initXside();
    delete options.xAxis[0].axisLabel.interval;
  }
}

const initXside = () => {
  options.dataZoom = {
    type: "slider",
    showDetail: false, //即拖拽时候滚动条两侧不显示信息 默认true
    realtime: true, //拖动滚动条时是否动态的更新图表数据
    height: 20, //滚动条高度
    start: unref(xAxisData).length, //滚动条开始位置（共100等份）
    end: 100, //结束位置（共100等份）
    handleSize: "100%", // 两侧手柄的大小
    backgroundColor: "#32496D", // 滚动条背景色
    borderColor: "#32496D", // 滚动条边框色
    bottom: 0, // 滚动条位置
    handleIcon: "image://" + img1,
    minSpan: 6,
    dataBackground: {
      lineStyle: {
        color: "rgba(84, 188, 255, 1)", // 滚动条内线颜色
      },
    },
    moveHandleSize: 0, // 移动手柄高度
  };
};
const initAutoXAxis = () => {
  if (unref(autotip)) return;
  if (
    unref(autoAxis) &&
    unref(chartData).length > 0 &&
    unref(xAxisData).length > 7
  ) {
    options.dataZoom = {
      type: "slider",
      show: false,
      xAxisIndex: 0,
      startValue: 0,
      endValue: 6,
    };
    if (stopAutoSwipeFun) {
      stopAutoSwipeFun();
    }
    const chartInstance = getInstance();
    const { stopAutoSwipe } = useLineXAxisAuto(
      chartInstance,
      options,
      unref(xAxisData)
    );
    stopAutoSwipeFun = stopAutoSwipe;
  }
};

function openAutoTooltip() {
  if (unref(autotip) && unref(chartData).length > 0) {
    if (stopAutoShowFun) {
      stopAutoShowFun();
    }
    const instance = getInstance();
    const { stopAutoShow } = useEchartsAutoTooltip(instance, options);
    stopAutoShowFun = stopAutoShow;
  }
}
onMounted(() => {
  initChart();
});

watchEffect(() => {
  initChart();
});

onUnmounted(() => {
  stopAutoSwipeFun && stopAutoSwipeFun();
  stopAutoShowFun && stopAutoShowFun();
});
</script>

<template>
  <div class="chart" ref="chartRef" :style="{ width: '100%', height: '100%' }"></div>
</template>

<style lang="scss">
.light-linechart-tooltip {
  padding: 6px 12px;
  box-sizing: border-box;
  background: rgba(255, 255, 255, 0.96);
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  display: flex;
  flex-direction: column;

  &-subtitle {
    font-size: 12px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.65);
    line-height: 1;
  }

  &-content {
    // display: flex;
    // max-width: 200px;
    // flex-wrap: wrap;
    // flex-shrink: 0;

    &-item {
      display: flex;
      align-items: center;
      margin-top: 8px;

      &-icon {
        width: 6px;
        height: 6px;
        border-radius: 6px;
        margin-right: 5px;
      }

      &-name {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.65);
        margin-right: 8px;
        min-width: 100px;
      }

      &-value {
        width: 77px;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.4);
        text-align: right;
        flex: 1;
      }
    }
  }
}

.light-linechart-tooltip-vertical {
  &-content {
    display: flex;
    flex-direction: column;
  }
}

.line-chart-tool-bg {
  background: rgba(9, 103, 138, 0.8);
  padding: 9px 12px;
  border-radius: 3px;
  color: #fff;
  font-size: 12px;
  font-weight: 400;
  min-width: 150px;

  .line-chart-tool-bg-subtitle {
    font-weight: bold;
  }

  .line-chart-tool-info {
    display: flex;
    align-items: center;
  }

  .line-chart-tool-item {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .line-chart-tool-item-icon {
      width: 9px;
      height: 9px;
      border-radius: 50%;
      margin-right: 5px;
    }

    .line-chart-tool-item-value {
      font-weight: 400;
      margin-left: 10px;
      font-family: YouSheBiaoTiHei;
    }
  }
}
</style>
