const config = require('../../config/index.js')
const {
  api,
  rapi,
  formatTime,
  mapApi,
  mockApi,
  imgName,
  getUserInfo,
  wxLogin,
  alertTip,
  wxscan,
  authAgainByUser,
  userLocation
} = require('../../lib/util.js')
// user point device
let carTimer = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //详情页数据
    username: '', //用户名
    userId: '', //用户id
    userPhone: '', //手机号
    comment: '',
    user: null,
    time: '', //时间
    date: '', //日期
    img_arr: [], //上传图片数组
    pics: '', //图片线上路径数组
    imgScan: imgName('imgscan.png'),
    imgClose: imgName('close.png'),    
  },
  onShow: function() {

  },
  onLoad: function() {
    let {
      userMapp
    } = wx.getStorageSync('user')
    let {
      model
    } = wx.getStorageSync('device')
    this.setData({
      username: userMapp.realName, //用户名
      userPhone: userMapp.mobile, //手机号
      cartype: model, //手机号
      userId: userMapp.id
    })
  },
  carTypeChange(e) {

  },
  numInput(e) {
    this.setData({
      [e.target.id]: e.detail.value
    })
  },
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function(e) {
    this.setData({
      time: e.detail.value
    })
  },
  //提交工单
  submitServer() {
    let {
      username,
      userPhone,
      comment,
      date,
      time,
      userId
    } = this.data
    //判断有米有绑定车辆
    api.get('user/getVcuByUserId', {
        user_id: userId
      })
      .then(res => {
        let {
          id: nodeId
        } = wx.getStorageSync('point')

        let {
          vcuNo,
          frameNo,
          model: vehicleModel
        } = wx.getStorageSync('device')
        // 图片
        if (!comment) {
          alertTip('请简单描述下问题')
          return false
        }
        if (!time || !date) {
          alertTip('选择预约时间')
          return false
        }
        Promise.all(this.uploadIdPhoto())
          .then(res => {
            let pics = res.join(',') || ''
            let orderTime = date.replace(/-/gi, '/') + " " + time + ":00"
            console.log(orderTime)
            rapi.get('userOrder/commitOrder', {
              userId,
              nodeId,
              userName: username,
              userPhone,
              comment,
              vcuNo,
              frameNo,
              vehicleModel,
              pics,
              orderTime
            }).then(res => {
              alertTip('提交成功', () => {
               wx.navigateBack(2)
              })
            }).catch(err => {
              alertTip(err)
            })

          })
          .catch(err => {
            alertTip(err)
            console.log(err)
          })
      })
      .catch(err => {
        if (/数据为空/.test(err)) {
          alertTip('你当前无使用中车辆，无法报修')
          return
        }
        alertTip(err)
      })



  },
  //选择图片
  upimg: function() {
    var that = this;
    let hasImgLength = this.data.img_arr.length
    if (hasImgLength < 3) {
      wx.chooseImage({
        count: 3 - hasImgLength, // 默认9  
        sizeType: ['original', 'compressed'],
        success: function(res) {
          let img_arr = that.data.img_arr.concat(res.tempFilePaths)
          that.setData({
            img_arr
          })
          console.log(img_arr)
        }
      })

    } else {
      alertTip('最多上传三张图片')
    }
  },
  //删除图片
  deleteImg(e) {
    let index = Number(e.currentTarget.id)
    this.data.img_arr.splice(index, 1)
    this.setData({
      img_arr: this.data.img_arr
    })
  },
  bindTextAreaBlur(e) {
    let comment = e.detail.value
    this.setData({
      comment
    })
  },
  //上传图片
  uploadIdPhoto() {
    let that = this
    if (that.data.img_arr.length == 0) {
      return [Promise.resolve()]
    } else {
      wx.showLoading({
        title: '上传图片中',
        mask: true,
      })
      return that.data.img_arr.map(item => {
        return new Promise((resolve, reject) => {
          wx.uploadFile({
            url: 'https://zhizuxia.zhizukj.com/ydb/app/manage/file/upload.json',
            filePath: item,
            name: 'file',
            success(res) {
              resolve(JSON.parse(res.data).picUrl)
            },
            fail(err) {
              reject('图片上传失败')
            },
            complete(res) {
              wx.hideLoading()
            }
          })
        })
      })
    }
  }
})