<template>
  <div
    class="line-box"
    v-loading="lineLoading"
    element-loading-text="正在加载中..."
  >
    <div class="title">
      {{ type.name }}({{ type.unit }})
      <div class="tools">
        <div class="">
          <el-date-picker
            v-model="temperatureTime"
            :type="active"
            placeholder="选择日期"
          >
          </el-date-picker>
        </div>
        <div class="timeType">
          <span
            :class="{ active: active === 'date' }"
            @click="dateClick('date')"
            >日</span
          >
          <!-- <span
              :class="{ active: active === 'week' }"
              @click="dateClick('week')"
              >周</span
            > -->
          <span
            :class="{ active: active === 'month' }"
            @click="dateClick('month')"
            >月</span
          >
          <span
            :class="{ active: active === 'year' }"
            @click="dateClick('year')"
            >年</span
          >
        </div>
        <el-button type="primary" size="small" @click="getInfo">查询</el-button>
      </div>
    </div>
    <div class="value-box">
      最高值<span class="danger-text">{{ lineData.max }} {{ type.unit }}</span>
      <el-divider direction="vertical"></el-divider>
      最低值<span class="danger-text">{{ lineData.min }} {{ type.unit }}</span>
      <el-divider direction="vertical"></el-divider>
      平均值<span class="average-text">{{ lineData.avg }} {{ type.unit }}</span>
    </div>
    <div class="chart-wrapper">
      <div ref="chart_speed"></div>
    </div>
  </div>
</template>
<script>
  // import {
  //   getEquHistory,
  //   getAlarmThreshold
  // } from '@/api/ledgerAssets/booksList';
  import { getMonday } from '@/utils/index';
  export default {
    props: ['id'],
    data() {
      return {
        lineLoading: false,
        temperatureTime: '',
        active: 'month',
        dict: {
          chartTime: {
            date: 3,
            month: 2,
            year: 1
          }
        },
        lineData: {
          max: '',
          min: '',
          avg: ''
        },
        alarmValue: 0,
        myChart: null,
        type: {
          name: '速度',
          property: 'speed',
          unit: 'mm/s'
        }
      };
    },
    created() {
      this.setMonth();
      this.getInfo();
    },
    methods: {
      dateClick(date) {
        this.temperatureTime = '';
        this.active = date;
      },
      getInfo() {
        let time = this.getTimeList(this.temperatureTime);
        let params = {
          equId: this.id,
          property: this.type.property,
          startTime: time.startTime,
          endTime: time.endTime,
          timeType: this.dict.chartTime[this.active]
        };

        this.lineLoading = true;
        // getEquHistory(params)
        //   .then((res) => {
        //     getAlarmThreshold(params).then((res111) => {
        //       this.alarmValue =
        //         res111.data.length > 0 ? res111.data[0].alarmValue : 0;
        //       this.initTemperature(res.data.timeHistoryList);
        //       this.lineData.max = res.data.maxValue.toFixed(2);
        //       this.lineData.min = res.data.minValue.toFixed(2);
        //       this.lineData.avg = res.data.avgValue.toFixed(2);
        //     });
        //   })
        //   .finally(() => {
        //     this.lineLoading = false;
        //   });
      },
      // 日期数据格式化
      getTimeList(date) {
        function fnNum(num) {
          return num < 10 ? '0' + num : num;
        }

        let startTime;
        let endTime;

        let ndate = date ? new Date(date) : new Date();
        let year = ndate.getFullYear();
        let month = ndate.getMonth() + 1;
        let day = ndate.getDate();

        switch (this.active) {
          case 'date': {
            let _date = `${year}-${fnNum(month)}-${fnNum(day)}`;
            startTime = _date + ' 00:00:00';
            endTime = _date + ' 23:59:59';
            break;
          }
          case 'month': {
            let month = getMonday(date);
            startTime = month[0] + ' 00:00:00';
            endTime = month[1] + ' 23:59:59';
            break;
          }
          case 'year': {
            let year = ndate.getFullYear();
            startTime = year + '-01-01 00:00:00';
            endTime = year + '-12-31 23:59:59';
            break;
          }
          default:
            break;
        }
        return {
          startTime,
          endTime
        };
      },
      //
      initTemperature(data) {
        console.log(data);
        let Axis = [];
        let seriesData = [];
        for (const item of data) {
          const time = item.time.split(' ');
          switch (this.active) {
            case 'date': {
              Axis.push(time[1]);
              break;
            }
            case 'month': {
              Axis.push(time[0].substr(-5, 5));
              break;
            }
            case 'year': {
              Axis.push(time[0]);
              break;
            }
            default:
              break;
          }
          seriesData.push(item.value.toFixed(2));
        }
        this.$nextTick(() => {
          this.myChart = this.$echarts.init(this.$refs['chart_speed']);
          let option = this.getLineOption(Axis, seriesData);
          this.myChart.setOption(option);
        });
      },
      //
      getLineOption(xAxisData = [], seriesData = []) {
        // 颜色
        const color = {
          max: '#0052d9',
          min: '#bbd3fb',
          avg: '#157a2c'
        };

        let markLine = {
          symbol: 'none',
          //  /*symbol:"none",               //去掉警戒线最后面的箭头
          // label: {
          //   position: "end", //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
          // },
          data: [
            {
              silent: false, //鼠标悬停事件  true没有，false有
              lineStyle: {
                //警戒线的样式  ，虚实  颜色
                type: 'dashed',
                // color: "#FA3934",
                color: this.alarmValue === 0 ? 'transparent' : '#FA3934'
              },
              label: {
                position: 'end'
                // formatter: "500",
                // fontSize: "8",
              },
              yAxis: this.alarmValue
            }
          ]
        };
        let option = {
          // legend: {
          //   show: true,
          //   top: 0,
          //   icon: "rect",
          //   itemHeight: 4,
          //   itemWidth: 16,
          //   textStyle: {
          //     fontSize: 16,
          //   },
          // },
          grid: {
            top: 50,
            left: 50,
            right: 50,
            bottom: 60
          },
          xAxis: {
            type: 'category',
            data: xAxisData
          },
          yAxis: {
            type: 'value'
          },
          tooltip: {
            show: true,
            trigger: 'axis'
          },
          dataZoom: [
            {
              show: true,
              bottom: 10,
              start: 0,
              end: 100
            }
          ],
          series: [
            {
              data: seriesData,
              type: 'line',
              name: `${this.type.name}(${this.type.unit})`,
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: {
                color: color.max
              },
              lineStyle: {
                color: color.max
              }
            }
          ]
        };
        if (this.alarmValue === 0) {
          return option;
        } else {
          option.series[0].markLine = markLine;
          option.yAxis.max = this.checkMax(seriesData);

          return option;
        }
      },
      checkMax(seriesData) {
        let max = Math.max(...seriesData, this.alarmValue);
        return max;
      },
      // 默认当月
      setMonth() {
        this.temperatureTime = new Date();
      }
    }
  };
</script>
<style lang="scss" scoped>
  .line-box {
    height: 500px;
    // height: 50%;
    background: #fff;
    padding: 20px;
    margin-top: 10px;
    box-sizing: border-box;

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .tools {
      display: flex;
      align-items: center;
      .el-button {
        margin: 0 12px;
      }
      .timeType {
        margin: 0 20px;
        // letter-spacing: 8px;
        span {
          cursor: pointer;
          margin: 0 4px;
        }
        span.active,
        span:hover {
          // border-bottom: 2px solid $mainColor;
          // color: $mainColor;
        }
      }
    }

    .el-icon-download {
      font-size: 18px;
      cursor: pointer;
    }

    .chart-wrapper {
      height: 400px;
      > div {
        height: 100%;
      }
    }

    .value-box {
      text-align: center;
      span {
        font-weight: bold;
        margin-left: 4px;
      }
      .average-text {
        color: #0052d9;
      }
    }
  }
</style>
