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'),
    locMap: {
      latitude: 30.334546,
      longitude: 120.121121,
      markers: [{
        id: 0,
        latitude: 0,
        longitude: 0,
        iconPath: imgName('location_sucess.png'),
      }]
    },
    user: {},
    gprsImei: '',
    bmsSn: '',
    bmsVolt: 0,
    bmsCurrent: 0,
    bmsState: '',
    bmsCycles: 0,
    bmsSoc: 0,
    updateTime: '--',
    gpsSnr: '--',
    actionVisible: false, //
    navHeight: 0,
    myModel: false,
    hasBattery: true,
    auth: false,
    batteryList: [],
    batteryDeatil: {},
    serverEndDate:'',
  },
  nullfunc() {},
  // 绑定电池
  bindBattery() {
    wxscan()
      .then(code => {
        console.log('电池编号：', code)
        this.apiUseCar(code)
      })
  },
  getCarList() {
    let that = this
    api.post('device/userBindingDeviceList')
      .then(res => {
        console.log('设备列表：', res)
        if (res.items.length > 0) {
          this.setData({
            batteryList: res.items,
            hasBattery: true
          })
        }else{
          this.setData({
            hasBattery:false
          })
        }
      })
  },
  showBuying() {
    let { serverEndDate, batteryDeatil: { restDay}} = this.data
    wx.navigateTo({
      url: `/pages/pay/pay?day=${restDay}&serverEndDate=${serverEndDate}`,
    })
  },
  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();
  },
  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() {
    let { batteryDeatil} =this.data
    wx.setStorageSync('batteryDeatil', batteryDeatil)
    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
              })
            })
        })

    }

  },
  apiUseCar(vcuNo) {
    let that = this
    api.post('device/userBindingDevice', {
        vcuNo
      })
      .then(res => {
        //有使用的车辆 跳到用车
        console.log('bind:', res)
        let user = wx.getStorageSync('user')
        user.userMapp.nowVcuNo = vcuNo
        wx.setStorageSync('user', user)
        // app.socket.open = false
        // wx.switchTab({
        //   url: '/pages/user_index/user_index',
        // })
        that.getCarList()
        toastTip('绑定成功')
        return
      })
      .catch(err => {
        alertTip(err)
        console.error(err)
      })

  },
  changeCar(e) {
    let vcuNo = e.currentTarget.dataset.deviceno
    confirmTip(`确定切换设备为${vcuNo}`, () => {
      api.post('device/changeDevice', {
          vcuNo
        })
        .then(res => {
          const user = wx.getStorageSync('user')
          user.userMapp.nowVcuNo = vcuNo
          wx.setStorageSync('user', user)
          toastTip(res.message)
        })
        .catch(err => {
          alertTip(err)
        })
    })
  },
  // 去设置求救电话
  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',
    })
  },
  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
    // sokect
    // if (!app.socket.open) {
    //   app.socket.repeat = 0
    //   this.socketLink()
    // }else{
    //   this.socketSend('firstDevice')
    // }
    let user = wx.getStorageSync('user').userMapp
    if (!user) {
      this.setData({
        auth: false
      })
      return
    } else {
      this.setData({
        user,
        auth: true
      })
    }
    // 获取车辆信息或者用户列表
    clearInterval(deviceTimer)
    that.getCarList()
    that.getCarDetail()
    deviceTimer = setInterval(() => {
      that.getCarDetail()
    }, 3000)
    // 重置消息
    // this.setData({
    //   message: app.socket.alarmMsg,
    // })
  },
  //获取硬件信息
  /*
    新增 type
    type 2 是小定位器
    无操作 无数据
    大于等于3定位有效
   */
  getCarDetail() {
    api.get('device/base/deviceDetailNew', {}, true)
      .then(res => {
        let {
          data,
          model: {
            deviceBmsInfo
          }
        } = res
        let carData = { ...data,
          ...deviceBmsInfo
        }
        this.setUI2(carData)
      })
      .catch(err => {
        console.error(1, err)
      })

  },
  // 轮询设置
  setUI2(data) {
    let {
      gprsImei,
      bmsSn,
      bmsVolt,
      bmsCurrent,
      bmsState,
      bmsCycles,
      bmsSoc,
      gpsSnr,
      gpsLocate,
      restDay,
      updateTime
    } = data
    gpsLocate = (gpsLocate).split(',')
    if (gpsLocate && gpsLocate.length){
      this.setMap(gpsLocate[0], gpsLocate[1])
    }
    if (bmsState ==1){
      bmsState='开锁'
    }else{
      bmsState='关锁'
    }
    let serverEndDate = moment().add(restDay, 'days').format('YYYY-MM-DD');
    this.setData({
      gprsImei,
      bmsVolt,
      bmsCurrent,
      bmsSn,
      bmsState,
      bmsCycles,
      bmsSoc,
      updateTime,
      gpsSnr,
      serverEndDate,
      batteryDeatil:data
    })
    this.drawCircle(bmsSoc);

  },
  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}
    })
  },
  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.navigateTo({
      url: '/pages/register2/register2',
    })
  },
})