var app = getApp();
const util = require('../../utils/utils.js');
var img = app.globalData.imgUrl;
Page({
  data: {
    list: [{
        id: 0,
        text: '刹车',
        imgUrl: img+'weapp/handlebar.png'
      },
      {
        id: 1,
        text: '车胎',
        imgUrl: img+'weapp/wheel.png'
      },
      {
        id: 2,
        text: '链条',
        imgUrl: img+'weapp/chain.png'
      },
      {
        id: 3,
        text: '车座',
        imgUrl: img+'weapp/saddle.png'
      },
      {
        id: 4,
        text: '二维码',
        imgUrl: img+'weapp/code1.png'
      },
      {
        id: 5,
        text: '其他',
        imgUrl: img+'weapp/other.png'
      }
    ],
    index1: 0,
    arr: [],
    value: '',
    trouble_part: '',
    photos: [],
    bike_id: '',
    riding: '',
    currentNum: 0, //已输入字符数
    count: 0, //已上传图片数
    img:app.globalData.imgUrl
  },
  onLoad: function (options) {
    console.log(options.bike_id)
    if (options.bike_id && options.bike_id != undefined) {
      this.setData({
        bike_id: options.bike_id
      })
    }
    if (options.riding) {
      this.setData({
        riding: options.riding
      })
    }
    this.setData({trouble_part:this.data.list[0].text})
  },

  saoma: function () {
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: function (res) {
        // console.log(res)
        var index = res.result.lastIndexOf("\=");
        var code = res.result.substring(index + 1, res.result.length);
        console.log(code.length)
        if (code.length == 11) {
          that.setData({
            bike_id: code
          })
        } else {
          wx.showToast({
            title: '请扫描正确的二维码！',
            icon: 'none'
          })
        }

      },
      fail: function (err) {
        wx.showToast({
          title: '扫码失败~',
          icon: 'none'
        })
      }
    })
  },
  //手动输入车辆编号
  inputVal(e) {
    this.setData({
      bike_id: e.detail.value
    })
  },
  tap: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index;
    var name = e.currentTarget.dataset.name.text;
    this.setData({
      index1: index,
      trouble_part: name
    })
  },
  input: function (e) {
    //多行文本框
    if (e.detail.cursor == 240) {
      wx.showToast({
        title: '最多只能输入240个字符',
        icon: 'none'
      })
    } else {
      this.setData({
        value: e.detail.value,
        currentNum: e.detail.cursor,
      })
    }
  },
  firm: function (e) {
    //点击小键盘上的完成时触发获取value
    this.setData({
      value: e.detail.value
    })
  },
  blur: function (e) {
    //失去焦点时触发获取value
    this.setData({
      value: e.detail.value
    })
  },
  photo: function () {
    var that = this;
    var number = 3 - that.data.arr.length;
    console.log(number)
    if (number >= 0) {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          console.log(res)
          let count = that.data.count + 1;
          that.setData({
            count
          })
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths
          that.setData({
            arr: that.data.arr.concat(tempFilePaths)
          })

          that.uploadimg({
            url: app.globalData.url + '/upload/image',
            path: tempFilePaths
          });
        }
      })
    } else {
      wx.showToast({
        title: '最多能上传4张图片',
        icon: 'none'
      })
    }

  },
  imgYu: function (e) {
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.arr[index], // 当前显示图片的http链接
      urls: this.data.arr // 需要预览的图片http链接列表
    })
  },
  delete1: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var list = that.data.arr;
    var photos = that.data.photos
    console.log(photos)
    list.splice(index, 1);
    photos.splice(index, 1);
    that.setData({
      arr: list,
      photos,
      count:photos.length
    })
  },
  uploadimg: function (data) {
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': wx.getStorageSync('token'),
        'merchant-id': app.globalData.merchant_id
      },
      name: 'file', //这里根据自己的实际情况改
      formData: {
        type: 'trouble'
      }, //这里是上传图片时一起上传的数据
      success: (resp) => {
        success++; //图片上传成功，图片上传成功的变量+1
        console.log(resp)
        var data = JSON.parse(resp.data)
        var photo1 = [];
        if (data.length > 1) {
          for (var i = 0; i < data.length; i++) {
            photo1.push(data[i].id)
          }
        } else {
          photo1.push(data.id)
        }
        that.setData({
          photos: that.data.photos.concat(photo1)
        })
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用          
          //console.log('执行完毕');
          //console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          //console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },
  form: util.throttle(function () {
    //点击提交
    // this.setData({show:true})
    var that = this;
    if (this.data.value == '') {
      wx.showModal({
        title: '提示',
        content: '问题描述不能为空',
        showCancel: false
      })
      return;
    } else if (this.data.value.length < 2) {
      wx.showModal({
        title: '提示',
        content: '请输入不少于2个字的描述',
        showCancel: false
      })
      return;
    } else if (that.data.trouble_part == '') {
      wx.showModal({
        title: '提示',
        content: '请选择故障部位',
        showCancel: false
      })
      return;
    }else if (that.data.bike_id.length != 11) {
      wx.showToast({
        title: '车牌号输入不正确',
        icon:'none'
      })
      return;
    } else {
      var tu = '';
      if (that.data.photos != '') {
        var photo = that.data.photos;
        var photo1 = [];
        for (var i = 0; i < photo.length; i++) {
          photo1.push(photo[i])
        }
        console.log(photo1)
        tu = photo1.toString();
        console.log(tu)
      }
      if (app.globalData.req) {
        var data = {
          bike_no: that.data.bike_id,
          area_id: wx.getStorageSync('home').id,
          trouble_part: that.data.trouble_part,
          trouble_description: that.data.value,
          trouble_imgs: tu
        }
        console.log(data)
        app.request('/trouble', data, 'POST', app.globalData.req).then(res => {
          console.log(res)
          if (res.data.is_up_trouble == true) {
            wx.reLaunch({
              url: '../repair_success/repair_success?riding=' + that.data.riding,
            })
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        wx.showToast({
          title: '您的操作过于频繁，请稍后再试~',
          icon: 'none'
        })
      }

    }
  }, 1000),
  onReady: function () {

  },
  onShow: function () {

  },
  onHide: function () {

  },
  onUnload: function () {

  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {
    
  }
})