// pages/rentManagement/rentManagement.js
const app = getApp()
const WXAPI = require('../../utils/request')
var util = require('../../utils/util');
const moment = require('../../utils/moment')
function getChild(nodes, item, arr) {
  for (let el of nodes) {
    if (el.id === item) {
      arr.push(el.id);
      if (el.children) {
        childNodesDeep(el.children, arr);
      }
    } else if (el.children) {
      getChild(el.children, item, arr);
    }
  }
  return arr;
}
function childNodesDeep(nodes, arr) {
  if (nodes)
    nodes.forEach((ele) => {
      arr.push(ele.id);
      if (ele.children) {
        childNodesDeep(ele.children, arr);
      }
    });
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showOne:false,
    list:[],
    pageNum:1,
    pageStatus:true,
    searchValue:'',
    search:{
      name:''
    },
    show:false,
    radio:'2',
    leases:{},
    selectKey:'',
    selectRoomName:'',
    pid:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLeasesList()
    this.getTree()
  },
  confirmMethods(event) {
    this.confimPay()
  },
  selectRoomMethods(){
    this.setData({
      showOne:true
    })
  },
  // 清空选择的房源
  clearSelect(){
    this.setData({
      pid:'',
      selectKey:'',
      selectRoomName:''
    })
  },
  onClose() {
    this.setData({ show: false });
  },
  onCloseOne() {
    this.setData({ showOne: false });
  },
  getTree() {
    var _this = this
    WXAPI.getTree('').then(res => {
      var list=res.data.sort((pre, cur)=>pre.id - cur.id)
      var newArr = util.uniqueArray(list, "id");
      var setting = {
        data: {
          simpleData: {
            idKey: 'id',
            pIdKey: 'pid'
          },
          key: {
            children: 'children'
          }
        }
      }
      var dataList = this.transformTozTreeFormat(setting, newArr)
      this.setData({
        dataList: dataList
      })      
    })
  },
  transformTozTreeFormat(setting, sNodes) {
    var i, l,
      key = setting.data.simpleData.idKey,
      parentKey = setting.data.simpleData.pIdKey,
      childKey = setting.data.key.children
    if (!key || key == "" || !sNodes) return [];
    var r = [];
    var tmpMap = [];
    for (i = 0, l = sNodes.length; i < l; i++) {
      tmpMap[sNodes[i][key]] = sNodes[i];
    }
    for (i = 0, l = sNodes.length; i < l; i++) {
      if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
        if (!tmpMap[sNodes[i][parentKey]][childKey])
          tmpMap[sNodes[i][parentKey]][childKey] = [];
        tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
      } else {
        r.push(sNodes[i]);
      }
    }
    return r;
  },
  handleSelect(e) {
    wx.showToast({
      title: `已选择${e.detail.item.name}`,
      icon: 'none',
      duration: 1000
    })
    let item =  getChild(this.data.dataList,e.detail.item.id,[])
    this.setData({
      selectKey: item,
      selectRoomName: e.detail.item.name,
      pid:e.detail.item.id,
      showOne: false
    })
    this.getLeasesList()
  },
validObject(obj) {
  let objectData = new Object()
  for (let i in obj) {
    if (obj[i] != '' && obj[i]) {
      objectData[i] = obj[i]
    }
  }
  return objectData;
},
  // 获取对应租约
  getLeasesList(){
    let  siteIds = this.data.selectKey
    let QData = {}
    if(this.data.selectKey){
      QData = this.validObject({
        name:this.data.search.name,
        siteIds:JSON.stringify(siteIds)
      })
    }else{
      QData = this.validObject({
        name:this.data.search.name
      })
    }
    
    let data={
      orderBy: "create_time desc",
      pageNum: this.data.pageNum,
      pageSize: 10,
      q:JSON.stringify(QData)
    }
    WXAPI.getLeasesList(data).then(res=>{
      if(res.success){
        if(res.data.list.length<10){
          this.setData({
            pageStatus:false
          })
        }else{
          this.setData({
            pageStatus:true
          })
        }
        res.data.list.map(li=>{
          li.signingTime = moment(li.signingTime).format('YYYY-MM-DD')
          li.contractTime = moment(li.contractTime).format('YYYY-MM-DD')
          li.expand = JSON.parse(li.expand)
        })
        let list = []
        if(this.data.pageNum === 1){
          list = res.data.list
        }else{
          list = this.data.list.concat(res.data.list)
        }
        wx.showToast({
          title: `已为您搜索到${res.data.total}条记录`,
          duration:2000,
          icon:'none'
        })
        this.setData({
          list
        })
      }else{
        wx.showToast({
          title: '获取合约失败',
          mask:true,
          duration:'2000',
          icon:'none'
        })
      }
    })
  },
  onChange(event) {
    let search={
      name:event.detail
    }
    this.setData({
      search: search
    })
  },
  onClick(e) {
    this.setData({
      pageNum:1
    })
    this.getLeasesList()
  },
  onChangeRadio(event){
    this.setData({
      radio: event.detail,
    });
  },
  rentMethods(e){
    let leases = e.currentTarget.dataset.item
    // wx.setStorageSync('leases', leases)
    // wx.navigateTo({
    //   url: '/pages/paymentInterface/paymentInterface?type=1',
    //   data:{

    //   }
    // })
    this.setData({
      show:true,
      leases
    })
  },
  confimPay(){
    let leases =this.data.leases
    let userInfo = wx.getStorageSync('userInfo')
    var data = {
      description: "交租",
      productName: "交租",
      total: parseInt(leases.monthRent)*100,//parseInt(this.data.leases.expand.rent)*100,
      userId: leases.cardId,
      cardId:leases.cardId,
      openid:wx.getStorageSync('openid'),
      appid:'wx20de9fe5943934a1',
      uid:userInfo.id,
      eid:userInfo.enterpriseId,
      orderType:1,
      payType:this.data.radio,
      expand:JSON.stringify({
        phone:leases.phone,
        nickname:leases.name
      })
    }
    WXAPI.miniPrepayOrder(data).then(res=>{
      // if(this.data.radio == '0'){
      //   wx.requestPayment({
      //     timeStamp: res.data.data.timeStamp,
      //     appid: res.data.data.appId,
      //     nonceStr: res.data.data.nonceStr,
      //     package: res.data.data.package,
      //     signType: res.data.data.signType,
      //     totalFee: parseInt(leases.monthRent)*100,
      //     paySign: res.data.data.paySign,
      //     success (res1) {
      //       wx.showToast({
      //         title: "支付成功",
      //         duration: 2000,
      //         icon: 'success'
      //       })
      //       let dataOne={
      //         code: "wx/updatePrepayStatus",
      //         signature:wx.getStorageSync('signature'),
      //         data: {
      //           orderNo: res.data.data.orderNo,
      //           status:0
      //         }
      //       }
      //       WXAPI.sendCommandOne(dataOne).then(res2=>{
  
      //       })
      //     },
      //     fail (res1) {
      //       wx.showToast({
      //         title: "支付失败",
      //         duration: 2000,
      //         icon: 'none'
      //       })
      //       let dataOne={}
      //       if(res1.errMsg == 'requestPayment:fail cancel'){
      //         dataOne={
      //           code: "wx/updatePrepayStatus",
      //           signature:wx.getStorageSync('signature'),
      //           data: {
      //             orderNo: res.data.data.orderNo,
      //             status:8
      //           }
      //         }
      //       }else{
      //         dataOne={
      //           code: "wx/updatePrepayStatus",
      //           signature:wx.getStorageSync('signature'),
      //           data: {
      //             orderNo: res.data.data.orderNo,
      //             status:6
      //           }
      //         }
      //       }
      //       WXAPI.sendCommandOne(dataOne).then(res2=>{
  
      //       })
      //     }
      //   })
      // }else{
        let dataOne={
          code: "wx/updatePrepayStatus",
          data: {
            orderNo: res.data.data.orderNo,
            status:0
          }
        }
        WXAPI.sendCommand(dataOne).then(res2=>{
          if(res2.success){
            wx.showToast({
              title: "支付成功",
              duration: 2000,
              icon: 'success'
            })              
          }else{
            wx.showToast({
              title: res2.message,
              duration: 2000,
              icon: 'error'
            })
          }
        })
      // }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.pageStatus){
      let page = this.data.pageNum+1
      this.setData({
        pageNum:page
      })
      this.getLeasesList()
    }
  },

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

  }
})