const config = require('../../config/index.js')
const {
  $Message
} = require('../../components/base/index');
const {
  api,
  mapApi,
  imgName,
  getUserInfo,
  wxLogin,
  alertTip,
  toastTip,
  confirmTip,
  authAgainByUser,
  userLocation,
  getRgbColor,
  getPx,
  wxscan
  } = 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, timer, deviceTimer = null //体检 延时器

Page({
  /**
   * 页面的初始数据
   */
  data: {
    progress_txt: '正在匹配中...',  
    imgLoc: imgName('homoeLoc.png'),
    imgToloc: imgName('toloc.png'),
    dangerStatus: false,
    person: 1, //个租
    deviceLocError: false,
    device: null, //设备
    timerDevice: null,
    message: '',
    baseMsg: true, //基础数据获取是否正常
    hasaAuthorization: false,
    animation2: '',
    lockAction: false,
    percent: 0,
    targetStatus: null,
    online:false,//在线
    weather: {
      city: '获取中',
      area: '',
      type: '。。。',
      maxt: '',
      mint: ''
    }, //天气
    assistActions: [{
      name: '禁车',
      width: 60,
      color: '#fff',
      fontsize: '14',
      background: '#d43030'
    }],
    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'),
        }]
      },
      bmsVolt: '', //电压 v
      bmsCurrent: '', //电流 a
      bmsTempetrue: '', //温度 ℃
      bmsState: '', //电池状态
      bmsSoc: '', //电量
      bmsSn: '', //电池编号
      bmsVer: '', //电池版本

    },
    user: {
      nickname: '王榕',
      avatarUrl: 'http://ruiju.oss-cn-hangzhou.aliyuncs.com/ruijub8c4cbd4-4a1b-45fa-a288-ac430d5fc03d.jpg',
    },
    location: null,
    latitude: null, //维度
    longitude: null, //经度
    rent: 'false', //物联网到期
    carDetail: false, //车辆详情
    hasMedical: false, //是否体检
    medicalNum: 0, //体检百分比
    medicalScore: 80, //体检百分比
    actionVisible: false, //
    navHeight:0,
    myModel:false,
    hasBattery:true,
  },
  nullfunc(){},
  // 绑定电池
  bindBattery(){
    wxscan()
      .then(code=>{
        console.log('电池编号：',code)
      })
  },
  showBuying(){
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },
  commonNavAttr(e) {
    console.log(e);
    if (e.detail) {
      this.setData({
        navHeight: e.detail.height
      })
    }
  },
  drawProgressbg: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    var ctx = wx.createCanvasContext('canvasProgressbg', this)
    // 划线
    var lineGradient = ctx.createLinearGradient(getPx(490), 0, getPx(690), 0);
    lineGradient.addColorStop("0", "#333333");
    lineGradient.addColorStop("0.3", "#0089f8");
    ctx.setLineWidth(getPx(2));
    ctx.setStrokeStyle('#0089f8');
    ctx.moveTo(getPx(10), getPx(166))
    ctx.lineTo(getPx(170), getPx(166))
    ctx.stroke()
    ctx.beginPath()
    ctx.moveTo(getPx(60), getPx(276))
    ctx.lineTo(getPx(210), getPx(276))
    ctx.stroke()
    ctx.beginPath()
    ctx.setStrokeStyle(lineGradient);
    ctx.moveTo(getPx(520), getPx(166))
    ctx.lineTo(getPx(690), getPx(166))
    ctx.stroke()
    ctx.beginPath()
    ctx.moveTo(getPx(500), getPx(276))
    ctx.lineTo(getPx(640), getPx(276))
    ctx.stroke()
    ctx.draw(true)
    ctx.setLineWidth(getPx(20));// 设置圆环的宽度
    ctx.setStrokeStyle('#333333'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath();//开始一个新的路径
    ctx.arc(getPx(350), getPx(180), getPx(170), 0.75*Math.PI, 2.25 * Math.PI, false);
    //设置一个原点(110,110)，半径为100的圆的路径到当前路径
    ctx.stroke();//对当前路径进行描边
    ctx.draw(true);
    // Fill with gradient
    ctx.beginPath()
    ctx.arc(getPx(10), getPx(166), getPx(8), 0,2 * Math.PI)
    ctx.setFillStyle(this.getCircularGradient(10, 166, ctx))
    ctx.fill()
    ctx.beginPath()
    ctx.arc(getPx(60), getPx(276), getPx(8), 0, 2 * Math.PI)
    ctx.setFillStyle(this.getCircularGradient(60, 276, ctx))
    ctx.fill()
    ctx.beginPath()
    ctx.arc(getPx(690), getPx(166), getPx(8), 0, 2 * Math.PI)
    ctx.setFillStyle(this.getCircularGradient(690, 166, ctx))
    ctx.fill()
    ctx.beginPath()
    ctx.arc(getPx(640), getPx(276), getPx(8), 0, 2 * Math.PI)
    ctx.setFillStyle(this.getCircularGradient(640, 276, ctx))
    ctx.fill()
    ctx.draw(true)
  },
  getCircularGradient(x,y,ctx){
    const grd = ctx.createCircularGradient(getPx(x), getPx(y), getPx(10))
    grd.addColorStop(0, '#ffffff')
    grd.addColorStop(0.5, '#0089f8')
    grd.addColorStop(1, '#171b1f')
    return grd
  },
  drawCircle: function (step=100) {
    var context = wx.createCanvasContext('canvasProgress', this);
    // 设置渐变
    var gradient = context.createLinearGradient(getPx(150), 0, getPx(550), 0);
    gradient.addColorStop("0", "#0089f8");
    gradient.addColorStop("1.0", "#6bcaff");

    context.setLineWidth(getPx(20));
    context.setStrokeStyle(gradient);
    context.setLineCap('round')
    context.beginPath();
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
    context.arc(getPx(350), getPx(180), getPx(170), 0.75 * Math.PI, (0.75+(step/100)*1.5) * Math.PI, false);
    context.stroke();
    context.draw()


  },
  onReady: function () {
    this.drawProgressbg();
    this.drawCircle(40);
  },
  toHeath(){
    wx.navigateTo({
      url: '/pages/batteryHeath/batteryHeath',
    })
  },
  showMy(){
    this.setData({
      myModel: !this.data.myModel
    })
  },
  markerTap() {

  },
  // 报警查看
  toMessage() {
    wx.navigateTo({
      url: '/pages/user_message/user_message',
    })
  },
  handleCancel() {
    this.setData({
      actionVisible: false
    });
  },
  disableCar() {
    confirmTip(`确定${this.data.assistActions[0].name}？`, () => {
      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)
          })
      }
    })
  },
  seeMap() {
    wx.navigateTo({
      url: '/pages/car_action/index',
    })
  },
  getWeather(lat, log) {

    if (lat && log) {
      api.get('weather/getWeather', {
          longitude: log,
          latitude: lat
        })
        .then(we => {
          setTimeout(() => {
            this.setData({
              hasaAuthorization: true,
              'weather.city': we.data.address,
              'weather.maxt': we.data.temperature,
              'weather.mint': 'car',
              'weather.type': we.data.weather,
            })

          })
        })
        .catch(err => {
          this.setData({
            hasaAuthorization: false
          })
        })
    } else {
      userLocation()
        .then(res => {
          this.setData({
            hasaAuthorization: true
          })
          let {
            longitude,
            latitude
          } = res
          api.get('weather/getWeather', {
              longitude,
              latitude
            })
            .then(we => {
              this.setData({
                'weather.city': we.data.address,
                'weather.maxt': we.data.temperature,
                'weather.mint': 'person',
                'weather.type': we.data.weather,
              })
            })
            .catch(err => {
              this.setData({
                hasaAuthorization: false
              })
            })
        })

    }

  },
  // 去设置求救电话
  toSetHelp() {
    if (this.data.ui.hasSetHelp) {
      // 一键求救 
      api.get('sos/oneSos')
        .then(res => {
          wx.showToast({
            title: '已经联系紧急联系人',
            icon: 'none'
          })
        })
        .catch(err => {
          alertTip(err)
        })
    } 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() {
    return

    const user = wx.getStorageSync('user')
    if (!user) {
      wx.redirectTo({
        url: '/pages/register2/register2',
      })
      return
    }
    this.setData({
      user
    })
    // 查询时间
    // this.initDate()
  },
  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() {
    let that = this
    return
    // 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()
    }, 3000)
    // 重置消息
    this.setData({
      message: app.socket.alarmMsg,
    })
    // this.getWeather()
  },
  //获取硬件信息
  /*
    新增 type
    type 2 是小定位器
    无操作 无数据
    大于等于3定位有效
   */
  getCarDetail() {
    api.get('device/base/deviceDetailNew', {}, true)
      .then(res => {
        let {
          data,
          model: {
            deviceInfo,
            deviceBmsInfo
          }
        } = res
        let carData = { ...data,
          ...deviceInfo,
          ...deviceBmsInfo
        }
        this.setUI2(carData)
      })
      .catch(err => {
        console.error(1, err)
      })

  },
  // 轮询设置
  setUI2(data) {
    const {
      ui,
      targetStatus
    } = 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.isSetSos) {
      ui.hasSetHelp = data.isSetSos == 'no' ? false : true
    }
    // 电池内容
    ui.bmsVolt = data.bmsVolt||'--' //电压 v
    ui.bmsCurrent = data.bmsCurrent || '--' //电流 a
    ui.bmsTempetrue = data.bmsTempetrue || '--' //温度 ℃
    ui.bmsState = (data.bmsState && ['', '静止', '放电', '充电'][data.bmsState]) || '--' //电池状态
    ui.bmsSoc = data.bmsSoc || '--' //电量
    ui.bmsSn = data.bmsSn || '--' //电池编号
    ui.bmsVer = data.bmsVer || '--' //电池版本
    if (data.disable) {
      ui.disable = data.disable === 'yes' ? true : false
      if (ui.disable) {
        this.setData({
          'assistActions[0].name': '解禁',
          'assistActions[0].background': '#00baad',
        })
      } else {
        this.setData({
          'assistActions[0].name': '禁车',
          'assistActions[0].background': '#d43030',
        })
      }
    }
    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.batteryAPower == 'null' || data.batteryAPower > 100 || data.batteryAPower == -1) {
      ui.batteryAPower = -1
    } else {
      ui.batteryAPower = data.batteryAPower
    }
    if (data.batteryBPower == 'null' || data.batteryBPower > 100 || data.batteryBPower == -1) {
      ui.batteryBPower = -1
    } else {
      ui.batteryBPower = data.batteryBPower
    }
    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 == '2' ? 0 : 1 //锁 2是关锁状态 1开锁状态
    if (targetStatus !== null) {
      if (ui.lockState === targetStatus) {
        if (targetStatus === 0) {
          toastTip({
            title: '关锁成功',
            icon: 'none'
          })
        } else {
          toastTip({
            title: '开锁成功',
            icon: 'none'
          })
        }

        this.closeTimer()
      }
    }
    ui.speed = data.speed || '--' //行驶速度 
    //地图内容
    let deviceLocError = true
    let [longitude, latitude, online = 0, utcTime = 0] = data.gpsLocate.split(',')
    longitude = Number(longitude)
    latitude = Number(latitude)
    online = Number(online)
    utcTime = Number(utcTime)
    if (longitude && latitude) {
      ui.locMap.latitude = latitude
      ui.locMap.longitude = longitude
      ui.locMap.markers[0].latitude = latitude
      ui.locMap.markers[0].longitude = longitude
      deviceLocError = false
      // if (!weather.maxt || this.data.mint == 'person') {
      //   this.getWeather(data.lat, data.lng)
      // }
    } 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 == '2' ? 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)
    //   })
    this.openTimer()
    api.post('device/base/lockAndUnLock?state=2', {
        state: 2
      }, true)
      .then(res => {
        // alertTip('关锁成功')
        // this.setData({
        //   'ui.lockState': 0,
        // })
      })
      .catch(err => {
        this.closeTimer()
        alertTip(err)
      })
  },
  //开锁
  netOpenCar() {
    // this.socketSend('unlock')
    //   .then(res => {
    //     $Message({
    //       content: '发送成功',
    //       type: 'success'
    //     });
    //   })
    //   .catch(err => {
    //     alertTip(err)
    //   })
    this.openTimer()
    api.post('device/base/lockAndUnLock?state=1', {
        state: 1
      }, true)
      .then(res => {
        // alertTip('开锁成功')
        // this.setData({
        //   'ui.lockState': 1,
        // })
      })
      .catch(err => {
        this.closeTimer()
        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
    })
  },
  closeTimer() {
    clearInterval(timer)
    this.setData({
      percent: 0,
      targetStatus: null,
      lockAction: false
    })
  },
  openTimer() {
    let i = 1
    clearInterval(timer)
    timer = setInterval(() => {
      this.setData({
        percent: i * 3
      })
      i++
      if (i == 33) {
        clearInterval(timer)
        this.setData({
          percent: 0,
          targetStatus: null,
          lockAction: false
        })
        alertTip('设备未响应请重试')
      }
    }, 1000)
  },
  //开关锁
  apiActionDevice(e) {
    if (!this.data.ui.canLock) {
      return
    }
    let {item} = e.currentTarget.dataset
    if (item == 2) { //开
      this.setData({
        lockAction: true,
        percent: 0,
        targetStatus: 0
      })
      this.netCloseCar()
    } else if (item == 1) {
      this.setData({
        lockAction: true,
        percent: 0,
        targetStatus: 1
      })
      this.netOpenCar()
    }
  },
  // 打开车座位
  apiOpenSeat() {
    api.post('device/base/lockAndUnLock?state=17', {
        state: 17
      })
      .then(res => {
        alertTip('打开坐垫成功')
      })
      .catch(err => {
        alertTip(err)
      })
  },
  //我的
  toMy() {
    wx.navigateTo({
      url: '/pages/my/my',
    })
  },
  showMyLoc() {
    if (!this.mapCtx) {
      this.mapCtx = wx.createMapContext('carMap')
    }
    this.mapCtx.moveToLocation()
  },
  //无数据返回登录
  reLogin() {
    wx.redirectTo({
      url: '/pages/register2/register2',
    })
  },
})