import HTTP from "../../../../requestFn/Api"
const app = getApp();
Page({

  data: {
    garden_id: "",
    house_id: "",
    propertyInfo: {},
    should_pay_amount: 0,
    order_id:""
  },

  onLoad(options) {
    const {
      garden_id,
      house_id
    } = app.globalData;
    this.setData({
      garden_id
    })
    this.getProperty(garden_id, house_id)
  },
  async getProperty(garden_id, house_id) {
    const data = await HTTP.GetMonthsProperty({
      garden_id,
      house_id
    })
    const month_list = data.month_list.map(item => {
      return {
        ...item,
        checked: false
      }
    })
    this.setData({
      propertyInfo: {
        ...data,
        month_list
      },
    })
  },
  choiceMonth(e) {
    const {
      index,
      months,
      package_id
    } = e.currentTarget.dataset;
    this.setData({
      months,
      package_id
    })
    const {
      propertyInfo,
      garden_id
    } = this.data;
    const month_list = propertyInfo.month_list.map((item, num) => {
      if (index == num) {
        return {
          ...item,
          checked: true
        }
      } else {
        return {
          ...item,
          checked: false
        }
      }
    })
    this.setData({
      propertyInfo: {
        ...propertyInfo,
        month_list
      }
    })
    const {
      bind_id
    } = propertyInfo;
    HTTP.Getpre_pay_info({
      garden_id,
      bind_id,
      months
    }).then(res => {
      console.log(res);
      const {
        should_pay_amount
      } = res;
      this.setData({
        should_pay_amount
      })
    })
  },
  pre_pay() {
    const that = this;
    const {
      propertyInfo: {
        bind_id
      },
      garden_id,
      months,
      package_id,
      should_pay_amount,
    } = that.data;
    if (!months) {
      wx.showToast({
        title: '请选择预存月份',
        icon: "error",
      })
      return false
    }
    HTTP.Pre_pay({
      bind_id,
      garden_id,
      months,
      package_id,
      should_pay_amount,
      pay_amount:should_pay_amount
    }).then(res=>{
      if(res.code==0){
        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);
          },
          fail(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"
                })
              }
            })
          }
        })
      }
    })
  },
})