<template>
    <page title="收货地址" ref="pageRef" nav-color="transparent">
        <empty v-if="isEmpty" :top="100" />
        <view>
            <cell
                v-for="(item, index) in list"
                :data="item"
                :key="index"
                @delete="onDelete(item)"
                @setAddress="setAddress(item)"
                :type="type"
            />
        </view>
        <view class="marginX14 marginT30">
            <cm-button  @click="showAdd">添加新地址</cm-button>
        </view>
    </page>
</template>

<script>
import empty from '@/components/empty'
import cell from './cell'
import loginMixin from '@/mixin/login'

export default {
    mixins: [loginMixin],
    components: { empty, cell },
    data() {
        return {
            list: [],
            isEmpty: false,
            type: 0, // 0正常进，1选择
            tradeNo: ''
        }
    },
    onLoad(options) {
        this.type = options.type
        this.tradeNo = options.tradeNo || ''
        this.$event.on(this.$event.key.ADDRESS, this.getData)
    },
    mounted() {
        setTimeout(() => {
            this.getData(true)
        }, 100)
    },
    onUnload() {
        this.$event.off(this.$event.key.ADDRESS)
    },
    onPullDownRefresh() {
        this.getData(false)
    },
    methods: {
        init() {
            this.getData()
        },
        async getData(loading = false) {
            const res = await this.$service.address.list(loading)
            this.list = res || []
            uni.stopPullDownRefresh()
            this.isEmpty = this.list.length === 0
        },
        showAdd() {
            this.$router.push('address_edit')
        },
        onDelete(item) {
            this.$message.confirm('确定删除吗?', async () => {
                const res = await this.$service.address.delete(item.id)
                res && this.getData(false)
            })
        },
        async setAddress(data) {
            if (this.tradeNo) {
                await this.$service.address
                    .updateAddress({
                        addressBookId: data.id,
                        tradeNo: this.tradeNo
                    })
                    .then(res => {
                        if (res.code === '0') {
                            this.$message.success('修改成功！')
                            this.$router.back()
                        }
                    })
            }
        }
    }
}
</script>