<template>
  <div>
    <CusModule title="告警信息">
      <BaseChart height="200px" width="100%" :option="pieOptions"/>
      <div class="custom-table">
        <el-table :data="tableData" class="customer-table" style="width: 100%" height="650">
          <el-table-column type="index" label="序号" width="60" align="center"/>
          <el-table-column prop="type" label="报警类型" align="center">
            <template #default="{ row }">
              <dict-tag :options="dict.type.alarm_type" :value="row.alarmType"/>
            </template>
          </el-table-column>
          <el-table-column prop="alarmMsg" label="报警内容" align="center"/>
          <el-table-column prop="alarmTime" label="告警事件" align="center"/>
        </el-table>
        <el-pagination :current-page="page.pageIndex" :page-size="page.pageSize" :small="'small'" :background="true"
                       layout="total,  prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </CusModule>
  </div>
</template>
<script>
import CusModule from '../components/CusModule.vue';
import BaseChart from '@/components/BaseChart/index.vue'
import {mapState} from 'vuex';
import {fetchCntDateAlarmType, listAlarmInfo} from "@/api/alarm/alarm-info";
import {ALARM_STATE} from "@/enums/alarm";
import {ApiCode} from "@/api/apiEmums";

const colorDic = {
  3: {
    itemStyle: {
      color: '#FF4949'
    },
  },
  2: {
    itemStyle: {
      color: '#FFBD1F'
    },
  },
  1: {
    itemStyle: {
      color: '#1990FF'
    },
  },
  4: {
    itemStyle: {
      color: '#2fe30f'
    },
  },
  5: {
    itemStyle: {
      color: '#737386'
    },
  },
  6: {
    itemStyle: {
      color: 'rgba(232,244,255,0.58)'
    },
  }
}
export default {
  name: 'DeviceRight',
  dicts: ['alarm_type'],
  data() {
    return {
      pieData: [],
      tableData: [],
      page: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  components: {
    CusModule,
    BaseChart,
  },
  computed: {
    ...mapState('userState', ['areaType']),
    pieOptions() {
      return this.getPie3D(this.pieData, 0)// 可做为调整内环大小 0为实心圆饼图，大于0 小于1 为圆环
    }
  },
  watch: {
    areaType() {
      this.getPieData()
    }
  },
  mounted() {
    this.getPieData()
    this.timer && clearInterval(this.timer)
    this.timer = setInterval(() => {
      this.getPieData()
    }, 60000 * 3)
  },
  beforeDestroy() {
    this.timer && clearInterval(this.timer)
  },
  methods: {
    handleSizeChange(size) {
      this.page.pageIndex = 1
      this.page.pageSize = size
      this.getRealTimeAlarm()
    },
    handleCurrentChange(index) {
      this.page.pageIndex = index
      this.getRealTimeAlarm()
    },
    getPieData() {
      this.getDateAlarmType()
      this.getRealTimeAlarm()
    },
    getParametricEquation(startRatio, endRatio, isSelected, isHovered, k, h) {
      const midRatio = (startRatio + endRatio) / 2;
      const startRadian = startRatio * Math.PI * 2;
      const endRadian = endRatio * Math.PI * 2;
      const midRadian = midRatio * Math.PI * 2;
      // 如果只有一个扇形，则不实现选中效果。
      if (startRatio === 0 && endRatio === 1) {
        isSelected = false;
      }
      k = typeof k !== 'undefined' ? k : 1 / 3;
      const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
      const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;
      // 鼠标滑过时外环放大大小
      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) * h * 0.1;
          }
          // 当前图形的高度是Z根据h（每个value的值决定的）
          return Math.sin(v) > 0 ? 1 * h * 0.1 : -1;
        },
      };
    },
    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 / 3;
      for (let i = 0; i < pieData.length; i += 1) {
        sumValue += pieData[i].value;
        const seriesItem = {
          name: typeof pieData[i].name === 'undefined' ? `series${i}` : pieData[i].name,
          type: 'surface',
          parametric: true,
          wireframe: {
            show: false,
          },
          pieData: pieData[i],
          pieStatus: {
            selected: false,
            hovered: false,
            k,
          },
        };
        if (typeof pieData[i].itemStyle !== 'undefined') {
          const {itemStyle} = pieData[i];
          // eslint-disable-next-line no-unused-expressions
          typeof pieData[i].itemStyle.color !== 'undefined' ? (itemStyle.color = pieData[i].itemStyle.color) : null;
          // eslint-disable-next-line no-unused-expressions
          typeof pieData[i].itemStyle.opacity !== 'undefined'
            ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
            : null;

          seriesItem.itemStyle = itemStyle;
        }
        series.push(seriesItem);
      }
      for (let i = 0; i < series.length; i += 1) {
        endValue = startValue + series[i].pieData.value;
        series[i].pieData.startRatio = startValue / sumValue;
        series[i].pieData.endRatio = endValue / sumValue;
        series[i].parametricEquation = this.getParametricEquation(
          series[i].pieData.startRatio,
          series[i].pieData.endRatio,
          false,
          false,
          k,
          10//在此处传入饼图初始高度h
        );
        startValue = endValue;
        legendData.push(series[i].name);
      }
      // 准备待返回的配置项，把准备好的series 传入。
      const option = {
        legend: {
          orient: "vertical",
          right: '8%',
          top: '22%',
          textStyle: {
            color: "#fff",
            fontSize: 14,
          },
          icon: 'circle',
          formatter: (name) => {
            if (this.pieData.length) {
              const item = this.pieData.filter((item) => item.name === name)[0];
              let str = `${name}(${item.value}) ${item.proportion}%`
              return str
            }
          },
        },
        tooltip: {
          formatter: (params) => {
            let str = `${params.marker}${params.seriesName}：${this.pieData[params.seriesIndex].value}` + '个，占比：' + `${this.pieData[params.seriesIndex].proportion}` + '%'
            return str;

          },
        },
        xAxis3D: {
          min: -1,
          max: 1,
        },
        yAxis3D: {
          min: -1,
          max: 1,
        },
        zAxis3D: {
          min: -1,
          max: 1,
        },
        grid3D: {
          show: false,
          boxHeight: 25,//修改立体饼图的高度
          top: '-10%',
          left: '-20%',
          viewControl: {
            // 3d效果可以放大、旋转等，
            alpha: 35,//饼图翻转的程度
            beta: 30,
            rotateSensitivity: 1,
            zoomSensitivity: 0,
            panSensitivity: 0,
            autoRotate: true,//是否自动旋转
            distance: 300,//距离越小看到的饼图越大
          },
        },
        series,
      };
      return option;
    },

    async getDateAlarmType() {
      const {data} = await fetchCntDateAlarmType(
        {
          areaCode: this.areaType,
        }
      )
      if (!data) {
        return
      }
      const pieData = data.map(item => {
        return {
          name: this.dict.label.alarm_type[item.alarmType],
          alarmType: item.alarmType,
          value: item.cnt,
          proportion: item.proportion,
        }
      })


      let totalValue = pieData.reduce((acc, cur) => acc + cur.value, 0);
      this.pieData = pieData.map(item => {
        item.proportion = (item.value / totalValue * 100).toFixed(2)
        let color = colorDic[item.alarmType] || colorDic['6']
        return {
          ...item,
          ...color
        }
      })
    },
    async getRealTimeAlarm() {
      let result = [];
      const {
        code,
        rows,
        total,
      } = await listAlarmInfo({
        pageNum: this.page.pageIndex,
        pageSize: this.page.pageSize,
        areaCode: this.areaType,
        alarmStateList: [
          ALARM_STATE.new.value, ALARM_STATE.disposing.value,
        ]
      });
      if (ApiCode.SUCCESS === code && rows && rows.length > 0) {
        result = rows;
      }
      this.tableData = result;
      this.page.total = total
    },
  }
}
</script>
<style lang='scss' scoped>
@import url("../index.scss");


.custom-table {
  position: relative;

  /* 去掉table所有边框 */
  ::v-deep.el-table--border th.el-table__cell,
  ::v-deep.el-table td.el-table__cell {
    border-bottom: 1px solid #204D74;
  }

  ::v-deep .el-table th.is-leaf {
    /* 去除上边框 */
    border: none;
  }

  ::v-deep.el-table--border .el-table__cell {
    border-right: none !important;
  }

  ::v-deep.el-table--group,
  .el-table--border {
    border: none !important;
  }

  ::v-deep.el-table::before,
  .el-table--group::after,
  .el-table--border::after {
    background-color: unset !important;
  }

  // 去掉el-table的所有背景颜色以及所有hover的颜色
  ::v-deep.el-table,
  ::v-deep.el-table .el-table__header-wrapper th,
  ::v-deep.el-table--border {
    background-color: transparent;
    color: #07e3f9;
  }

  ::v-deep.el-table tr,
  ::v-deep.el-table__body tr:hover > td {
    background-color: transparent !important;
  }

  ::v-deep .el-table__header-wrapper thead th {
    background: #1B4B6D !important;
    color: #07e3f9;
  }

  ::v-deep .el-table__body-wrapper td {
    color: #B3E3E8;
    background: #0A2431;
  }
}

.el-pagination {
  margin-top: 10px;
}

::v-deep .el-pagination__total,
::v-deep .el-pagination__jump {
  color: #fff;
}
</style>
