<template>
    <view class="address-list">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <!-- 收货地址为空 -->
        <template v-if="list.length === 0">
            <tui-no-data :imgUrl="staticUrl + 'icon-empty-address.png'" :imgHeight="230" :imgWidth="290">
                <view class="empty-tip">您还没有收货地址</view>
                <view class="empty-tip">点击底部按钮添加收货地址吧~~</view>
            </tui-no-data>
        </template>
        <!-- 收货地址列表 -->
        <template v-else>
            <view class="address" v-for="item in list" :key="item.addressId" @click="chooseAddress(item)">
                <text v-if="item.defaultFlag == 1" class="default-tag">默认</text>
                <view class="contact">
                    <text class="name" v-text="item.shouHuoRen"></text>
                    <text class="mobile" v-text="item.mobile"></text>
                </view>
                <view class="detail">
                    <text class="opacity">收货地址：</text>
                    {{ item.provinceName }}{{ item.cityName }}{{ item.townName }}{{ item.address }}
                </view>
                <view class="control">
                    <view class="default">
                        <view class="iconfont icon-xuanze icon" v-if="item.defaultFlag == 1">
                            <text class="opacity">已设为默认地址</text>
                        </view>
                        <view class="iconfont icon-weixuanze" v-else @click.stop="setDefalut(item)">
                            <text class="opacity">设为默认地址</text>
                        </view>
                    </view>
                    <view class="update">
                        <text
                            class="iconfont icon-shanchu"
                            @click.stop="handleRemoveAddress(item)"
                            v-if="type !== 'choose'"
                        >
                            删除
                        </text>
                        <text class="iconfont icon-bianji" @click.stop="editAddress(item)">编辑</text>
                    </view>
                </view>
            </view>
            <cm-loadmore :hasMore="hasNextPage" :isLoading="isLoading" :visiable="visiable"></cm-loadmore>
        </template>

        <tui-button
            class="create"
            type="base"
            :size="28"
            width="650rpx"
            height="88rpx"
            shape="circle"
            @click="createAddress"
        >
            添加新地址
        </tui-button>

        <!-- 确认弹框 -->
        <tui-modal :show="removeModal" content="确认删除该地址吗？" @click="modalClick"></tui-modal>
    </view>
</template>

<script>
import { fetchAddressList, removeAddress, setDefaultAddress } from '@/services/api/user.js'
import { debounce } from '@/common/utils.js'
import { mapGetters } from 'vuex'
export default {
    data() {
        return {
            type: 'list',
            isRequest: true,
            isLoading: false,
            listQuery: {
                userId: 0,
                pageNum: 1,
                pageSize: 10
            },
            list: [],
            total: 0,
            hasNextPage: true,
            removeModal: false,
            currentRemove: null // 当前选中需要被删除的地址
        }
    },
    computed: {
        ...mapGetters(['userId']),
        visiable() {
            return this.list.length > this.listQuery.pageSize
        }
    },
    onLoad(options) {
        this.type = options.type

        this.initAddressList()
    },
    onShow() {
        if (this.$router.checkRefreshType('createAddressBack')) {
            this.initAddressList()
        }
    },
    onReachBottom() {
        this.fetchAddressList()
    },
    methods: {
        // 选择收货地址
        chooseAddress(item) {
            if (this.type !== 'choose') {
                return
            }
            this.$router.addRefreshType('chooseAddress')
            uni.setStorageSync('CHOOSE_ADDRESS', item)
            this.$router.navigateBack()
        },

        // 新增收货地址
        createAddress() {
            this.$router.navigateTo('address/address-create?type=add')
        },

        // 编辑收货地址
        editAddress(item) {
            uni.setStorageSync('eidtAddress', item)
            this.$router.navigateTo('address/address-create?type=edit')
        },

        // 删除收货地址事件
        handleRemoveAddress(item) {
            this.currentRemove = item
            this.removeModal = true
        },

        // 删除收货地址
        async removeAddress() {
            try {
                const { addressId } = this.currentRemove
                await removeAddress({ userId: this.listQuery.userId, addressId })
                this.$toast.success('删除地址成功')
                const index = this.list.findIndex(item => item.addressId === addressId)
                this.list.splice(index, 1)
            } catch (e) {
                console.log(e)
            } finally {
                this.removeModal = false
            }
        },

        // 删除确认框事件
        modalClick({ index }) {
            if (!index) return (this.removeModal = false)
            this.removeAddress()
        },

        // 设为默认地址
        async setDefalut(item) {
            try {
                const userId = this.listQuery.userId
                const addressId = item.addressId
                await setDefaultAddress({ userId, addressId })
                this.$toast.success('默认地址修改成功')
                // 更新列表信息
                const find = this.list.find(item => item.defaultFlag === '1')
                if (find) {
                    find.defaultFlag = '0'
                }
                item.defaultFlag = '1'
            } catch (e) {
                //TODO handle the exception
            }
        },

        // 初始化地址列表
        initAddressList() {
            this.listQuery.userId = this.userId
            this.listQuery.pageNum = 1
            this.list = []
            this.hasNextPage = true
            this.fetchAddressList()
        },

        // 获取地址列表
        fetchAddressList: debounce(async function() {
            if (!this.hasNextPage) return
            this.isLoading = true
            try {
                const res = await fetchAddressList(this.listQuery)
                this.list = [...this.list, ...res.data.list]
                this.total = res.data.total
                this.hasNextPage = res.data.hasNextPage
                this.listQuery.pageNum++
            } catch (e) {
                console.log(e)
            } finally {
                this.isRequest = false
                this.isLoading = false
                uni.stopPullDownRefresh()
            }
        }, 500)
    }
}
</script>

<style lang="scss" scoped>
.address-list {
    color: #333;
    padding-bottom: 138rpx;
    overflow: hidden;

    .create {
        position: fixed;
        left: 50rpx;
        bottom: 50rpx;
        z-index: 9;
    }

    .address {
        position: relative;
        padding: 24rpx;
        margin: 24rpx 0;
        background-color: #fff;

        .default-tag {
            position: absolute;
            right: 24rpx;
            top: 24rpx;
            font-size: 22rpx;
            padding: 0 24rpx;
            line-height: 40rpx;
            background: #f83c6c;
            color: #fff;
            border-radius: 20rpx;
        }

        .contact {
            @include ellipsis(1);
            font-size: 30rpx;
            font-weight: bold;
            .name {
                margin-right: 24rpx;
            }
        }

        .detail {
            // @include ellipsis(1);
            margin: 8rpx 0;
            max-width: 650rpx;
            font-size: 28rpx;
            color: #333;
        }
    }

    .control {
        @extend .cm-flex-between;
        .iconfont {
            font-size: 24rpx;
        }
        .default {
            .opacity {
                margin-left: 8rpx;
            }
        }

        .update {
            .icon-shanchu {
                margin-right: 40rpx;
            }
        }
    }

    .opacity {
        opacity: 0.8;
        color: #333;
    }
}
</style>
