<template>
    <view class="page">
        <view class="form">
            <u-form :model="form" ref="uForm" label-width="180rpx" :error-type="['toast']" :rules="rules">
                <u-form-item label="您的姓名" prop="name">
                    <u-input v-model="form.name" placeholder="请输入您的姓名" />
                </u-form-item>
                <u-form-item label="联系方式" prop="mobile">
                    <u-input type="number" v-model="form.mobile" placeholder="请输入联系方式" />
                </u-form-item>
                <u-form-item label="所在地区">
                    <uni-data-picker v-model="selAddressCodes" :localdata="dataList" placeholder="请选择所在地区"
                        popup-title="请选择所在地区" @change="cityChange"></uni-data-picker>
                </u-form-item>
                <u-form-item label="详细地址" prop="detailAddress">
                    <u-input v-model="form.detailAddress" placeholder="请输入详细地址" />
                </u-form-item>
                <u-form-item :border-bottom="false" label="设为默认地址">
                    <u-switch slot="right" v-model="form.defaultFlag" :active-value="1" :inactive-value="0"
                        :active-color="appThemeColor" @change="changeDefaultFlag"></u-switch>
                </u-form-item>
            </u-form>
        </view>
        <view class="btn">
            <u-button type="primary" shape="circle" @click="submit">
                <u-icon name="plus"></u-icon>
                <text>保存地址</text>
            </u-button>
        </view>
    </view>
</template>

<script>
import CityPicker from '@/pages-mine/components/city-picker.vue';
export default {
    components: {
        CityPicker
    },
    data() {
        return {
            // 标题
            title: '收货地址',
            appThemeColor: this.$appTheme.appThemeColor,
            // 表单
            form: {
                id: '',
                "provinceId": '',
                "cityId": '',
                "districtId": '',
                "detailAddress": "",
                "name": "",
                "mobile": "",
                "defaultFlag": 0
            },
            // 表单校验规则
            rules: {
                name: [{
                    required: true,
                    message: '请输入收货人姓名',
                    trigger: ['change', 'blur'],
                }],
                mobile: [{
                    required: true,
                    message: '请输入手机号',
                    trigger: ['change', 'blur'],
                }, {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '请输入正确的手机号',
                    trigger: ['change', 'blur'],
                }],
                detailAddress: [{
                    required: true,
                    message: '请输入详细地址',
                    trigger: ['change', 'blur'],
                }],
            },
            // 省市区
            selAddressCodes: [],
            dataList: [],
        };
    },
    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
    onLoad(ops) {
        if (ops.id) {
            this.form.id = ops.id;
            this.form.type = 'edit';
            this.title = '修改地址';
            this.getAddressDetail(ops.id);
        } else {
            this.form.id = '';
            this.form.type = 'add';
            this.title = '新建地址';
        }
        uni.setNavigationBarTitle({
            title: this.title
        })

        uni.$u.http.get('/token/getAllDistrict').then(res => {
            if (res.code == 200) {
                this.dataList = res.data
            }
        })
    },
    methods: {
        // 设置默认地址
        changeDefaultFlag(value) {
            this.form.defaultFlag = value
        },

        // 省市区选择回调
        cityChange(e) {
            let {
                value
            } = e.detail
            if (!value.length) return
            this.form.provinceId = value[0].value;
            this.form.cityId = value[1].value
            this.form.districtId = value[2].value || ''
        },

        // 提交表单
        submit() {
            if (!this.form.provinceId) {
                uni.showToast({
                    title: '请选择所在地区',
                    icon: 'none'
                })
                return
            }

            this.$refs.uForm.validate(valid => {
                console.log(valid, 'valid')
                if (valid) {
                    let path = this.form.id ? '/token/user/address/update' : '/token/user/address/add'
                    uni.$u.http.post(path, this.form).then(res => {
                        if (res.code == 200) {
                            uni.showToast({
                                title: '操作成功',
                                icon: 'success'
                            });
                            uni.navigateBack();
                        } else {
                            uni.showToast({
                                title: res.msg,
                                icon: 'none'
                            })
                        }
                    })
                } 
            });
        },
        // 编辑
        getAddressDetail(id) {
            uni.showLoading();
            uni.$u.http.get(`/token/user/address/getDetail/${id}`).then((res) => {
                if (res.code == 200) {
                    this.form = res.data
                    this.selAddressCodes = [res.data.provinceId, res.data.cityId, res.data.districtId]
                }
            }).finally(() => {
                uni.hideLoading();
            })
        },
    }
};
</script>

<style lang="scss" scoped>
.form {
    background-color: $app-theme-bg-color;
    padding: 30rpx;
}

.btn {
    padding: 60rpx 30rpx;
}
</style>