<template>
  <div id="print">
    <el-tabs v-model="activeName" type="border-card" stretch @tab-click="handleClick">
      <el-tab-pane label="温湿度信息" name="first">
        <div id="body" :style="{width: width - 300 + 'px'}">
          <!-- 单据信息 -->
          <el-timeline>
            <el-timeline>
              <el-descriptions>
                <el-descriptions-item label="订单编号">{{this.basicData.billCode}}</el-descriptions-item>
                <el-descriptions-item label="车牌号">{{this.basicData.plateNumber}}</el-descriptions-item>
              </el-descriptions>
              <el-descriptions>
                <el-descriptions-item label="开始时间">{{this.basicData.startTime}}</el-descriptions-item>
                <el-descriptions-item label="结束时间">{{this.basicData.endTime}}</el-descriptions-item>
              </el-descriptions>
              <!--导出按钮-->
              <el-button class="OutCss" v-print="'#print'" type="primary">导出</el-button>
            </el-timeline>
          </el-timeline>
          <el-timeline>
            <!-- 数据表 -->
            <h2>订单温湿度列表</h2>
            <el-table :data="tableData2" stripe border style="width: 97%">
              <el-table-column prop="measuringPointName" label="车牌号或保温箱" align="center" min-width="150" />
              <el-table-column prop="measuringPointAddr" label="探头" align="center" min-width="90" />
              <el-table-column prop="temperature" label="温度" align="center" min-width="80" />
              <el-table-column prop="hisDate" label="时间点" align="center" min-width="200" />
              <el-table-column prop="measuringPointName1" label="车牌号或保温箱" align="center" min-width="150" />
              <el-table-column prop="measuringPointAddr1" label="探头" align="center" min-width="90" />
              <el-table-column prop="temperature1" label="温度" align="center" min-width="80" />
              <el-table-column prop="hisDate1" label="时间点" align="center" min-width="200" />
              <!-- <el-table-column prop="address" label="地址" width="400" /> -->
            </el-table>
          </el-timeline>
        </div>
        <br>
        <div id="body" :style="{width: width - 300 + 'px'}">
          <el-timeline>
            <h2>订单温度折线图</h2>
            <div class="echart" id="mychart" :style="myChartStyle"></div>
          </el-timeline>
        </div>
      </el-tab-pane>
      <el-tab-pane label="运输信息" name="second">
        <div id="body" :style="{width: width - 300 + 'px'}">
          <!-- 单据信息 -->
          <el-timeline>
            <el-timeline>
              <el-descriptions>
                <el-descriptions-item label="订单编号">{{this.basicData.billCode}}</el-descriptions-item>
                <el-descriptions-item label="车牌号">{{this.basicData.plateNumber}}</el-descriptions-item>
              </el-descriptions>
              <el-descriptions>
                <el-descriptions-item label="开始时间">{{this.basicData.startTime}}</el-descriptions-item>
                <el-descriptions-item label="结束时间">{{this.basicData.endTime}}</el-descriptions-item>
              </el-descriptions>
            </el-timeline>
          </el-timeline>

          <!-- 地图 -->
          <div id="container"></div>

          <!-- 订单温湿度列表 -->
          <el-timeline>
            <br>
            <h2>订单温湿度列表</h2>
            <el-table :data="tableData1" height="200" style="width: 97%">
              <el-table-column prop="maxTemperature" label="温度最大值" align="center" min-width="100" />
              <el-table-column prop="avgTemperature" label="温度平均值" align="center" min-width="100" />
              <el-table-column prop="minTemperature" label="温度最小值" align="center" min-width="100" />
              <el-table-column prop="maxHumidity" label="湿度最大值" align="center" min-width="100" />
              <el-table-column prop="avgHumidity" label="湿度平均值" align="center" min-width="100" />
              <el-table-column prop="minHumidity" label="湿度最小值" align="center" min-width="100" />
              <el-table-column prop="startTime" label="开始时间" align="center" min-width="250" />
              <el-table-column prop="endTime" label="结束时间" align="center" min-width="250" />
            </el-table>
          </el-timeline>
        </div>
      </el-tab-pane>

    </el-tabs>
  </div>
</template>

<script>
  import AMapLoader from '@amap/amap-jsapi-loader'
  window._AMapSecurityConfig = {
    securityJsCode: '8e23904a0cf421675353f31fd1fc213c'
  }
  import historyApi from '@/api/WMS/historical-route'
  import * as echarts from "echarts";

  export default {
    data() {
      return {
        width: document.documentElement.clientWidth - 10,
        param: this.$route.query,
        basicData: {
          billCode: "",
          plateNumber: "",
          startTime: "",
          endTime: ""
        },
        //标签页
        activeName: 'first',
        //地图对象
        map: null,
        //图表
        myChart: {},
        xData: [], //横坐标
        temperatureData: [], //温度数据
        humidityData: [], //湿度数据
        myChartStyle: {
          float: "left",
          width: "100%",
          height: "400px"
        }, //图表样式
        //运输信息表单数据
        tableData1: [],
        //运输信息表单数据准备
        modelData1: [{
          maxTemperature: "",
          avgTemperature: "",
          minTemperature: "",
          maxHumidity: "",
          avgHumidity: "",
          minHumidity: "",
          startTime: "",
          endTime: ""
        }],
        //温湿度信息表单数据
        tableData2: [],
        resData: [],
        carMessage: {
          billCode: "",
          plateNumber: "",
          boxCode: [],
          startTime: "",
          endTime: ""
        },
        option: {},
        //表单各值
        maxT: 0,
        maxH: 0,
        minT: 0,
        minH: 0,
        aggT: 0,
        aggH: 0,
        avgT: 0,
        avgH: 0
      };
    },
    mounted() {
      //DOM初始化完成进行地图初始化
      this.initMap();
    },
    created() {
      //把传参中的保温箱转换成数组
      this.carMessage = this.$route.query;
      if (this.carMessage.boxCode != null) {
        this.carMessage.boxCode = this.$route.query.boxCode.split(',');
      }
      //当结束时间为空时，默认为当前时间
      if (this.carMessage.endTime == '' || this.carMessage.endTime == null) {
        this.carMessage.endTime = this.formatDateTime(this.getCurrentTime(), 'yyyy-MM-dd HH:mm:ss');
      }
      console.log(this.carMessage, 'this.carMessage')
      this.handleGeocodeRepo(this.carMessage);
    },
    methods: {
      //通过传参查询数据
      handleGeocodeRepo(data) {
        historyApi.queryAddress(data).then(res => {
          console.log(res, 'res-----------------');
          if (res.code == 200) {
            //定义路线数组
            let path = [];
            //筛选含经纬度的数组
            let latitudeLongitude = [];
            let count = 0;
            for (let i = 0; i < res.data.length; i++) {
              if (res.data[i].gpsLatitude != 0 && res.data[i].gpsLongitude != 0) {
                latitudeLongitude[count++] = res.data[i];
              }
            }
            //定义整数递增值，并且绘制初始路径
            if (latitudeLongitude.length >= 14) {
              this.increment = Math.trunc(latitudeLongitude.length / 14);
              for (let i = 0; i < latitudeLongitude.length; i = i + this.increment) {
                path.push([latitudeLongitude[i].gpsLongitude, latitudeLongitude[i].gpsLatitude]);
              }
            } else {
              for (let i = 0; i < latitudeLongitude.length; i++) {
                path.push([latitudeLongitude[i].gpsLongitude, latitudeLongitude[i].gpsLatitude]);
              }
            }
            //计算各值
            this.calculate(res.data);
            //对订单温湿度列表进行赋值
            this.assignmentTable1(res.data);
            //提取探头种类数量
            let probeSum = [];
            let probe = [];
            for (let i = 0; i < latitudeLongitude.length; i++) {
              probeSum[i] = latitudeLongitude[i].measuringPointAddr;
            }
            probe = Array.from(new Set(probeSum));
            //车辆温度数组
            let c, d;
            this.initEcharts();
            for (let i = 0; i < probe.length; i++) {
              let carForm = {
                name: this.carMessage.plateNumber + '/' + probe[i],
                data: [],
                type: "line",
                smooth: true,
                showSymbol: false,
                label: {
                  show: true,
                  position: "top",
                  textStyle: {
                    fontSize: 12
                  }
                },
                markArea: {
                  itemStyle: {
                    color: 'rgba(255, 0, 0)'
                  },
                  data: [
                    [{
                        name: '冷藏温度警戒线',
                        yAxis: '8'
                      },
                      {
                        yAxis: '8.1'
                      }
                    ],
                    [{
                        name: '冷藏温度警戒线',
                        yAxis: '2'
                      },
                      {
                        yAxis: '1.9'
                      }
                    ],
                    [{
                        name: '冷冻温度警戒线',
                        yAxis: '-15'
                      },
                      {
                        yAxis: '-14.9'
                      }
                    ],
                    [{
                        name: '冷冻温度警戒线',
                        yAxis: '-25'
                      },
                      {
                        yAxis: '-25.1'
                      }
                    ]
                  ]
                }
              }
              // count = 0;
              for (let j = 0; j < latitudeLongitude.length; j++) {
                if (carForm.name.indexOf(latitudeLongitude[j].measuringPointAddr) != -1) {
                  c = latitudeLongitude[j].hisDate;
                  d = latitudeLongitude[j].temperature;
                  carForm.data.push([c, d]);
                }
              }
              this.option.series.push(carForm);
              this.option.legend.data.push(carForm.name);
            }
            //筛选保温箱的数组
            if (this.carMessage.boxCode != null) {
              let e, f;
              for (let i = 0; i < this.carMessage.boxCode.length; i++) {
                let boxForm = {
                  name: this.carMessage.boxCode[i],
                  data: [],
                  type: "line",
                  smooth: true,
                  showSymbol: false,
                  label: {
                    show: true,
                    position: "top",
                    textStyle: {
                      fontSize: 12
                    }
                  },
                  markArea: {
                    itemStyle: {
                      color: 'rgba(255, 0, 0)'
                    },
                    data: [
                      [{
                          name: '冷藏温度警戒线',
                          yAxis: '8'
                        },
                        {
                          yAxis: '8.1'
                        }
                      ],
                      [{
                          name: '冷藏温度警戒线',
                          yAxis: '2'
                        },
                        {
                          yAxis: '1.9'
                        }
                      ],
                      [{
                          name: '冷冻温度警戒线',
                          yAxis: '-15'
                        },
                        {
                          yAxis: '-14.9'
                        }
                      ],
                      [{
                          name: '冷冻温度警戒线',
                          yAxis: '-25'
                        },
                        {
                          yAxis: '-25.1'
                        }
                      ]
                    ]
                  }
                }
                // count = 0;
                for (let j = 0; j < res.data.length; j++) {
                  if (boxForm.name == res.data[j].measuringPointName) {
                    e = res.data[j].hisDate;
                    f = res.data[j].temperature;
                    boxForm.data.push([e, f]);
                  }
                }
                this.option.series.push(boxForm);
                this.option.legend.data.push(boxForm.name);
              }
            }
            //如果车辆温度数组为空，则其它数组前移一位
            for (let i = 1;;) {
              if (this.option.series[0].data.length == 0) {
                for (let j = 0; j < this.option.series.length - i; j++) {
                  this.option.series[j] = this.option.series[j + 1];
                  this.option.legend.data[j] = this.option.legend.data[j + 1];
                }
                this.option.series[this.option.series.length - i] = '';
                this.option.legend.data[this.option.series.length - i++] = '';
              }
              if (this.option.series[0].data.length != 0) {
                break;
              }
            }
            this.windowSize();
            //对基础数据进行赋值
            this.basicData.billCode = this.carMessage.billCode;
            this.basicData.plateNumber = this.carMessage.plateNumber;
            this.basicData.startTime = this.xData[0];
            this.basicData.endTime = this.xData[this.xData.length - 1];
            //基本地图加载
            this.loadMap(path);
          }
        })
      },
      handleClick(tab, event) {
        console.log(tab, event);
        this.handleGeocodeRepo(this.carMessage);
      },
      //地图初始化
      initMap() {
        AMapLoader.load({
            //申请好的Web端开发者Key，首次调用 load 时必填
            key: 'f953210b2d5276ffbf5a2bc01ef80f55',
            //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            version: '2.0',
            //需要使用的的插件列表，如比例尺'AMap.Scale'等
            plugins: ['']
          })
          .then(AMap => {
            this.map = new AMap.Map('container', {
              //设置地图容器id
              //是否为3D地图模式
              viewMode: '3D',
              //初始化地图级别
              zoom: 13,
              //初始化地图中心点位置
              center: [112.976376, 28.195318]
            })
          })
          .catch(e => {
            console.log(e)
          })
      },
      //基本地图加载
      loadMap(path) {
        var map, route;
        map = new AMap.Map("container", {
          resizeEnable: true
        });
        map.plugin("AMap.DragRoute", function () {
          //构造拖拽导航类
          route = new AMap.DragRoute(map, path, AMap.DrivingPolicy.LEAST_FEE);
          //查询导航路径并开启拖拽导航
          route.search();
        });
      },
      //图表属性赋值
      initEcharts() {
        this.option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            }
          },
          grid: {
            x: 22,
            y: 30,
            x2: 20,
            y2: 18,
            borderWidth: 1,
          },
          toolbox: {
            //保存图
            // show: true,
            // feature: {
            //   saveAsImage: {}
            // }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.xData
          },
          //图例
          legend: {
            data: [],
            // bottom: "0%"
          },
          yAxis: {
            name: '温度',
            // Y轴最大值
            max: 10,
            // Y轴最大值
            min: -30,
            splitNumber: 2,
            // 间隔值
            // interval: 3
          },
          //加上dataZoom可实现缩放
          dataZoom: [{
              //x轴
              type: 'slider',
              xAxisIndex: 0,

            },
            {
              //x轴
              type: 'inside',
              xAxisIndex: 0,
              /**
               * 如何触发缩放。可选值为：true：表示不按任何功能键，鼠标滚轮能触发缩放。false：表示鼠标滚轮不能触发缩放。
               * 'shift'：表示按住 shift和鼠标滚轮能触发缩放。
               * 'ctrl'：表示按住 ctrl 和鼠标滚轮能触发缩放。'alt'：表示按住 alt 和鼠标滚轮能触发缩放。
               */
              zoomOnMouseWheel: 'true',
            },
          ],
          /**
           * series中的参数：
           * smooth：是否曲线，showSymbol：是否显示数据和数据点
           */
          series: [],
        }
      },
      //渲染图表
      windowSize() {
        this.myChart = echarts.init(document.getElementById("mychart"));
        this.myChart.setOption(this.option);
        window.addEventListener("resize", () => {
          this.myChart.resize();
        });
      },
      //计算各值
      calculate(array) {
        //数组中的温度湿度的字符串转成浮点
        for (let i = 0; i < array.length; i++) {
          array[i].temperature = parseFloat(array[i].temperature);
          array[i].humidity = parseFloat(array[i].humidity);
        }
        //定义初始值
        this.maxT = array[0].temperature;
        this.maxH = array[0].humidity;
        this.minT = array[0].temperature;
        this.minH = array[0].humidity;
        this.aggT = 0;
        this.aggH = 0;
        let x = [];
        for (let i = 0; i < array.length; i++) {
          //对X轴的时间进行赋值
          x[i] = array[i].hisDate;
          //对Y轴的温度进行赋值
          // this.temperatureData[i] = array[i].temperature;
          //温度最大值
          if (array[i].temperature > this.maxT) {
            this.maxT = array[i].temperature;
          }
          //湿度最大值
          if (array[i].humidity > this.maxH) {
            this.maxH = array[i].humidity;
          }
          //温度最小值
          if (array[i].temperature < this.minT) {
            this.minT = array[i].temperature
          }
          //湿度最小值
          if (array[i].humidity < this.minH) {
            this.minH = array[i].humidity
          }
          //温湿度合计值
          this.aggT += array[i].temperature;
          this.aggH += array[i].humidity;
        }
        //x数组去重
        x = Array.from(new Set(x));
        let xSort = [];
        for (let i = 0; i < x.length; i++) {
          xSort[i] = new Date(x[i]);
        }
        xSort.sort(function (a, b) {
          return a - b;
        })
        for (let i = 0; i < xSort.length; i++) {
          x[i] = this.formatDateTime(xSort[i], 'yyyy-MM-dd HH:mm:ss');
        }
        this.xData = x;
        //温湿度平均值
        this.avgT = this.aggT / array.length;
        this.avgH = this.aggH / array.length;
      },
      //对订单温湿度列表进行赋值
      assignmentTable1(array) {
        this.modelData1[0].maxTemperature = this.maxT;
        this.modelData1[0].maxHumidity = this.maxH;
        this.modelData1[0].minTemperature = this.minT;
        this.modelData1[0].minHumidity = this.minH;
        this.modelData1[0].avgTemperature = this.avgT.toFixed(2);
        this.modelData1[0].avgHumidity = this.avgH.toFixed(1);
        this.modelData1[0].startTime = array[0].hisDate;
        this.modelData1[0].endTime = array[array.length - 1].hisDate;
        this.tableData1 = this.modelData1;
        let median = (array.length / 2).toFixed(0);
        let table = []
        for (let i = 0; i < median; i++) {
          table[i] = {
            measuringPointName: '',
            measuringPointAddr: '',
            temperature: '',
            hisDate: '',
            measuringPointName1: '',
            measuringPointAddr1: '',
            temperature1: '',
            hisDate1: ''
          }
        }
        if (array.length % 2 == 0) {
          for (let i = 0, j = 0, z = 1; i < median; i++, j = j + 2, z = z + 2) {
            table[i].measuringPointName = array[j].measuringPointName;
            table[i].measuringPointAddr = array[j].measuringPointAddr;
            table[i].temperature = array[j].temperature;
            table[i].hisDate = array[j].hisDate;
            table[i].measuringPointName1 = array[z].measuringPointName;
            table[i].measuringPointAddr1 = array[z].measuringPointAddr;
            table[i].temperature1 = array[z].temperature;
            table[i].hisDate1 = array[z].hisDate;
          }
        } else {
          for (let i = 0, j = 0, z = 1; i < median; i++, j = j + 2, z = z + 2) {
            table[i].measuringPointName = array[j].measuringPointName;
            table[i].measuringPointAddr = array[j].measuringPointAddr;
            table[i].temperature = array[j].temperature;
            table[i].hisDate = array[j].hisDate;
            if (i != median - 1) {
              table[i].measuringPointName1 = array[z].measuringPointName;
              table[i].measuringPointAddr1 = array[z].measuringPointAddr;
              table[i].temperature1 = array[z].temperature;
              table[i].hisDate1 = array[z].hisDate;
            }
          }
        }
        this.tableData2 = table;
      },
      //获取当前时间
      getCurrentTime() {
        let date = new Date();
        return date;
      },
      //日期名称格式化
      formatDateTime(date, format) {
        const o = {
          'M+': date.getMonth() + 1, // 月份
          'd+': date.getDate(), // 日
          'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
          'H+': date.getHours(), // 小时
          'm+': date.getMinutes(), // 分
          's+': date.getSeconds(), // 秒
          'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
          S: date.getMilliseconds(), // 毫秒
          a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
          A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
        };
        if (/(y+)/.test(format)) {
          format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
          if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(
              RegExp.$1,
              RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
            );
          }
        }
        return format;
      },
    }
  };

</script>

<style scoped>
  #container {
    padding: 100px;
    margin: 10px;
    width: 1000;
    height: 800px;
  }

  .OutCss {
    float: right;
  }

  #body {
    /* padding: 0px 200px 0px 200px; */
    margin: 0 auto;

  }

  @media print {
    @page {
      margin: 0;
      size: portrait;
      /* size: A4 landscape; size: landscape横向，size: portrait;纵向，如果不设置，则页面有横向和纵向的选择框 */
    }

    #body {
      /* margin: 20cm; */
      margin: 0 auto;
      /* 打印时缩放，防止页面溢出 */
      zoom: 0.6;
    }
  }

</style>
