<template>
	<view class="page">
		<NoData v-if="!loading&&list.length<1"></NoData>
		<view class="list" v-else>
			<!-- @open="open" -->
			<u-swipe-action :show="item.show" :index="index" 
						v-for="(item, index) in list" :key="item.id" 
						@click="click" 
						:options="options"
						@open="open"
					>
					<AddressCard  :isBack="isBack" :data="item" :showEdit="!isSelect" :showBorderBottom="index != list.length - 1"></AddressCard>
			</u-swipe-action>
			
		</view>
		<view class="btn">
			<u-button type="primary" shape="circle" @click="$u.route({ url: '/pages-mine/pages/address/add-or-update' })">
				<u-icon name="plus"></u-icon>
				<text>新建收货地址</text>
			</u-button>
		</view>
	</view>
</template>

<script>
import AddressCard from '@/pages/mine/components/address-card.vue';
export default {
	components: {
		AddressCard
	},
	data() {
		return {
			isSelect: false,
			isBack: false,
			loading:false,
			list: [],
			options: [
				{
					text: '设为默认',
					style: {
						backgroundColor: '#22ac38'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}
			]
		};
	},
	onLoad(ops) {
		if (ops.isSelect) {
			this.isSelect = ops.isSelect;
			this.isBack = ops.isBack;
		}
		// this.getAddressList();
	},
	onShow(ops) {
		this.getAddressList();
	},
	methods:{
		click(index, index1) {
			if(index1 == 1) {
				this.delFun(index);
			} else {
				this.setDefaultAddress(index);
			}
		},
		// 删除
		delFun(index) {
			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(index) {
			this.$u.api.setDefaultAddressAjax(this.list[index].id).then(({code,data})=>{
				uni.hideLoading();
				if(code==1){
					this.list.forEach(e=>{
						e.is_default = 0;
						e.show = false;
					})
					this.list[index].is_default = 1;
				}
			})
		},
		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;
			this.$u.api.getAddressListAjax().then(({code,data})=>{
				this.loading = false;
				if(code==1){
					data.forEach(e=>{
						e.show = false;
					})
					this.list = data;
					console.log(this.list);
				}
			}).catch(()=>{
				this.loading = false;
			})
		},
	},
};
</script>

<style lang="scss" scoped>
.page {
	background-color: $app-theme-bg-color;
}
.list {
	padding: 0 30rpx 180rpx;
	// height: calc(100vh - 200rpx);
}
.btn {
	position: fixed;
	bottom: 40rpx;
	left: 0;
	padding: 30rpx;
	width: 100%;
	text {
		margin-left: 8rpx;
	}
}
</style>
