// pages/mine/livingPay/index.js
import HTTP from "../../../../requestFn/Api"
import {
  formatMonth,
  formatTime
} from "../../utils/util"
const app = getApp();
Page({
  data: {
    navbarActiveIndex: 0,
    navbarTitle: [
      "待缴费",
      "待支付",
      "已缴费"
    ],
    garden_id: null,
    house_id: null,
    charge_type: {
      1: '物业费',
      2: '水费',
      3: '电费',
      4: '气费',
      5: '车位管理费',
      6: '月租停车费',
      99: '其他'
    },
    pay_amount: 0,
    payed_amount: 0,
    should_pay_amount: 0,
    bind_ids: [],
    can_pay: false,
    checked: false,
    unpay_list: [],
    order_list: [],
    payed_list: [],
    list: {},
    hiddenName: {
      toPay: false,
      noPay: true,
      havePay: true
    },
    Dialog: false,
    order_id: null,
    time: "全部账单",
    date: '',
    start: '',
    end: "",
    bill_ids: [],
    checkedNum: 0,
    countNum: 0
  },
  onLoad(options) {
    const that = this;
    const {
      garden_id,
      house_id,
      can_pay
    } = app.globalData;
   if(garden_id){
    that.setData({
      garden_id,
      house_id,
      can_pay
    })
   }
   that.getUnpay_List()
  },
  onShow() {

  },
  getTime() {
    const date = formatMonth(new Date())
    const time = this.formatNumber(date.split('-'))
    const start = this.getStart(date.split('-'))
    this.setData({
      time,
      date,
      start,
      end: date
    })
  },
  getOrder_List() {
    const that = this;
    const {
      garden_id,
    } = that.data
    HTTP.GetOrder_list({
      garden_id
    }).then(res => {
      that.setData({
        order_list: res.list
      })
    })
  },
  onNavBarTap: function (event) {
    const that = this;
    let navbarTapIndex = event.currentTarget.dataset.navbarIndex
    that.setData({
      navbarActiveIndex: navbarTapIndex
    })
    if (that.data.navbarActiveIndex == 0) {
      that.getUnpay_List()
      console.log(1);
      that.setData({
        hiddenName: {
          toPay: false,
          noPay: true,
          havePay: true,
        },
        checked: false,
        countNum: 0,
        pay_amount: 0
      })
    } else if (that.data.navbarActiveIndex == 1) {
      that.getOrder_List()
      that.setData({
        hiddenName: {
          toPay: true,
          noPay: false,
          havePay: true,
        }
      })
    } else {
      that.getTime()
      that.getPayed_list()
      that.setData({
        hiddenName: {
          toPay: true,
          noPay: true,
          havePay: false
        }
      })
    }
  },
  checkboxChange(e) {
    const {
      bind_id
    } = e.currentTarget.dataset;
    this.checkboxChange1(bind_id);
  },
  async checkboxChange1(bind_id) {
    const that = this;
    const items = this.data.unpay_list;
    let {
      pay_amount,
      checkedNum
    } = this.data;
    let checked = false;
    let newArr = items.map((item, index) => {
      if (item.bind_id == bind_id) {
        that.setData({
          [`unpay_list[${index}].checked`]: !items[index].checked,
        })
        if (item.checked) {
          that.setData({
            checkedNum: checkedNum + 1,
          })
          if (item.detail) {
            const {
              countNum,
              pay_amount
            } = that.data;
            let page = 0;
            let money = 0;
            let newArr = item.detail.list.map(key => {
              if (!key.checked) {
                page = page + 1;
                money = money + key.amount
              }
              return {
                ...key,
                checked: true
              }
            })
            that.setData({
              [`unpay_list[${index}].detail.list`]: newArr,
              countNum: countNum + page,
              pay_amount: money + pay_amount
            })
          }
          that.getBill_id(bind_id, false)
        } else {
          if (item.detail) {
            const {
              countNum
            } = that.data;
            let newArr = item.detail.list.map(key => {
              return {
                ...key,
                checked: false
              }
            })
            that.setData({
              [`unpay_list[${index}].detail.list`]: newArr,
              countNum: countNum - newArr.length
            })
          }
          that.setData({
            pay_amount: pay_amount - item.unpay_amount,
            checkedNum: checkedNum - 1,
          })
        }
      }
    })
    const num = that.data.checkedNum;
    if (num == items.length) {
      checked = true
    } else {
      checked = false
    }
    this.setData({
      checked,
    });
  },
  async checkAllBox() {
    const that = this;
    const {
      unpay_list,
      checked,
    } = that.data;
    unpay_list.map((item, index) => {
      that.setData({
        [`unpay_list[${index}].checked`]: !checked
      })
      if (!checked) {
        that.setData({
          checkedNum: unpay_list.length,
        })
        if (!item.detail) {
          const {
            garden_id
          } = that.data;
          HTTP.GetBill_List({
            garden_id,
            bind_id: item.bind_id
          }).then(res => {
            const {
              countNum
            } = that.data;
            let result = res.list.map(item => {
              return {
                ...item,
                checked: true
              }
            })
            that.setData({
              [`unpay_list[${index}].detail`]: {
                ...res,
                list: result,
                num: result.length
              },
              [`unpay_list[${index}].show`]: true,
              countNum: result.length + countNum
            })
          })
        } else {
          const {
            countNum
          } = that.data;
          let result = item.detail.list.map(item => {
            return {
              ...item,
              checked: true
            }
          })
          that.setData({
            [`unpay_list[${index}].detail.list`]: result,
            [`unpay_list[${index}].show`]: true,
            countNum: result.length + countNum,
          })
        }
      } else {
        that.setData({
          checkedNum: 0,
          countNum: 0
        })
        let result = item.detail.list.map(item => {
          return {
            ...item,
            checked: false
          }
        })
        that.setData({
          [`unpay_list[${index}].detail.list`]: result,
        })
      }
    })
    let pay_amount = 0;
    for (let i = 0; i < unpay_list.length; i++) {
      if (unpay_list[i].checked) {
        pay_amount += unpay_list[i].unpay_amount
      }
    }
    that.setData({
      pay_amount,
      checked: !checked,
    })
  },
  getBill_ids() {
    const {
      unpay_list
    } = this.data;
    let bill_ids = [];
    unpay_list.map(item => {
      if (item.detail) {
        item.detail.list.map(key => {
          if (key.checked) {
            bill_ids.push(key.bill_id)
          }
        })
      }
    })
    this.setData({
      bill_ids
    })
  },
  getCountNum() {
    const {
      unpay_list
    } = this.data;
    let page = 0;
    unpay_list.map(item => {
      item.detail.list.map(key => {
        if (key.checked) {
          page = page + 1
        }
      })
    })
    this.setData({
      countNum: page
    })
  },
  Pay_amount() {
    const that = this;
    that.getBill_ids();
    const {
      garden_id,
      pay_amount,
      can_pay,
      unpay_list,
      bill_ids
    } = that.data;
    console.log(bill_ids);
    if (bill_ids.length == 0) {
      wx.showToast({
        title: '请选择缴费订单',
        icon: "error",
      })
      return false
    }
    if (!can_pay) {
      wx.showToast({
        title: '占不支持线上缴费',
        icon: "none"
      })
      return false
    }
    HTTP.Pay({
      bill_ids,
      garden_id,
      pay_amount,
      should_pay_amount: pay_amount
    }).then(res => {
      that.setData({
        order_id: res.data.order_id,
      })
      const data = JSON.parse(res.data.prepay_info)
      wx.requestPayment({
        ...data,
        timeStamp: data.timeStamp + "",
        success(res) {
          console.log(res);
          wx.showToast({
            title: '支付成功',
            icon: "success",
            success() {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        },
        fail(res) {
          console.log(res);
          const {
            order_id
          } = that.data;
          HTTP.CancleOrder({
            order_id,
            garden_id,
            by_user: false,
          }).then(res => {
            if (res.code == 0) {
              wx.showToast({
                title: '取消支付',
                icon: "error"
              })
            }
          })
        }
      })
    })
  },
  async getBill_List(e) {
    const {
      bind_id
    } = e.currentTarget.dataset;
    this.getBill_id(bind_id, true);
  },
  async getBill_id(bind_id, flag = false) {
    const that = this;
    const {
      garden_id,
      unpay_list
    } = that.data
    let newArr = await Promise.all(unpay_list.map(async (item) => {
      if (item.bind_id == bind_id && !item.detail) {
        let res = await HTTP.GetBill_List({
          bind_id,
          garden_id
        })
        let money = 0;
        const newArr = res.list.map(key => {
          if (item.checked) {
            money = money + key.amount;
            return {
              ...key,
              checked: true,
            }
          } else {
            return {
              ...key,
              checked: false,
            }
          }

        })
        if (item.checked) {
          const {
            countNum,
            pay_amount
          } = that.data;
          that.setData({
            countNum: countNum + res.list.length,
            pay_amount: money + pay_amount
          })
        }
        return {
          ...item,
          show: !item.show,
          detail: await {
            ...res,
            num: flag ? 0 : newArr.length,
            list: newArr
          },
        }
      } else {
        if (item.bind_id == bind_id && flag) {
          return {
            ...item,
            show: !item.show
          }
        } else {
          return {
            ...item,
          }
        }

      }
    }))
    that.setData({
      unpay_list: newArr
    })
  },
  async goDetail(e) {
    let data = e.currentTarget.dataset.detail;
    wx.navigateTo({
      url: './billList/index',
      success: function (res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', data)
      }
    })
  },
  affirmCancle(e) {
    const that = this;
    const {
      garden_id,
      order_id
    } = that.data
    HTTP.CancleOrder({
      order_id,
      garden_id,
      by_user: true
    }).then(res => {
      if (res.code == 0) {
        wx.showToast({
          title: '取消成功',
          icon: "success"
        })
        that.close()
        that.getOrder_List()
      }
    })
  },
  close() {
    this.setData({
      Dialog: false,
    });
  },
  openDialog(e) {
    const {
      order_id
    } = e.currentTarget.dataset
    this.setData({
      Dialog: true,
      order_id
    });
  },
  getOrder_Info(e) {
    const that = this;
    const {
      order_id
    } = e.currentTarget.dataset
    const {
      garden_id
    } = that.data
    HTTP.GetOrderInfo({
      order_id,
      garden_id
    }).then(r => {
      console.log(r);
      let data = r.list
      wx.navigateTo({
        url: './detail/detail',
        success: function (res) {
          res.eventChannel.emit('acceptDataFromOpenerPage', data)
        }
      })
    })
  },
  getPayed_Info(e) {
    const that = this;
    const {
      bill_id
    } = e.currentTarget.dataset
    const data = that.data.payed_list.filter(item => item.bill_id == bill_id)[0]
    wx.navigateTo({
      url: './billList/index',
      success: function (res) {
        res.eventChannel.emit('acceptDataFromOpenerPage', data)
      }
    })
  },
  getPayed_list(time = "") {
    const that = this;
    const {
      garden_id,
      house_id,
    } = that.data
    HTTP.GetPayed_list({
      garden_id,
      house_id,
      pay_time: time
    }).then(res => {
      let payed_amount = 0;
      for (let i = 0; i < res.list.length; i++) {
        payed_amount += res.list[i].amount
      }
      that.setData({
        payed_list: res.list,
        payed_amount
      })
    })
  },
  chickAll() {
    this.getPayed_list();
  },
  checkChange(e) {
    const that = this;
    const {
      bill_id,
      bind_id,
    } = e.currentTarget.dataset;
    const {
      pay_amount,
      unpay_list,
      checkedNum
    } = that.data;
    let flag = 0;
    unpay_list.map((item, index) => {
      if (item.bind_id == bind_id) {
        item.detail.list.map((key, num) => {
          if (key.bill_id == bill_id) {
            that.setData({
              [`unpay_list[${index}].detail.list[${num}].checked`]: !key.checked
            })
            const {
              countNum
            } = that.data;
            if (key.checked) {
              that.setData({
                [`unpay_list[${index}].detail.num`]: item.detail.num + 1,
                pay_amount: pay_amount + key.amount,
                countNum: countNum + 1,
              })
            } else {
              that.setData({
                [`unpay_list[${index}].detail.num`]: item.detail.num - 1,
                pay_amount: pay_amount - key.amount,
                countNum: countNum - 1
              })
            }
          }
          if (item.detail.num == item.detail.list.length) {
            that.setData({
              [`unpay_list[${index}].checked`]: true,
            })
          } else {
            that.setData({
              [`unpay_list[${index}].checked`]: false,
            })
          }
        })
      }
      if (item.checked) {
        flag = flag + 1
      }
    })
    if (flag !== unpay_list.length) {
      that.setData({
        checked: false,
      })
    } else {
      that.setData({
        checked: true,
      })
    }
    that.setData({
      checkedNum: flag
    })
  },
  getUnpay_List() {
    const that = this;
    const {
      garden_id,
      house_id
    } = that.data
    HTTP.GetUnpay_list({
      garden_id,
      house_id
    }).then(res => {
      const unpay_list = res.list.map(item => {
        return {
          ...item,
          checked: false,
          show: false,
        }
      })
      that.setData({
        unpay_list
      })
    })
  },
  bindDateChange(e) {
    const date = e.detail.value
    const time1 = new Date(date)
    var time2 = time1.getTime() / 1000
    const time = this.formatNumber(date.split('-'))
    this.setData({
      date,
      time
    })
    this.getPayed_list(time2)
  },
  formatNumber(n) {
    return n[0] + '年' + n[1] + '月'
  },
  getStart(e) {
    if (e[1] - 6 < 0) {
      return `${e[0]-1}-${e[1]-6+12}`
    } else {
      return `${e[0]}-${e[1]-6}`
    }
  },
})