// pages/breakdown/breakdown.js
var app = getApp();
const util = require('../../utils/utils.js');
var img = app.globalData.imgUrl;
Page({

  data: {
    bikeError: [{
      id: 1,
      name: '刹车'
    }, {
      id: 2,
      name: '车胎'
    }, {
      id: 3,
      name: '链条'
    },
    {
      id: 4,
      name: '车座'
    },
    {
      id: 5,
      name: '二维码'
    },
    {
      id: 6,
      name: '其他'
    },
    ],
    cardTitle: 0,
    currentProblem: 0,
  
    count: 0, //已上传图片数
    arr: [],//图片列表
    currentNum: 0,//已输入的字数
    value: '',
    bike_no: '',//车辆编号
    problemName:'',//故障名称
    photos:[],

  },
  onLoad: function (options) {
    let index=this.data.currentProblem
    console.log(this.data.bikeError[index],'8989')

    let name=this.data.bikeError[index].name
    this.setData({
      problemName:name
    })
  },
  onReady: function () {

  },
  onShow: function () {

  },
  //扫描二维码获取车牌号
  saoma: function () {
    var that = this;
    my.scan({
      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)
        console.log(code)
        if (code.length == 9) {
          that.setData({
            bike_no: code
          })
        } else {
          my.showToast({
            content: '请扫描正确的车辆二维码！',
            icon: 'none'
          })
        }

      },
      fail: function (err) {
        my.showToast({
          content: '扫码失败~',
          icon: 'none'
        })
      }
    })
  },
  //选择故障类型
  selectProblem: function (e) {
  console.log(e)
  let index=e.currentTarget.dataset.index
  let name=this.data.bikeError[index].name
    this.setData({
      currentProblem: e.currentTarget.dataset.index,
      problemName:name
    })
    
  },
  //输入车辆编号
  inputBikeNo: function (e) {
    console.log(e, '--------------------')
    if (e.detail.value) {
      this.setData({
        cardTitle: 1,
        bike_no:e.detail.value
      })
    } else {
      this.setData({
        cardTitle: 0
      })
    }
  },
  //输入问题
  input: function (e) {

    if (e.detail.cursor == 240) {
      my.showToast({
        content: '最多只能输入240个字符',
        icon: 'none'
      })
    } else {
      console.log(e,'wenti')
      this.setData({
        value: e.detail.value,
        currentNum: e.detail.cursor,
      })
    }
  },
  //失去焦点时触发获取value
  blur: function (e) {
    this.setData({
      value: e.detail.value
    })
  },
  //点击小键盘上的完成时触发获取value
  firm: function (e) {
    this.setData({
      value: e.detail.value
    })
  },
  //拍照
  photo: function () {
    var that = this;
    var number = 3 - that.data.arr.length;
    console.log(number)
    if (number >= 0) {
      my.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 {
      my.showToast({
        title: '最多能上传4张图片',
        icon: 'none'
      })
    }
  },
  //上传图片
  uploadimg: function (data) {
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    my.uploadFile({
      url: data.url,
      filePath: data.path[i],
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': my.getStorageSync({'key':'token'}).data,
        '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);
        }
      }
    });
  },
  //点击提交问题保修
  submitForm: util.throttle(function () {
    //点击提交
    // this.setData({show:true})
    var that = this;
    if (this.data.value == '') {
      my.alert({
        title: '提示',
        content: '问题描述不能为空'
      })
      return;
    } else if (this.data.value.length < 2) {
      my.alert({
        title: '提示',
        content: '请输入不少于2个字的描述',
      })
      return;
    } else if (that.data.problemName == '') {
      my.alert({
        title: '提示',
        content: '请选择故障部位',
      })
      return;
    }else if (that.data.bike_no.length != 9) {
      console.log(that.data.bike_no,'bike_No')
      my.showToast({
        content: '车牌号输入不正确',
        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_no,
          area_id: my.getStorageSync({'key':'home'}).data.id,
          trouble_part: that.data.problemName,
          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) {
          my.showToast({
            content: '报修成功',
            success:{
            
            }
          })
          setTimeout(function(){
            my.reLaunch({
              url: '/pages/index/index',
            })
          },1500)
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        my.showToast({
          content: '您的操作过于频繁，请稍后再试~',
          icon: 'none'
        })
      }

    }
  }, 1000),
//删除照片
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
  })
},
})