const config = require('../../config/index.js')
const {
  $Message
} = require('../../components/base/index');
const {
  api,
  mapApi,
  imgName,
  getUserInfo,
  wxLogin,
  alertTip,
  toastTip,
  authAgainByUser,
  userLocation
} = require('../../lib/util.js')
const moment = require('../../lib/moment.js')
import Cmd from '../../lib/cmd.js'
let cmd = null
let app = getApp()
let medicalTimer, actionTimer, deviceTimer = null //体检 延时器

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgCardevice: imgName('car_device.png'),
    imgCartrail: imgName('car_trail.png'),
    imgRefresh: imgName('refresh.png'),
    imgRightarr: imgName('right_arr.png'),
    imgVcu: imgName('vcu.png'),
    imgArrowdown: imgName('arrowdown.png'),
    imgArrowup: imgName('arrowup.png'),
    imgBattery: imgName('battery.png'),
    imgFind: imgName('find.png'),
    imgLoc: imgName('loc.png'),
    imgLock: imgName('lock.png'),
    imgToloc: imgName('toloc.png'),
    imgcarloc: imgName('timeline_location.png'),
    imgMore: imgName('more.png'),
    imgSpeed: imgName('speed.png'),
    imgMedical: imgName('medical.png'),
    user: null, //用户
    person: 1, //个租
    deviceLocError: false,
    device: null, //设备
    timerDevice: null,
    message: '',
    baseMsg: true, //基础数据获取是否正常
    ui: {
      message: '22', //消息内容
      froNo: '--', //车架号
      vcuNo: '--', //中控号
      licensePlate: '--', //号牌
      vehicleTypeName: '--', //车型名称
      rentStartTime: '--', //起租时间
      fee: '1.5',
      deviceAdress: '--', //位置
      last_communication_time: '--', //更新时间
      lockState: 0, //锁
      speed: '0',
      estimatedMileage: '--', //预估里程
      dumpEnergy: '--', //剩余电量
      bluetoothAddress: null,
      showMoreInfo: true, //显示速度信息 
      canLock: true, //能否锁车
      gps_time: '--',

      locMap: {
        latitude: 30.334546,
        longitude: 120.121121,
        markers: [{
          id: 0,
          latitude: 0,
          longitude: 0,
          iconPath: imgName('location_sucess.png'),
        }]
      },
    },
    location: null,
    latitude: null, //维度
    longitude: null, //经度
    rent: 'false', //物联网到期
    carDetail: false, //车辆详情
    tab: '',
    hasMedical: false, //是否体检
    medicalNum: 0, //体检百分比
    medicalScore: 80, //体检百分比

    //详情页数据
    details: [{
        title: '智能中控',
      },
      {
        title: '电机',
      },
      {
        title: '电池',
      },
      {
        title: '仪表',
      },
      {
        title: '版本',
      },
    ],
    bms: {},
    multiArray: [
      ['2018-06-01', '2018-06-02', '2018-06-03'],
      ['00:00起', '01:00起', '02:00起', '03:00起', '04:00起', '05:00起', '06:00起', '07:00起', '08:00起', '09:00起', '10:00起', '11:00起', '12:00起', '13:00起', '14:00起', '15:00起', '16:00起', '17:00起', '18:00起', '19:00起', '20:00起', '21:00起', '22:00起', '23:00起'],
      ['01:00止', '02:00止', '03:00止', '04:00止', '05:00止', '06:00止', '07:00止', '08:00止', '09:00止', '10:00止', '11:00止', '12:00止', '13:00止', '14:00止', '15:00止', '16:00止', '17:00止', '18:00止', '19:00止', '20:00止', '21:00止', '22:00止', '23:00止', '24:00止']
    ],

    multiIndex: [0, 0, 23],
  },
  markerTap() {

  },
  //消息
  toMsgPage() {
    app.socket.alarmMsg = false
    this.setData({
      message: false,
    })
    wx.navigateTo({
      url: '/pages/user_message/user_message',
    })
  },
  //tab切换
  tabCarMenu(e) {
    let id = e.target.id
    if (e.target.id === this.data.tab) return
    let tab = this.data.tab === '' ? 'tab' : ''
    this.setData({
      tab
    })
  },
  onLoad: function() {
    const user = wx.getStorageSync('user')
    if (!user) {
      wx.redirectTo({
        url: '/pages/welcome2/welcome2',
      })
      return
    }
    this.setData({
      user
    })
    // 查询时间
    this.initDate()
  },
  socketLink() {
    const {
      user
    } = this.data
    app.socketLink(user.userMapp.id)
    cmd = new Cmd(user.userMapp.nowVcuNo, user.token)
  },
  // 刷新车况
  refreshCar() {
    wx.showToast({
      icon: 'none',
      title: '车况信息已更新',
    })
  },
  socketClose() {
    app.socketClose()
  },
  socketSend(msg) {
    // wx.onSocketMessage((res) => {
    //   let data = cmd.parse(res.data)
    //   console.log('收到服务器内容2：', data)
    //   if (data.type == msg) {
    //     app.onSocketMessage()
    //   }
    // })
    const stringifyMsg = cmd.stringify(msg)
    if (stringifyMsg) {
      if (msg != 'findcar' && msg != 'firstDevice') {
        clearTimeout(actionTimer)
        actionTimer = setTimeout(() => {
          $Message({
            content: '操作超时可能失败',
            type: 'warning'
          });
        }, 8000)
      }
      return app.sendSocketMessage(stringifyMsg)
    } else {
      return Promise.reject('不存在的指令')
    }
  },
  setSocketUI(ui) {
    const msg = cmd.parse(ui)
    const dataUi = this.data.ui
    switch (msg.type) {
      case 'carinfo':
        this.setUI(msg.val)
        break;
      case 'lock':
        wx.hideLoading()
        dataUi.lockState = 0
        this.setData({
          ui: dataUi,
        })
        clearTimeout(actionTimer)
        $Message({
          content: '锁车成功',
          type: 'success'
        });
        break;
      case 'alarm':
        app.socket.alarmMsg = msg.val
        this.setData({
          message: msg.val,
        })
        wx.vibrateLong()
        alertTip(`您的车辆发生${msg.val}报警！`)
        break;
      case 'unlock':
        wx.hideLoading()
        dataUi.lockState = 1
        this.setData({
          ui: dataUi,
        })
        clearTimeout(actionTimer)
        $Message({
          content: '开锁成功',
          type: 'success'
        });
        break;
      case 'findcar':
        wx.hideLoading()
        clearTimeout(actionTimer)
        $Message({
          content: '寻车成功',
          type: 'success'
        });
        break;
      case 'gps':
        console.log('gps')
        break;
    }
  },
  onHide: function() {
    clearInterval(deviceTimer)
  },
  onUnload() {
    clearInterval(deviceTimer)
  },
  onShow: function() {
    let that = this
    // sokect
    // if (!app.socket.open) {
    //   app.socket.repeat = 0
    //   this.socketLink()
    // }else{
    //   this.socketSend('firstDevice')
    // }
    let user = wx.getStorageSync('user').userMapp
    if (!user) {
      wx.redirectTo({
        url: '/pages/welcome2/welcome2',
      })
      return
    }
    // 获取车辆信息或者用户列表
    clearInterval(deviceTimer)
    that.getCarDetail()
    deviceTimer = setInterval(() => {
      that.getCarDetail()
    }, 5000)
    // 重置消息
    this.setData({
      message: app.socket.alarmMsg,
    })

  },
  //获取硬件信息
  /*
    新增 type
    type 2 是小定位器
    无操作 无数据
    大于等于3定位有效
   */
  getCarDetail() {
    api.get('device/base/deviceDetailNew', {}, true)
      .then(res => {
        let {
          data,
          model: {
            deviceInfo,
            deviceBmsInfo
          }
        } = res
        let carData = {
          ...data,
          ...deviceInfo
        }
        this.setBms(deviceBmsInfo)
        this.setUI2(carData)
      })
      .catch(err => {
        console.error(1, err)
      })

  },
  // 电池
  setBms(bms) {
    let [longitude, latitude, online = 0, utcTime = 0] = bms.gpsLocate.split(',')
    bms.longitude = longitude
    bms.latitude = latitude
    bms.online = online==0?'不在线':'在线'
    bms.utcTime = utcTime
    let nameMap = {
      bmsCellOt: '充电单节高压',
      bmsCellUt: '充电单节低压',
      bmsChgDt: '充电延时',
      bmsChgOt: '充电高温',
      bmsChgOtDt: '充电高温延时',
      bmsChgUt: '充电低温',
      bmsCurrent: '电流(A)',
      bmsCycles: '循环次数(次)',
      bmsDsgCurLimit: '电池放电电流限制',
      bmsDsgDt: '放电延时',
      bmsDsgOt: '放电高温值',
      bmsDsgOtDt: '放电高温延时',
      bmsDsgUt: '放电低温',
      bmsErrCode: '电池异常状态',
      bmsSn: '电池编号',
      bmsSoc: '电量(%)',
      bmsState: '电池状态',
      bmsTempetrue: '电池温度(℃)',
      bmsVer: '电池版本',
      bmsVolt: '电压(V)',
      cellDsgUvDt: '放电单节低压延时',
      cellVolt: '单节电压(V)',
      longitude: '经度',
      latitude: '维度',
      online: '在线状态',
      gpsLNum: 'GPS定位数',
      gpsSNum: 'GPS搜索数',
      // createTime: '创建时间',
      // gprsIccid: 'gprsIccid',
      // gprsImei: 'gprsImei',
      // gprsImsi: 'gprsImsi',
      // gpsLNum: '卫星数量',
      // gpsLocate: '定位地址',
      // gpsSNum: '卫星数量',
      // gpsSnr: '充电低温',
      updateTime: '上报时间',
    }
    let bmsnow = []
    for (let key in bms) {
      if (nameMap[key]) {
        if (key ==='bmsState'){
          bms[key] = (bms.bmsState && ['', '静止', '放电', '充电'][bms.bmsState]) || '--' 
        }
        bmsnow.push([nameMap[key], bms[key]||'--'])
      }
    }
    longitude = Number(longitude)
    latitude = Number(latitude)
    online = Number(online)
    utcTime = Number(utcTime)
    bmsnow.push()

    this.setData({
      bms: bmsnow
    })
  },
  // 轮询设置
  setUI2(data) {
    const {
      ui,
    } = this.data
    let last_communication_time = null
    let gps_time = null
    if (data.message) {
      ui.message = data.message //消息
    }
    if (data.address) {
      ui.deviceAdress = data.address //位置
    }
    if (data.type == 2) {
      ui.showMoreInfo = false //小定位器
      ui.canLock = false
    }
    if (data.dbDate) {
      last_communication_time = moment(data.dbDate).format('YYYY-MM-DD HH:mm')
      ui.last_communication_time = last_communication_time //更新时间
    }
    if (data.gps_datetime && data.gps_datetime != 'null') {
      // gps_time = moment(data.gps_datetime).format('YYYY-MM-DD HH:mm')
      gps_time = data.gps_datetime
      ui.gps_time = moment(gps_time).format('HH:mm/YYYY.MM.DD')
    }
    ui.vcuNo = data.vcuNo
    ui.estimatedMileage = (data.mile / 1000 || '0') + 'km' //预估里程
    ui.lockState = data.lock_state == '1' ? 0 : 1 //锁 1开锁状态
    ui.dumpEnergy = data.power //剩余电量 
    ui.speed = data.speed || '--' //行驶速度 
    // if (data.batteryAPower == 'null' || data.batteryAPower > 100 || data.batteryAPower == -1) {
    //   details[2].menus[0].des = [`电池A：--`, `电池A故障码：${data.batteryACode}`]
    // } else {
    //   details[2].menus[0].des = [`电池A：${data.batteryAPower}%`]
    // }
    // if (data.batteryBPower == 'null' || data.batteryBPower > 100 || data.batteryBPower == -1) {
    //   details[2].menus[0].des = details[2].menus[0].des.concat([`电池B：--`, `电池B故障码：${data.batteryBCode}`])
    // } else {
    //   details[2].menus[0].des = details[2].menus[0].des.concat([`电池B：${data.batteryBPower}%`])
    // }
    // details[0].menus[0].des = [`信号强度：${data.gprs_signal}`, `最后通信时间：${last_communication_time}`]
    // details[0].menus[1].des = [`经度：${data.lng}`, `纬度：${data.lat}`, `gps：${data.gps_effective == '0' ? '有效' : '无效'}`, `位置：${data.address || '--'}`, `定位时间：${gps_time || '--'}`, `${data.gps_effective == '0' ? '' : '当前定位不精确,将车辆移至信号良好处, 可增强通讯和定位。'}`]
    // details[1].menus[0].des = [`电机温度：${data.temperature || '--'}`, `档位：${data.gear == '0' ? '低速档' :'高速档' || '--'}`, `电机电压：${data.total_voltage || '--'}`]
    // details[3].menus[0].des = [`行驶里程：${data.odometer + 'km' || '--'}`, `行驶速度：${data.speed || '--'}km/h`]
    // details[4].menus[0].des = [`中控硬件版本号：${data.tbox_boot_ver_hw || '--'}`, `中控软件版本号：${data.tbox_boot_ver_sw || '--'}`]
    //地图内容
    let deviceLocError = true
    if (data.lng && data.lat) {
      ui.locMap.latitude = data.lat
      ui.locMap.longitude = data.lng
      ui.locMap.markers[0].latitude = data.lat
      ui.locMap.markers[0].longitude = data.lng
      deviceLocError = false
    } else {
      deviceLocError = true
    }
    //详情内容
    // this.setCarDetail(data)
    this.setData({
      ui: {
        ...ui
      },
      // details: [...details],
      deviceLocError
    })
  },
  getUserLoc() {
    let This = this
    userLocation()
      .then(location => {
        This.setData({
          location
        })
      })
      .catch(err => {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '需要授权地理定位才能正常使用，点击确定去授权',
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                complete() {
                  This.getUserLoc()
                }
              })
            }
          }
        })
      })
  },
  //关锁
  netCloseCar() {
    // this.socketSend('lock')
    //   .then(res=>{
    //     $Message({
    //       content: '发送成功',
    //       type: 'success'
    //     });

    //   })
    //   .catch(err => {
    //     alertTip(err)
    //   })

    api.post('device/base/lockAndUnLock?state=2', {
        state: 2
      })
      .then(res => {
        alertTip('锁车成功')
        this.setData({
          'ui.lockState': 0,
        })
      })
      .catch(err => {
        alertTip(err)
      })
  },
  //开锁
  netOpenCar() {
    // this.socketSend('unlock')
    //   .then(res => {
    //     $Message({
    //       content: '发送成功',
    //       type: 'success'
    //     });
    //   })
    //   .catch(err => {
    //     alertTip(err)
    //   })

    api.post('device/base/lockAndUnLock?state=1', {
        state: 1
      })
      .then(res => {
        alertTip('开锁成功')
        this.setData({
          'ui.lockState': 1,
        })
      })
      .catch(err => {
        alertTip(err)
      })
  },
  //寻车
  netFindCar() {
    // this.socketSend('findcar')
    //   .then(res => {
    //     $Message({
    //       content: '发送成功',
    //       type: 'success'
    //     });
    //   })
    //   .catch(err => {
    //     alertTip(err)
    //   })
    api.post('device/base/lockAndUnLock?state=3', {
        state: 3
      })
      .then(res => {
        alertTip('寻车成功')
      })
      .catch(err => {
        alertTip(err)
      })
    // alertTip('寻车成功')
  },
  //导航
  toLocCar() {
    let ui = this.data.ui.locMap
    wx.openLocation({
      latitude: Number(ui.latitude),
      longitude: Number(ui.longitude),
      scale: 28
    })
  },
  //开关锁
  apiActionDevice() {
    if (!this.data.ui.canLock) {
      return
    }
    if (this.data.ui.lockState) { //开
      this.netCloseCar()
    } else {
      this.netOpenCar()
    }
  },
  //我的
  toMy() {
    wx.navigateTo({
      url: '/pages/my/my',
    })
  },
  showMyLoc() {
    if (!this.mapCtx) {
      this.mapCtx = wx.createMapContext('carMap')
    }
    this.mapCtx.moveToLocation()
  },
  progressChange(e) {
    console.log(e)
  },
  //体检
  reMedical() {
    this.changeBar()
  },
  changeBar() {
    if (medicalTimer) {
      return
    }
    this.setData({
      hasMedical: false, //是否体检
      medicalNum: 0
    })
    //请求体检内容
    this.setData({
      medicalNum: 100
    })

    let that = this
    medicalTimer = setTimeout(() => {
      that.setData({
        hasMedical: true, //是否体检
        medicalNum: 0, //体检百分比
      })
      medicalTimer = null
    }, 3000)
  },
  //统一设置ui
  // setUi() {
  //   let {
  //     user,
  //     device,
  //     ui
  //   } = this.data
  //   //基础信息
  //   if (user && device) {
  //     ui.froNo = device.frameNo || '未录入' //车架号
  //     ui.vcuNo = device.vcuNo || '未录入' //中控号
  //     ui.licensePlate = device.licensePlate || '未录入' //号牌      
  //     ui.rentStartTime = moment(device.createDate).format('YYYY-MM-DD HH:mm') //租车起始时间
  //   }
  //   //车辆信息
  //   this.setData({
  //     ui
  //   })
  // },
  //查看二维码
  seeQrCode(e) {
    let code = e.currentTarget.id
    wx.navigateTo({
      url: `/pages/qr_code/qr_code?vcu=${code}`,
    })
  },
  //无数据返回登录
  reLogin() {
    wx.redirectTo({
      url: '/pages/welcome2/welcome2',
    })
  },
  //维修服务
  toServer() {
    wx.navigateTo({
      url: '/pages/server_point/server_point',
    })
  },
  // 时间选择
  bindTimeChange(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
    let [x, y, z] = e.detail.value
    let data = {
      start: moment(this.data.multiArray[0][x] + ' ' + this.data.multiArray[1][y].slice(0, -1) + ':00').format('x'),
      end: moment(this.data.multiArray[0][x] + ' ' + (z == 23 ? '23:59:59' : (this.data.multiArray[2][z].slice(0, -1) + ':00'))).format('x'),
      vcuNo: this.data.ui.vcuNo
    }
    console.log(data)
    wx.setStorageSync('trailQuery', data)
    wx.navigateTo({
      url: "/pages/user_travel_query/index",
    })
    // start: 2019-03-03 00: 00: 00
    // end: 2019-03-03 23: 59: 59
    // imei: -559038737
  },
  // 时间变化
  bindTimeColumnChange(e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let {
      column,
      value
    } = e.detail
    let {
      multiIndex: [x, y, z]
    } = this.data
    if (column === 0) {
      this.setData({
        'multiIndex[0]': value,
      })
    }
    if (column === 1) {
      this.setData({
        'multiIndex[1]': value,
      })
      if (value > z) {
        this.setData({
          'multiIndex[1]': value,
          'multiIndex[2]': value
        })
      }
    }
    if (column === 2) {
      this.setData({
        'multiIndex[2]': value,
      })
      if (value < y) {
        this.setData({
          'multiIndex[1]': value,
          'multiIndex[2]': value
        })
      }
    }


  },
  initDate() {
    let now = moment().format('YYYY-MM-DD')
    let lastMonthDay = moment().subtract(1, 'months').format('YYYY-MM-DD')
    let daysArr = [now]
    for (let i = 1; i < 31; i++) {
      let day = moment().subtract(i, 'days').format('YYYY-MM-DD')
      daysArr.unshift(day)
      if (day === lastMonthDay) {
        break;
      }
    }
    this.setData({
      'multiArray[0]': daysArr,
      'multiIndex[0]': daysArr.length - 1
    })
  }
})