// pages/reservationMan/index.js
const app = getApp();
var startPoint
Page({

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

    filterWidth: 0, //获取顶部筛选宽度
    filterHeight: 0, //获取顶部筛选高度
    safeAreaHeight: 0, //底部安全区域的高度
    //按钮位置参数
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth: '',

    searchVal: '', //筛选条件
    type:'',//预约类型
    appointmentClassifyArray: [
      { label:'充电预约',value:'1' },
      { label:'管桩预约',value:'2' },
      { label:'其他预约',value:'3' },
    ], //预约类型

    appointmentTypeArray: [{
      dictValue: "",
      dictLabel: "全部状态"
    }],
    appointmentTypeIndex: 0,

    appointmentStatusArray: [{
      dictValue: "",
      dictLabel: "全部状态"
    }],
    appointmentStatusIndex: 0,

    appointmentType: '', //切换显示
    appointmentTypeSha: '', //砂石
    appointmentTypeQi: '', //起卸
    appointmentTypeGuan: '', //管桩
    appointmentTypeChong: '', //充电桩
    appointmentTypeOther: '', //其他

    //分页
    limit: 10,
    requestStatu: '加载中...',
    page: 1,
    totalPages: 1,
    more: false,
    nomore: '',

    //筛选E
    setIndex: 0,
    resData: [],

    show:false,
    auditFlag:'false',
    appointmentReason:'',//审核备注
    
    showQrcode:false, 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  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, //这里定义按钮的初始位置
        })
      }
    })

  },

  //获取顶部筛选区域的高度
  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();
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const roleCodeList = wx.getStorageSync('roleCodeList')
    let loginStatus = wx.getStorageSync('loginStatus')
    this.setData({
      searchVal: '',
      roleCodeList: roleCodeList ? roleCodeList : '',
      loginStatus: loginStatus ? loginStatus : false
    })
    //动态tabbar
    // if (roleCodeList == 'bizAdmin') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list2,
    //   })
    // } else if(roleCodeList == 'send') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list3,
    //   })
    // } else if(roleCodeList == 'sale') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list4,
    //   })
    // }else if(roleCodeList == 'customer') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list5,
    //   })
    // } else if (roleCodeList=='driver'||roleCodeList==''){
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list1,
    //   })
    // }
    // if (typeof this.getTabBar === 'function' && this.getTabBar()) {
    //   this.getTabBar().setData({
    //     selected: 2
    //   })
    // }

    if(wx.getStorageSync('loginStatus')){
      this.getListFun();
    }

    if(this.data.appointmentStatusArray.length==1 || this.data.appointmentTypeArray.length==1){
      this.getTree()
    }
  },

  //获取字典数据
  getTree:function(){
    app.request.GET({
      url:app.API.getTree,
      page:this,
      successFun:true
    }).then(res=>{
      if(this.data.appointmentStatusArray.length==1){
        let treeData = res.data.data
        for (const element of treeData) {
          let arrStr;
          switch (element.dictValue) {
            case 'appointment_status':
              arrStr = "appointmentStatusArray";
              break;
          }
          let getArray = this.data.appointmentStatusArray
          this.setData({
            [arrStr]: getArray.concat(element.children)
          })
        }
      }
      if(this.data.appointmentTypeArray.length==1){
        let treeData = res.data.data
        for (const element of treeData) {
          let arrStr;
          switch (element.dictValue) {
            case 'appointment_type':
              arrStr = "appointmentTypeArray";
              break;
          }
          let getArray = this.data.appointmentTypeArray
          this.setData({
            [arrStr]: getArray.concat(element.children)
          })
        }
      }
      
    })
  },

  //搜索框请求S
  onChange(e) {
    this.setData({
      searchVal: e.detail,
    });
  },
  onSearch: function (event) {
    this.setData({
      searchVal: event.detail
    })
    this.getListFun();
  },
  typeFun: function (e) {
    this.setData({
      appointmentType : e.currentTarget.dataset.type
    })
    this.getListFun()
  },
  onCancel: function () {
    this.setData({})
  },
  toSearch: function (event) {
    this.getListFun();
  },

  //列表
  getListFun: function () {
    this.setData({
      page: 1
    })
    let params = {
      current         : this.data.page,
      size            : this.data.limit,
      licenseNumber   : this.data.searchVal,
      type            : this.data.appointmentType
      //status:1
    }
    app.request.pageFirst({
      url: app.API.appointmentPage,
      page: this,
      params: params,
    })
  },

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

        }
      }
    })
  },

  //完成装货  管桩预约
  completePipeFun: function (e) {
    let _this = this
    let { id, licenseNumber } = e.currentTarget.dataset
    wx.showModal({
      title: '提示！',
      content: `确定【${licenseNumber}】完成装货？`,
      confirmColor: '#FF5B5B',
      success: function (res) {
        if (res.confirm) {
          app.request.POST({
            url: app.API.completePipeAppoint,
            params: {
              id: id
            },
            page: _this,
            isLoadingTxt: '取消中...',
            successFun: true
          }).then(res => {
            wx.showToast({
              title: '取消成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
            _this.getListFun(); //刷新列表
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  //完成装货  其他预约
  completeOtherFun: function (e) {
    let _this = this
    let { id, licenseNumber } = e.currentTarget.dataset
    wx.showModal({
      title: '提示！',
      content: `确定【${licenseNumber}】完成装货？`,
      confirmColor: '#FF5B5B',
      success: function (res) {
        if (res.confirm) {
          app.request.POST({
            url: app.API.completeOtherAppoint,
            params: {
              id: id
            },
            page: _this,
            isLoadingTxt: '取消中...',
            successFun: true
          }).then(res => {
            wx.showToast({
              title: '取消成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
            _this.getListFun(); //刷新列表
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  // 授权出场：其他预约
  exitFun: function (e) {
    let _this = this
    let { id, licenseNumber } = e.currentTarget.dataset
    wx.showModal({
      title: '提示！',
      content: `确定授权【${licenseNumber}】出场，操作后无法撤回，请确认？`,
      confirmColor: '#FF5B5B',
      success: function (res) {
        if (res.confirm) {
          app.request.POST({
            url: app.API.otherAuthorize,
            params: {
              id: id
            },
            page: _this,
            isLoadingTxt: '授权中...',
            successFun: true
          }).then(res => {
            wx.showToast({
              title: '授权成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
            _this.getListFun(); //刷新列表
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  // 强制结束
  overFun: function (e) {
    let _this = this
    let { id, licenseNumber } = e.currentTarget.dataset
    wx.showModal({
      title: '提示！',
      content: `确定强制结束【${licenseNumber}】预约信息，操作后无法撤回，请确认？`,
      confirmColor: '#FF5B5B',
      success: function (res) {
        if (res.confirm) {
          app.request.POST({
            url: app.API.appointmentExit,
            params: {
              id: id
            },
            page: _this,
            isLoadingTxt: '授权中...',
            successFun: true
          }).then(res => {
            wx.showToast({
              title: '授权成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
            _this.getListFun(); //刷新列表
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  // 强制结束  其他预约
  overOtherFun: function (e) {
    let _this = this
    let { id, licenseNumber } = e.currentTarget.dataset
    wx.showModal({
      title: '提示！',
      content: `确定强制结束【${licenseNumber}】预约信息，操作后无法撤回，请确认？`,
      confirmColor: '#FF5B5B',
      success: function (res) {
        if (res.confirm) {
          app.request.POST({
            url: app.API.otherExit,
            params: {
              id: id
            },
            page: _this,
            isLoadingTxt: '授权中...',
            successFun: true
          }).then(res => {
            wx.showToast({
              title: '授权成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
            _this.getListFun(); //刷新列表
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  // 审核S
  showPopup(e) {
    let { id,type } = e.currentTarget.dataset
    this.setData({
      show: true,
      appointmentReason: '',
      type:type,
      id: id
    });
  },
  onClose() {
    this.setData({
      show: false,
      auditFlag:'false',
      appointmentReason:'',
      id: ''
    });
  },
  // 单选
  dangerStatusChange: function (e) {
    this.setData({
      [e.currentTarget.dataset.radiotype]: e.detail.value
    })
  },

  //审核
  formSubmit: function (e) {
    let formData = e.detail.value;
    var warn = ""; //弹框时提示的内容
    if (formData.auditFlag == '') {
      warn = "选择审核结果！";
    } else if (formData.auditFlag == 'false' && formData.appointmentReason == '') {
      warn = "审核不通过时备注不能为空！";
    }
    formData.auditFlag = formData.auditFlag=='true'
    if (warn != '') {
      app.util.checkForm(warn);
    } else {
      let url = app.API.appointmentAudit
      if(this.data.type == '2'){
        url = app.API.tempAudit
      }
      app.request.POST({
        url: url,
        params: formData,
        page: this,
        isLoadingTxt: '审核中...',
        successFun: true
      }).then(res => {
        wx.showToast({
          title: '审核成功',
          icon: 'success',
          duration: 1000,
          mask: true
        })
        this.onClose()
        this.getListFun(); //刷新列表
      })
    }
  },
  // 审核E

  //申请
  changeAdd() {
    wx.navigateTo({
      url: '/pages/reservationOther/add'
    })
  },

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

        }
      }
    })
  },

  //修改
  toUpdate: function (e) {
    let { id, index } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/reservationOther/edit?id=' + id + '&index=' + index,
    })
    
  },

  //页面跳转
  toLink: function (e) {
    let { url } = e.currentTarget.dataset
    wx.navigateTo({
      url: url
    })
  },

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

  },

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

  },

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.page++;
    let params = {
      current       : this.data.page,
      size          : this.data.limit,
      licenseNumber : this.data.searchVal,
      // reservationStatus: this.data.applyData[this.data.setIndex].value,,
      type            : this.data.appointmentType
    }
    app.request.pageOther({
      url: app.API.appointmentPage,
      page: this,
      params: params,
      loadType: true, //加载类型，是否是下拉加载
    });
    //this.getTypeCount()
  },

  //以下是按钮拖动事件
  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 () {

  }
})