// pages/index/index.js
const app = getApp()
var QRCode = require('../../utils/weapp-qrcode.js');
var startPoint
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,

    content: '',

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

    searchVal: '', //筛选条件

    appointmentClassifyArray: [
      { label:'充电预约',value:'1' },
      { label:'管桩预约',value:'2' },
      { label:'其他预约',value:'3' },
    ], 

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

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

    registStatus: '', //状态

    registStatusdrc: '', //显示状态数值
    registStatusdgb: '', //显示状态数值
    registStatusgbz: '', //显示状态数值
    registStatusdcc: '', //显示状态数值
    registStatusycc: '', //显示状态数值

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

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

    showQrcode:false, 
    
    show:false,
    auditFlag:'false',
    auditReason: '',
  },

  //下拉选择
  bindPickerChange: function (e) { //下拉菜单
    //方法一动态的
    let getIndex = e.target.dataset.pickername + 'Index'
    app.util.getPickerIndex(this, getIndex, e);
    this.getListFun()
  },

  //去登录页面
  toLogin(e) {
    wx.navigateTo({
      url: '../login/index',
    })
  },

  //拨打电话
  call: function (e) {
    e.currentTarget.dataset.phone && wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone
    })
  },

  //变动筛选条件时
  changeFilter: function (e) {
    let getFilterType = e.currentTarget.dataset.filtertype + 'Value'
    this.setData({
      [getFilterType]: e.detail
    })
    //重新请求
    this.getListFun();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //订单状态
    if(wx.getStorageSync('loginStatus')){
      this.getTree()
    }
    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();
  },

  
  // 二维码弹框
  showQrcodePopup(e) {
    let { id, licenseNumber } = e.currentTarget.dataset
    this.setData({
      showQrcode : true,
      id         : id,
    });
    this.makeCode(JSON.stringify({
      "id"            : id,
      "licenseNumber" : licenseNumber
    }))
  },
  // 二维码
  makeCode(data) {
    var qrcode;
    qrcode = new QRCode('canvas', {
      text: data,
      width: 220,
      height: 220,
      colorDark: "#000000",
      colorLight: "#ffffff",
      correctLevel: QRCode.CorrectLevel.H,
    });
    qrcode.makeCode(data);
  },
  onCloseQrcode() {
    this.setData({
      showQrcode : false,
      id         : '',
    });
  },

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

  },

  //绑定微信
  bindingWX: function () {
    let _this = this;
    if (this.data.loginStatus) {
      wx.showModal({
        title: '提示',
        content: '确定绑定该微信账号？',
        success: function (res) {
          if (res.confirm) {
            wx.login({
              success: (res) => {
                //console.log(res.code)
                app.request.requestPostApi(app.API.api.bindingWX, {
                  id: wx.getStorageSync('id'),
                  appCode: res.code
                }, _this, function (res, that) {
                  if (res.code == '200') { //退出登录
                    wx.showToast({
                      title: '绑定成功',
                      icon: 'none',
                      duration: 1500,
                      mask: true
                    })
                  } else {
                    wx.showToast({
                      title: res.data.msg ? res.data.msg : '出错了',
                      icon: 'none',
                      duration: 1500,
                      mask: true
                    })
                  }
                });

              },
            })

          }
        }
      })
    } else {
      wx.showToast({
        title: '您还未登录！',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    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: 0
    //   })
    // }

    if (wx.getStorageSync('loginStatus')) {
      // if (roleCodeList=='bizAdmin') {
      //   wx.switchTab({
      //     url: '/pages/queueCar/index',
      //   })
      // } else if (roleCodeList=='send') {
      //   wx.switchTab({
      //     url: '/pages/deliveryConfirm/index',
      //   })
      // } else if (roleCodeList=='sale') {
      //   wx.switchTab({
      //     url: '/pages/salesOrderMan/index',
      //   })
      // }
      if(this.data.filterHeight){
        const query = wx.createSelectorQuery();
        query.select('.topFilter').boundingClientRect(function (rect) {
          that.setData({
            filterWidth: rect.width,
            filterHeight: rect.height,
          });
        }).exec();
      }
      
      if(roleCodeList=='driver'||roleCodeList=='customer'){
        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)
          })
        }
      }
      
    })
  },

  //获取通知消息
  getContent: function () {
    app.request.GET({
      url: app.API.getContent,
      params: {},
      page: this,
      successFun: true
    }).then(res => {
      //console.log(res.data.data)
      this.setData({
        content: res.data.data.content
      })
    })
  },

  //预约列表页面审核状态汇总页面接口
  getReservationCount: function () {
    app.request.GET({
      url: app.API.reservationCount,
      params: {},
      page: this,
      successFun: true
    }).then(res => {
      let resData = res.data.data
      let getApplyData = this.data.applyData
      resData.forEach(element => {
        //console.log(element)
        switch (Number(element.reservationStatus)) {
          case 0:
            getApplyData[1].label = '待审核' + "(" + element.recordCount + ")辆"
            break;
          case 1:
            getApplyData[2].label = '审核通过' + "(" + element.recordCount + ")辆"
            break;
          case 2:
            getApplyData[3].label = '过磅中' + "(" + element.recordCount + ")辆"
            break;
        }
      });
      this.setData({
        applyData: getApplyData
      })
    })
  },


  //搜索框请求S
  onChange(e) {
    this.setData({
      searchVal: e.detail,
    });
  },
  onSearch: function (event) {
    this.setData({
      searchVal: event.detail
    })
    this.getListFun();
  },
  onCancel: function () {
    this.setData({})
  },
  toSearch: function (event) {
    this.getListFun();
  },
  statusFun: function (e) {
    this.setData({
      registStatus : e.currentTarget.dataset.status
    })
    this.getListFun()
  },
  typeFun: function (e) {
    this.setData({
      appointmentType : e.currentTarget.dataset.type
    })
    this.getListFun()
  },
  //状态筛选
  clickScroll: function (e) {
    this.setData({
      setIndex: e.detail.index
    })
    this.getListFun()
  },
  //预约类型
  onClick() {
    this.getListFun()
  },

  //列表
  getListFun: function () {
    this.setData({
      page: 1
    })
    let params = {
      current           : this.data.page,
      size              : this.data.limit,
      appointmentStatus : this.data.appointmentStatusArray[this.data.appointmentStatusIndex].dictValue,
      licenseNumber     : this.data.searchVal,
      type              : this.data.appointmentType
    }
    app.request.pageFirst({
      url: app.API.appointmentPage,
      page: this,
      params: params,
    })
    // if (this.data.roleCodeList != '0') {
    //   this.getReservationCount()
    // }
  },

  //分类统计数据获取
  getTypeCount: function () {
    app.request.GET({
      url: app.API.typeCount,
      page: this,
      params: {
        appointmentType: this.data.appointmentType,
        searchKey: this.data.searchVal
      },
      successFun: true
    }).then(res => {
      let getCount = res.data.data
      for (let key in getCount) {
        let setStr = 'appointmentType' + key
        this.setData({
          [setStr]: getCount[key]
        })
      }
    })
  },

  //扫码预约申请
  changeAdd() {
    // wx.navigateTo({
    //   url: '/pages/reservationOther/add?orderId=1'
    // })

    wx.scanCode({
      success: (res) => {
        let info = JSON.parse(res.result.trim())
        console.log(info)
        //console.log(JSON.parse(info)) //{id: "1712651156370632706", projectCode: "D456"}
        if(info.type=='1'){
          // 砂石预约
          wx.navigateTo({
            url: '/pages/reservationStone/add?orderId=' + info.id + '&orderName='+ info.orderName+'&orderNumber='+ info.orderNumber
          })
        // }else if(info.type=='2'){
        //   // 临时预约----已作废
        //   wx.navigateTo({
        //     url: '/pages/reservationTemp/add?orderId=' + info.id + '&orderName='+ info.orderName+'&orderNumber='+ info.orderNumber
        //   })
        }else if(info.type=='3'){
          // 起卸预约
          wx.navigateTo({
            url: '/pages/reservationLoadAppoint/add?orderId=' + info.id
          })
        }else if(info.type=='4'){
          // 充电桩预约
          wx.navigateTo({
            url: '/pages/reservationChargestation/add?orderId=' + info.id
          })
        }else if(info.type=='5'){
          // 管桩预约
          wx.navigateTo({
            url: '/pages/reservationPipe/add?orderId=' + info.id
          })
        }else if(info.type=='6'){
          // 其他预约
          wx.navigateTo({
            url: '/pages/reservationOther/add?orderId=' + info.id
          })
        }
    
      },
      fail: (res) => {
        wx.showToast({
          title: '请重试！',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },

  //删除
  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.appointmentDelete,
            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) {

        }
      }
    })
  },

  //取消预约
  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) {

        }
      }
    })
  },

  //司机取消预约
  driverCancelFun: 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.stoneAppointCancel,
            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.chargestationExit,
            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, type } = e.currentTarget.dataset
    if(type=='1'){
      wx.navigateTo({
        url: '/pages/reservationStone/edit?id=' + id + '&index=' + index,
      })
    // }else if(type=='2'){
    //   wx.navigateTo({
    //     url: '/pages/reservationTemp/edit?id=' + id + '&index=' + index,
    //   })
    }else if(type=='3'){
      wx.navigateTo({
        url: '/pages/reservationLoadAppoint/edit?id=' + id + '&index=' + index,
      })
    }else if(type=='4'){
      wx.navigateTo({
        url: '/pages/reservationChargestation/edit?id=' + id + '&index=' + index,
      })
    }else if(type=='5'){
      wx.navigateTo({
        url: '/pages/reservationPipe/edit?id=' + id + '&index=' + index,
      })
    }else if(type=='6'){
      wx.navigateTo({
        url: '/pages/reservationOther/edit?id=' + id + '&index=' + index,
      })
    }
    
  },

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

  // 审核S
  showPopup(e) {
    let { id } = e.currentTarget.dataset
    this.setData({
      show: true,
      auditReason: '',
      id: id
    });
  },
  onClose() {
    this.setData({
      show: false,
      auditFlag:'false',
      auditReason: '',
      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.auditReason == '') {
      warn = "审核不通过时备注不能为空！";
    }
    formData.auditFlag = formData.auditFlag=='true'
    if (warn != '') {
      app.util.checkForm(warn);
    } else {
      app.request.POST({
        url: app.API.appointmentAudit,
        params: formData,
        page: this,
        isLoadingTxt: '审核中...',
        successFun: true
      }).then(res => {
        wx.showToast({
          title: '审核成功',
          icon: 'success',
          duration: 1000,
          mask: true
        })
        this.onClose()
        this.getListFun(); //刷新列表
      })
    }
  },
  // 审核E

  //提交申请
  sendFun: function (e) {
    let _this = this;
    if (this.data.loginStatus) {
      wx.showModal({
        title: '提示',
        content: '确定立即提交申请？',
        success: function (res) {
          if (res.confirm) {
            app.request.requestGetApi(app.API.api.appointmentSend, {
              id: e.currentTarget.dataset.id
            }, _this, function (res, that) {
              if (res.statusCode == '200') { //退出登录
                wx.showToast({
                  title: '提交成功',
                  icon: 'success',
                  duration: 2000,
                  complete: function () {
                    setTimeout(function () {
                      that.getListFun();
                    }, 1500) //延迟时间 
                  }
                })
              } else {
                wx.showToast({
                  title: res.data.msg ? res.data.msg : '出错了',
                  icon: 'none',
                  duration: 1500,
                  mask: true
                })
              }
            });
          }
        }
      })
    } else {
      wx.showToast({
        title: '您还未登录，无需退出哦！',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  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,
      appointmentStatus : this.data.appointmentStatusArray[this.data.appointmentStatusIndex].dictValue,
      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 () {

  }
})