const app = getApp();
const util = require("../../../util/util.js")
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    loadModal:false,
    from:0,
    size:6,
    TabCur:0,
    scrollLeft:0,
    tabList:["待接任务","已确认","已交付","已完成"],
    list:[
    ]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ( opt) {
    let TabCur = +opt.tab||0
    this.setData( {TabCur} )
    app.checkLogin( ()=>{
      this.loadData()
    } )
  },
  tabSelect(e){
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      list:[],
      scrollLeft: (e.currentTarget.dataset.id - 1) * 80
    })
    this.getTaskList(0)
  },
  bidTask: function( e ){
    let index = e.currentTarget.dataset.index;
    let item = this.data.list[index]
    util.http("/wx/applyWxTask", {id:item.id}, (err, res) =>{
      if( err != 0) return;
      item.is_bid = 1
      this.setData({ list: this.data.list})
      util.showMsg("抢单子成功");
    })
  },

  onPullDownRefresh: function () {
    this.getTaskList( 0, ()=>{
      wx.stopPullDownRefresh();
    })
  },
  onReachBottom: function () {
    var that = this
    let newFrom = that.data.from
    if (newFrom == -1) {
      wx.stopPullDownRefresh();
      return;
    }
    this.getTaskList(newFrom, wx.stopPullDownRefresh);
  },
  doUpload( err, {url} ){
    if( err !=0 || !url ) {
      util.showMsg("图片上传失败")
      return
    }
    let {index,list} = this.data
    let id = list[index].id
    util.http( '/maker/addDeliverImg', {id, url}, (err,res)=>{
      if( err!= 0 ) return;
      list[index].deliver_img = url;
      this.setData({list});
    })
  },
  getTaskList: function( newFrom, cb){
    let type = this.data.TabCur +1;
    let param = { from: newFrom, size:this.data.size, type }
    let list = this.data.list
    let that = this
    util.http("/wx/getWxTaskList", param, function (err, res) {
      if( err != 0) return;
      if (newFrom == 0) list = [];
      let newlist = res.list.map( item =>{
        return item
      });
      that.setData({
        from: res.from || -1,
        list: list.concat(newlist)
      })
      cb && cb()
    });
  },
  loadData :function( ){
    this.getTaskList(0)
  },
  previewImage: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, 
      urls: [current]
    })
  } ,
  uplodImg: function(e ){
    let index = e.currentTarget.dataset.index;
    console.log("uplodImg", e.currentTarget.dataset)
    this.setData({index});
    wx.chooseImage({  
      count: 1,  
      sizeType: ['compressed'], 
      sourceType: ['album', 'camera'],
      success:  (res) =>{
        var tempImagePath = res.tempFilePaths[0];
        util.uploadFile( tempImagePath, this.doUpload )
      },
      fail:()=>{
        app.showMsg('选择失败')
      }
    })
  }
})