<template>
  <view class="content">
    <EmptyAddress v-if="isEmpty" />

    <AddressCard
      v-for="(address, index) in addressList"
      :key="index"
      :item="address"
      @bundleClick="selectIt"
    />

    <view class="bar-bottom">
      <button class="add-btn" type="default" @click="toAdd">
        添加新收货地址
      </button>
    </view>
  </view>
</template>

<script>
import EmptyAddress from "./emptyAddress";
import AddressCard from "./addressCard";
import address from "@/api/address.api";
let pageNum = 0;
export default {
  components: {
    EmptyAddress,
    AddressCard
  },
  data() {
    return {
      source: 0,
      isSelect: false,
      addressList: []
    };
  },
  computed: {
    isEmpty() {
      return !this.addressList.length;
    }
  },
  onLoad(option) {
    this.isSelect = option.source == 1;
    this.loginPopupFn();
    pageNum = getCurrentPages().length;
  },
  onShow() {
    this.loadAddress();
  },
  onUnload() {
    if (!this.addressList.length) {
      uni.$emit("confirmPageUpdateAddress", { noAddr: true });
    }
  },
  methods: {
    loginPopupFn() {
      if (!uni.getStorageSync("token")) {
        this.$refs["login-popup"].open();
      }
    },
    toAdd() {
      uni.navigateTo({
        url: "/subPackages/common/address/addressManage"
      });
    },
    selectIt(e) {
      if (!this.isSelect) return;
      uni.$emit("confirmPageUpdateAddress", e);
      if (getCurrentPages().length == pageNum) {
        uni.navigateBack();
      }
    },
    async loadAddress() {
      const [res] = await address.getAddressList();
      this.addressList = res && res.addrReceiverList ? res.addrReceiverList : [];
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/style/var.scss";
.content {
  position: relative;
  /* height: 100%; */
  padding: $padding-xs + 4;
  padding-bottom: 120rpx;
}

.bar-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: $bar-bottom-height;
  background-color: $uni-bg-color;
  padding: $uni-spacing-row-base;
  display: flex;
  align-items: center;

  .add-btn {
    @include primary-bg;
    color: $uni-bg-color;
    font-size: $uni-font-size-base;
    font-weight: bold;
    border-radius: $uni-border-radius-xl;
    flex: 1;
  }
}
</style>
