// pages/home/index.js
import { getMeterDetail, getMeterList, getTenementMeterList } from "../../service/meter";
import { getOwnTenementList, getTenementExceptionalCase ,
   getTenementBackInfo, getTenementDetail, getTenementInfoDetail,
} from "../../service/tenement";
import { alertInfo, alertSuccess } from "../../utils/index";
import request from '../../utils/request';
import { getDot } from "../../utils/system";
import { getUserInfo } from "../../service/user"
import { requestRecharge } from "../../service/recharge";
const { OK } = request;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    all: [],
    park: {},
    tenement: {},
    show: false,
    columns: [],
    pickerType: "",
    meterList: [],
    meterIndex: 0,
    rechargeVisible: false,
    actions: [
      { name: '微信支付', },
      { name: '对公支付' },
    ],
    
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
  },
  choosePark() {
    this.setData({
      columns: this.data.all,
      show: true,
      pickerType: "park"
    })
  },
  chooseTenement() {
    const { all = [], park = {} } = this.data;
    const tenements = all.find(item => item.id === park?.id)?.tenements
    this.setData({
      columns: tenements,
      show: true,
      pickerType: "tenement"
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },
  async changeMeter() {
    const { meterList = [] } = this.data;
    const newColumns = meterList.map(item => { item.id = item.code; item.name = `${item.code} - ${item.address}`; return item; })
    this.setData({
      columns: newColumns,
      show: true,
      pickerType: "meter"
    })
  },
  async refreshMeter() {
    const { meter } = this.data;
    this.handleGetMeterDetail(meter.id);
  },
  onOk(e) {
    const { type, index, value } = e.detail;
    const  currentPark = this.data.park;
    switch(type) {
      case "park": 
        this.setData({
          show: false,
          park: value,
          tenement: value.tenements?.[0]
        })
        wx.setStorageSync('park', value)
        wx.setStorageSync('tenement', value.tenements?.[0])
        break;
      case "tenement": 
        wx.setStorageSync('tenement', value)
        this.setData({
          show: false,
          tenement: value
        })

        break;
      case "meter":
        const { code, id } = e.detail.value;
        this.handleGetMeterDetail(id)
        break;
    }
  },
  async handleGetMeterDetail(meterId) {
    const { tenement } = this.data;
    const { code, message, data } = await getMeterDetail({ tenement: tenement?.id, id: meterId });
    if (code !== OK) {
      alertInfo(message);
      return;
    }
    this.setData({
      meter: data,
      show: false,
    })
  },
  onCancel() {
    this.setData({
      show: false,
    })
  },
  jumpToMeterBalanceRecord(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/meterBalanceRecord/index?id=${id}`,
    })
  },
  changeMoney(e) {
    const { money } = e.currentTarget.dataset;
    this.setData({
      money: money
    })
  },
  onChangeMoney(e) {
    this.setData({ money: e.detail })
  },
  jumpToMeterList() {
    const { tenement, user } = this.data;
    if (!user) {
      alertInfo("请先登录")
      return
    }
    if (!tenement) {
      alertInfo("请先选择商户")
      return
    }
    wx.navigateTo({
      url: '/pages/meterList/index?id=' + tenement?.id,
    })
  },
  async recharge() {
    const { user, money, meter, tenement, park } = this.data;
    if (!user || !user.id) {
      alertInfo("请先登录")
      return;
    }
    const { code, message, data } = await getTenementExceptionalCase(park?.id, tenement?.id);
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    if (data === 1) {
      alertInfo("账号存在异常，无法进行充值，请联系客服处理")
      return;
    }
    const { 
      code: tenementDetailCode, 
      message: tenementDetailMessage, 
      tenement: tenementDetail,
    } = await getTenementBackInfo(park?.id, tenement?.id)
    if (tenementDetailCode !== OK) {
      alertInfo(tenementDetailMessage)
      return
    }
    if (tenementDetail?.stop_top) {
      alertInfo("您暂不可使用此功能，可联系客服处理。")
      return;
    }
    const that  = this;
    if (!user || !user.id) {
      alertInfo("请先登录")
      return
    }
    if (!money) {
      alertInfo("请先输入金额")

      return;
    }
    if (!meter?.code) {
      alertInfo("没有选择表计")
      return;
    }
    if (money < 0.01) {
      alertInfo("最少为1分")
      return
    }
    this.setData({ rechargeVisible: true })
  },
  jumpToInvoice() {
    const { user, } = this.data;
    if (!user || !user.id) {
      alertInfo("请先登录")
      return
    }
    wx.navigateTo({
      url: '/pages/invoiceList/index',
    })
  },
  jumpToLogin() {
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAllList();
    this.watchTenement();
    this.watchPark();
    getDot();
  },
  watchTenement() {
    const that = this;
    let value = this.data.tenement; // 获取被监听属性的当前值
 
    // 使用 Object.defineProperty 方法在数据对象上定义属性的 getter 和 setter
    Object.defineProperty(this.data, 'tenement', {
      configurable: true, // 可配置
      enumerable: true, // 可枚举
      get: function () {
        return value; // 返回属性的当前值
      },
      set: function (newVal) {
        // const oldValue = value;
        wx.setStorageSync('tenement', newVal)
        that.getMeters(newVal);
        that.setUser(newVal.id);
        value = newVal;
      }
    });
  },
  watchPark() {
    const that = this;
    let value = this.data.park; // 获取被监听属性的当前值
 
    // 使用 Object.defineProperty 方法在数据对象上定义属性的 getter 和 setter
    Object.defineProperty(this.data, 'park', {
      configurable: true, // 可配置
      enumerable: true, // 可枚举
      get: function () {
        return value; // 返回属性的当前值
      },
      set: function (newVal) {
        // const oldValue = value;
        value = newVal;
        wx.setStorageSync('park', newVal)
      }
    });
  },
  watchMeter() {
    const that = this;
    let value = this.data.meter; // 获取被监听属性的当前值
 
    // 使用 Object.defineProperty 方法在数据对象上定义属性的 getter 和 setter
    Object.defineProperty(this.data, 'meter', {
      configurable: true, // 可配置
      enumerable: true, // 可枚举
      get: function () {
        return value; // 返回属性的当前值
      },
      set: function (newVal) {
        // const oldValue = value;
        value = newVal;
        wx.setStorageSync('meter', newVal)
      }
    });
  },
  async getMeters({ id }) {
    const { code, message, data } = await getTenementMeterList(id);
    if (code !== OK) {
      alertInfo(message)
      this.setData({ meterList: [], meter: {} })
      wx.setStorageSync('meter', {})
      return;
    }
    this.setData({
      meterList: data || [],
      meter:  (data?.[0] || {})
    })
    // if (!storageMeter) {
      wx.setStorageSync('meter', data?.[0] || {} )
    // }
  },
  jumpToElectric() {
    const { user, } = this.data;
    if (!user || !user.id) {
      alertInfo("请先登录")
      return
    }
    wx.navigateTo({
      url: '/childPackage/pages/electricQuery/index',
    })
  },
  async setUser(id) {
    const result = await getUserInfo(id);
    if (result.code !== OK) {
      const user = wx.getStorageSync('user')
      this.setData({ user: user })
      return;
    }
    this.setData({ user: result.data })
    wx.setStorageSync('user', result.data)
  },
  async getAllList() {
    const { code, message, data } = await getOwnTenementList()
    if (code !== OK) {
      alertInfo(message)
      return
    }
    if (!data?.length) {
      alertInfo("尚无信息")
      
      setTimeout(() => {
        wx.clearStorageSync()
        wx.redirectTo({
          url: '/pages/login/index',
        })
      }, 500)
      return;
    }
    const [firstPark = {}] = data;
    const { park, tenement } = this.data;
    const updateDatas = {}
    if (!park || !park.id) {
      const storagePark = wx.getStorageSync('park')
      if (!data.find(item => item.id === storagePark?.id)) {
        updateDatas.park = firstPark
      } else {
        updateDatas.park = storagePark || firstPark
      }
    } else {
      updateDatas.park = park;
    }
    if (!tenement || !tenement.id) {
      const storageTenement = wx.getStorageSync('tenement')
      if (!updateDatas.park.tenements?.find(item => item.id === storageTenement?.id)) {
        updateDatas.tenement = updateDatas.park.tenements?.[0]
      } else {
        updateDatas.tenement = storageTenement || park.tenements?.[0]
      }
      
    } else {
      updateDatas.tenement = tenement
    }
    updateDatas.all = data;
    this.setData({
      ...updateDatas
    }, () => {
      if (updateDatas?.tenement?.id) {
        this.getMeters({ id: updateDatas?.tenement?.id })
      }
    })
  },
  jumpToRecord() {
    const { user, } = this.data;
    if (!user || !user.id) {
      alertInfo("请先登录")
      return
    }
    wx.navigateTo({
      url: '/pages/rechargeRecord/index',
    })
  },
  jumpToOrder() {
    const { user, } = this.data;
    if (!user || !user.id) {
      alertInfo("请先登录")
      return
    }
    wx.navigateTo({
      url: '/pages/billList/index',
    })
  },
  onCloseRechargeWay() {
    this.setData({ rechargeVisible: false })
  },
  onSelectRechargeWay(e) {
    switch(e.detail.name) {
      case "对公支付":
        const { user, money, meter, tenement, park } = this.data;
        wx.navigateTo({
          url: `/pages/publicTransfer/index?money=${money}&meterId=${meter.id}&tenementId=${tenement.id}&tenementName=${tenement.name}&park=${park.id}`,
        })
        break;
      default:
        this.wxRecharge();
        break;
    }
  },
  async wxRecharge() {
    const { money, meter, tenement, park } = this.data;
    const { code, message, data } = await requestRecharge({ money: Number(money), id: meter?.id, tenement: tenement?.id, park: park?.id })
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    const that = this;
    wx.requestPayment({
      timeStamp: data?.time,
      nonceStr: data?.nonceStr,
      package: "prepay_id=" + data?.prepay_id,
      paySign: data?.paySign,
      signType: 'RSA',
      success: (res) => {
        alertSuccess("充值成功")
        that.setData({
          money: null
        })
      },
      fail: (res) => {
        console.log('fail', res)
        alertInfo("请稍后重试")
      },
      complete: (res) => {
        console.log('complete')
        that.handleGetMeterDetail(meter.id)
      }
    })
  },

})