<template>
  <div class="edit_add_coffee">
    <van-address-edit
      :show-area="false"
      :show-delete="!!item.id"
      :address-info="item"
      @save="e => (item.id ? editAdderss(e) : addAddress(e))"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import { pushAddress, editAddress, deleteAddress } from "@/api/index";
import { AddressEdit as VanAddressEdit } from "vant";
import "vant/lib/address-list/style/index";
import "vant/lib/toast/style/index";
export default {
  name: "edit_add",
  data() {
    return {
      item: {},
    };
  },
  mounted() {
    let u = JSON.parse(localStorage.getItem("user") || "{}");
    this.item = {
      tel: u.loginName || "",
    };
    if (!this.$route.query.add) return;
    let p = JSON.parse(this.$route.query.add);
    p.address && (p.addressDetail = p.address);
    p.address && delete p.address;
    this.item = p;
  },
  computed: {},
  methods: {
    onDelete() {
      // 删除地址
      let t = JSON.parse(localStorage.getItem("addr") || "{}");
      if (!this.item.id) return;
      deleteAddress({
        address_id: this.item.id,
      }).then(() => {
        this.item.id == t.id && localStorage.setItem("addr", "{}");
        this.$router.go(-1);
      });
    },
    addAddress(e) {
      pushAddress({
        address_phone: e.tel || "",
        address_name: e.name || "",
        address_detail: e.addressDetail || "",
      }).then(r => {
        localStorage.setItem("addr", JSON.stringify(r || "{}"));
        this.$router.go(-2);
      });
    },
    editAdderss(e) {
      editAddress({
        address_phone: e.tel || "",
        address_name: e.name || "",
        address_detail: e.addressDetail || "",
        address_id: this.item.id,
      }).then(() => this.$router.go(-1));
    },
  },
  beforeUnmount: function () {},
  components: {
    VanAddressEdit,
  },
};
</script>

<style>
.edit_add_coffee {
}
</style>
