<template>
  <div
    class="line-box"
    v-loading="lineLoading"
    element-loading-text="正在加载中..."
  >
    <div class="title">
      温度(℃)
      <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">{{ tempMax }}℃</span>
      <el-divider direction="vertical"></el-divider>
      最低值<span class="danger-text">{{ tempMin }}℃</span>
      <el-divider direction="vertical"></el-divider>
      平均值<span class="average-text">{{ tempAvg }}℃</span>
    </div>
    <div class="chart-wrapper">
      <div ref="chart-temperature"></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
          }
        },
        echartsOptions: (option = {
          title: {
            text: 'Stacked Line'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['Union Ads']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: 'Union Ads',
              type: 'line',
              stack: 'Total',
              data: [220, 182, 191, 234, 290, 330, 310]
            }
          ]
        }),
        lineDataList: {},
        myChart: null,
        propertyList: [
          {
            name: '温度1',
            property: 'temp1'
          },
          {
            name: '温度2',
            property: 'temp2'
          },
          {
            name: '温度3',
            property: 'temp3'
          },
          {
            name: '温度4',
            property: 'temp4'
          }
        ]
      };
    },
    computed: {
      tempMax() {
        let item = Object.entries(this.lineDataList);
        if (item.length > 0) {
          let maxList = item.map((n) => {
            return n[1].max;
          });
          return Math.max(...maxList);
        } else {
          return null;
        }
      },
      tempMin() {
        let item = Object.entries(this.lineDataList);
        if (item.length > 0) {
          let minList = item.map((n) => {
            return n[1].min;
          });
          return Math.min(...minList);
        } else {
          return null;
        }
      },
      tempAvg() {
        let item = Object.entries(this.lineDataList);
        if (item.length > 0) {
          let avgList = item.map((n) => {
            return n[1].avg;
          });
          let sum = avgList.reduce((a, b) => {
            return Number(a) + Number(b);
          });
          return (sum / avgList.length).toFixed(2);
        } else {
          return null;
        }
      }
    },
    created() {
      this.setMonth();
      this.getInfo();
    },
    methods: {
      dateClick(date) {
        this.temperatureTime = '';
        this.active = date;
      },
      async getInfo() {
        let time = this.getTimeList(this.temperatureTime);
        let params = {
          equId: this.id,
          // property: "temp",
          startTime: time.startTime,
          endTime: time.endTime,
          timeType: this.dict.chartTime[this.active]
        };

        this.lineLoading = true;

        let dataList = [];
        let alList = [];
        for (const item of this.propertyList) {
          params.property = item.property;

          // let data = await getEquHistory(params);
          // let temp = await getAlarmThreshold(params);
          // alList.push(temp.data.length > 0 ? temp.data[0] : {});
          // dataList.push(data);
        }
        this.lineLoading = false;

        // let PromiseAll = Promise.all(dataList, alList);

        console.log('dataList', dataList);
        console.log('alList', alList);
        this.initTemperature(dataList, alList);
      },
      // 日期数据格式化
      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(resList, alList) {
        console.log(alList, 'alll');
        let Axis = [];
        let seriesData = [];
        resList.forEach((n, index) => {
          // 最高值，最低值，平均值
          let data = n.data;
          let key_ineData = this.propertyList[index].property;
          let value_ineData = {
            max: data.maxValue.toFixed(2),
            min: data.minValue.toFixed(2),
            avg: data.avgValue.toFixed(2)
          };
          this.$set(this.lineDataList, key_ineData, value_ineData);

          // 数据
          let chartItemData = data.timeHistoryList.map((el) => {
            return el.value.toFixed(2);
          });

          seriesData.push({
            name: this.propertyList[index].name,
            property: this.propertyList[index].property,
            data: chartItemData
          });
        });
        for (const item of resList[0].data.timeHistoryList) {
          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;
          }
        }
        this.$nextTick(() => {
          this.myChart = this.$echarts.init(this.$refs['chart-temperature']);
          let option = this.getLineOption(Axis, seriesData, alList);
          this.myChart.setOption(option);
        });
      },
      checkAL(data, arr) {
        let obj = arr.find((item) => data.property === item.alarmType);
        if (obj) {
          return obj.alarmValue;
        } else {
          return 0;
        }
      },
      //
      getMax(seriesData, alList) {
        console.log(seriesData);
        let arr1 = [];
        seriesData.forEach((item) => {
          arr1.push(...item.data);
        });
        let arr2 = [];
        alList.forEach((item) => {
          arr2.push(item.alarmValue);
        });
        let arr = [...arr1, ...arr2];
        let max = Math.max(...arr);

        return max;
      },
      getLineOption(xAxisData = [], seriesData = [], alList = []) {
        const color = ['#0052d9', '#bbd3fb', '#157a2c', '#FF4949'];
        let option = {
          legend: {
            show: true,
            bottom: 0,
            icon: 'rect',
            itemHeight: 4,
            itemWidth: 16,
            textStyle: {
              fontSize: 16
            }
          },
          grid: {
            top: 50,
            left: 50,
            right: 50,
            bottom: 90
          },
          dataZoom: [
            {
              show: true,
              bottom: 40,
              start: 0,
              end: 100
            }
          ],
          xAxis: {
            type: 'category',
            data: xAxisData
          },
          yAxis: {
            type: 'value',
            max: this.getMax(seriesData, alList)
          },
          tooltip: {
            show: true,
            trigger: 'axis'
          },
          series: []
        };
        for (const [index, item] of seriesData.entries()) {
          if (this.checkAL(item, alList) !== 0) {
            option.series.push({
              data: item.data,
              type: 'line',
              name: `${item.name}(℃)`,
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: {
                color: color[index]
              },
              lineStyle: {
                color: color[index]
              },
              markLine: {
                symbol: 'none',

                data: [
                  {
                    silent: false,
                    lineStyle: {
                      type: 'dashed',
                      color: color[index]
                    },
                    // label: {
                    //   position: "end",
                    // },
                    yAxis: this.checkAL(item, alList)
                  }
                ]
              }
            });
          } else {
            option.series.push({
              data: item.data,
              type: 'line',
              name: `${item.name}(℃)`,
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: {
                color: color[index]
              },
              lineStyle: {
                color: color[index]
              }
            });
          }
        }
        return option;
      },
      // 默认当月
      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>
