<!--
 * @Author: SunTao 328867980@qq.com
 * @Date: 2024-10-18 10:19:56
 * @LastEditors: SunTao 328867980@qq.com
 * @LastEditTime: 2024-10-29 13:43:38
 * @FilePath: \znxjxt-ui\src\views\big-screen\disease-components\disease-current.vue
 * @Description: 病害巡检-病害三维饼图
-->

<template>
  <div class="content">
    <div class="content-select">
      <el-select
        :popper-append-to-body="false"
        v-model="itemSelect"
        placeholder="请选择"
      >
        <el-option
          v-for="item in currentList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <div class="echart" ref="currentChart"></div>
    <div class="food-legend">
      <div
        class="legend-div"
        v-for="(item, index) in dataList"
        :key="`chart-${index}`"
      >
        <div class="index" :style="{ backgroundColor: colorList[index] }"></div>
        <div class="name">{{ item.typeName }}</div>
        <div class="rate">{{ item.rate }}%</div>
        <div class="value">{{ item.value }}</div>
      </div>
    </div>
  </div>
</template>
  
  <script>
import * as echarts from "echarts";
import "echarts-gl";
import { roadCurrent, getDropList } from "@/api/xj/screen/disease-screen";
export default {
  name: "DiseaseCurrent",
  props: {
    select: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 下拉框绑定
      itemSelect: "",
      // 下拉框数据
      currentList: [],
      // 配置项数据
      options: {},
      // 颜色盘
      colorList: [
        "#18F7FF",
        "#FFEA68",
        "#AE74F3",
        "#6FC36F",
        "#FF8F5F",
        "#6FC36F",
        "#4C83FF",
        "#FC5976",
        "#5B40B6",
      ],
      // echart数据
      dataList: [],
      // echart实例
      chart: "",
    };
  },
  watch: {
    select: {
      handler(val) {
        if (val) {
          this.itemSelect = "";
          this.getCurrentList();
          this.getChartList();
        }
      },
      immediate: true,
    },
    itemSelect: {
      handler() {
        this.getChartList();
      },
    },
  },
  created() {
    this.getChartList();
  },
  methods: {
    /* 获取右上角下拉框数据 */
    getCurrentList() {
      getDropList({ type: this.select }).then(({ data, code }) => {
        if (code === 200) {
          this.currentList = data;
        }
      });
    },
    /* 获取echart数据 */
    getChartList() {
      const data = {
        type: this.select,
        itemName: this.itemSelect,
      };
      roadCurrent(data).then(({ code, data }) => {
        if (code === 200) {
          let allSum = 0;
          data?.forEach((element) => {
            allSum += element.value;
          });
          this.dataList = data.map((item) => {
            return {
              ...item,
              rate: ((item.value / allSum) * 100).toFixed(1),
            };
          });
        }
        this.$nextTick(() => {
          //获取echart图所需的options
          this.drawChart();
        });
      });
    },
    /* 绘制echart图 */
    drawChart() {
      const data = this.dataList;
      if (this.$refs.currentChart) {
        if (this.chart) {
          this.chart.dispose();
        }
        this.chart = echarts.init(this.$refs.currentChart);
        this.chart.setOption({
          legend: {
            show: false,
          },
          animation: false,
          tooltip: {
            show: true,
            confine: false,
            backgroundColor: "rgba(9, 24, 48, 0.5)",
            borderColor: "rgba(75, 253, 238, 0.4)",
            textStyle: {
              fontSize: 12,
              color: "#ffffff",
            },
            formatter: (params) => {
              return `${params.marker}${params.seriesName}：${
                data[params.seriesIndex].value
              }`;
            },
          },
          labelLine: {
            show: false,
          },
          label: {
            show: false,
          },
          xAxis3D: {
            min: -1,
            max: 1,
          },
          yAxis3D: {
            min: -1,
            max: 1,
          },
          zAxis3D: {
            min: -1,
            max: 1,
          },
          grid3D: {
            show: false,
            width: "250%",
            height: "250%",
            // boxWidth: 100,
            boxHeight: 2,
            top: "-75%",
            left: "-75%",
            viewControl: {
              // 是否自动旋转
              autoRotate: true,
              // 调节角度
              alpha: 25,
              rotateSensitivity: 0, //设置旋转灵敏度，为0无法旋转
              zoomSensitivity: 0, //设置缩放灵敏度，为0无法缩放
              panSensitivity: 0, //设置平移灵敏度，0无法平移
            },
          },
          //最上方的series
          series: this.getPie3D(this.dataList, 0.8),
        });
        window.addEventListener("resize", () => {
          this.chart.resize();
        });
      }
    },
    /* 绘制3d饼图配置项 */
    getPie3D(pieData, internalDiameterRatio) {
      const series = [];
      let sumValue = 0;
      let startValue = 0;
      let endValue = 0;
      const legendData = [];
      const k =
        typeof internalDiameterRatio !== "undefined"
          ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio * 1)
          : 1 / 3;

      // 为每一个饼图数据，生成一个 series-surface 配置
      for (let i = 0; i < pieData.length; i++) {
        sumValue += pieData[i].value;

        const seriesItem = {
          name:
            typeof pieData[i].typeName === "undefined"
              ? `series${i}`
              : pieData[i].typeName,
          type: "surface",
          parametric: true,
          wireframe: {
            show: false,
          },
          pieData: pieData[i],
          pieStatus: {
            selected: false,
            hovered: false,
            k: 1 / 10,
          },
        };

        seriesItem.itemStyle = { color: this.colorList[i] };
        series.push(seriesItem);
      }

      // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
      // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
      for (let i = 0; i < series.length; i++) {
        endValue = startValue + series[i].pieData.value * 1;

        series[i].pieData.startRatio = startValue / sumValue;
        series[i].pieData.endRatio = endValue / sumValue;

        //绘制3d饼图
        series[i].parametricEquation = this.getParametricEquation(
          series[i].pieData.startRatio,
          series[i].pieData.endRatio,
          false,
          false,
          k,
          // 设置饼图高度
          series[i].pieData.value / 1000
        );

        startValue = endValue;

        legendData.push(series[i].typeName);
      }
      return series;
    },
    /* 配置项参数 */
    getParametricEquation(
      startRatio,
      endRatio,
      isSelectedValue,
      isHovered,
      kk,
      height
    ) {
      // 计算
      const midRatio = (startRatio + endRatio) / 2;

      const startRadian = startRatio * Math.PI * 2;
      const endRadian = endRatio * Math.PI * 2;
      const midRadian = midRatio * Math.PI * 2;
      let isSelected = isSelectedValue;

      // 如果只有一个扇形，则不实现选中效果。
      if (startRatio === 0 && endRatio === 1) {
        isSelected = false;
      }

      // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
      const k = typeof kk !== "undefined" ? kk : 1 / 3;

      // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
      const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
      const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;
      // const offsetZ = i == 1 ? 2 : 0;
      // 计算高亮效果的放大比例（未高亮，则比例为 1）
      const hoverRate = isHovered ? 1.05 : 1;

      // 返回曲面参数方程
      return {
        u: {
          min: -Math.PI,
          max: Math.PI * 3,
          step: Math.PI / 32,
        },

        v: {
          min: 0,
          max: Math.PI * 2,
          step: Math.PI / 20,
        },

        x: (u, v) => {
          if (u < startRadian) {
            return (
              offsetX +
              Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          if (u > endRadian) {
            return (
              offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
        },

        y: (u, v) => {
          if (u < startRadian) {
            return (
              offsetY +
              Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          if (u > endRadian) {
            return (
              offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
        },

        z: (u, v) => {
          if (u < -Math.PI * 0.5) {
            return Math.sin(u);
          }
          if (u > Math.PI * 2.5) {
            return Math.sin(u);
          }
          return Math.sin(v) > 0 ? 1 * height : -1;
        },
      };
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;

  .content-select {
    position: absolute;
    z-index: 1;
    right: 0;
    top: 0.2rem;

    ::v-deep .el-select {
      width: 6.5rem;

      .el-input .el-select__caret {
        line-height: 1.5rem;
      }

      .el-input--medium .el-input__inner {
        height: 1.5rem;
        background-color: transparent;
        color: #89c5e8;
        border-color: #6991cd;
      }

      .el-select-dropdown {
        background-color: #102649;
        border-color: #08204f;
        .el-scrollbar {
          .el-select-dropdown__wrap {
            .el-scrollbar__view {
              .el-select-dropdown__item:hover {
                background-color: #2b4c7e;
              }

              .el-select-dropdown__item.selected {
                background-color: #2b4c7e;
              }

              .el-select-dropdown__item.hover {
                background-color: #2b4c7e;
              }
            }

            .el-select-dropdown__list {
              background-color: #102649;
            }
          }
        }
      }
    }
  }

  .echart {
    width: 100%;
    height: 70%;
    z-index: 0;
  }

  .food-legend {
    height: 30%;
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    .legend-div {
      width: 32%;
      height: 30%;
      display: flex;
      align-items: center;

      .index {
        width: 0.5rem;
        height: 0.5rem;
      }

      .name {
        width: 4.5rem;
        padding-left: 0.3rem;
        color: #aac6c7;
        font-size: 0.7rem;
      }

      .rate {
        width: 2rem;
        color: #808c9f;
        font-size: 0.65rem;
      }

      .value {
        width: 2rem;
        color: #808c9f;
        font-size: 0.65rem;
      }
    }
  }
}
</style>
  