<!--
 * @Author: changjun
 * @FilePath: /yuan-qingdao-zld-browser/src/components/chart/CustomChart/crossBarChart.vue
 * @Date: 2022-08-29 16:06:58
 * @Description: 
 * @LastEditTime: 2023-08-31 14:20:21
 * @LastEditors: 曹文丽
-->
<script setup lang="ts">
import { Ref, defineProps, watchEffect, unref, ref, computed } from "vue";
import type { EChartsOption } from "echarts";
import { useECharts } from "../../../hooks/web/useECharts";
import { bigNumberTransform } from "../../../utils/utils";
import {
  colorNewList,
  mergeOptions,
  getBarChartThemeColor,
  getCommonTheme,
} from "../../../components/chart/options/index";
import { isObject } from "../../../utils/is";
import img1 from "../../../assets/image/monitor.png";
const chartRef = ref<HTMLDivElement | null>(null);
const { setOptions, getInstance, echarts } = useECharts(
  chartRef as Ref<HTMLDivElement>
);
import { useLineXAxisAuto } from "../logic/useLineXAxisAuto";
import { isArray } from "@vue/shared";
import { getThemeColor } from "../../../components/chart/options/theme";
import { mapMapping } from "../../../assets/map/provinceData";
const mapData = mapMapping();
const yaTheme = localStorage.getItem("YA_THEME");
/**
 * @author changjun
 * @description 基础组件-柱状图组件
 * @prop { String } title 图表左上显示内容
 * @prop { Array } xAxisData x轴数据
 * @prop { Function } legendFormatter 图例自定义显示
 * @prop { Object } otherOptions 手动设置一些其它的设置 结合manual
 * @prop { Function } legendFormatter 图例自定义显示函数
 * @date 2022/08/29
 */
interface BarChartProps {
  title?: string;
  yAxisData: any[];
  theme?: string;
  autoXAxis?: boolean;
  /**
   * 图表数据
   */
  chartData: any[];
  /**
   * 格式化图例显示函数 用于需要显示图例名称之外内容的时候
   */
  legendFormatter?: string | ((name: string) => string);
  italics?: boolean;
  /**
   * 是否需要手动设置一些其它的设置，需要结合otherOptions才能起作用
   */
  manual?: boolean;
  /**
   * 手动设置色盘
   */
  colors?: string[];
  /**
   * 柱状图同一系列是否开启堆叠
   */
  stack?: boolean;
  tooltipValueFormatter?: any;
  /**
   * 手动设置一些其它的设置，需要结合manual才能起作用
   */
  otherOptions?: EChartsOption;
  barGradientColor?: string[];
  barGradientColorList?: any[];
  xInterval?: number;
  gridTop?: string | number;
  gridBottom?: string | number;
  gridLeft?: string | number;
  gridRight?: string | number;
  xname?: string;
  yname?: string;
  tootbackgroundColor?: string;
  legendLeft: number;
  legendRight: number;
  xAxisData: any[];
  xAxisType: string;
  interval: number;
  isShowSide?: boolean;
  legendShow?: boolean;
  tooltipFormatter?:
  | string
  | ((params: any, ticket: any, callback: any) => string);
}

const {
  xAxisType = "value",
  xAxisData = [],
  yAxisData = [],
  title = "",
  chartData = [],
  legendFormatter = (name) => name,
  manual = false,
  theme = "light",
  otherOptions = {},
  colors = [],
  barGradientColor = [],
  barGradientColorList = [],
  stack = false,
  tooltipValueFormatter = (val) => val,
  autoXAxis = false,
  gridTop = 44,
  gridBottom = 0,
  gridLeft = 0,
  gridRight = 24,
  xname = "",
  yname = "",
  tootbackgroundColor = "rgba(35, 67, 107, .9)",
  legendRight = 0,
  interval = 0,
  isShowSide = false,
  legendShow = true,
  tooltipFormatter = "",
} = defineProps<BarChartProps>();
let colorsNew = colors;
let barGradientColorListNew = barGradientColorList;
if (colorsNew.length === 0) {
  colorsNew = getThemeColor()[
    mapData?.en === "anhui" ? "colorList" : "colorList"
  ] || ["#E9533A", "#FF9235", "#4BC795"];
}
if (barGradientColorListNew.length === 0) {
  barGradientColorListNew = getThemeColor()[
    mapData?.en === "anhui" ? "colorList" : "colorList"
  ] || [
      ["rgba(231, 86, 45, 1)", "rgba(255, 94, 94, 0.12)"],
      ["rgba(255, 159, 36, 1)", "rgba(241, 131, 1, 0.12)"],
      ["rgba(33, 210, 142, 1)", "rgba(75, 199, 149, 0.13)"],
    ];
}
const currentTheme = computed(() => {
  console.log(getBarChartThemeColor);
  return getBarChartThemeColor(unref(theme));
}) as any;

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

let options: EChartsOption = {
  title: {
    show: true,
    text: unref(title),
    top: 16,
    left: 0,
    textStyle: {
      fontSize: 12,
      color: "#8CECFF",
      fontWeight: 400,
    },
  },

  tooltip: {
    trigger: "axis",
    show: true,
    confine: true,
    textStyle: {
      color: unref(commonChartTheme).tooltip.textStyle.color,
    },
    backgroundColor: unref(commonChartTheme).tooltip.backgroundColor,
    borderColor: "transparent",
    extraCssText: "border-radius: 4px;",
    valueFormatter: unref(tooltipValueFormatter),
    formatter: unref(tooltipFormatter) as any,
  },
  grid: {
    top: unref(gridTop),
    left: unref(gridLeft),
    right: unref(gridRight),
    bottom: unref(gridBottom),
    containLabel: true,
    backgroundColor: "rgba(0,172,236,0.08)",
  },
  // dataZoom : [{
  //   type: 'slider',//给x轴设置滚动条
  //   show: true, //flase直接隐藏图形
  //   xAxisIndex: [0],
  //   bottom:0,
  //   height:20,
  //   showDetail: false,
  //   startValue: 0,//滚动条的起始位置
  //   endValue: 9 //滚动条的截止位置（按比例分割你的柱状图x轴长度）
  // },
  // {
  //   type: 'inside',//设置鼠标滚轮缩放
  //   show: true,
  //   xAxisIndex: [0],
  //   startValue: 0,
  //   endValue: 9
  // }],
  legend: {
    show: unref(legendShow),
    top: 16, // 距离容器上边界的距离
    right: legendRight, // 距离容器右边界的距离
    itemWidth: 8, // 图例宽度
    itemHeight: 8, // 图例高度
    itemGap: 9, // 图例间距
    icon: "roundRect",
    // 图例文字的样式
    textStyle: {
      fontSize: 12,
      fontWeight: 400,
      color:
        yaTheme === "light"
          ? "rgba(0, 0, 0, 0.4)"
          : yaTheme === "jasper"
            ? "#fff"
            : "#8CECFF",
    },
    formatter: unref(legendFormatter),
  },
  xAxis: [
    {
      type: "category",
      data: [],
      name: unref(xname),
      nameTextStyle: {
        color: unref(currentTheme).axisLabelColor,
        fontSize: 12,
      },
      axisLabel: {
        fontSize: 12,
        fontWeight: 400,
        color: yaTheme === "light" ? "rgba(0, 0, 0, 0.4)" : "#8CECFF",
        interval: interval || 0, //demo
      },
      axisTick: { show: false },
      axisLine: {
        show: true,
        lineStyle: {
          color: unref(currentTheme).axisLineColor,
          width: 1,
        },
      },
      splitLine: {
        show: false,
      },
    },
  ],
  yAxis: [
    {
      name: unref(yname),
      type: "value",
      nameTextStyle: {
        color: yaTheme === "light" ? "rgba(0, 0, 0, 0.4)" : "#8CECFF",
        fontSize: 12,
      },
      minInterval: 1,
      min: xAxisData.length ? 0 : 5,
      axisLabel: {
        fontSize: 12,
        fontWeight: 400,
        color: yaTheme === "light" ? "rgba(0, 0, 0, 0.4)" : "#8CECFF",
        width: 100,
        // @ts-ignore
        overflow: "break",
        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;
          }
        },
      },
      splitLine: {
        // 坐标轴分割线
        show: false,
        lineStyle: {
          color: yaTheme === "light" ? "#f4f4f4" : "#32496D",
        },
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: unref(currentTheme).axisLineColor,
          width: 1,
        },
      },
    },
  ],
  series: [],
};

const getSeriesData = function (list) {
  console.log(colorsNew, "=====");
  let _colors = colorNewList;
  if (colorsNew) {
    _colors = colorsNew;
  }
  return list.map((item, index) => {
    const newItem = {
      type: "bar",
      barWidth: "30%",
      itemStyle: {
        borderRadius: [0, 0, 0, 0],
      },
      smooth: true,
    } as any;

    if (unref(stack)) {
      newItem.stack = "stack";
    }

    if (unref(barGradientColor).length > 0) {
      newItem.itemStyle.color = {
        type: "linear",
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [
          {
            offset: 0,
            color: unref(barGradientColor)[0], // 0% 处的颜色
          },
          {
            offset: 1,
            color: unref(barGradientColor)[1], // 100% 处的颜色
          },
        ],
        global: false,
      };
    }
    if (unref(barGradientColorListNew).length > 0) {
      newItem.itemStyle.color = isArray(barGradientColorListNew[index])
        ? {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: unref(barGradientColorListNew)[index][0], // 0% 处的颜色
            },
            {
              offset: 1,
              color: unref(barGradientColorListNew)[index][1], // 100% 处的颜色
            },
          ],
          global: false,
        }
        : barGradientColorListNew[index];
    }
    console.log(unref(barGradientColorListNew), "listtt");
    return {
      ...newItem,
      ...item,
    };
  });
};

let stopAutoShowFun = null as any;
let activeList = ref([]) as any; // 定义一个激活的状态表
watchEffect(() => {
  initChart();
});
function initChart() {
  options.xAxis![0].data = unref(xAxisData);
  options.xAxis![0].axisLabel.interval = interval;
  options.series = getSeriesData(unref(chartData));
  let yAXisValue = null;
  chartData.forEach((item) => {
    yAXisValue = item.data.find((item) => Number(item) > 0) || yAXisValue;
  });
  options.yAxis![0].min = yAXisValue ? 0 : 5;
  // @ts-ignore
  options.title!.text = unref(title);
  // @ts-ignore
  options.legend!.formatter = unref(legendFormatter);
  // 如果是手动设置模式的话
  if (unref(manual) && isObject(unref(otherOptions))) {
    options = mergeOptions(options, unref(otherOptions));
  }
  options.series = options.series.map((item) => {
    if (item.type == "line") {
      delete item.stack;
    }
    return item;
  });
  if (unref(tooltipFormatter)) {
    // @ts-ignore
    options.tooltip!.formatter = unref(tooltipFormatter);
  }
  setOptions(options);
  if (unref(isShowSide)) {
    initXside();
    delete options.xAxis[0].axisLabel.interval;
  }
  initChartDataActiveList();
}
function initXside() {
  options.dataZoom = {
    type: "slider",
    showDetail: false, //即拖拽时候滚动条两侧不显示信息 默认true
    realtime: true, //拖动滚动条时是否动态的更新图表数据
    height: 20, //滚动条高度
    start: 0, //滚动条开始位置（共100等份）
    end: 100, //结束位置（共100等份）
    handleSize: "100%", // 两侧手柄的大小
    backgroundColor: "#32496D", // 滚动条背景色
    borderColor: "#32496D", // 滚动条边框色
    bottom: 0, // 滚动条位置
    handleIcon: "image://" + img1,
    dataBackground: {
      lineStyle: {
        color: "rgba(84, 188, 255, 1)", // 滚动条内线颜色
      },
    },
    moveHandleSize: 0, // 移动手柄高度
  };
  console.log(options, "optionsoptionsoptions");
}
function openAutoAxis() {
  if (
    unref(autoXAxis) &&
    unref(chartData).length > 0 &&
    unref(yAxisData).length > 7
  ) {
    if (stopAutoShowFun) {
      stopAutoShowFun();
    }
    const instance = getInstance();
    const { stopAutoSwipe } = useLineXAxisAuto(
      instance,
      options,
      unref(yAxisData)
    );
    stopAutoShowFun = stopAutoSwipe;
  }
}

const handleClick = (name) => {
  const instance = getInstance();
  if (instance) {
    instance.dispatchAction({
      type: "legendToggleSelect",
      name: name,
    });
    console.log(name);
    if (unref(activeList).includes(name)) {
      activeList.value = unref(activeList).filter((item) => item !== name);
    } else {
      activeList.value = [...unref(activeList), name];
    }
  }
};

function initChartDataActiveList() {
  const list = unref(chartData).map((item) => {
    return item.name;
  });
  activeList.value = list;
}

const handleHover = (name) => {
  const instance = getInstance();
  if (instance) {
    instance.dispatchAction({
      type: "highlight",
      name: name,
    });
  }
};

const handleHoverLeave = (name) => {
  const instance = getInstance();
  if (instance) {
    instance.dispatchAction({
      type: "downplay",
      name: name,
    });
  }
};
</script>

<template>
  <div class="position-relative" v-if="!legendShow">
    <div class="flex-st">
      <div @mouseover="handleHover(item.name)" @mouseleave="handleHoverLeave(item.name)"
        :class="activeList.includes(item.name) ? 'is-active' : 'is-unactive'" v-for="(item, index) in chartData"
        @click="handleClick(item.name)">
        <div class="flex-x-st">
          <div class="circle-icon" :style="{
            background: activeList.includes(item.name)
              ? colorsNew[index]
              : '#ddd',
          }"></div>
          <div class="circle-name" :class="yaTheme == 'jasper' ? 'jasper-circle-name' : ''">
            {{ item.name }}
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="chart" ref="chartRef" :style="{ width: '100%', height: '100%' }"></div>
</template>
<style scoped lang="scss">
.flex-st {
  display: flex;
  color: #96a2b5;
  font-size: 12px;
  position: absolute;
  right: 20px;
  top: 15px;
}

.circle-icon {
  border-radius: 2px;
  width: 12px;
  height: 12px;
  margin-right: 5px;
}

.position-relative {
  position: relative;
  z-index: 1;
}

.flex-x-st {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
}

.rose-linechart-tooltip {
  background: rgba(9, 103, 138, 0.8);
  padding: 9px 12px;
  border-radius: 3px;
  color: #fff;
  font-size: 12px;
  font-weight: 400;
  min-width: 150px;
  padding-top: 12px;

  .rose-linechart-tooltip-content-item-icon {
    margin-top: 12px;
  }

  .rose-linechart-tooltip-subtitle {
    color: #fff;
    font-size: 12px;
    margin-top: 12px;
  }

  .rose-linechart-tooltip-content-item-value {
    font-weight: 400;
    color: #fff;
  }
}
</style>
