<template>
    <!-- Header Start -->
    <header class="header">
        <div class="logo-wrap">
            <i class="icon-arrow-left-bold-box icli" @click="$router.go(-1)"></i>
            <h1 class="title-color font-md">選擇收貨地址</h1>
        </div>
    </header>
    <!-- Header End -->
    <!-- Main Start -->
    <main class="main-wrap address2-page mb-xxl">
        <!-- Address Section Start -->
        <section class="pt-0">
            <button class="d-block btn-outline-grey" @click="showOffcanvas = true">+ 增加新地址</button>

            <div class="address-wrap">
                <!-- Address Star -->
                <div
                    class="address-box"
                    :class="{ active: ua.is_default }"
                    v-for="(ua, index) in userAddr"
                    :key="ua.address_id"
                    @click="handleSetDefault(ua.address_id)"
                >
                    <div class="conten-box">
                        <div class="heading">
                            <div class="heading-left">
                                <i class="icon-home icli"></i>
                                <h2 class="title-color font-md">{{ ua.address_name }}</h2>
                                <span class="badges-round font-white bg-theme-theme font-xs" v-if="ua.is_default"
                                    >預設</span
                                >
                            </div>
                            <div class="heading-right">
                                <i class="icon-trash" @click.stop="handleDelete(ua.address_id)"></i>
                            </div>
                        </div>
                        <h3 class="title-color font-sm">{{ ua.consignee }}</h3>
                        <h3 class="title-color font-sm">{{ ua.tel }}</h3>
                        <p class="content-color font-sm">{{ua.city + '' + ua.district + '' + ua.address }}</p>
                    </div>
                    <!-- <img src="/src/assets/images/map/map.jpg" alt="map" /> -->
                </div>
                <!-- Address End -->
            </div>
        </section>
        <!-- Address Section End -->
    </main>
    <!-- Main End -->

    <!-- Footer Start -->
    <!-- <footer class="footer-wrap footer-button">
    <a href="payment.html" class="font-md">Proceed to Payment</a>
  </footer> -->
    <!-- Footer End -->

    <!-- Add New Address Off Canvas Start -->
    <van-popup v-model:show="showOffcanvas" round closeable position="bottom">
        <div class="offcanvas-header">
            <h5 class="title-color font-md fw-600">增加住址</h5>
        </div>
        <van-form @submit="onSubmit" ref="addrForm">
            <div class="offcanvas-body small">
                <van-cell-group inset>
                    <van-field
                        v-model="form.name"
                        name="name"
                        label="住址名稱"
                        placeholder="自己可以識別的名稱"
                        :rules="[{ required: true, message: '請填寫住址名稱' }]"
                    />
                    <van-field
                        v-model="form.consignee"
                        name="consignee"
                        label="聯絡人"
                        placeholder="聯絡人"
                        :rules="[{ required: true, message: '請填寫聯絡人姓名' }]"
                    />
                    <van-field
                        v-model="form.tel"
                        name="tel"
                        label="聯絡電話"
                        placeholder="聯絡電話"
                        :rules="[{ required: true, message: '請填寫聯絡電話' }]"
                    />
                    <van-field
                        v-model="fieldValue"
                        is-link
                        readonly
                        name="area"
                        label="地區"
                        placeholder="請選擇區域"
                        @click="showPicker = true"
                    />
                    <van-popup v-model:show="showPicker" position="bottom">
                        <van-picker
                            name="selectedValue"
                            v-model="selectedValue"
                            :columns="columns"
                            @confirm="onConfirm"
                            @cancel="showPicker = false"
                            confirm-button-text="確認"
                            cancel-button-text="取消"
                        />
                    </van-popup>
                    <van-field v-model="form.zipcode" name="zipcode" label="郵遞區號" placeholder="郵遞區號" />
                    <van-field
                        v-model="form.address"
                        name="address"
                        label="詳細地址"
                        placeholder="詳細地址"
                        :rules="[{ required: true, message: '請填寫詳細地址' }]"
                    />
                    <van-field name="is_default" label="是否為預設">
                        <template #input>
                            <van-switch v-model="form.is_default" />
                        </template>
                    </van-field>
                </van-cell-group>
            </div>
            <div style="margin: 16px">
                <van-button round block type="primary" native-type="submit"> 新增 </van-button>
            </div>
        </van-form>
    </van-popup>
    <!-- Add New Address Off Canvas End -->
</template>

<script setup>
import { ref, onMounted } from "vue";

import { useRouter, useRoute } from "vue-router";

import { useOrderStore } from "@/store/Order";

import { showToast } from "vant";
import "vant/es/toast/style";

import { getArea } from "@/services/shop";
import { getUserAddress, addUserAddress, delUserAddress, setUserAddressDefault } from "@/services/user";

const route = useRoute();
const router = useRouter();
const orderStore = useOrderStore();

const showPicker = ref(false);

const showOffcanvas = ref(false);

const fieldValue = ref("");

const userAddr = ref([]);

const columns = ref([]);

const addrForm = ref();

const form = ref({
    name: "住家",
    consignee: '',
    tel: '',
    city: '',
    district: '',
    zipcode: '',
    address: '',
    is_default: false,
});

const selectedValue = ref(["0"])

onMounted(async () => {
    let addrRes = await getUserAddress();

    if (addrRes.code === 200) {
        userAddr.value = addrRes.data;
    }

    let areaRes = await getArea();
    if (areaRes.code === 200) {
        columns.value = areaRes.data;
    }
});

const onConfirm = ({ selectedOptions }) => {
    showPicker.value = false;

    let selectedArea = selectedOptions[0].text;

    if (selectedOptions[1]) {
        selectedArea += "-" + selectedOptions[1].text;
    }
    if (selectedOptions[2]) {
        selectedArea += "-" + selectedOptions[2].text;
    }

    fieldValue.value = selectedArea;

    form.value.city = selectedOptions[0].text;
    form.value.district = selectedOptions[1].text;
};

const handleSubmit = () => {
    // addrForm.value.submit()
};

const handleClose = () => {
    addrForm.value.resetValidation();
};

const onSubmit = async () => {
    let res = await addUserAddress(form.value);

    showOffcanvas.value = false;
    if (res.code === 200) {
        userAddr.value = res.data;
        return showToast("新增成功");
    } else {
        return showToast("新增失敗");
    }
};

const handleDelete = async (id) => {
    let res = await delUserAddress(id);

    if (res.code === 200) {
        userAddr.value = userAddr.value.filter((item) => {
            if (item.address_id !== id) {
                return item;
            }
        });
        showToast("刪除成功");
    } else {
        showToast("刪除失敗");
    }
};

const handleSetDefault = async (id) => {
    let res = await setUserAddressDefault(id);

    if (res.code === 200) {
        // userAddr.value = res.data
        userAddr.value = userAddr.value.map((item) => {
            if (item.address_id === id) {
                item.is_default = true;
            } else {
                item.is_default = false;
            }
            return item;
        });
        //判斷是否從order頁面過來，是的話就寫入piana及跳回checkout page
        if (route.query.from === "order") {
            let addr = userAddr.value.find((item) => {
                if (item.address_id === id) {
                    return item;
                }
            });

            orderStore.shipping = {
                shipping_code: "shipping",
                extra_data: {
                    address: addr.address,
                    consignee: addr.consignee,
                    tel: addr.tel,
                },
            };

            router.replace("/checkout");
        }
    }
};
</script>

<style lang="less" scoped>
.conten-box {
    width: 100%;
}

.heading {
    display: flex;
    justify-content: space-between;
    .heading-left {
        display: flex;
        h2 {
            margin: 0 10px;
        }
    }

    .heading-right {
    }
}
</style>
