// pages/loadAppoint/dispatch.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    str:'&emsp;',
    str2: '&ensp;',
    loginStatus: wx.getStorageSync('loginStatus') ? wx.getStorageSync('loginStatus') : false,
    roleCodeList: wx.getStorageSync('roleCodeList') ? wx.getStorageSync('roleCodeList') : '',

    //按钮位置参数
    safeAreaHeight: 0, //底部安全区域的高度
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth: '',

    showModal: false,
    defaultText: '请选择',
    isSubmitting: false,
    
    //分页
    limit: 10,
    requestStatu: '加载中...',
    page: 1,
    totalPages: 1,
    more: false,
    nomore: '',
    resData:[],
    searchVal: '',

    show: false,
    loadPointId:'',//装货地点
    loadTimeId:'',//装货时段

    loadPointArray:[],//装卸点位
    loadPointIndex:null,

    loadTimeArray:[], //装卸时间
    loadTimeIndex:null,

    // loadUserArray:[], //执行员
    // loadUserIndex:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      safeAreaHeight: app.globalData.windowInfo.screenHeight - app.globalData.systemInfo.safeArea.bottom
    })

    // 使用选择器选择节点
    this.getFilterHeight()
    
    //获取页面高度设置新增按钮的初始位置
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        // 高度,宽度 单位为px
        that.setData({
          windowHeight: res.windowHeight, //屏幕宽度、高度
          windowWidth: res.windowWidth,
          buttonTop: res.windowHeight * 0.8 - that.data.safeAreaHeight-60, //这里定义按钮的初始位置
          buttonLeft: res.windowWidth * 0.80, //这里定义按钮的初始位置
        })
      }
    })

    this.setData({
      appointId  : options.appointId,
    })
    //装货点位
    this.getAllocationListFun()
  },

  //获取顶部筛选区域的高度
  getFilterHeight:function(){
    let that = this;
    // 使用顶部筛选高度选择器选择节点的高度
    const query = wx.createSelectorQuery();
    query.select('.topFilter').boundingClientRect(function (rect) {
      if(rect){
        that.setData({
          filterWidth: rect.width,
          filterHeight: rect.height,
        });
      }
    }).exec();
  },

  //列表   appointType   1起卸点位    2装货点位
  getAllocationListFun: function () {
    this.setData({
      page: 1
    })
    let params = {
      current   : this.data.page,
      size      : this.data.limit,
      appointId : this.data.appointId,
      appointType  : '2'
    }
    app.request.pageFirst({
      url: app.API.bizloaddispatchPage,
      page: this,
      params: params,
    })
  },  

  //装卸点位   appointType   1起卸点位    2装货点位
  loadPointData:function(loadPointId){
    app.request.GET({
      url: app.API.loadPoint,
      params: {'appointType' : '2'},
      page: this,
      successFun: true
    }).then(res => {
      this.setData({
        loadPointArray : res.data.data,
        loadPointIndex : loadPointId?app.util.getDicIndex(res.data.data, loadPointId, 'id'):''
      })
    })
  },

  //装卸时间
  loadTimeData:function(loadPointId, loadTimeId){
    let pointId = loadPointId? loadPointId : this.data.loadPointArray[this.data.loadPointIndex].id;
    if(pointId && pointId != ''){
      app.request.GET({
        url: app.API.loadTimeNow,
        params: {
          pointId : pointId,
        },
        page: this,
        successFun: true
      }).then(res => {
        let timeList = res.data.data
        timeList.forEach((element,index) => {
          timeList[index].time = element.beginTime + '~' + element.endTime
        });
        this.setData({
          loadTimeArray   : timeList,
          loadTimeIndex   : loadTimeId != ''?app.util.getDicIndex(res.data.data, loadTimeId, 'id'):'',
        })
        if(loadTimeId!=''){
          this.setData({
            availableNumber : loadTimeId != ''?this.data.loadTimeArray[this.data.loadTimeIndex].availableNumber:'',
            alreadyNumber   : loadTimeId != ''?this.data.loadTimeArray[this.data.loadTimeIndex].alreadyNumber:'',
          })
        }
      })
    }
  },

  //装货员
  // loadUserData:function(loadUserId){
  //   app.request.GET({
  //     url: app.API.roleUser,
  //     params: {
  //       roleName : '装货员',
  //     },
  //     page: this,
  //     successFun: true
  //   }).then(res => {
  //     this.setData({
  //       loadUserArray : res.data.data,
  //       loadUserIndex : loadUserId?app.util.getDicIndex(res.data.data, loadUserId, 'id'):''
  //     })
  //   })
  // },

  //下拉选择
  bindPickerChange: function (e) { //下拉菜单
    let { pickername } = e.target.dataset
    let getIndex = pickername + 'Index'
    app.util.getPickerIndex(this, getIndex, e);
    switch (pickername) {
      case 'loadPoint': //点位
        this.loadTimeData('', '') //获取装货时段
        break;
      case 'loadTime': //点位
        this.setData({
          availableNumber : this.data.loadTimeArray[this.data.loadTimeIndex].availableNumber,
          alreadyNumber   : this.data.loadTimeArray[this.data.loadTimeIndex].alreadyNumber,
        })
        break;
    }
  }, 

  //删除
  delFun: function (e) {
    let _this = this
    let { id, loadPoint } = e.currentTarget.dataset
    wx.showModal({
      title: '提示！',
      content: `删除【${loadPoint}】后不可恢复。确定要删除吗？`,
      confirmColor: '#FF5B5B',
      success: function (res) {
        if (res.confirm) {
          app.request.POST({
            url: app.API.appointDelete,
            params: [{
              id: id
            }],
            page: _this,
            isLoadingTxt: '删除中...',
            successFun: true
          }).then(res => {
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
            _this.getAllocationListFun(); //刷新列表
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  // 添加S
  showPopup(e) {
    let { id, loadPoint, loadTime} = e.currentTarget.dataset
    this.setData({
      show            : true,
      id              : id ? id : '',
      loadPointId     : loadPoint,//装货地点
      loadTimeId      : loadTime,//装货时段
      // userId          : loadUser
    });
    this.loadPointData(loadPoint);
    // this.loadUserData(loadUser);
    if(loadPoint){
      this.loadTimeData(loadPoint, loadTime);
    }
  },
  onClose() {
    this.setData({
      show: false,
      id: '',
      loadPointId:'',//装货地点
      loadTimeId:'',//装货时段
      // userId:'',//执行员
      loadPointArray:'',
      loadTimeArray:'',
      // loadUserArray:''
    });
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  //页面跳转
  toLink: function (e) {
    let { url } = e.currentTarget.dataset
    wx.navigateTo({
      url: url
    })
  },
  
  //表单提交 carTaskAdd
  formSubmitAllocation: function ({detail:{value}}) {
    let _this = this
    var warn = ""; //弹框时提示的内容
    if (value.loadPointId == '') {
      warn = "请选择装卸点位！";
    } else if(value.loadTimeId == ''){
      warn = "请选择装卸时间！";
    // } else if(value.userId == ''){
    //   warn = "请选择执行员！";
    }
    if (warn != '') {
      app.util.checkForm(warn);
    } else {
      app.request.POST({
        url: value.id=='' ? app.API.dispatchAdd : app.API.dispatchReplace,
        params: value,
        page: this,
        isLoadingTxt: '提交中...',
        isSubmitting: true,
        successFun: true
      }).then(res => {
        wx.showToast({
          title: value.id=='' ? '新增成功' : '更换成功',
          icon: 'success',
          duration: 1000,
          mask: true
        })
        _this.onClose()
        _this.getAllocationListFun(); //刷新列表
      })
    }
  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      searchVal: ''
    })
    if (wx.getStorageSync('loginStatus')) {
      this.getAllocationListFun();
    } else {
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   *    appointType   1起卸点位    2装货点位
   */
  onReachBottom: function () {
    this.data.page++;
    let params = {
      current   : this.data.page,
      size      : this.data.limit,
      appointId : this.data.appointId,
      appointType  : '2'
    }
    app.request.pageFirst({
      url: app.API.bizloaddispatchPage,
      page: this,
      params: params,
      loadType: true //加载类型，是否是下拉加载
    });
  },

  

  //以下是按钮拖动事件
  buttonStart: function (e) {
    startPoint = e.touches[0] //获取拖动开始点
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1] //获取拖动结束点
    //计算在X轴上拖动的距离和在Y轴上拖动的距离
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint //重置开始位置
    var buttonTop = this.data.buttonTop + translateY
    var buttonLeft = this.data.buttonLeft + translateX
    //判断是移动否超出屏幕
    if (buttonLeft + 60 >= this.data.windowWidth) {
      buttonLeft = this.data.windowWidth - 60;
    }
    if (buttonLeft <= 0) {
      buttonLeft = 0;
    }
    if (buttonTop <= this.data.filterHeight) {
      buttonTop = this.data.filterHeight
    }
    if (buttonTop + 60 + 48 + this.data.safeAreaHeight >= this.data.windowHeight) {
      buttonTop = this.data.windowHeight - 60 - 48 - this.data.safeAreaHeight;
    }
    this.setData({
      buttonTop: buttonTop,
      buttonLeft: buttonLeft
    })
  },
  buttonEnd: function (e) {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})