// pages/vehicleMonitoring/global/global.ts
import { getAction } from '../../../api/base';

Page({
  /**
   * 页面的初始数据
   */

  // lat: 30.435934
  // lon: 104.065605
  data: {
    mapCenter: {
      longitude: '104.065605',
      latitude: '30.435934'
    },
    mapObj: null as any,
    tabList: [],
    active: 0,
    showStatus: 0,
    carList: [],
    carMarkers: [],
    carMarkersInfList: [],
    includePoints: [],
    timer: null as any,

    projectOptions: [],
    selectProjectIndex: 0,
    selectProject: {} as any,

    loading: false,
    current: 1,
    isLast: false,
    mapScale: 0,
    // 是否展示车牌
    showPlateNumber: true
  },
  init() {
    // this.initDateList()
    // this.setData({
    //   routeId: wx.getStorageSync('diagramRouteInf'),
    // })
    // console.log(wx.getStorageSync('diagramRouteInf'))
    this.data.mapObj = wx.createMapContext('map-container');
    // console.log('地图对象', this.data.mapObj)
    // this.getRealData()
    // let that = this
    // this.data.mapObj.getScale({
    //   success: function (res: any) {
    //     console.log('当前地图缩放级别：', res.scale);
    //     that.setData({
    //       mapScale: res.scale
    //     })
    //   }
    // })
  },
  // 切换显示  0:地图  1:列表
  swicthShow() {
    console.log(this.data.showStatus);
    this.setData({
      showStatus: this.data.showStatus == 0 ? 1 : 0
    });
    if (this.data.showStatus == 0) {
      this.getMapCarList();
    } else {
      this.getListByView();
    }
  },
  toSearch() {
    wx.setStorageSync('isGlobal', 1);
    wx.navigateTo({
      url: '../component/vehicleSearch/vehicleSearch',
      fail: e => {
        console.log(e);
      }
    });
  },
  toDetailPage(e: any) {
    console.log(e.currentTarget.dataset.inf);
    wx.setStorageSync('selectCar', e.currentTarget.dataset.inf);
    wx.navigateTo({
      url: '../realtime/realtime',
      fail: e => {
        console.log(e);
      }
    });
  },
  getProjectOptions() {
    getAction('api/projects/list').then((res: any) => {
      if (res.code == 200) {
        res.result.unshift({
          id: '',
          projectName: '全部'
        });
        this.setData({
          projectOptions: res.result,
          selectProjectIndex: 0,
          selectProject: res.result[0]
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  bindPickerProject(e: any) {
    console.log(e);
    let index = Number(e.detail.value);
    this.setData({
      selectProject: this.data.projectOptions[index],
      selectProjectIndex: index
    });
    this.getTabList();
    if (this.data.showStatus == 0) {
      this.getMapCarList();
    } else {
      this.getListByView();
    }
  },
  tabOnChange(e: any) {
    console.log(e);
    this.setData({
      active: e.detail.index
    });
    this.getTabList();
    if (this.data.showStatus == 0) {
      this.getMapCarList();
    } else {
      this.getListByView();
    }
  },
  getNextList() {
    if (this.data.loading) return;
    if (!this.data.isLast) {
      this.setData({
        current: this.data.current + 1
      });
      this.getListByView();
    } else {
      wx.showToast({
        title: '告警信息已加载完毕',
        duration: 1000,
        icon: 'none'
      });
    }
  },
  getListByView() {
    let parms = {
      projectId: this.data.selectProject.id,
      statusType: this.data.active == 0 ? '' : this.data.active, //不传查所有，1在线，2-离线，3-故障告警，4-围栏告警，5-超速告警，6-主动安全告警
      pageNo: this.data.current,
      pageSize: 500
    };
    getAction('api/monitor/vehicle/listByView', parms).then((res: any) => {
      if (res.code == 200) {
        this.setData({
          carList: res.result.records
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  getMapCarList(isFirst = false) {
    let parms = {
      projectId: this.data.selectProject.id,
      statusType: this.data.active == 0 ? '' : this.data.active, //不传查所有，1在线，2-离线，3-故障告警，4-围栏告警，5-超速告警，6-主动安全告警
      lng: this.data.mapCenter.longitude,
      lat: this.data.mapCenter.latitude
      // mapLevel: 3 // 地图当前层级，默认3
    };
    this.setData({
      loading: true
    });
    wx.showLoading({
      title: '加载中'
    });
    getAction('api/monitor/vehicle/listByMap', parms).then((res: any) => {
      wx.hideLoading();
      this.setData({
        loading: false
      });
      if (res.code == 200) {
        let tmp = [] as any;
        let imgUrl = '../../../images/car.png';
        res.result.map((item: any, i: Number) => {
          tmp.push({
            id: i,
            plateNumber: item.plateNumber,
            latitude: item.gdLat,
            longitude: item.gdLon,
            iconPath: imgUrl,
            anchor: {
              //	经纬度在标注图标的锚点，
              x: 0.5,
              y: 1
            },
            customCallout: {
              anchorX: 0,
              anchorY: 54,
              display: 'ALWAYS'
            },
            width: 21,
            height: 24
          });
        });
        this.setData({
          carMarkers: tmp,
          includePoints: tmp,
          carMarkersInfList: res.result,
          loading: false
        });
        // 获取当前层级
        let that = this;
        // 第一次加载点标记，防止点标记气泡的闪现画面
        if (isFirst) {
          this.data.mapObj.getScale({
            success: function (res: any) {
              that.setData({
                mapScale: 10
              });
            }
          });
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  // setMapCar() {
  //   // 车辆数据，调用地图方法渲染
  //   console.log('渲染车辆')
  // },
  getTabList() {
    let parms = {
      projectId: this.data.selectProject.id,
      plateNumber: ''
    };
    getAction('api/monitor/vehicle/count', parms).then((res: any) => {
      if (res.code == 200) {
        this.setData({
          tabList: res.result
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  bindtap(e: any) {
    console.log(e);
  },
  // 视野发生变化时触发，
  regionChange(e: any) {
    console.log(e);
    // 变化完后重载数据，若继续变化就先不重载数据
    if (e.causedBy == '"drag"' && e.type == 'end') {
      if (this.data.loading) {
        return;
      }
      // let timer = setInterval(() => {
      //   debugger
      //   if(this.data.timer) {
      //     clearInterval(this.data.timer)
      //     this.setData({
      //       timer: null
      //     })
      //   }
      this.getMapCarList();
      // },1000)
      // this.setData({
      //   timer: timer
      // })
    } else {
      // clearInterval(this.data.timer)
      // this.setData({
      //   timer: null
      // })
    }
    // 获取当前层级
    if (e.type == 'end') {
      this.setData({
        mapScale: e.detail.scale
      });
    }
  },
  showCarInf(e: any) {
    //点击车辆图标 跳转到展示车辆信息

    let tmp = this.data.carMarkersInfList;
    let index = e.detail.markerId;
    wx.setStorageSync('selectCar', tmp[index]);
    // 存信息然后跳转
    wx.navigateTo({
      url: '../realtime/realtime',
      fail: e => {
        console.log(e);
      }
    });
  },
  setTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    let timer = setInterval(() => {
      this.getTabList();
      if (this.data.showStatus == 0) {
        this.getMapCarList();
      } else {
        this.getListByView();
      }
    }, 30000);
    this.setData({
      timer: timer
    });
  },
  showPlateNumberFn() {
    this.setData({
      showPlateNumber: !this.data.showPlateNumber
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getProjectOptions();
    this.init();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabList();
    if (this.data.showStatus == 0) {
      this.getMapCarList(true);
    } else {
      this.getListByView();
    }
    this.setTimer();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
