const {
  formatGlDate,
  platform,
  cutDownTime,
  formatTs,
  getDayList
} = require('../../utils/util.js')
const { postGeoCoder } = require('../../api/common')
const { fetchOrderCount, fetchDistanceInfo } = require('./api/index')
const { sessionStorageKey } = require('../../api/request')
const { one, two, three } = formatGlDate()
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sessionId: '',
    navBarHeight: app.globalData.navBarHeight,
    navBarConfig: {
      booFixed: true,
      backgroundColor: '',
      icon: 'home',
      iconPath: '/common/nav_logo@2x.png',
      label: '',
      title: ''
    },
    introduceList: [
      {
        icon: '/home/Frame_291@2x.png',
        name: '正规车辆'
      },
      {
        icon: '/home/Home_icon_professional@2x.png',
        name: '专业司机'
      },
      {
        icon: '/home/Home_icon_standard@2x.png',
        name: '标准定价'
      },
      {
        icon: '/home/Home_icon_bus@2x.png',
        name: '车型丰富'
      }
    ],
    originLocation: {},
    travelerPopup: false,
    isAutoFocus: false,
    form: {
      'start_point': {
        'longitude': 0, // 经度
        'latitude': 0, // 纬度
        'address_name': '', // 起点位置名称
        'name': ''
      }, // 起点
      'end_point': {
        'longitude': 0, // 经度
        'latitude': 0, // 纬度
        'address_name': '', // 起点位置名称
        'name': ''
      }, // 终点
      'order_pass_location': [], // 途径地点
      'order_user_num': '', // 乘车用户数量
      'order_start_time': '', // 开始时间
      'order_end_time': '无返程', // 返程时间
      'order_car': [], // 从订单详情跳转至创建订单页使用参数：车辆信息
      'order_car_action': '', // 车辆用途
      'driver_cost': {}, // 司机费用
      'order_remark': '', // 订单备注
      'gaosu_distance': 0, // 出发的高速里程(米)
      'order_time': 0, // 出发的耗时(分)
      'order_distance': 0, // 出发的总里程(米)
      'gaosu_distance_back': 0, // 返程的高速里程(米)
      'order_time_back': 0, // 返程的耗时(分)
      'order_distance_back': 0 // 返程的总里程(米)
    },
    booGoTimePicker: false,
    multiIndexGoTimePicker: [0, 0, 0],
    booBackTimePicker: false,
    multiIndexBackTimePicker: [0, 0, 0],
    booLock: false,
    objOrderCount: {
      // 'count': 0, // 订单数量
      // 'id': '' // 订单ID(当数量为1时存在)
    },
    startColumns: [
      {
        values: [],
        defaultIndex: 0
      },
      {
        values: [],
        defaultIndex: 0
      },
      {
        values: [],
        defaultIndex: 0
      }
    ],
    endColumns: [
      {
        values: [],
        defaultIndex: 0
      },
      {
        values: [],
        defaultIndex: 0
      },
      {
        values: [],
        defaultIndex: 0
      }
    ]
  },
  tempFormKey: '', // 用于当前所在城市、选择出发、途径地、终点的字段名，默认为空：为空表示当前所在城市
  tempPostData: {},
  tempStartOptions: {},
  tempEndOptions: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.tempFormKey = ''
    await this.setForm()
    await this.getDistance()
    // this.handleGetSetting()
  },
  bindCallBack() {
    // this.handleGetSetting()
    this.getOrderCount()
    this.getDistance()
  },
  // 从订单详情页进入首页时
  async init() {
    await this.setForm()
    await this.getDistance()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      sessionId: wx.getStorageSync(sessionStorageKey)
    })
    this.getOrderCount()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '来吧上车，我们一起去看看',
      path: '/pages/home/home',
      imageUrl: 'https://bashi-1311374120.cos.ap-shanghai.myqcloud.com/wxMini/image/common/friend500x400.png'
    }
  },
  onPageScroll({ scrollTop }) {
    let backgroundColor = ''
    if (Math.abs(scrollTop) >= Math.floor(this.data.navBarHeight / 2)) {
      backgroundColor = 'rgba(106, 134, 177)'
    }
    if (backgroundColor === this.data.navBarConfig.backgroundColor) {
      return
    }
    this.setData({
      'navBarConfig.backgroundColor': backgroundColor
    })
  },
  // 获取定位权限、定位权限授权
  async handleGetSetting() {
    const that = this

    if (that.tempFormKey === '') {
      // 清除缓存定位数据
      wx.removeStorageSync(app.globalData.homeMyCityKeyOfStorage)
    }

    try {
      const { errMsg, authSetting } = await wx.getSetting()
      if (errMsg === 'getSetting:ok') {
        // 有定位授权
        if (authSetting['scope.userLocation']) {
          if (that.tempFormKey === '') {

          } else {
            await that.chooseLocationBridge()
          }
          return
        }
      }
    } catch (err) {}

    try {
      await wx.authorize({ scope: 'scope.userLocation' })
      if (that.tempFormKey === '') {

      } else {
        await that.chooseLocationBridge()
      }
    } catch (err) {
      wx.showModal({
        title: '提示',
        content: '未开启获取地理位置权限，去设置中打开',
        success(res) {
          if (res.confirm) {
            that.openSetting()
          }
        }
      })
    }
  },
  // 去小程序自带设置页：返回
  async openSetting() {
    try {
      const openSettingData = await wx.openSetting()
      // 开启了定位权限
      if (openSettingData.authSetting['scope.userLocation']) {
        if (this.tempFormKey === '') {

        } else {
          await this.chooseLocationBridge()
        }
      }
    } catch (err) {}
  },
  // 经纬度解析为地址
  async getCity() {
    const { latitude, longitude } = this.data.originLocation
    let city = '定位失败'
    try {
      const { status, data } = await postGeoCoder(latitude, longitude)
      if (status) {
        const { address_component } = data
        city = address_component.city
      }
    } catch (err) {}
    this.setData({
      'navBarConfig.label': city
    })
    wx.setStorage({
      key: app.globalData.homeMyCityKeyOfStorage,
      data: city
    })
  },
  async handleChooseLocation(e) {
    const { lat, lon, formkey } = e.currentTarget.dataset
    this.tempPostData = lat && lon ? {
      latitude: lat,
      longitude: lon
    } : {}
    this.tempFormKey = /^order_pass_location/.test(formkey) ? 'form.order_pass_location[' +
      formkey.split('-')[1] * 1 + ']' : 'form.' + formkey
    await this.handleGetSetting()
  },
  async chooseLocationBridge() {
    if (!this.tempFormKey) {
      return
    }
    try {
      const { errMsg, address, latitude, longitude, name } = await wx.chooseLocation(
        this.tempPostData)
      if (errMsg === 'chooseLocation:ok' && address && name) {
        const pointInfo = {
          address_name: address,
          name,
          latitude,
          longitude
        }
        if (this.checkSimilarPoint(this.tempFormKey, pointInfo)) {
          wx.showModal({
            title: '提示',
            content: '起点、途经点与终点不能相同~',
            showCancel: false
          })
          return
        }
        this.setData({
          [this.tempFormKey]: pointInfo
        }, () => {
          this.getDistance()
        })
      }
    } catch (err) {
      // 点击了取消按钮
      if (err.errMsg === 'chooseLocation:fail cancel') {
      }
      // 未开启授权
      if (err.errMsg === 'chooseLocation:fail auth deny') {
      }
    }
  },
  // 检查起点、途经点、终点是否相同了：判断依据相邻的2个点不同就可以了
  checkSimilarPoint(formKey, value) {
    const { start_point, order_pass_location, end_point } = this.data.form
    let start = JSON.parse(JSON.stringify(start_point))
    let passLocation = JSON.parse(JSON.stringify(order_pass_location))
    let end = JSON.parse(JSON.stringify(end_point))
    let arr = []
    let isSimilar = false

    if (formKey.indexOf('start_point') > -1) {
      start = value
    }
    if (formKey.indexOf('end_point') > -1) {
      end = value
    }
    // formKey：form.order_pass_location[0]
    if (formKey.indexOf('order_pass_location') > -1) {
      const index = formKey.replace(/.*\[|]$/g, '')
      passLocation[index * 1] = value
    }
    arr = [].concat(start, ...passLocation, end)
    arr = arr.filter(item => item.address_name)

    if (arr.length > 1) {
      for (let i = 1; i < arr.length; i++) {
        if (arr[i].address_name === arr[i - 1].address_name) {
          isSimilar = true
          break
        }
      }
    }

    return isSimilar
  },
  addWay() {
    let temp = JSON.parse(JSON.stringify(this.data.form.order_pass_location))
    if (this.data.form.order_pass_location.length > 4) {
      wx.showToast({
        title: '最多可添加5个途经点',
        icon: 'none'
      })
      return
    }
    temp.push({ address_name: '', name: '', latitude: 0, longitude: 0 })
    this.setData({
      'form.order_pass_location': temp
    })
  },
  delWay(e) {
    const { index } = e.currentTarget.dataset
    let temp = JSON.parse(JSON.stringify(this.data.form.order_pass_location))
    temp.splice(index, 1)
    this.setData({
      'form.order_pass_location': temp
    })
  },
  async navBarEvent() {
    wx.navigateTo({
      url: '/pages/selectCity/selectCity'
    })
  },
  onClose() {
    this.setData({
      travelerPopup: false
    })
  },
  showTravelerPopup() {
    this.setData({
      travelerPopup: true
    })

    setTimeout(() => {
      this.setData({
        isAutoFocus: true
      })
    }, 500)
  },
  bindInput(e) {
    return {
      value: e.detail.value.replace(/[^\d$]/, '').replace(/^0/, '')
    }
  },
  initColumnData(pickerType, val0 = {}, val1 = {}) {
    const date = new Date()
    const curMS = date.getTime()
    const minMS = curMS + 2 * 60 * 60 * 1000
    // 每一天的23:50:00必须大于当前时间加2小时
    const firstColumn = one.filter(item => {
      const temp = platform().ios ? item._text.replace(/-/g, '/') : item._text

      return new Date(`${temp} 23:50:00`).getTime() > minMS
    })

    if (pickerType === 'end_point') {
      firstColumn.unshift({
        value: '10',
        text: '无返程',
        _text: '无返程'
      })
    }
    let YYYYIndex = firstColumn.findIndex(item => item.value === val0.value)
    if (YYYYIndex === -1) {
      YYYYIndex = 0
    }

    let YYYYMMDD = firstColumn[YYYYIndex]._text
    if (/^\d{4}/.test(YYYYMMDD) && platform().ios) {
      YYYYMMDD = YYYYMMDD.replace(/-/g, '/')
    }

    const secondColumn = /^\d{4}/.test(YYYYMMDD) ? two.filter(item => {
      return new Date(`${YYYYMMDD} ${item._text}:50:00`).getTime() > minMS
    }) : []

    let HHIndex = secondColumn.findIndex(item => item.value === val1.value)
    if (HHIndex === -1) {
      HHIndex = 0
    }

    const thirdColumn = /^\d{4}/.test(YYYYMMDD) ? three.filter(item => {
      const str = `${YYYYMMDD} ${secondColumn[HHIndex]._text}:${item._text}:00`
      return new Date(str).getTime() > minMS
    }) : []

    return {
      firstColumn,
      secondColumn,
      thirdColumn
    }
  },
  setStartColumnsDefaultIndex(value) {
    let startOptions = {}
    let index0 = 0
    let index1 = 0
    let index2 = 0
    if (Object.prototype.toString.call(value) === '[object Number]' && value > 0) {
      const { YYYY, MM, DD, HH, mm } = formatTs(value)
      const YYYYMMDD = `${YYYY}-${MM}-${DD}`
      const val0 = one.filter(item => item._text === YYYYMMDD)
      const val1 = two.filter(item => item._text === HH)
      startOptions = this.initColumnData('start_point', val0[0], val1[0])
      index0 = startOptions.firstColumn.findIndex(item => item._text === YYYYMMDD)
      index1 = startOptions.secondColumn.findIndex(item => item._text === HH)
      index2 = startOptions.thirdColumn.findIndex(item => item._text === mm)
    } else {
      startOptions = this.initColumnData('start_point')
    }

    if (index0 === -1) {
      index0 = 0
    }
    if (index1 === -1) {
      index1 = 0
    }
    if (index2 === -1) {
      index2 = 0
    }

    this.tempStartOptions = {
      firstColumn: startOptions.firstColumn,
      secondColumn: startOptions.secondColumn,
      thirdColumn: startOptions.thirdColumn
    }
    this.setData({
      multiIndexGoTimePicker: [index0, index1, index2],
      'startColumns[0].values': startOptions.firstColumn,
      'startColumns[0].defaultIndex': index0,
      'startColumns[1].values': startOptions.secondColumn,
      'startColumns[1].defaultIndex': index1,
      'startColumns[2].values': startOptions.thirdColumn,
      'startColumns[2].defaultIndex': index2
    }, () => {
      const instance = this.selectComponent('#van-picker-start_time')
      instance && instance.setIndexes && instance.setIndexes(this.data.multiIndexGoTimePicker)
    })
  },
  setEndColumnsDefaultIndex(value) {
    let endOptions = {}
    let index0 = 0
    let index1 = 0
    let index2 = 0
    if (Object.prototype.toString.call(value) === '[object Number]' && value > 0) {
      const { YYYY, MM, DD, HH, mm } = formatTs(value)
      const YYYYMMDD = `${YYYY}-${MM}-${DD}`
      const val0 = one.filter(item => item._text === YYYYMMDD)
      const val1 = two.filter(item => item._text === HH)
      endOptions = this.initColumnData('end_point', val0[0], val1[0])
      index0 = endOptions.firstColumn.findIndex(item => item._text === YYYYMMDD)
      index1 = endOptions.secondColumn.findIndex(item => item._text === HH)
      index2 = endOptions.thirdColumn.findIndex(item => item._text === mm)
    } else {
      endOptions = this.initColumnData('end_point')
    }

    if (index0 === -1) {
      index0 = 0
    }
    if (index1 === -1) {
      index1 = 0
    }
    if (index2 === -1) {
      index2 = 0
    }

    this.tempEndOptions = {
      firstColumn: endOptions.firstColumn,
      secondColumn: endOptions.secondColumn,
      thirdColumn: endOptions.thirdColumn
    }
    this.setData({
      multiIndexBackTimePicker: [index0, index1, index2],
      'endColumns[0].values': endOptions.firstColumn,
      'endColumns[0].defaultIndex': index0,
      'endColumns[1].values': endOptions.secondColumn,
      'endColumns[1].defaultIndex': index1,
      'endColumns[2].values': endOptions.thirdColumn,
      'endColumns[2].defaultIndex': index2
    }, () => {
      const instance = this.selectComponent('#van-picker-back_time')
      instance && instance.setIndexes && instance.setIndexes(this.data.multiIndexBackTimePicker)
    })
  },
  showGoTimePicker() {
    this.setData({ booGoTimePicker: true })
  },
  bindChangeGoTimePicker(e) {
    const { picker, value, index } = e.detail
    const options = this.initColumnData('start_point', value[0], value[1])
    if (index === 0) {
      picker.setColumnValues(1, options.secondColumn)
      picker.setColumnValues(2, options.thirdColumn)
    } else if (index === 1) {
      picker.setColumnValues(2, options.thirdColumn)
    } else {
      picker.setColumnValues(2, options.thirdColumn)
    }
  },
  getValueGoTimePicker() {
    const instance = this.selectComponent('#van-picker-start_time')
    const indexes = instance.getIndexes()
    const values = instance.getValues()
    const HH = values.length >= 2 ? values[1]._text : ''
    const mm = values.length === 3 ? values[2]._text : ''
    let YYYYMMDD = values.length >= 1 ? values[0]._text : ''

    if (platform().ios) {
      YYYYMMDD = YYYYMMDD.replace(/-/g, '/')
    }

    if (['02', '03', '04'].findIndex(item => item === HH) > -1 || (HH === '05' && mm === '00')) {
      wx.showModal({
        title: '提示',
        content: '凌晨2点~5点高速不通行，请选择其它时间~',
        showCancel: false
      })
      return
    }

    this.tempStartOptions = {
      firstColumn: instance.getColumnValues(0),
      secondColumn: instance.getColumnValues(1),
      thirdColumn: instance.getColumnValues(2)
    }
    this.setData({
      'form.order_start_time': new Date(`${YYYYMMDD} ${HH}:${mm}:00`).getTime(),
      multiIndexGoTimePicker: indexes
    }, () => {
      this.onCloseGoTimePicker()
    })

  },
  onCloseGoTimePicker() {
    const startOptions = this.tempStartOptions
    this.setData({
      booGoTimePicker: false,
      'startColumns[0].values': startOptions.firstColumn,
      'startColumns[1].values': startOptions.secondColumn,
      'startColumns[2].values': startOptions.thirdColumn
    }, () => {
      const instance = this.selectComponent('#van-picker-start_time')
      instance.setIndexes(this.data.multiIndexGoTimePicker)
    })
  },
  showBackTimePicker() {
    if (!(this.data.form.start_point.address_name) || !(this.data.form.end_point.address_name)) {
      wx.showToast({
        title: '请选择出发地与目的地',
        icon: 'none'
      })
      return
    }

    if (!(this.data.form.order_start_time)) {
      wx.showToast({
        title: '请选择出发时间',
        icon: 'none'
      })
      return
    }

    this.setData({
      booBackTimePicker: true
    })
  },
  bindChangeBackTimePicker(e) {
    const { picker, value, index } = e.detail
    const options = this.initColumnData('end_point', value[0], value[1])
    if (index === 0) {
      picker.setColumnValues(1, options.secondColumn)
      picker.setColumnValues(2, options.thirdColumn)
    } else if (index === 1) {
      picker.setColumnValues(2, options.thirdColumn)
    } else {
      picker.setColumnValues(2, options.thirdColumn)
    }
  },
  getValueBackTimePicker() {
    const orderStartTime = this.data.form.order_start_time
    // 单程耗时
    const orderDuration = this.data.form.order_time * 60 * 1000
    const instance = this.selectComponent('#van-picker-back_time')
    const indexes = instance.getIndexes()
    const values = instance.getValues()
    let YYYYMMDD = values.length >= 1 ? values[0]._text : ''
    const HH = /^\d{4}/.test(YYYYMMDD) && values.length >= 2 ? values[1]._text : ''
    const mm = /^\d{4}/.test(YYYYMMDD) && values.length === 3 ? values[2]._text : ''
    let formTime = YYYYMMDD

    if (orderDuration <= 0) {
      wx.showToast({
        title: '正在规划路线，请稍后选择返程时间~',
        icon: 'none'
      })
      return
    }

    if (/^\d{4}/.test(YYYYMMDD) && platform().ios) {
      YYYYMMDD = YYYYMMDD.replace(/-/g, '/')
    }

    if (['02', '03', '04'].findIndex(item => item === HH) > -1 || (HH === '05' && mm === '00')) {
      wx.showModal({
        title: '提示',
        content: '凌晨2点~5点高速不通行，请选择其它时间~',
        showCancel: false
      })
      return
    }

    if (/^\d{4}/.test(YYYYMMDD)) {
      formTime = new Date(`${YYYYMMDD} ${HH}:${mm}:00`).getTime()
      const dayList = getDayList(orderStartTime, orderDuration)
      const endTs = dayList.length > 0 ? dayList[dayList.length - 1].endTs : orderStartTime
      const duration = endTs - orderStartTime
      if (formTime < endTs) {
        wx.showModal({
          title: '提示',
          content: `当前时间可能无法返程：去程耗时约${cutDownTime(duration / 1000, 'hh:mm zh')}~`,
          showCancel: false
        })
        return
      }
    }

    this.tempEndOptions = {
      firstColumn: instance.getColumnValues(0),
      secondColumn: instance.getColumnValues(1),
      thirdColumn: instance.getColumnValues(2)
    }
    this.setData({
      'form.order_end_time': formTime,
      multiIndexBackTimePicker: indexes
    }, () => {
      this.onCloseBackTimePicker()
    })
  },
  onCloseBackTimePicker() {
    const endOptions = this.tempEndOptions
    this.setData({
      booBackTimePicker: false,
      'endColumns[0].values': endOptions.firstColumn,
      'endColumns[1].values': endOptions.secondColumn,
      'endColumns[2].values': endOptions.thirdColumn
    }, () => {
      const instance = this.selectComponent('#van-picker-back_time')
      instance.setIndexes(this.data.multiIndexBackTimePicker)
    })
  },
  bindSubmit(e) {
    const {
      number
    } = e.detail.value
    if (!number) {
      wx.showToast({
        title: '请输入乘车人数',
        icon: 'none'
      })
      return
    }
    this.setData({
      'form.order_user_num': number,
      travelerPopup: false
    })
  },
  async getDistance() {
    const that = this
    const { start_point, order_pass_location, end_point } = that.data.form
    // 去除选择的同一个地点
    const orderPassLocation = order_pass_location.filter(item => item.address_name)
    const formData = {
      start_point,
      end_point,
      order_pass_location: orderPassLocation
    }
    that.setData({
      'form.gaosu_distance': 0,
      'form.order_time': 0,
      'form.order_distance': 0,
      'form.gaosu_distance_back': 0,
      'form.order_time_back': 0,
      'form.order_distance_back': 0
    })

    if (!start_point.address_name) {
      return
    }
    if (!end_point.address_name) {
      return
    }
    try {
      const { status, data, msg } = await fetchDistanceInfo(formData)
      if (status) {
        const {
          gaosu_distance,
          order_time,
          order_distance,
          gaosu_distance_back,
          order_time_back,
          order_distance_back
        } = data
        that.setData({
          'form.gaosu_distance': gaosu_distance,
          'form.order_time': order_time,
          'form.order_distance': order_distance,
          'form.gaosu_distance_back': gaosu_distance_back,
          'form.order_time_back': order_time_back,
          'form.order_distance_back': order_distance_back
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    } catch (err) {}
  },
  verify() {
    const orderStartTime = this.data.form.order_start_time
    const orderDuration = this.data.form.order_time * 60 * 1000
    const dayList = getDayList(orderStartTime, orderDuration)
    const endTs = dayList.length > 0 ? dayList[dayList.length - 1].endTs : orderStartTime

    let errorList = []
    if (!(this.data.form.start_point.address_name)) {
      errorList.push({ errMsg: '请选择出发地' })
    }
    if (!(this.data.form.end_point.address_name)) {
      errorList.push({ errMsg: '请选择目的地' })
    }
    if (this.data.form.order_distance <= 1 || this.data.form.order_time <= 1) {
      errorList.push({ errMsg: '正在规划路线，请稍后点击下一步~' })
    }
    if (!(this.data.form.order_user_num)) {
      errorList.push({ key: 'order_user_num' })
    }
    if (!orderStartTime) {
      errorList.push({ key: 'order_start_time' })
    }
    // 返程时间限制：返程时间要大于单程到达时间
    if (this.data.form.order_end_time !== '无返程' && this.data.form.order_end_time < endTs) {
      errorList.push({ key: 'order_end_time' })
    }
    return errorList
  },
  async onsubmit() {
    const verifyList = this.verify()
    if (verifyList.length) {
      const { errMsg, key } = verifyList[0]
      if (errMsg) {
        wx.showToast({
          title: errMsg,
          icon: 'none'
        })
      } else if (key) {
        switch (key) {
          case 'order_user_num':
            this.showTravelerPopup()
            break
          case 'order_start_time':
            this.showGoTimePicker()
            break
          case 'order_end_time':
            this.showBackTimePicker()
            break
          default:
        }
      }
      return
    }
    // 去除途径地未完善信息的
    // 创建订单数据：存入本地
    wx.setStorage({
      key: app.globalData.homeCreateOrderKeyOfStorage,
      data: JSON.stringify({
        ...this.data.form,
        'order_pass_location': this.data.form.order_pass_location.filter(item => item.address_name),
        'order_start_time': Math.round(this.data.form.order_start_time / 1000), // 后端要求时间戳为秒
        'order_end_time': this.data.form.order_end_time === '无返程' ? '' : Math.round(
          this.data.form.order_end_time / 1000),
        'is_return_back': this.data.form.order_end_time === '无返程' ? 0 : 1 // 是否返程(0否1是)
      })
    })

    wx.navigateTo({
      url: !this.data.sessionId ? '/pages/login/login' : '/pages/createOrder/createOrder'
    })
  },
  jumpInvoice() {
    wx.navigateTo({
      url: '/pages/invoice/invoice'
    })
  },
  jumpHelp() {
    wx.navigateTo({
      url: '/pages/help/help'
    })
  },
  jumpFeedback() {
    wx.navigateTo({
      url: '/pages/feedback/feedback'
    })
  },
  // 设置form的初始值
  async setForm() {
    const date = new Date()
    const curMS = date.getTime()
    const minMS = curMS + 2 * 60 * 60 * 1000
    const key = app.globalData.homeCreateOrderKeyOfStorage
    try {
      const { data, errMsg } = await wx.getStorage({ key })
      if (errMsg === 'getStorage:ok' && /^{/.test(data)) {
        const temp = JSON.parse(data)
        for (let key in temp) {
          let value = temp[key]
          if (this.data.form.propertyIsEnumerable(key)) {
            // 检查出发时间是否大于当前时间2小时
            if (key === 'order_start_time') {
              if (value && value * 1000 > minMS) {
                value = value * 1000
              } else {
                value = ''
              }
            }
            if (key === 'order_end_time') {
              if (value && value * 1000 > minMS) {
                value = value * 1000
              } else {
                value = '无返程'
              }
            }
            this.setData({
              ['form.' + key]: value
            })
          }
        }
      }
    } catch (err) {}
    const { order_start_time, order_end_time } = this.data.form
    this.setStartColumnsDefaultIndex(order_start_time)
    this.setEndColumnsDefaultIndex(order_end_time)
  },
  async getOrderCount() {
    try {
      const { status, data } = await fetchOrderCount()
      if (status) {
        this.setData({
          objOrderCount: data
        })
      }
    } catch (err) {}
  },
  jumpOrder() {
    const { count, id } = this.data.objOrderCount
    if (count === 1) {
      wx.navigateTo({
        url: '/pages/orderDetail/orderDetail?orderId=' + id
      })
      return
    }
    wx.navigateTo({
      url: '/pages/order/order'
    })
  },
  jumpCompany() {
    wx.navigateTo({
      url: '/pages/company/company'
    })
  }
})
