<template>
  <!-- 保温箱追溯地图-设备定位 -->
  <div class="home_card_screen">
    <div class="map_card" v-loading="mapLoading">
      <div id="container"></div>
    </div>
    <div class="card_switchover">
      <div class="title_head_rol center_in" :class="item.flag ? 'active_bgcolor' : ''" v-for="(item,index) in list"
        :key="index" @click="selectRol(item)">{{item.title}}</div>
    </div>
    <div class="card_bottom_control" :class="logisticsFlag ? 'height_300' : 'height_30'">
      <div style="cursor: pointer;" class="center_in" @click="clickImg">
        <el-image :class="logisticsFlag ? '' : 'overturn'" style="height: 29px;width: 40px;flex: none;"
          :src="require('@/assets/images/unfold.png')"></el-image>
      </div>
      <div style="width: 100%;height: calc(100% - 30px);" v-show="logisticsFlag">
        <div class="card_unpack_control">
          <div style="display: flex;align-items: center;">
            <div style="width: 260px;margin-right: 10px;">
              <el-input size="small" v-model="incubatorName" placeholder="请输入内容" @input="incubatorSearch"></el-input>
            </div>
          </div>
          <div>
            <el-button type="primary" size="small" :loading="mapLoading" @click="examine"
              v-if="currentId == 1">查看实时数据</el-button>
          </div>
        </div>
        <div class="history_warp" v-loading="tableLoading">
          <el-table class="top" label-position="center" :data="tableData"
            :highlight-current-row="currentId == 2 ? true : false" border style="width: 100%"
            @selection-change="handleSelectionChange" @cell-click="selectIncubator"
            :row-key="(row) => { return row.id }" :key="currentId">
            <el-table-column reserve-selection type="selection" width="55" v-if="currentId == 1"></el-table-column>
            <el-table-column type="index" width="50" v-else></el-table-column>
            <el-table-column prop="name" width="220" label="名称"></el-table-column>
            <el-table-column prop="sn" width="180" label="SN"></el-table-column>
            <el-table-column prop="status" align="center" width="70" label="状态">
            </el-table-column>
            <el-table-column prop="monitorStatus" align="center" width="80" label="监控状态">
            </el-table-column>
            <el-table-column prop="deviceData.address" label="当前地址"></el-table-column>
            <el-table-column prop="deviceData.T_t" align="center" width="80" label="最新温度">
            </el-table-column>
            <el-table-column prop="deviceData.T_time" width="180" label="最新记录时间"></el-table-column>
          </el-table>
          <vue-seamless-scroll style="height: calc(100% - 100px);overflow: hidden;" ref="vueSeamlessScroll"
            :data="tableData" :class-option="classOption" @mousewheel.native="handleScroll" v-if="updataFlag">
            <el-table class="bottom" ref="multipleTable" label-position="center" :data="tableData"
              :highlight-current-row="currentId == 2 ? true : false" border style="width: 100%"
              @selection-change="handleSelectionChange" @cell-click="selectIncubator"
              :row-key="(row) => { return row.id }" :key="currentId">
              <el-table-column reserve-selection type="selection" width="55" v-if="currentId == 1"></el-table-column>
              <el-table-column type="index" width="50" v-else></el-table-column>
              <el-table-column prop="name" width="220" label="名称"></el-table-column>
              <el-table-column prop="sn" width="180" label="SN"></el-table-column>
              <el-table-column prop="status" align="center" width="70" label="状态">
                <template slot-scope="scope">
                  <div :style="{color: filterColor(scope.row,startStatus,'status')}">
                    {{initDictvalueil(scope.row,startStatus,'status')}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="monitorStatus" align="center" width="80" label="监控状态">
                <template slot-scope="scope">
                  <div :style="{color: filterColor(scope.row,deviceState,'monitorStatus')}">
                    {{initDictvalueil(scope.row,deviceState,'monitorStatus')}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="deviceData.address" label="当前地址"></el-table-column>
              <el-table-column prop="deviceData.T_t" align="center" width="80" label="最新温度">
                <template slot-scope="scope">
                  <div>{{scope.row.deviceData.T_t || ''}}</div>
                </template>
              </el-table-column>
              <el-table-column prop="deviceData.T_time" width="180" label="最新记录时间"></el-table-column>
            </el-table>
          </vue-seamless-scroll>
          <div v-if="Total">
            <pagination :total="Total" :currentPage="Pagination.PageIndex" layout="total, prev, pager, next,jumper"
              @changeSize="changeSize" @changeCurrent="changeCurrent">
            </pagination>
          </div>
        </div>
      </div>
      <div class="track_visit scale-up-tr" v-if="currentId == 2 && playbackControl">
        <div class="playback">轨迹回放控制</div>
        <div class="card_cartoon">
          <div class="cartoo_title center_in margin_10" @click="startAnimation()">开始动画</div>
          <div class="cartoo_title center_in" @click="pauseAnimation()">暂停动画</div>
          <div class="cartoo_title center_in margin_10" @click="resumeAnimation()">继续动画</div>
          <div class="cartoo_title center_in" @click="stopAnimation()">停止动画</div>
        </div>
      </div>
    </div>

    <div class="card_right_information" v-if="currentId == 2" v-loading="timeLoading">
      <div class="hide_information center_in" v-if="!optionFlag && trackCircle" @click="reelect">
        <span class="iconfont icon-guiji"></span>
      </div>
      <div class="information_card scale-up-tr" v-infinite-scroll="scrollLoad" v-if="optionFlag && timeData.length > 0">
        <div class="card_time_box" v-for="(item,index) in timeData" :key="index" @click="getTrack(item)">
          <div class="sn_card_box">{{item.sn}}</div>
          <div class="box_time">{{item.coolerBoxUserTime}}</div>
          <div class="box_time">{{item.coolerEndUseTime}}</div>
        </div>
      </div>
      <div class="information_card" v-else-if="optionFlag && timeData.length == 0">
        <el-empty description="暂无数据"></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
  import vueSeamlessScroll from "vue-seamless-scroll";
  import {
    getCoolerBox,
    getCoolerBoxLocus,
    getHistoryLocus,
    getNewlocus,
    getcoolerboxall
  } from '@/api/incubator'
  import {
    startStatus,
    deviceState
  } from '@/assets/js/blockSort'
  import pagination from '@/components/pagination'
  export default {
    name: 'IncubatorTable',
    components: {
      vueSeamlessScroll,
      pagination,
    },
    data() {
      return {
        fullScreen: false,
        input: '',
        value1: '',
        logisticsFlag: true,
        list: [{
          id: 1,
          flag: true,
          title: '实时监控',
        }, {
          id: 2,
          flag: false,
          title: '历史轨迹',
        }],
        controlVisible: false,
        map: null,
        currentId: 1,
        incubatorData: [],
        incubatorID: null,
        optionFlag: true,
        timeData: [],
        polyline: null,
        passedPolyline: null,
        marker: null,
        endMarker: null,
        trackList: [],
        trackPlayback: null,
        playbackControl: false,
        trackCircle: false,
        Total: 0,
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },

        eventSource: [],
        incubatorSn: [],
        jointSn: [],
        realTimeTrajectory: [],
        carMarker: [],
        mapLoading: false,
        tableData: [],
        tableLoading: false,
        incubatorName: '',
        timeLoading: false,
        startStatus: startStatus(),
        deviceState: deviceState(),
        asyncDataLoaded: false,
        limitNoil: true,
        timePage: 1,
        updataFlag: false,
      }
    },
    computed: {
      classOption() {
        return {
          step: 0.2, // 数值越大速度滚动越快
          limitMoveNum: 10, // 开始无缝滚动的数据量
          hoverStop: true, // 是否开启鼠标悬停stop
          direction: 1, // 0向下 1向上 2向左 3向右
          openWatch: true, // 开启数据实时监控刷新dom
          singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
          singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
          waitTime: 500, // 单步运动停止的时间(默认值1000ms)
        };
      },
    },
    // 页面销毁
    beforeDestroy() {
      if (this.jointSn.length > 0) {
        this.jointSn.forEach(item => {
          if (this.eventSource[item.sn]) {
            this.eventSource[item.sn].close()
          }
        })
      }
      this.map = null
      this.currentId = 1
      this.list.forEach((item) => {
        if (item.id == 1) {
          item.flag = true
        } else {
          item.flag = false
        }
      })
      this.incubatorSn = []
      this.jointSn = []
      this.realTimeTrajectory = []
      this.carMarker = []
      this.logisticsFlag = true
    },
    mounted() {
      this.incubatorSearch()
      this.$nextTick(() => {
        setTimeout(() => {
          this.keyUpSearch()
        }, 100)
      })
    },
    methods: {
      // 搜索保温箱
      incubatorSearch() {
        this.getList()
      },
      // 获取保温箱列表
      async getList() {
        this.tableLoading = true
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          showTemp: true,
          name: this.incubatorName,
          monitorStatus: 1, //监控中
        }
        if (this.currentId == 2) {
          delete params.monitorStatus
        }
        await getCoolerBox(params).then(res => {
          if (res.code == 200) {
            res.data.list.forEach(async item => {
              item.deviceData.address = ''
              item.deviceData.address = await this.longitudeLatitude(item.deviceData.T_site)
            })
            this.tableData = res.data.list
            this.Total = res.data.count
            this.updataFlag = true
            this.$forceUpdate()
          }
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      // 滚动代码
      handleScroll(e) {
        // 改变组件内部 yPos 的值，这样html的translate(0, yPos)就会随之改变
        // e.deltaY是滚动的距离
        this.$refs.vueSeamlessScroll.yPos = this.$refs.vueSeamlessScroll.yPos - e.deltaY
        // 如果是正数 说明是往上滚
        if (this.$refs.vueSeamlessScroll.yPos > 0) {
          this.$refs.vueSeamlessScroll.yPos = 0
          return
        }
        // 如果yPos超过内部实际高度的一半则重新到顶部滚动
        // 一半的原因是因为组件实际上创建了两个dom，以达到无缝衔接的效果
        if (Math.abs(this.$refs.vueSeamlessScroll.yPos) > this.$refs.vueSeamlessScroll.realBoxHeight / 2) {
          this.$refs.vueSeamlessScroll.yPos = 0
        }
      },
      // 更新保温箱实时数据
      refreshData(event, soleSn) {
        this.tableData.map(async item => {
          if (item.sn === soleSn) {
            item.deviceData.address = await this.longitudeLatitude(event.T_site)
            item.deviceData.T_rh = event.T_rh
            item.deviceData.T_t = event.T_t
            item.deviceData.T_time = event.T_time
            item.deviceData.T_site = event.T_site
            return
          }
        });
      },
      // 选中实时轨迹或者历史轨迹
      selectRol(event) {
        if (this.currentId != event.id) {
          if (event.id == 1) {
            this.playbackControl = false
            this.keyUpSearch()
          } else {
            this.incubatorSn = []
            this.examine(true)
            this.historicalRoute()
          }
        }
        this.list.forEach(item => {
          if (item.id == event.id) {
            this.currentId = event.id
            item.flag = true
            this.Pagination.PageIndex = 1
            this.Pagination.PageSize = 10
            this.updataFlag = false
            this.getList()
          } else {
            item.flag = false
          }
        })
        this.$forceUpdate()
      },
      // 普通类型文字匹配
      initDictvalueil(value, list, type) {
        let name = ''
        if (list) {
          list.forEach(item => {
            if (value[type] === item.value) {
              name = item.label
            }
          })
        }
        return name
      },
      // tag颜色获取
      filterColor(value, list, type) {
        let color = ''
        if (list) {
          list.forEach(item => {
            if (value[type] === item.value) {
              color = item.bgcolor
            }
          })
        }
        return color
      },
      // 获取经纬度
      longitudeLatitude(latitude) {
        return new Promise((resolve, inject) => {
          let addressArr = ''
          var geocoder = new AMap.Geocoder({
            city: "010", //城市设为北京，默认：“全国”
            radius: 1000 //范围，默认：500
          });
          geocoder.getAddress(latitude, function(status, result) {
            if (status === 'complete' && result.regeocode) {
              var address = result.regeocode.formattedAddress;
              resolve(address)
            } else {
              resolve('')
            }
          });
        })
      },
      // 选择保温箱某项
      handleSelectionChange(event) {
        let arr = []
        event.forEach(item => {
          let list = {
            sn: item.sn,
            name: item.name,
          }
          arr.push(list)
        })
        this.incubatorSn = arr
      },
      // 查看实时数据
      async examine(event) {
        const that = this
        that.realTimeTrajectory = []

        function difference(arr1, arr2) {
          return arr1.filter(item => !arr2.includes(item.sn));
        }

        const uniqueToFirstArray = difference(that.incubatorSn, that.jointSn);
        // console.log(uniqueToFirstArray,324)
        that.jointSn.forEach(item => {
          that.eventSource[item.sn].close()
          if (that.carMarker[item.sn]) {
            if (that.carMarker[item.sn].marker) {
              that.carMarker[item.sn].marker.setMap(null)
            }
            if (that.carMarker[item.sn].startMarker) {
              that.carMarker[item.sn].startMarker.setMap(null)
            }
            if (that.carMarker[item.sn].polyline) {
              that.carMarker[item.sn].polyline.setMap(null)
            }
            that.carMarker[item.sn] = null
          }
        })
        const userData = localStorage.getItem('userList')
        const deptId = JSON.parse(userData)
        that.map.setFitView(null, false, [20, 30, 100, 30])
        if (event == true) {
          return
        }
        if (that.incubatorSn.length > 0) {
          that.jointSn = that.incubatorSn
          // 处理 SSE 流
          for (let i = 0; i < uniqueToFirstArray.length; i++) {
            that.mapLoading = true
            const T_sn = uniqueToFirstArray[i].sn
            const CoolerName = uniqueToFirstArray[i].name
            await that.getDeviceAttachment(T_sn, CoolerName, deptId, i)
            that.mapLoading = false
          }
        } else {
          that.$message({
            message: '请选择保温箱',
            type: 'warning'
          });
        }
      },
      // sse连接保温箱设备
      getDeviceAttachment(T_sn, CoolerName, deptId, index) {
        return new Promise((resolve, inject) => {
          const that = this
          // that.eventSource[T_sn] = new EventSource(
          //   `http://182.43.247.65:6280/api/waybill/newlocus?T_sn=${T_sn}&Id=${deptId.dept.id}&CoolerName=${CoolerName}`
          // ); //测试
          // that.eventSource[T_sn] = new EventSource(
          //   `https://colddelivery.coldbaozhida.com/cold_delivery/api/waybill/newlocus?T_sn=${T_sn}&Id=${deptId.dept.id}&CoolerName=${CoolerName}`
          // ); //正式
          that.eventSource[T_sn] = new EventSource(
            `${process.env.VUE_APP_BASE_API}/api/waybill/newlocus?T_sn=${T_sn}&Id=${deptId.dept.id}&CoolerName=${CoolerName}`
          ); //正式
          that.eventSource[T_sn].onopen = function(e) {
            // console.log('Connection to SSE opened.', e);
          };
          that.eventSource[T_sn].onmessage = function(e) {
            resolve()
            // console.log('Message from SSE stream:', e.data);
            const arr = JSON.parse(e.data)
            // console.log('Message from SSE stream:', arr);
            if (arr.data) {
              if (arr.code == 200) {
                that.initMarker(arr.data[0], arr, index)
                // 更新数据
                that.refreshData(arr.data[0], arr.sn)
              } else {
                that.jointSn = deleteElementById(that.jointSn, T_sn)

                function deleteElementById(arr, id) {
                  return arr.filter((item) => item !== id);
                }
                that.$message.error(arr.msg);
                that.eventSource[T_sn].close()
              }
            } else {
              that.eventSource[T_sn].close()
              that.$message({
                message: '设备:' + T_sn + '暂无数据！请开启监控设备',
                type: 'warning'
              });
            }
          };
          that.eventSource[T_sn].onerror = function(e) {
            that.mapLoading = false
            // console.error('Error from SSE stream:', uniqueToFirstArray[i], e);
          };
        })
      },
      // 初始化坐标点的icon
      initMarker(location, information, index) {
        let that = this
        let latitude = location.T_site.split(',')
        let dataList = information.data
        var trackList = []
        var correctionTrajectory = []
        var positions = information.data
        var truckUrl = ['0070ff', 'E6A23C', '67C23A', 'f9ff00', 'd4237a', '17abe3', 'a4579d', '00fdff', '9f00ff',
          'ff0000'
        ]
        if (positions.length > 0) {
          positions.forEach(item => {
            if (item.T_site != '0,0' && item.T_site) {
              const data = item.T_site.split(',')
              let arrTrack = [Number(data[0]), Number(data[1])]
              let corre = {
                'x': Number(data[0]),
                'y': Number(data[1]),
                'sp': 10,
                'ag': 130,
                'tm': convertToTimestamp(item.T_time)
              }

              function convertToTimestamp(dateString) {
                return new Date(dateString).getTime();
              }
              correctionTrajectory.push(corre)
              trackList.push(arrTrack)
            }
          })
        }
        // 生成坐标点icon
        if (that.carMarker[information.sn] && that.carMarker[information.sn] != null) {
          if (that.carMarker[information.sn].marker) {
            that.carMarker[information.sn].marker.setMap(null)
            let icon = new AMap.Icon({
              size: new AMap.Size(50, 40),
              image: require(`@/assets/vehicle/${truckUrl[index]}.png`),
              imageSize: new AMap.Size(50, 40),
            });
            that.carMarker[information.sn].marker = new AMap.Marker({
              icon: icon, // 坐标点图标
              position: [Number(latitude[0]), Number(latitude[1])], // 左边点的经纬度
              offset: new AMap.Pixel(-20, -15) // 坐标点偏移量
            });
            var geocoder = new AMap.Geocoder({
              city: "010", //城市设为北京，默认：“全国”
              radius: 1000 //范围，默认：500
            });
            geocoder.getAddress([Number(latitude[0]), Number(latitude[1])], function(status, result) {
              if (status === 'complete' && result.regeocode) {
                var address = result.regeocode.formattedAddress;
                // 点标记显示内容，HTML要素字符串
                var markerContent = '' +
                  '<div class="incubator_card_map">' +
                  '   <div class="map_title_incu">' + information.CoolerName + '</div>' +
                  '   <div class="map_content"><div class="map_title_incu1">' + information.sn + '</div>' +
                  '   <div class="map_title_incu1">最新温度: <span>' + location.T_t + '</span></div>' +
                  '   <div class="map_title_incu2">记录时间: ' + location.T_time + '</div>' +
                  '   <div class="map_title_incu3">当前地址: ' + address + '</div>' +
                  '   </div><div class="map_arrows"></div>' +
                  '</div>';
                that.carMarker[information.sn].marker.setLabel({
                  offset: new AMap.Pixel(-3, -68),
                  content: markerContent,
                  direction: 'center',
                })
                that.carMarker[information.sn].marker.setMap(that.map)
              }
            });
          }
          that.carMarker[information.sn].polyline = that.carMarker[information.sn].polyline
          that.carMarker[information.sn].startMarker = that.carMarker[information.sn].startMarker
          if (that.carMarker[information.sn].polyline) {
            that.carMarker[information.sn].polyline.setPath(trackList)
          }
        } else {
          // 创建一个 起点Icon
          var startIcon = new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            imageSize: new AMap.Size(135, 40),
            imageOffset: new AMap.Pixel(-9, -3)
          });
          let icon = new AMap.Icon({
            size: new AMap.Size(50, 40),
            image: require(`@/assets/vehicle/${truckUrl[index]}.png`),
            imageSize: new AMap.Size(50, 40),
          });
          that.carMarker[information.sn] = {
            marker: null,
            polyline: null,
            startMarker: null,
          }
          // 坐标点 生成方法
          that.carMarker[information.sn].marker = new AMap.Marker({
            icon: icon, // 坐标点图标
            position: [Number(latitude[0]), Number(latitude[1])], // 左边点的经纬度
            offset: new AMap.Pixel(-20, -15) // 坐标点偏移量
          });
          // 起点
          var startArr = positions[positions.length - 1].T_site.split(',')
          that.carMarker[information.sn].startMarker = new AMap.Marker({
            icon: startIcon, // 坐标点图标
            position: [Number(startArr[0]), Number(startArr[1])], // 左边点的经纬度
            offset: new AMap.Pixel(-11, -28) // 坐标点偏移量
          });
          that.carMarker[information.sn].startMarker.setMap(that.map)
          var geocoder = new AMap.Geocoder({
            city: "010", //城市设为北京，默认：“全国”
            radius: 1000 //范围，默认：500
          });
          geocoder.getAddress([Number(latitude[0]), Number(latitude[1])], function(status, result) {
            if (status === 'complete' && result.regeocode) {
              var address = result.regeocode.formattedAddress;
              // 点标记显示内容，HTML要素字符串
              var markerContent = '' +
                '<div class="incubator_card_map">' +
                '   <div class="map_title_incu">' + information.CoolerName + '</div>' +
                '   <div class="map_content"><div class="map_title_incu1">' + information.sn + '</div>' +
                '   <div class="map_title_incu1">最新温度: <span>' + location.T_t + '</span></div>' +
                '   <div class="map_title_incu2">记录时间: ' + location.T_time + '</div>' +
                '   <div class="map_title_incu3">当前地址: ' + address + '</div>' +
                '   </div><div class="map_arrows"></div>' +
                '</div>';
              that.carMarker[information.sn].marker.setLabel({
                offset: new AMap.Pixel(-3, -68),
                content: markerContent,
                direction: 'center',
              })
              that.carMarker[information.sn].marker.setMap(that.map)
              let colorArr = ['#0070ff', '#E6A23C', '#67C23A', '#f9ff00', '#d4237a', '#17abe3', '#a4579d',
                '#00fdff', '#9f00ff', '#ff0000',
              ]
              that.carMarker[information.sn].polyline = new AMap.Polyline({
                map: that.map,
                path: trackList,
                showDir: true,
                strokeColor: colorArr[index], //线颜色
                strokeWeight: 10, //线宽
                strokeStyle: "solid",
                lineJoin: 'round',
                lineCap: 'round',
              });
              that.carMarker[information.sn].polyline.setMap(that.map)
              that.map.setFitView(null, false, [20, 30, 100, 30])
              // var graspRoad;
              // if (!graspRoad) {
              //   graspRoad = new AMap.GraspRoad()
              // }
              // console.log(correctionTrajectory, 25425)
              // graspRoad.driving(correctionTrajectory, function(error, result) {
              //   console.log(error, result, 25425)
              //   if (!error) {
              //     var path2 = [];
              //     var newPath = result.data.points;
              //     for (var i = 0; i < newPath.length; i += 1) {
              //       path2.push([newPath[i].x, newPath[i].y])
              //     }
              //     var newLine = new AMap.Polyline({
              //       path: path2,
              //       strokeWeight: 8,
              //       strokeOpacity: 0.8,
              //       strokeColor: '#28F',
              //       showDir: true
              //     })
              //     that.map.add(newLine)
              //     that.map.setFitView()
              //   }
              // })
            } else {
              console.error('根据经纬度查询地址失败')
            }
          });
        }
        that.map.setFitView(null, false, [20, 30, 100, 30])
      },
      keyUpSearch() {
        var that = this
        // var positions = this.trackList;
        that.map = new AMap.Map("container", {
          resizeEnable: true,
          zoom: 2,
        });
        that.map.setFitView()
        var styleName = "amap://styles/fresh";
        that.map.setMapStyle(styleName);
      },
      // 历史轨迹
      historicalRoute() {
        var that = this
        that.map = new AMap.Map("container", {
          resizeEnable: true,
          zoom: 2,
        });
        that.map.setFitView()
        var styleName = "amap://styles/fresh";
        that.map.setMapStyle(styleName);
      },
      // 选择保温箱
      selectIncubator(event) {
        this.$refs.multipleTable.toggleRowSelection(event);
        if (event.monitorStatus == 4) {
          this.optionFlag = true
          this.timePage = 1
          this.limitNoil = true
          this.timeData = []
          this.$message.error('该保温箱暂未绑定平台');
        } else {
          this.incubatorID = event.id
          if (this.currentId == 2) {
            event.flag = true
            this.optionFlag = true
            this.timePage = 1
            this.limitNoil = true
            this.timeData = []
            this.getBoxLocus()
          }
        }
      },
      // 重选时间段轨迹
      reelect() {
        this.optionFlag = true
      },
      // 滚动触底
      scrollLoad() {
        if (this.limitNoil && this.timeData.length > 0) {
          this.getBoxLocus()
        }
      },
      // 获取保温箱历史时间段
      getBoxLocus() {
        this.timeLoading = true
        getcoolerboxall({
          coolerBoxId: this.incubatorID,
          page: this.timePage,
          pageSize: 10,
        }).then(res => {
          if (res.code == 200) {
            let arr = res.data.list
            if (this.limitNoil == true && arr) {
              this.timeData = this.timeData.concat(arr)
            }
            if (arr.length >= 10) {
              this.timePage = ++this.timePage;
            } else {
              // 已经没数据了 不需要增加数据
              this.limitNoil = false;
            }
          } else {
            this.timeData = []
          }
          this.timeLoading = false
        }).catch(() => {
          this.timeLoading = false
        })
      },
      // 获取保温箱历史轨迹
      getTrack(event) {
        if (this.marker) {
          this.marker.stopMove();
        }
        if (event.sn) {
          getHistoryLocus({
            sn: event.sn,
            start_time: event.coolerBoxUserTime,
            end_time: event.coolerEndUseTime,
            // t_id: event.t_id,
            page: 1,
            page_z: 999,
          }).then(res => {
            if (res.code == 200) {
              var trackList = []
              var positions = res.data
              if (positions && positions.length > 0) {
                positions.forEach(item => {
                  if (item.T_site != '0,0' && item.T_site) {
                    const data = item.T_site.split(',')
                    trackList.push(data)
                  }
                })
              }
              if (this.polyline) {
                this.polyline.setMap(null); // 移除轨迹
              }
              this.polyline = null
              if (this.passedPolyline) {
                this.passedPolyline.setMap(null)
              }
              this.passedPolyline = null
              if (this.marker) {
                this.marker.setMap(null)
              }
              this.marker = null
              if (this.endMarker) {
                this.endMarker.setMap(null)
              }
              this.endMarker = null
              this.trackList = trackList
              this.optionFlag = false
              this.trackCircle = true
              if (trackList.length > 0) {
                this.initMap(trackList)
              }
            }
          })
        }
      },
      // 历史轨迹
      initMap(arr) {
        // 聚焦到标记点位置的方法
        // this.map.setZoomAndCenter(10, arr[0].split(','))
        var marker, positions = arr
        const that = this
        setTimeout(() => {
          // 地图渲染完成后修改zoom
          that.map.setZoom(14);
          const num = positions.length
          // 创建一个 终点icon
          var endIcon = new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            imageSize: new AMap.Size(135, 40),
            imageOffset: new AMap.Pixel(-95, -3)
          });
          if (positions.length > 0) {
            // 终点
            that.endMarker = new AMap.Marker({
              position: positions[num - 1],
              icon: endIcon,
              offset: new AMap.Pixel(-13, -30),
            });
            that.map.add(that.endMarker);
          }
          var truckIcon = new AMap.Icon({
            size: new AMap.Size(40, 45),
            image: require(`@/assets/vehicle/67C23A.png`),
            imageSize: new AMap.Size(40, 45),
          });
          that.marker = new AMap.Marker({
            map: that.map,
            position: positions[0],
            icon: truckIcon,
            offset: new AMap.Pixel(-13, -23),
            autoRotation: true,
          });
          // 绘制轨迹
          that.polyline = new AMap.Polyline({
            map: that.map,
            path: positions,
            showDir: true,
            strokeColor: "#28F", //线颜色
            strokeWeight: 10, //线宽
            strokeStyle: "solid",
            lineJoin: 'round',
            lineCap: 'round',
          });
          that.passedPolyline = new AMap.Polyline({
            map: that.map,
            strokeColor: "#AF5", //线颜色
            strokeWeight: 10, //线宽
            strokeOpacity: .7,
            strokeStyle: "solid",
            lineJoin: 'round',
            lineCap: 'round',
          });
          that.map.add(that.polyline);
          that.map.setFitView(null, false, [150, 60, 100, 60]);
          that.marker.on("moving", function(e) {
            that.passedPolyline.setPath(e.passedPath);
          });
          that.playbackControl = true
        }, 500)
      },
      // 开始动画
      startAnimation() {
        var num = this.trackList.length * 3
        this.optionFlag = false
        this.marker.moveAlong(this.trackList, num);
      },
      // 暂停动画
      pauseAnimation() {
        this.marker.pauseMove();
      },
      // 继续动画
      resumeAnimation() {
        this.marker.resumeMove();
      },
      // 停止动画
      stopAnimation() {
        this.marker.stopMove();
      },
      destroyMap() {
        this.map && this.map.destroy();
      },
      clickImg() {
        if (this.logisticsFlag) {
          this.logisticsFlag = false
        } else {
          this.logisticsFlag = true
        }
      },
      // 全屏
      experMode() {
        const full = localStorage.getItem('fullScreen')
        if (full == 'true' || full == true) {
          this.fullScreen = false
          localStorage.setItem("fullScreen", this.fullScreen);
          this.exitFullscreen()
        } else {
          this.fullScreen = true
          localStorage.setItem("fullScreen", this.fullScreen);
          let element = document.documentElement;
          this.launchFullscreen(element);
        }
      },
      // 全屏
      launchFullscreen(element) {
        if (element.requestFullscreen) {
          element.requestFullscreen();
        } else if (element.webkitRequestFullscreen) {
          element.webkitRequestFullscreen();
        } else if (element.mozRequestFullscreen) {
          element.mozRequestFullscreen();
        } else if (element.msRequestFullscreen) {
          element.msRequestFullscreen();
        }
      },
      // 推出全屏
      exitFullscreen() {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      },
      // 弹窗关闭
      dialogClose() {
        if (this.jointSn.length > 0) {
          this.jointSn.forEach(item => {
            if (this.eventSource[item.sn]) {
              this.eventSource[item.sn].close()
            }
          })
        }
        this.map = null
        this.currentId = 1
        this.list.forEach((item) => {
          if (item.id == 1) {
            item.flag = true
          } else {
            item.flag = false
          }
        })
        this.incubatorSn = []
        this.jointSn = []
        this.realTimeTrajectory = []
        this.carMarker = []
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
        })
        this.logisticsFlag = true
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      close() {
        this.controlVisible = false
      },
      clickImg() {
        if (this.logisticsFlag) {
          this.logisticsFlag = false
        } else {
          this.logisticsFlag = true
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .amap-logo {
    bottom: -20px !important;
  }

  ::v-deep .amap-copyright {
    bottom: -20px !important;
  }

  ::v-deep .amap-marker-label {
    bottom: -3px !important;
    top: unset !important;
    border: unset !important;
    padding: 0px !important;
    background-color: unset !important;
  }

  .home_card_screen {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .map_card {
    width: 100%;
    height: 100%;
    flex: 1;
  }

  #container {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .card_switchover {
    position: absolute;
    top: 10px;
    right: 10px;
    display: flex;
    align-items: center;
  }

  .title_head_rol {
    cursor: pointer;
    width: 100px;
    height: 40px;
    color: #ffffff;
    background-color: rgba(7, 56, 78, 1);
  }

  .active_bgcolor {
    background-color: rgba(4, 137, 170, 1);
  }

  .card_bottom_control {
    position: absolute;
    left: 10px;
    right: 10px;
    bottom: 10px;
    background-color: #ffffff;
    border-radius: 6px;
  }

  .height_300 {
    height: 300px;
  }

  .height_30 {
    height: 30px;
  }

  .card_unpack_control {
    padding: 0px 10px 5px 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .history_warp {
    height: calc(100% - 35px);
    width: 100%;
    overflow: hidden;
  }

  ::v-deep .top .el-table__body-wrapper {
    display: none;
  }

  ::v-deep .bottom .el-table__header-wrapper {
    display: none;
  }

  .history_warp ::v-deep .el-table {
    color: #606266;
  }

  .history_warp ::v-deep .el-table tr {
    background-color: #FFF;
  }

  .history_warp ::v-deep .el-table thead {
    color: #909399;
  }

  .history_warp ::v-deep .el-table td.el-table__cell,
  .history_warp ::v-deep .el-table th.el-table__cell.is-leaf {
    border-bottom: 1px solid #EBEEF5;
  }

  .history_warp ::v-deep .el-table--border,
  .history_warp ::v-deep .el-table--group {
    border: 1px solid #EBEEF5;
  }

  .history_warp ::v-deep .el-table td.el-table__cell,
  .history_warp ::v-deep .el-table th.el-table__cell.is-leaf {
    border-bottom: 1px solid #EBEEF5;
  }

  .history_warp ::v-deep .el-table--border .el-table__cell,
  .history_warp ::v-deep .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed {
    border-right: 1px solid #EBEEF5;
  }

  .history_warp ::v-deep .el-table--border::after,
  .history_warp ::v-deep .el-table--group::after,
  .history_warp ::v-deep .el-table::before {
    background-color: #EBEEF5;
  }

  .history_warp ::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell {
    background-color: #F5F7FA;
  }

  .history_warp ::v-deep .el-pagination__total {
    color: #606266;
  }

  .history_warp ::v-deep .el-pagination.is-background .btn-next,
  .history_warp ::v-deep .el-pagination.is-background .btn-prev,
  .history_warp ::v-deep .el-pagination.is-background .el-pager li {
    background-color: #f4f4f5;
  }

  .history_warp ::v-deep .el-pagination__jump {
    color: #606266;
  }

  .history_warp ::v-deep .el-pagination.is-background .btn-next,
  .history_warp ::v-deep .el-pagination.is-background .btn-prev,
  .history_warp ::v-deep .el-pagination.is-background .el-pager li {
    color: #606266;
  }

  .history_warp ::v-deep .el-pagination.is-background .btn-next.disabled,
  .history_warp ::v-deep .el-pagination.is-background .btn-next:disabled,
  .history_warp ::v-deep .el-pagination.is-background .btn-prev.disabled,
  .history_warp ::v-deep .el-pagination.is-background .btn-prev:disabled,
  .history_warp ::v-deep .el-pagination.is-background .el-pager li.disabled {
    color: #C0C4CC;
  }

  .history_warp ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #409EFF;
    color: #FFF;
  }

  .history_warp ::v-deep .el-input__inner {
    color: #606266;
    border: 1px solid #DCDFE6;
    background-color: #FFF;
  }

  .card_unpack_control ::v-deep .el-input__inner {
    color: #606266;
    border: 1px solid #DCDFE6;
    background-color: #FFF;
  }

  .card_unpack_control ::v-deep .el-input.is-active .el-input__inner,
  .card_unpack_control ::v-deep .el-input__inner:focus {
    border-color: #409EFF;
  }

  .history_warp ::v-deep .el-pagination .btn-next,
  .history_warp ::v-deep .el-pagination .btn-prev {
    color: #303133;
  }

  ::v-deep .history_warp .current-row>td.el-table__cell {
    background-color: #9eb1f7 !important;
  }

  .overturn {
    transform: rotate(180deg);
  }

  ::v-deep .incubator_card_map {
    position: relative;
    // width: 190px;
    width: fit-content;
    width: -webkit-fit-content;
    width: -moz-fit-content;
    background-color: #fff;
    border: 1px solid #DCDFE6;
    padding: 5px;
    border-radius: 4px;
    // overflow: hidden;
  }

  ::v-deep .map_title_incu {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 4px;
  }

  ::v-deep .map_content {
    display: flex;
    // display: none;
    flex-direction: column;
  }

  ::v-deep .map_title_incu1 {
    font-size: 14px;

    span {
      font-weight: bold;
      color: #67C23A;
    }
  }

  ::v-deep .map_title_incu2 {
    white-space: normal;
    font-size: 12px;
    margin: 2px 0px;
    min-width: 180px;
  }

  ::v-deep .map_title_incu3 {
    font-size: 12px;
    margin: 2px 0px;
    overflow-wrap: break-word;
    white-space: pre-wrap;
  }

  ::v-deep .map_arrows {
    position: absolute;
    bottom: 0px;
    left: calc(50% - 5px);
  }

  ::v-deep .map_arrows::before {
    position: absolute;
    content: '';
    border-top: 11px #DCDFE6 solid;
    border-left: 10px transparent solid;
    border-right: 10px transparent solid;
    border-bottom: 10px transparent solid;
  }

  ::v-deep .map_arrows::after {
    position: absolute;
    content: '';
    border-top: 10px #fff solid;
    border-left: 10px transparent solid;
    border-right: 10px transparent solid;
    border-bottom: 10px transparent solid;
  }

  .card_right_information {
    position: absolute;
    top: 60px;
    right: 10px;
  }

  .information_card {
    width: 260px;
    max-height: 400px;
    overflow: hidden auto;
    border-radius: 5px;
    background-color: #ffffff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .hide_information {
    cursor: pointer;
    width: 50px;
    height: 50px;
    background-color: #ffffff;
    border-radius: 50%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    span {
      color: #009efd;
      font-size: 30px;
    }
  }

  .track_visit {
    position: absolute;
    right: 10px;
    top: -130px;
    width: 240px;
    height: auto;
    background-color: #ffffff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 10px;
    border-radius: 5px;

    .playback {
      font-size: 15px;
      padding-bottom: 10px;
    }
  }

  .card_cartoon {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .cartoo_title {
    cursor: pointer;
    margin-bottom: 8px;
    width: 7rem;
    color: #25A5F7;
    border: 1px solid #25A5F7;
    border-radius: 30px;
    padding: 4px 0px;
    font-size: 14px;
  }

  .margin_10 {
    margin-right: 10px;
  }

  .card_time_box {
    cursor: pointer;
    padding: 6px 10px;
    border-bottom: 1px solid #E4E7ED;
  }

  .sn_card_box {
    font-size: 16px;
    font-weight: bold;
  }

  .box_time {
    font-size: 14px;
  }

  .scale-up-tr {
    -webkit-animation: scale-up-tr 0.4s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
    animation: scale-up-tr 0.4s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
  }

  @-webkit-keyframes scale-up-tr {
    0% {
      -webkit-transform: scale(0.5);
      transform: scale(0.5);
      -webkit-transform-origin: 100% 0%;
      transform-origin: 100% 0%;
    }

    100% {
      -webkit-transform: scale(1);
      transform: scale(1);
      -webkit-transform-origin: 100% 0%;
      transform-origin: 100% 0%;
    }
  }

  @keyframes scale-up-tr {
    0% {
      -webkit-transform: scale(0.5);
      transform: scale(0.5);
      -webkit-transform-origin: 100% 0%;
      transform-origin: 100% 0%;
    }

    100% {
      -webkit-transform: scale(1);
      transform: scale(1);
      -webkit-transform-origin: 100% 0%;
      transform-origin: 100% 0%;
    }
  }
</style>
