const config = require('../../config/index.js')
const {
  $Message
} = require('../../components/base/index');
const {
  api,
  mapApi,
  imgName,
  getUserInfo,
  wxLogin,
  alertTip,
  toastTip,
  authAgainByUser,
  userLocation,
  getRgbColor,
} = 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: {
    imgLogo2: imgName('logo2.png'),
    imgFind: imgName('find.png'),
    imgLoc: imgName('loc.png'),
    imgToloc: imgName('toloc.png'),
    imgcarloc: imgName('timeline_location.png'),
    imgMore: imgName('more.png'),
    imgCarLoc: imgName('carLoc.png'),
    imgWeatherbg: imgName('weatherbg.jpg'),
    user: null, //用户
    person: 1, //个租
    deviceLocError: false,
    device: null, //设备
    timerDevice: null,
    message: '',
    baseMsg: true, //基础数据获取是否正常
    weather: {
      city: '常州市',
      area: '武进区',
      type: '多云',
      maxt: '13',
      mint: '0'
    }, //天气
    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: '--',
      hasSetHelp: false, //设置求救电话
      disable: true, //禁车
      powerColor: '67, 207, 124', //电池颜色
      kmColor: '121,72,234)', //里程颜色
      GPS: "*",
      GSM: "*",
      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, //车辆详情
    hasMedical: false, //是否体检
    medicalNum: 0, //体检百分比
    medicalScore: 80, //体检百分比
  },
  markerTap() {

  },
  chooseTime(){
    
  },
  disableCar() {
    if (this.data.ui.disable) {
      // 解禁
      api.post('device/base/lockAndUnLock?state=8', {
        state: 8
      })
        .then(res => {
          alertTip('解禁成功')
          this.setData({
            'ui.disable': false,
          })
        })
        .catch(err => {
          alertTip(err)
        })
    } else {
      api.post('device/base/lockAndUnLock?state=7', {
        state: 7
      })
        .then(res => {
          alertTip('禁车成功')
          this.setData({
            'ui.disable': true,
          })
        })
        .catch(err => {
          alertTip(err)
        })
    }
  },
  // 去设置求救电话
  toSetHelp() {
    if (this.data.ui.hasSetHelp) {
      // 一键求救 
      alertTip('拨打求救电话')
    } else {
      wx.navigateTo({
        url: '/pages/urgent/index',
      })
    }
  },
  //消息
  toMsgPage() {
    app.socket.alarmMsg = false
    this.setData({
      message: false,
    })
    wx.navigateTo({
      url: '/pages/user_message/user_message',
    })
  },
  onLoad: function () {
    this.initDate()
    return
    const user = wx.getStorageSync('user')
    if (!user) {
      wx.redirectTo({
        url: '/pages/register2/register2',
      })
      return
    }
    this.setData({
      user
    })
    // 查询时间
  },
  socketLink() {
    const {
      user
    } = this.data
    app.socketLink(user.userMapp.id)
    cmd = new Cmd(user.userMapp.nowVcuNo, user.token)
  },
  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 () {
    return
    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/register2/register2',
      })
      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/deviceDetail', {}, true)
      .then(res => {
        let {
          data,
          model: {
            deviceInfo
          }
        } = res
        let carData = {
          ...data,
          ...deviceInfo
        }
        this.setUI2(carData)
      })
      .catch(err => {
        console.error(1, err)
      })

  },
  // 轮询设置
  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_cn) {
      ui.GPS = data.gps_cn
    }
    if (data.gprs_signal) {
      ui.GSM = data.gprs_signal
    }
    if (data.isSetSosyes) {
      ui.hasSetHelp = data.isSetSosyes == 'no' ? false : true
    }
    if (data.isSetSosyes) {
      ui.hasSetHelp = data.isSetSosyes == 'no' ? false : true
    }
    if (data.disable) {
      ui.disable = data.disable === 'yes' ? true : false
    }
    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.split('.')[0]
      ui.gps_time = moment(gps_time).format('HH:mm/YYYY.MM.DD')
    }
    ui.vcuNo = data.vcuNo
    ui.dumpEnergy = data.power //剩余电量
    ui.powerColor = getRgbColor('227,60,100', '67,207,124', ui.dumpEnergy)
    if (data.remainingMileage) {
      ui.estimatedMileage = data.remainingMileage
      if (data.maxMileage) {
        ui.estimatedMileage = data.remainingMileage
        ui.kmColor = getRgbColor('0,168,173', '121,72,234', Number(ui.estimatedMileage) / Number(data.maxMileage))
      }
    } else {
      ui.estimatedMileage = 0;
      ui.kmColor = getRgbColor('0,168,173', '121,72,234', 0)
    }
    ui.lockState = data.lock_state == '1' ? 0 : 1 //锁 1开锁状态
    ui.speed = data.speed || '--' //行驶速度 
    //地图内容
    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
      },
      deviceLocError
    })
  },
  setUI(data) {
    const {
      ui,
      details
    } = 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.gpsDate) {
      gps_time = moment(data.gpsDate * 1000).format('YYYY-MM-DD HH:mm')
      ui.gps_time = gps_time
    }
    ui.vcuNo = data.vcuNo
    ui.estimatedMileage = (data.mile / 1000 || '0') //预估里程
    ui.lockState = data.lock_state == '1' ? 0 : 1 //锁 1开锁状态
    ui.dumpEnergy = data.power //剩余电量 
    ui.speed = data.speed || '--' //行驶速度 

    details[0].des1 = `信号强度：${data.accuracy}`
    details[0].des2 = `最后通信时间：${last_communication_time}`
    details[1].des1 = `经度：${data.lng}`
    details[1].des2 = `纬度：${data.lat}`
    details[1].des3 = `gps：${data.accuracy >= 3 ? '有效' : '无效'}`
    details[1].des4 = `位置：${data.address || '--'}`
    details[1].des5 = `定位时间：${gps_time || '--'}`
    details[1].tip = `${data.accuracy >= 3 ? '' : '当前定位不精确,将车辆移至信号良好处, 可增强通讯和定位。'}`
    // details[2].des1 = `可用卫星：${d.number_satellite}`
    //地图内容
    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/register2/register2',
    })
  },
  //维修服务
  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: this.data.multiArray[0][x] + ' ' + this.data.multiArray[1][y].slice(0, -1) + ':00',
      end: this.data.multiArray[0][x] + ' ' + (z == 23 ? '23:59:59' : (this.data.multiArray[2][z].slice(0, -1) + ':00')),
      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
    })
  }
})