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 = null //体检 延时器

Page({
  /**
   * 页面的初始数据
   */
  data: {
    locMap: {
      latitude: 30.334546,
      longitude: 120.121121,
      markers: [{
        id: 0,
        latitude: 0,
        longitude: 0,
        iconPath: imgName('location_sucess.png'),
      }]
    },
    multiIndex: [0, 0, 23],
    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止']
    ],
    batteryDeatil:{},
    polyline:[],
    
  },
  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
    })
  },
  // 时间变化
  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
        })
      }
    }


  },
  // 时间选择
  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').valueOf(),
      end: moment(this.data.multiArray[0][x] + ' ' + (z == 23 ? '23:59:59' : (this.data.multiArray[2][z].slice(0, -1) + ':00'))).valueOf(),
    }
    api.get('gps/query',data)
      .then(res => {
        console.log('轨迹：', res)
        if(res.items){
          let polyline = [{ points: [], color: '#b80303FF', arrowLine: true, width: 3 }]
          items.map(item => {
            item = { latitude: item.lat, longitude: item.lng }
            polyline[0].points.push(item)
            return item
          })
          this.mapCtx.includePoints({points:polyline.points})
          this.setData({
            polyline,
          })
        }else{
          toastTip('无行驶记录')
        }
      })
      .catch(err=>{
        alertTip(err)
      })
      // start: 2019-03-03 00: 00: 00
    // end: 2019-03-03 23: 59: 59
    // imei: -559038737
  },
  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.mapCtx = wx.createMapContext('carMap')
    let batteryDeatil =wx.getStorageSync('batteryDeatil')
    this.setData({
      batteryDeatil
    })
    this.setUI2(batteryDeatil)
    // 查询时间
    this.initDate()
  },
  // 轮询设置
  setUI2(data) {
    let {
      gprsImei,
      bmsSn,
      bmsVolt,
      bmsCurrent,
      bmsState,
      bmsCycles,
      bmsSoc,
      gpsSnr,
      gpsLocate,
      restDay,
      updateTime
    } = data
    gpsLocate = JSON.parse(gpsLocate)
    if (gpsLocate && gpsLocate.length) {
      this.setMap(gpsLocate[0], gpsLocate[1])
    }
    if (bmsState == 1) {
      bmsState = '开锁'
    } else {
      bmsState = '关锁'
    }
    this.setData({
      gprsImei,
      bmsVolt,
      bmsCurrent,
      bmsSn,
      bmsState,
      bmsCycles,
      bmsSoc,
      updateTime,
      gpsSnr,
      batteryDeatil: data
    })
  },
  setMap(lat, lng) {
    let { locMap } = this.data
    locMap.latitude = lat
    locMap.longitude = lng
    locMap.markers[0].latitude = lng
    locMap.markers[0].longitude = lng

    this.setData({
      locMap: { ...locMap }
    })
  },
  //关锁
  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() {
    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)
  },
    //查看二维码
  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',
    })
  },
  // 时间变化
  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
    })
  }
})