<!--
 * @Author: euzhi
 * @Description: 编辑地址
-->
<template>
<view class="appCotent">
    <div class="editAddress">
        <u-gap bgColor="transparent" height="20"></u-gap>

        <div class="car_info">
            <u--form labelPosition="left" :model="model1" :rules="rules" ref="form1" labelWidth="100">
                <u-form-item label="收货人:" prop="addressInfo.userName" borderBottom ref="item1">
                    <u--input v-model="model1.addressInfo.userName" placeholder="请填写收货人姓名" border="none"></u--input>
                </u-form-item>
                <u-form-item label="手机号码:" prop="addressInfo.telNumber" borderBottom ref="item1">
                    <u--input v-model="model1.addressInfo.telNumber" placeholder="请填写收货人手机号码" border="none"></u--input>
                </u-form-item>
                <u-form-item label="收货地址:" prop="addressInfo.address" borderBottom ref="item1">
                    <u--input v-model="model1.addressInfo.address" placeholder="点击选择收货地址" border="none"></u--input>
                    <span @click.stop="getAuthorize">
                        <span class="app__gps">
                            <image src="@/static/my/gps.png">
                        </span>
                        <span class="app__right">
                            <image src="@/static/my/my6.png">
                        </span>
                    </span>
                </u-form-item>
                <u-form-item label="楼号门牌:" prop="addressInfo.detailInfo" borderBottom ref="item1">
                    <u--input v-model="model1.addressInfo.detailInfo" placeholder="例如  2栋3单元101室" border="none"></u--input>
                </u-form-item>
                <u-form-item label="设置默认地址:" prop="addressInfo.defaultFlag" ref="item1">
                    <u-switch class="del__address" v-model="model1.addressInfo.defaultFlag" activeColor="#5ac725"></u-switch>
                </u-form-item>

            </u--form>
        </div>
        <div class="add__tips">为保证您的商品准确送达，请填写正确的地址！</div>
        <div class="love__btn" @click="editAddress">
            保存地址
        </div>
        <div class="view__btn view__back" @click="del">
            删除该地址
        </div>
    </div>
</view>
</template>

<script>
export default {
    data() {
        return {
            carNumber: "",
            model1: {
                addressInfo: {},
                value: false,
            },
            rules: {
                "addressInfo.userName": {
                    type: "string",
                    required: true,
                    message: "收货人不能为空",
                    trigger: ["blur", "change"],
                },
                "addressInfo.telNumber": [{
                        type: "string",
                        required: true,
                        message: "手机号不能为空",
                        trigger: ["blur", "change"],
                    },
                    {
                        // 自定义验证函数，见上说明
                        validator: (rule, value, callback) => {
                            // 上面有说，返回true表示校验通过，返回false表示不通过
                            // uni.$u.test.mobile()就是返回true或者false的
                            return uni.$u.test.mobile(value);
                        },
                        message: '手机格式错误，请输入11位手机号',
                        // 触发器可以同时用blur和change
                        trigger: ['change', 'blur'],
                    }
                ],
                "addressInfo.address": {
                    type: "string",
                    required: true,
                    message: "收货地址不能为空",
                    trigger: ["blur", "change"],
                },
                "addressInfo.detailInfo": {
                    type: "string",
                    required: true,
                    message: "门牌号不能为空",
                    trigger: ["blur", "change"],
                },
            },
            //收货地址id
            id: '',
        };
    },
    methods: {
        goBack() {
            uni.navigateBack({
                delta: 1
            })
        },
        del() {
            uni.showModal({
                title: '提示',
                content: '确定删除该地址吗？',
                success: (res) => {
                    if (res.confirm) {
                        //提示删除成功
                        let opts = {
                            url: '/app/user/address/' + this.id,
                            method: 'delete'
                        };
                        this.http.httpTokenRequest(opts, {}).then(res => {
                            if (res.data.code == 200) {
                                uni.showToast({
                                    title: '删除成功',
                                    icon: 'success',
                                    duration: 2000
                                });
                                this.goBack()
                            }
                        })
                    } else if (res.cancel) {
                        //console.log('用户点击取消');
                    }
                }
            });
        },
        getAddress() {
            let opts = {
                url: '/app/user/address/info/' + this.id,
                method: 'get'
            };
            this.http.httpTokenRequest(opts, {}).then(res => {
                if (res.data.code == 200) {
                    this.model1.addressInfo = res.data.data
                }
            })
        },
        editAddress() {
            this.$refs.form1.validate().then(res => {
                let opts = {
                    url: '/app/user/address',
                    method: 'put'
                };
                this.http.httpTokenRequest(opts, this.model1.addressInfo).then(res => {
                    if (res.data.code == 200) {
                        //添加成功
                        uni.$u.toast('修改成功')
                        this.goBack()
                    }else{
                        uni.showModal({
                        	content: res.data.msg,
                        })
                    }
                })
            }).catch(errors => {
                uni.$u.toast('请正确填写信息')
            })
        },
        // 用户授权
        getAuthorize() {
            const _this = this
            uni.authorize({
                scope: 'scope.userLocation', // 获取地理信息必填的参数，其它参数见文档
                success(res) {
                    _this.getLocation()
                },
                // 授权失败
                fail(err) {
                    uni.showModal({
                        title: '温馨提示',
                        content: '无法获取当前位置，请手动开启授权',
                        success: function (res) {
                            if (res.confirm) {
                                //console.log('用户点击确定')
                                uni.openSetting({
                                    success(res) {
                                        if (res.authSetting['scope.userLocation']) {
                                            //console.log('打开授权设置定位')
                                            _this.getLocation()
                                        }
                                    },
                                })
                            } else if (res.cancel) {
                                //console.log('用户点击取消')
                            }
                        },
                    })
                },
            })
        },
        // 获取用户的地理位置，
        getLocation() {
            const _this = this
            uni.getLocation({
                type: 'wgs84',
                altitude: true,
                success(res) {
                    //小程序只能获取到位置经纬度，需要借助高德地图的逆解析地址，显示出中文具体城市名字
                    _this.loadCity(res.longitude, res.latitude)
                },
                fail() {
                    //console.log('拒绝获取地理位置')
                }
            })
        },
        // 经纬度转具体城市
        // 1）需要用到高德地图的逆地理编码
        // 2）需要当前地理位置的经纬度
        // 3）小程序的key值
        loadCity(longitude, latitude) {
            const that = this
            uni.request({
                header: {
                    'Content-Type': 'application/text',
                },
                //注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
                url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' +
                    longitude +
                    ',' +
                    latitude +
                    '&key=88cc9f2b486f21e85ef827131b3dd165&radius=1000&extensions=all',
                success(res) {
                    //console.log(res);
                    if (res.statusCode === 200) {
                        if (res.data.status === '1') {
                            let addressInfo = res.data
                            //详细地址
                            let detailInfo = addressInfo.regeocode.formatted_address
                            that.model1.addressInfo.address = detailInfo
                        }
                    } else {
                        //console.log('获取信息失败，请重试！')
                    }
                },
            })
        },
    },
    onLoad(option) {
        this.id = option.id
    },
    onShow() {
        this.getAddress()
    },

};
</script>

<style lang="scss" scoped>
.editAddress {
    .app__gps {
        display: inline-block;
            padding-left: 20rpx;
        image {
            width: 34rpx;
            height: 36rpx;
        }
    }

    .app__right {
        display: inline-block;
        padding-left: 20rpx;
        padding-bottom: 10rpx;

        image {
            width: 11rpx;
            height: 18rpx;
        }
    }

    .love__btn {
        height: 76rpx;
        background: url('@/static/move-car/love-car4.png') no-repeat;
        background-size: contain;
        font-size: 32rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #FFFFFF;
        line-height: 76rpx;
        text-align: center;
        width: 670rpx;
        margin: 0 auto;
        margin-top: 40rpx;
        margin-bottom: 30rpx;

        image {
            width: 30rpx;
            height: 30rpx;
            margin-right: 20rpx;

        }
    }

    .view__btn {
        width: 670rpx;
        height: 76rpx;
        text-align: center;
        line-height: 76rpx;
        margin: 0 auto;
        font-size: 32rpx;
    }

    .view__back {
        background: url('@/static/move-car/move-car-view1.png') no-repeat;
        background-size: contain;
        color: rgba(153, 153, 153, 1);
    }

    .add__tips {
        padding-left: 40rpx;
        font-size: 24rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #E1251B;
        line-height: 42px;
    }

    width: 100%;
    height: 100%;

    .car_info {
        padding: 20rpx 40rpx;
        background: #FFFFFF;
        box-shadow: 0rpx 0rpx 28rpx 1rpx rgba(232, 232, 232, 0.16);
        border-radius: 20rpx;

        /deep/ .u-form-item__body__right__content__slot {
            justify-content: flex-end;
            flex-direction: row !important;
        }
    }

}
</style>
