<template>
	<view class="page">
		<NoData v-if="!loading&&list.length<1"></NoData>
		<view class="list" v-else>
			<AddressCard v-for="item in list" :key="item.id" :address="item" :selected="item.id==selectId"
				@delete="deletePopup" @success="getAddressList" @tapItem="handleSelectAddr">
			</AddressCard>
		</view>
		<view class="bottom-fixed-con">
			<u-button class="flex-1" type="primary"
				@click="$u.route({ url: '/pages-mine/pages/address/add-or-update' })">
				<text>添加地址</text>
			</u-button>
		</view>

		<common-dialog ref="deleteDialog" title="温馨提示" @confirm="confirmDelete">
			<text>确定删除此地址信息吗？</text>
		</common-dialog>
	</view>
</template>

<script>
	import AddressCard from '@/pages-mine/components/address-card.vue';
	import commonDialog from '@/components/common-dialog.vue';
	export default {
		components: {
			AddressCard,
			commonDialog
		},
		data() {
			return {
				selectId: '',
				deleteId: '', //要删除的id
				isBack: false,
				loading: false,
				list: [],
				options: [{
						text: '设为默认',
						style: {
							backgroundColor: '#22ac38'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				]
			};
		},
		onLoad(ops) {
			if (ops.id) {
				this.selectId = ops.id
			}
		},
		onShow(ops) {
			this.getAddressList();
		},
		methods: {
			//选择地址
			handleSelectAddr(item) {
				console.log(item,'xxxx')
				uni.$emit('selectAddr', item)
				uni.navigateBack({delta:1})
			},
			//打开删除弹窗
			deletePopup(id) {
				this.deleteId = id
				this.$refs.deleteDialog?.openPopup()
			},
			// 删除
			confirmDelete() {
				this.$u.api.delAddressAjax(this.list[index].id).then(({
					code,
					data
				}) => {
					if (code == 1) {
						this.list.splice(index, 1);
						this.list[index].show = false;
					} else {
						this.$u.toast(`删除失败`);
					}
				})
			},
			// 设为默认
			setDefaultAddress({
				id
			}) {
				uni.$u.http.post(`/token/user/address/setDefault/${id}`).then(res => {
					if (res.code == 200) {
						uni.showToast({
							icon: "none",
							title: "设置默认地址成功"
						})
						this.getAddressList()
					} else {
						uni.showToast(res.msg)
					}
				})
			},
			open(index) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.list[index].show = true;
				this.list.map((val, idx) => {
					if (index != idx) this.list[idx].show = false;
				})
			},
			getAddressList() {
				this.loading = true;
				uni.$u.http.get('/token/user/address/list?content=' + '').then(res => {
					if (res.code == 200) {
						this.list = res.data;
					}
				}).finally(() => this.loading = false)
			}
		},
	};
</script>

<style lang="scss" scoped>
	.list {
		padding: 20rpx 30rpx 180rpx;
		box-sizing: border-box;
	}
</style>