<template>
    <!-- 收货地址空状态 -->
    <!-- 收货地址的列表数据 -->
    <view class="address-list">
        <view v-if="!type" class="text-error fixed top-0 left-0 pl-[20rpx] pt-[20rpx]">
            点击地址，将该地址设为默认地址
        </view>
        <z-paging
            auto-show-back-to-top
            ref="paging"
            v-model="addressList"
            @query="queryList"
            :fixed="false"
            use-page-scroll
            height="100%"
        >
            <view :style="{ 'padding-top': !type ? '62rpx' : '0' }">
                <block v-for="(item, index) in addressList" :key="item.id">
                    <view
                        class="address-list--item flex justify-between mt-[20rpx]"
                        :data-id="item.id"
                        @click.stop="onSelect(item)"
                    >
                        <view class="flex-1">
                            <view>
                                <text class="text-xl font-medium">
                                    {{ item.contact }} {{ item.mobile }}
                                </text>
                                <text class="default" v-if="item.isDefault">默认</text>
                            </view>
                            <view class="mt-[20rpx] sm text-muted">
                                {{ item.province }}
                                {{ item.city }}
                                {{ item.district }}
                                {{ item.address }}
                            </view>
                        </view>
                        <view class="setting" @click.stop="goEditAddress(item.id)">编辑</view>
                    </view>
                </block>
            </view>
        </z-paging>
    </view>

    <view class="fixed flex items-center justify-between bg-white footer">
        <!-- #ifdef H5 || MP-WEIXIN -->
        <!-- <view v-if="isWeixin" class="mr-[20rpx]">
            <button
                class="bg-color text-lg text-black border-none rounded-full flex items-center justify-center leading-[80rpx] h-[80rpx]"
                @click="getWxAddressFun"
            >
                <image
                    class="icon-md mr-[10rpx]"
                    :src="'../../static/images/icon_wechat.png'"
                ></image>
                微信导入
            </button>
        </view> -->
        <!-- #endif -->
        <view>
            <button
                class="text-lg text-white rounded-full leading-[80rpx] h-[80rpx] custom-button-bgColor"
                @click="goEditAddress('')"
            >
                添加地址
            </button>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { getGeocoder } from '@/api/app'
import { apiAddressEdit, apiAddressLists } from '@/api/user'
import { wxOaAddress } from '@/hooks/wechat'
import { useUserStore } from '@/stores/user'
import { isWeixinClient } from '@/utils/client'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { ref, shallowRef } from 'vue'

const paging = shallowRef<any>(null)
const type = ref(false)
const addressList = ref<any>([]) // 地址数据列表
const isWeixin = ref(true) // 是不是微信，如果是就显示微信导入地址按钮
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

// 获取地址列表
const queryList = async (pageNo, pageSize) => {
    try {
        const { lists } = await apiAddressLists({ pageNo, pageSize })
        paging.value.setLocalPaging(lists)
        if (lists.length > 0) {
            uni.$emit('address', lists[0])
        }
    } catch (e) {
        console.log('报错=>', e)
        //TODO handle the exception
        paging.value.setLocalPaging(false)
    }
}

// 选择当前地址作为支付地址
const onSelect = async (data: any) => {
    try {
        if (type.value) {
            uni.$emit('address', data)
            uni.navigateBack()
        } else {
            await apiAddressEdit({
                ...data,
                isDefault: 1,
                userId: userInfo.value.id
            })
            uni.redirectTo({
                url: '/bundle/pages/user_address/index'
            })
        }
    } catch (error) {
        console.log(error, '设置默认地址捕捉错误')
    }
}

// 编辑地址
const goEditAddress = (params = '') => {
    uni.navigateTo({
        url: `/bundle/pages/user_address_edit/index?id=${params}`
    })
}

// 微信导入地址
const getWxAddressFun = async () => {
    // #ifdef H5
    try {
        const res = await wxOaAddress()
        getLocation(res.cityName + res.countyName + res.detailInfo, res)
    } catch (error) {
        console.log('捕捉微信公众号导入地址报错', error)
    }
    // #endif
    // #ifdef MP-WEIXIN
    const { errMsg } = await uni.authorize({ scope: 'scope.address' })
    if (errMsg === 'authorize:ok') {
        try {
            const res = await uni.chooseAddress()
            console.log(res)
            getLocation(res.cityName + res.countyName + res.detailInfo, res)
        } catch (error) {
            console.log('导入微信地址地址', error)
        }
    }
    // #endif
}

// 解析地址转坐标d
const getLocation = async (address: string, address_info: any) => {
    try {
        const res = await getGeocoder({ keyWord: address })
        const obj = {
            latitude: res.lat,
            longitude: res.lng,
            name: address_info.userName,
            mobile: address_info.telNumber
        }
        console.log('obj', obj)

        uni.setStorageSync('wxAddress', JSON.stringify(obj))
        goEditAddress()
    } catch (error) {
        console.log('逆解析地址', error)
    }
}

onShow(() => {
    paging.value?.reload()
})

onLoad((options: { type?: boolean }) => {
    if (options.type) type.value = options.type
    //#ifdef H5
    isWeixin.value = isWeixinClient()
    //#endif
})

onUnload(() => {
    uni.$emit('changeAddress')
})
</script>
<style lang="scss">
page {
    // overflow: hidden;
    padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
}

.icon-md {
    width: 48rpx;
    height: 48rpx;
    vertical-align: top;
}

.address-list {
    &--item {
        border-radius: 14rpx;
        background-color: #ffffff;
        margin: 20rpx 20rpx 0 20rpx;
        padding: 30rpx 30rpx 36rpx 30rpx;

        .default {
            padding: 0 4rpx;
            margin-left: 20rpx;
            color: #f36161;
            font-size: 22rpx;
            background: rgba(#f36161, 0.1);
        }

        .setting {
            height: 90rpx;
            width: 100rpx;
            line-height: 90rpx;
            text-align: right;
            color: $blue5;
            font-size: 26rpx;
        }
    }
}

.footer {
    z-index: 999;
    left: 0;
    right: 0;
    bottom: 0;
    height: 118rpx;
    line-height: 118rpx;
    position: fixed;
    padding: 0 30rpx;
    box-sizing: content-box;
    padding-bottom: env(safe-area-inset-bottom);

    > view {
        width: 100%;
    }
}
</style>
