<!-- 趋势分析 -->
<template>
  <div class="trend-analysis">
    <div class="header">
      <div class="left">
        <el-button class="btn" @click="goPage">机组监测</el-button>
        <!-- <el-button class="btn">趋势分析</el-button> -->
        <el-button class="btn" @click="exportData">导出数据</el-button>
      </div>
      <div class="center">
        趋势分析
      </div>
      <div class="right">
        <!-- <i class="el-icon-close" @click="back" /> -->
      </div>
    </div>
    <div class="main">
      <div class="sidebar">
        <sidebar @changeMenu="changeMenu" />
      </div>
      <div class="charts">
        <chart-btn-list class="btns" :checkList="param.checkList" @changeBtn="changeChart" @changeAxis="changeAxis" />
        <div class="chart" v-loading="loadingChart" :element-loading-background="loadingColor">
          <chart-line v-if="dataTrend" ref="ChartTrend" id="ChartTrend" :chartData="dataTrend" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    ChartStyle
  } from '@/common/const.js';
  import {
    dateFormat,
    exportDataToFile
  } from '@/common/util.js';
  import Sidebar from '@/components/Sidebar';
  import ChartBtnList from '@/components/Charts/ChartBtnList';
  import ChartLine from '@/components/Charts/ChartLine';
  import API from '@/api/factory.js';
  export default {
    components: {
      Sidebar,
      ChartBtnList,
      ChartLine
    },
    data() {
      return {
        loadingChart: false,
        loadingColor: ChartStyle.loadingColor,
        dataTrend: null,
        // 按钮参数
        param: {
          pointValue: [],
          checkList: [], // 菜单里选择的列表，区别于menuCheckList，这个包含的信息更多
          chartBtn: null
        },
        requestIdChart: 0, // main内的图表请求记录，每次请求会+1，返回时，只处理最后一个请求，用于同时间发送多个请求时，抛弃调之前请求的结果
      };
    },
    methods: {
      // 跳转到机组监测
      goPage() {
        if(this.$x_crew) this.$router.push('/CrewMonitoring');
        else this.$router.push('/FactoryMonitoring')
      },
      // 切换菜单
      changeMenu(arr) {
        this.param.pointValue = arr.map(i => i.character.kksCode);
        this.param.checkList = arr;
      },
      // 切换图表
      changeChart(param) {
        this.param = Object.assign(this.param, param);
        if (!this.param.chartBtn || !this.param.pointValue.length) return;
        console.log('当前图表参数：', this.param);
        this.clearChart();
        // 查询趋势数据
        if (this.param.chartBtn == 1) this.getDataTendency();
      },
      // 切换共用坐标
      changeAxis(param) {
        if (this.dataTrend) {
          if (this.$refs.ChartTrend) this.$refs.ChartTrend.clear();
          this.dataTrend.sameAxis = param.sameAxis;
        }
      },
      // 获取趋势数据
      async getDataTendency() {
        // this.dataTrend = this.initDataTrend(); // 模拟数据
        let post = {
          keys: [...this.param.pointValue],
          status: 0,
          timeModelQuery: {
            start: this.param.dateSelect[0],
            end: this.param.dateSelect[1],
          }
        };
        this.loadingChart = true;
        let requestId = ++this.requestIdChart; // 当前请求标记id
        API.getTendency(post)
          .then(data => {
            if (requestId != this.requestIdChart) return; // 如果不是最后一个请求，则抛弃
            if (!data || !data.xaxis || !data.xaxis.length) {
              this.$message.warning('暂无数据，请更换测点或日期');
              return;
            }
            // 赋值数据
            let newData = {
              xAxis: [],
              dataList: [],
              sameAxis: this.param.sameAxis,
            };
            // 处理时间轴
            for (let i = 0; i < data.xaxis.length; i++) {
              // 这里不进行换行，因为要导出数据，换行在组件里处理
              newData.xAxis.push(dateFormat(new Date(parseInt(data.xaxis[i]) * 1000), 'YYYY/MM/DD HH:mm:ss'));
            }
            // 处理数据，这里是根据查询的测点，按顺序寻找结果中对应的测点数据，因为接口返回的顺序不能保证是查询顺序，并且还包含了功率和电流测点
            newData.dataList = this.param.pointValue.map(i => {
              let item = this.param.checkList.find(j => j.character.kksCode == i); // 从选择的测点里取出测点信息
              let itemRes = data.dataList.find(j => j.kksCode == item.character.kksCode); // 从返回的结果里取出测点
              return {
                name: item.character.cpName,
                value: itemRes?.value || [],
                kksCode: i,
                unit: item.character.cpUnit || '',
                // warning: itemRes?.color || ''
              };
            });
            this.dataTrend = newData;
          })
          .catch(e => console.log(e))
          .finally(() => {
            this.loadingChart = false;
          });
      },
      // 清空图表
      clearChart() {
        this.dataTrend = null;
        if (this.$refs.ChartTrend) this.$refs.ChartTrend.clear();
      },
      // 导出数据
      exportData() {
        if (!this.dataTrend) {
          this.$message.warning('无可导出数据');
          return;
        }
        let data, // 数据体
            txt = '', // 文件内容
            tmpArr = [], // 文件内容数组形式，每一列为一个数组元素
            name = '', // 文件名
            rowSplit = '\n', // 行分隔符
            colSplit = ',', // 列分隔符
            fileType = '.csv'; // 文件类型，注意不同类型的分隔符
        if (this.dataTrend) data = JSON.parse(JSON.stringify(this.dataTrend));
        data.xAxis.unshift('时间');
        tmpArr = [data.xAxis]; // 放入时间轴
        data.dataList.forEach(i => {
            name += i.name + ','; // 拼文件名
            i.value.unshift(i.name);
            tmpArr.push(i.value); // 放入数据y轴
        });
        // 删除最后一个逗号
        if (name.length) name = name.substr(0, name.length - 1) + fileType;
        else name = '图表数据' + fileType; // 如果没有名字，则数据有问题，需要检查
        // 拼数据格式
        for (let i = 0; i < tmpArr[0].length; i++) {
          tmpArr.forEach((item, index) => (index == tmpArr.length - 1 ? (txt += item[i]) : (txt += item[i] + colSplit)));
          txt += rowSplit;
        }
        exportDataToFile(txt, name, fileType);
      },
      // 模拟趋势数据
      initDataTrend() {
        let data = {
          xAxis: ['2020/11/23 08:00', '2020/11/23 09:00', '2020/11/23 10:00', '2020/11/23 11:00',
            '2020/11/23 12:00'
          ],
          dataList: [],
          sameAxis: this.param.sameAxis,
        };
        for (let i = 0; i < this.param.checkList.length; i++) {
          data.dataList.push({
            name: this.param.checkList[i].character.cpName,
            value: [Math.ceil(Math.random() * 20 + 20), Math.ceil(Math.random() * 20 + 20), Math.ceil(
              Math.random() * 20 + 20), Math.ceil(Math.random() * 20 + 20), Math.ceil(
              Math.random() * 20 + 20)],
            unit: 'km' + i
          });
        }
        return data;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .trend-analysis {
    height: 100%;
    padding: 1.875rem 3.125rem;
    box-sizing: border-box;

    .header {
      height: 4.25rem;
      line-height: 4.25rem;
      background-image: linear-gradient(270deg, rgba(197, 254, 255, 0.10) 0%, rgba(147, 252, 255, 0.50) 52%, rgba(147, 252, 255, 0.10) 100%);
      padding: 0 1.875rem;
      box-sizing: border-box;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        display: flex;
        z-index: 1;

        .btn {
          @extend %btn-default;
          margin: 0 1rem 0 0;
        }

        .btn:hover {
          @extend %btn-hover;
        }
      }

      .center {
        @extend %pos-center;
        font-size: 1.625rem;
        letter-spacing: 0.1625rem;
        text-shadow: 0 2px 8px rgba(78, 97, 214, 0.50);
      }

      .right {
        z-index: 1;

        i {
          font-size: 1.6rem;
        }
      }
    }

    .main {
      height: calc(100% - 4.25rem);
      background: rgba(147, 252, 255, 0.08);
      padding: 0 1rem 1rem;
      box-sizing: border-box;
      display: flex;

      .sidebar {
        width: 30rem;
        height: 100%;
      }

      .charts {
        width: calc(100% - 30rem);
		height: 100%;
        overflow: hidden;

        .btns {
          padding: 1rem;
          height: 6rem;
        }

        .chart {
          height: calc(100% - 6rem);
        }
      }

    }
  }
</style>
