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

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'KDEBZ-EV5KH-XN5DU-WYZGD-SN3YK-WZBZI'
});
Page({
  /**
   * 页面的初始数据
   */
  data: {
    mapCenter: {
      longitude: '104.06439',
      latitude: '30.57812'
    },
    mapObj: null as any,
    carMarkers: [],
    setting: {
      scale: 10
    },
    show: true,
    tabs: [
      {
        tabName: '实时状态'
      },
      {
        tabName: '整车数据'
      },
      {
        tabName: '报警数据'
      },
      {
        tabName: '电机'
      }
    ] as any,
    activeIndex: 0,
    infObj: {} as any,
    address: '',
    tmpOptions: {
      gpsTime: {
        key: 'gpsTime',
        value: '-',
        label: '定位时间'
      },
      totalMileage: {
        key: 'totalMileage',
        value: '-',
        label: '里程'
      },
      acc_dictText: {
        key: 'acc_dictText',
        value: '-',
        label: '点火状态'
      },
      isOnline: {
        key: 'isOnline',
        value: '-',
        label: '在线状态'
      },
      // {
      //   key: '',
      //   value: '-',
      //   label: 'GPS定位'
      // },
      chargeStatus_dictText: {
        key: 'chargeStatus_dictText',
        value: '-',
        label: '充电状态'
      },
      alert: {
        key: 'alert',
        value: '-',
        label: '告警'
      },
      // stateOfCharge:{
      //   key: 'stateOfCharge',
      //   value: '-',
      //   label: '剩余电量'
      // },
      maxRpm: {
        key: 'maxRpm',
        value: '-',
        label: '转速'
      },
      speed: {
        key: 'speed',
        value: '-',
        label: '速度'
      },
      stateOfCharge: {
        key: 'stateOfCharge',
        value: '-',
        label: 'SOC'
      }
    } as any,
    tmpOptions1: {
      status: {
        key: 'status',
        value: '-',
        label: '车辆状态'
      },
      speed: {
        key: 'speed',
        value: '-',
        label: '速度'
      },
      totalCurrent: {
        key: 'totalCurrent',
        value: '-',
        label: '总电流'
      },
      gearPosition: {
        key: 'gearPosition',
        value: '-',
        label: '档位'
      },
      // chargeStatus_dictText:{
      //   key: 'chargeStatus_dictText',
      //   value: '-',
      //   label: '制动踏板状态'
      // },
      chargeStatus: {
        key: 'chargeStatus',
        value: '-',
        label: '充电状态'
      },
      totalMileage: {
        key: 'totalMileage',
        value: '-',
        label: '累计里程'
      },
      stateOfCharge: {
        key: 'stateOfCharge',
        value: '-',
        label: 'SOC值'
      },
      insulationResistance: {
        key: 'insulationResistance',
        value: '-',
        label: '绝缘电阻'
      },
      // maxRpm:{
      //   key: 'maxRpm',
      //   value: '-',
      //   label: '驱动力状态'
      // },
      operatingMode: {
        key: 'operatingMode',
        value: '-',
        label: '运行模式'
      },
      totalVoltage: {
        key: 'totalVoltage',
        value: '-',
        label: '总电压'
      },
      dcDcStatus: {
        key: 'dcDcStatus',
        value: '-',
        label: 'DC-DC状态'
      }
    } as any,
    tmpOptions2: {
      maxAlarmLevel: {
        key: 'maxAlarmLevel',
        value: '-',
        label: '最高报警等级'
      },
      batteryHighTemperatureAlarm: {
        key: 'batteryHighTemperatureAlarm',
        value: '-',
        label: '电池高温报警'
      },
      underVoltageAlarm: {
        key: 'underVoltageAlarm',
        value: '-',
        label: '车载储能装欠压报警'
      },
      overVoltageSingleBatteryAlarm: {
        key: 'overVoltageSingleBatteryAlarm',
        value: '-',
        label: '单体电池过压报警'
      },
      highSocAlarm: {
        key: 'highSocAlarm',
        value: '-',
        label: 'SOC过高报警'
      },
      mismatchedEnergyStorageAlarm: {
        key: 'mismatchedEnergyStorageAlarm',
        value: '-',
        label: '可充电储能不匹配报警'
      },
      dcDcTemperatureAlarm: {
        key: 'dcDcTemperatureAlarm',
        value: '-',
        label: 'DC-DC温度报警'
      },
      overChargeAlarm: {
        key: 'overChargeAlarm',
        value: '-',
        label: '车载储能装置过充报警'
      },
      insulationAlarm: {
        key: 'insulationAlarm',
        value: '-',
        label: '绝缘报警'
      },
      brakeSystemAlarm: {
        key: 'brakeSystemAlarm',
        value: '-',
        label: '制动系统报警'
      },
      motorControllerTemperatureAlarm: {
        key: 'motorControllerTemperatureAlarm',
        value: '-',
        label: '驱动电机控制器温度报警'
      },
      driveMotorTemperatureAlarm: {
        key: 'driveMotorTemperatureAlarm',
        value: '-',
        label: '驱动电机温度报警'
      },
      energyStorageFaultCount: {
        key: 'energyStorageFaultCount',
        value: '-',
        label: '可充电储能装置故障总数'
      },
      dcDcStatusAlarm: {
        key: 'dcDcStatusAlarm',
        value: '-',
        label: 'DC-DC状态报警'
      },
      driveMotorFaultCount: {
        key: 'driveMotorFaultCount',
        value: '-',
        label: '驱动电机故障总数:'
      },
      engineFaultCount: {
        key: 'engineFaultCount',
        value: '-',
        label: '发动电机故障总数:'
      },
      temperatureDifferenceAlarm: {
        key: 'temperatureDifferenceAlarm',
        value: '-',
        label: '温度差异报警'
      },
      overVoltageAlarm: {
        key: 'overVoltageAlarm',
        value: '-',
        label: '车载储能装置过压报警'
      },
      lowSocAlarm: {
        key: 'lowSocAlarm',
        value: '-',
        label: 'SOC过低报警'
      },
      underVoltageSingleBatteryAlarm: {
        key: 'underVoltageSingleBatteryAlarm',
        value: '-',
        label: '单体电池欠压报警'
      },
      socJumpAlarm: {
        key: 'socJumpAlarm',
        value: '-',
        label: 'SOC跳变报警'
      },
      batteryInconsistencyAlarm: {
        key: 'batteryInconsistencyAlarm',
        value: '-',
        label: '电池单体一致性差报警'
      },
      highVoltageInterlockStatusAlarm: {
        key: 'highVoltageInterlockStatusAlarm',
        value: '-',
        label: '高压互锁状态报警'
      }
    } as any,
    tmpOptions3: {
      temperature: {
        key: 'temperature',
        value: '-',
        label: '电机温度'
      },
      controllerTemperature: {
        key: 'controllerTemperature',
        value: '-',
        label: '电机控制器温度'
      }
    } as any,
    tmpOptions4: {
      number: {
        key: 'number',
        value: '-',
        label: '序号'
      },
      status: {
        key: 'status',
        value: '-',
        label: '状态'
      },
      controllerTemperature: {
        key: 'controllerTemperature',
        value: '-',
        label: '控制器温度'
      },
      temperature: {
        key: 'temperature',
        value: '-',
        label: '温度'
      },
      torque: {
        key: 'torque',
        value: '-',
        label: '转矩'
      },
      inputVoltage: {
        key: 'inputVoltage',
        value: '-',
        label: '控制器输入电压'
      },
      dcBusCurrent: {
        key: 'dcBusCurrent',
        value: '-',
        label: '直流母线电流'
      }
    } as any,
    tmpOptions5: {
      compulsoryCompanyId_dictText: {
        key: 'compulsoryCompanyId_dictText',
        value: '-',
        label: '保险公司'
      },
      compulsoryStartTime: {
        key: 'compulsoryStartTime',
        value: '-',
        label: '起保日期'
      },
      compulsoryValidTime: {
        key: 'compulsoryValidTime',
        value: '-',
        label: '有效日期'
      },
      compulsoryInsuranceNo: {
        key: 'compulsoryInsuranceNo',
        value: '-',
        label: '交强险（保单号）'
      },
      compulsoryUrl: {
        key: 'compulsoryUrl',
        value: '-',
        label: '交强险'
      },
      commercialInsuranceNo: {
        key: 'commercialInsuranceNo',
        value: '-',
        label: '商业险（保单号）'
      },
      commercialUrl: {
        key: 'commercialUrl',
        value: '-',
        label: '商业险'
      }
    } as any
  },

  init() {
    this.data.mapObj = wx.createMapContext('map-container');
  },
  showPopup() {
    this.setData({ show: true });
    this.init();
  },

  onClose() {
    this.setData({ show: false });
    this.init();
  },
  changeTab(e: any) {
    console.log(e.currentTarget.dataset);
    this.setData({
      activeIndex: e.currentTarget.dataset.index
    });
  },
  reloadData() {
    this.getRealInfo();
  },
  // 导航
  navigate() {
    let mapCenter = this.data.mapCenter;
    this.data.mapObj.openMapApp({
      longitude: mapCenter.longitude,
      latitude: mapCenter.latitude,
      destination: this.data.address,
      fail: () => {
        wx.showToast({
          title: '获取定位失败，请开启定位服务',
          icon: 'none'
        });
      }
    });
  },
  getAddress(position: any) {
    var _this = this;
    qqmapsdk.reverseGeocoder({
      location: position,
      success: function (res: any) {
        //成功后的回调
        console.log(res.result.address);
        // var res = res.result;
        _this.setData({
          address: res.result.address
        });
        _this.setMarker();
      }
    });
  },
  getRealInfo() {
    let parms = {
      plateNumber: wx.getStorageSync('selectCar').plateNumber
    };
    getAction('api/monitor/vehicle/realInfo', parms).then((res: any) => {
      if (res.code == 200) {
        console.log(res);
        this.getAddress({
          latitude: res.result.gdLat,
          longitude: res.result.gdLon
        });
        let tmpOptions = this.data.tmpOptions;
        let tmpOptions1 = this.data.tmpOptions1;
        for (let key in tmpOptions) {
          if (key != 'alert') {
            if (!res.result[key]) {
              continue;
            }
          }
          tmpOptions[key].value = res.result[key] ? res.result[key] : '-';
          tmpOptions[key].type = 'val';
          if (key == 'acc_dictText') {
            tmpOptions[key].type = 'online';
            tmpOptions[key].value = res.result.isOnline ? '点火' : '熄火';
          }
          if (key == 'isOnline') {
            tmpOptions[key].type = 'online';
            tmpOptions[key].value = res.result.isOnline ? '在线' : '离线';
          }

          if (key == 'alert') {
            // "faultAlarm": 1, //故障报警 0-正常 1-异常
            // "fenceAlarm": 1, //围栏告警 0-正常 1-异常
            // "speedingAlarm": 1, //超速告警 0-正常 1-异常
            // "safetyAlarm": 1, //主动安全告警-0-正常 1-异常
            tmpOptions[key].type = 'errline';
            if (res.result.faultAlarm) {
              tmpOptions[key].value = res.result.faultAlarm ? '故障' : '';
            } else if (res.result.fenceAlarm) {
              tmpOptions[key].value = res.result.fenceAlarm ? '围栏' : '';
            } else if (res.result.speedingAlarm) {
              tmpOptions[key].value = res.result.speedingAlarm ? '超速' : '';
            } else if (res.result.safetyAlarm) {
              tmpOptions[key].value = res.result.safetyAlarm ? '主动安全' : '';
            } else {
              tmpOptions[key].type = 'offline';
              tmpOptions[key].value = '无告警';
            }
          }
          if (key == 'totalMileage') {
            tmpOptions[key].value += 'km';
          }
          if (key == 'maxRpm') {
            tmpOptions[key].value += 'r/min';
          }
          if (key == 'speed') {
            tmpOptions[key].value += 'km/h';
          }
          if (key == 'stateOfCharge') {
            tmpOptions[key].value += '%';
          }
        }

        for (let key in tmpOptions1) {
          if (!res.result.vehicleJSONObject) {
            break;
          }
          if (!res.result.vehicleJSONObject[key]) {
            continue;
          }
          tmpOptions1[key].value = res.result.vehicleJSONObject[key]
            ? res.result.vehicleJSONObject[key]
            : '-';

          if (key == 'status') {
            // 1: '启动',
            // 2: '熄火',
            // 3: '其他',
            // '-99': '无效',
            // '-100': '异常'
            switch (res.result[key]) {
              case 1:
                tmpOptions1[key].value = '启动';
                break;
              case 2:
                tmpOptions1[key].value = '熄火';
                break;
              case 3:
                tmpOptions1[key].value = '其他';
                break;
              case -99:
                tmpOptions1[key].value = '无效';
                break;
              case -100:
                tmpOptions1[key].value = '异常';
                break;
            }
          }
          if (key == 'chargeStatus') {
            // 1-停车充电、2-行驶充电、3-未充电  4-充电完成、-99-无效、-100-异常
            switch (res.result[key]) {
              case 1:
                tmpOptions1[key].value = '停车充电';
                break;
              case 2:
                tmpOptions1[key].value = '行驶充电';
                break;
              case 3:
                tmpOptions1[key].value = '未充电';
                break;
              case 4:
                tmpOptions1[key].value = '充电完成';
                break;
              case -99:
                tmpOptions1[key].value = '无效';
                break;
              case -100:
                tmpOptions1[key].value = '异常';
                break;
            }
          }
          if (key == 'operatingMode') {
            // 运行模式 1-纯电 2-混动 3-燃油 -99-无效、-100-异常
            switch (res.result[key]) {
              case 1:
                tmpOptions1[key].value = '纯电';
                break;
              case 2:
                tmpOptions1[key].value = '混动';
                break;
              case 3:
                tmpOptions1[key].value = '燃油';
                break;
              case -99:
                tmpOptions1[key].value = '无效';
                break;
              case -100:
                tmpOptions1[key].value = '异常';
                break;
            }
          }
          if (key == 'gearPosition') {
            tmpOptions1[key].value = res.result[key] ? res.result[key] : '-';
          }
          if (key == 'speed') {
            tmpOptions1[key].value += 'km/h';
          }
          if (key == 'stateOfCharge') {
            tmpOptions1[key].value += '%';
          }
          if (key == 'totalVoltage') {
            tmpOptions1[key].value += 'V';
          }
          if (key == 'totalCurrent') {
            tmpOptions1[key].value =
              Math.floor(tmpOptions1[key].value * 100) / 100;
            tmpOptions1[key].value += 'A';
          }
          if (key == 'insulationResistance') {
            tmpOptions1[key].value += 'kn';
          }
          if (key == 'dcDcStatus') {
            tmpOptions1[key].value =
              tmpOptions1[key].value == 1 ? '工作' : '断开';
          }
          if (key == 'totalMileage') {
            tmpOptions1[key].value =
              Math.floor(tmpOptions1[key].value * 100) / 100;
          }
        }
        let tmpOptions2 = this.data.tmpOptions2;
        for (let key in tmpOptions2) {
          if (!res.result.alarmDataJSONObject) {
            break;
          }
          if (
            res.result.alarmDataJSONObject[key] == undefined ||
            res.result.alarmDataJSONObject[key] == null
          ) {
            continue;
          }
          tmpOptions2[key].value = res.result.alarmDataJSONObject[key]
            ? '报警'
            : '正常';

          if (res.result.alarmDataJSONObject[key] == 1) {
            tmpOptions2[key].type = 'val-r';
          }

          if (key == 'maxAlarmLevel') {
            tmpOptions2[key].value =
              res.result.alarmDataJSONObject[key] + '级别';
            tmpOptions2[key].type = '';
          }
          if (key == 'energyStorageFaultCount') {
            tmpOptions2[key].value = res.result.alarmDataJSONObject[key]
              ? res.result.alarmDataJSONObject[key]
              : '0';
            tmpOptions2[key].type = '';
          }
          if (key == 'engineFaultCount') {
            tmpOptions2[key].value = res.result.alarmDataJSONObject[key]
              ? res.result.alarmDataJSONObject[key]
              : '0';
            tmpOptions2[key].type = '';
          }
          if (key == 'driveMotorFaultCount') {
            tmpOptions2[key].value = res.result.alarmDataJSONObject[key]
              ? res.result.alarmDataJSONObject[key]
              : '0';
            tmpOptions2[key].type = '';
          }
        }

        let tmpOptions3 = this.data.tmpOptions3;
        for (let key in tmpOptions3) {
          if (!res.result.electricMotorJSONArray) {
            break;
          }
          console.log(key, res.result.electricMotorJSONArray[0]);
          tmpOptions3[key].value = res.result.electricMotorJSONArray[0][key]
            ? res.result.electricMotorJSONArray[0][key]
            : '-';

          tmpOptions3[key].value += '℃';
        }
        let tabs = this.data.tabs;
        if (res.result.electricMotorJSONArray) {
          res.result.electricMotorJSONArray.map((x: any) => {
            let tmpOptions4 = this.data.tmpOptions4;
            for (let key in tmpOptions4) {
              tmpOptions4[key].value = x[key] ? x[key] : '-';
              if (key == 'controllerTemperature' || key == 'temperature') {
                tmpOptions4[key].value += '℃';
              }
              if (key == 'inputVoltage') {
                tmpOptions4[key].value += 'V';
              }
              if (key == 'dcBusCurrent') {
                if (tmpOptions4[key].value.indexOf('A') == -1) {
                  tmpOptions4[key].value += 'A';
                }
              }
              if (key == 'rpm') {
                tmpOptions4[key].value += 'r/min';
              }
              if (key == 'dcBusCurrent') {
                tmpOptions4[key].value += 'A';
              }
            }
            tabs.push({
              tabName: '驱动电机' + x.number,
              options: tmpOptions4
            });
          });
        }
        tabs.push({
          tabName: '保险信息'
        });
        let tmpOptions5 = this.data.tmpOptions5;
        for (let key in tmpOptions5) {
          if (key == 'compulsoryUrl' || key == 'commercialUrl') {
            if (res.result.insuranceInfo[key]) {
              let list = res.result.insuranceInfo[key].split(',');
              tmpOptions5[key].value = list.map((item: string) => {
                return {
                  label: item.split('/')[item.split('/').length - 1],
                  url: item
                };
              });
            } else tmpOptions5[key].value = res.result.insuranceInfo[key];
          } else tmpOptions5[key].value = res.result.insuranceInfo[key];
        }
        console.log(tabs);
        this.setData({
          tabs: tabs,
          infObj: res.result,
          tmpOptions: tmpOptions,
          tmpOptions1: tmpOptions1,
          tmpOptions2: tmpOptions2,
          tmpOptions3: tmpOptions3,
          tmpOptions5: tmpOptions5,
          mapCenter: {
            latitude: res.result.gdLat,
            longitude: res.result.gdLon
          },
          setting: { scale: 10 }
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  setMarker() {
    let tmp = [] as any;
    let imgUrl = '../../../images/car_select.png';
    tmp.push({
      id: 0,
      latitude: this.data.infObj.gdLat,
      longitude: this.data.infObj.gdLon,
      iconPath: imgUrl,
      anchor: {
        //	经纬度在标注图标的锚点，
        x: 0.5,
        y: 1
      },
      width: 48,
      height: 55,
      label: {
        content: this.data.address,
        color: '#FFFFFF',
        display: 'ALWAYS',
        fontSize: 13,
        borderRadius: 4,
        bgColor: '#2C6AF3',
        textAlign: 'center',
        anchorY: 20,
        padding: 8
      }
    });
    console.log(tmp);
    this.setData({
      carMarkers: tmp
    });
  },

  // 查看文件
  checkFile(event: any) {
    let url = event.currentTarget.dataset.url;
    let type = url.split('.')[url.split('.').length - 1];
    if (type == 'jpg' || type == 'jpeg' || type == 'png') {
      wx.previewImage({
        current: url, // 当前显示图片的http链接
        urls: [url] // 需要预览的图片http链接列表
      });
    } else {
      wx.showLoading({
        title: '数据加载中'
      });
      wx.downloadFile({
        // 示例 url，并非真实存在
        url: url,
        success: function (res) {
          const filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            showMenu: true,
            success: function (res) {
              wx.hideLoading();
            },
            fail: function () {
              wx.hideLoading();
            }
          });
        },
        fail: function () {
          wx.hideLoading();
        }
      });
    }
    console.log(url);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({
      tabs: [
        {
          tabName: '实时状态'
        },
        {
          tabName: '整车数据'
        },
        {
          tabName: '报警数据'
        },
        {
          tabName: '电机'
        }
      ]
    });
    this.getRealInfo();
    this.init();
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

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

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

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