<template>
    <view>
        <view class="add-address">
            <view class="add-form">
                <view class="form-item">
                    <view class="label">联系人</view>
                    <view class="content">
                        <input class="input" @input="bindinputName" placeholder="姓名" :value="address.name" auto-focus />
                    </view>
                </view>
                <view class="form-item">
                    <view class="label">电 话</view>
                    <view class="content">
                        <input class="input" @input="bindinputMobile" :value="address.tel" type="number" placeholder="手机号码" maxlength="11" />
                    </view>
                </view>
                <!-- bindtap="chooseRegion" -->
                <view class="form-item" @tap="goMap">
                    <view class="label">服务地址</view>
                    <view class="content">
					   <view style="flex: 1;">
						   <view class="address-name" v-if="address.addressName" style="height: 36rpx;line-height: 36rpx;font-weight: bold;">
						   	{{address.addressName}}
						   </view>
						<input class="input input1" :value="address.province + address.city + address.county+address.address" :disabled="true" placeholder="请选择服务地址" placeholder-class="custom-placeholder"/>
					   </view>
                        
                        <image src="/static/images/arrow.png" style="width: 12rpx; height: 20rpx; margin-right: 10rpx;margin-top: 10rpx;"></image>
                    </view>
                </view>
    
                <view class="form-item">
                    <view class="label">门牌号</view>
                    <view class="content">
                        <input class="input" @input="bindinputAddress" :value="address.detail" placeholder="例：9号楼1505室" />
                    </view>
                </view>
            </view>

            <view class="form-default">
                <view style="display: flex; flex-direction: column">
                    <text class="title">设为默认地址</text>
                    <text class="des">提醒：每次下单会默认推荐使用该地址</text>
                </view>
                <switch style="margin-right: 10rpx" :checked="address.isDefault == 1" @change="bindIsDefault" />
            </view>

            <view class="form-item" v-if="address.id > 0">
                <button style="background: #d77958; color: white" :data-address-id="address.id" @tap="deleteAddress">删除地址</button>
            </view>

            <view class="btns">
                <view class="save" @tap="saveAddress">保存</view>
                <view class="cannel" @tap="cancelAddress">取消</view>
            </view>

            <view class="region-select" v-if="openSelectRegion">
                <view class="hd">
                    <view class="region-selected">
                        <view
                            :class="'item ' + (item.code == 0 ? 'disabled' : '') + ' ' + (regionType - 1 === index ? 'selected' : '')"
                            @tap="selectRegionType"
                            :data-region-type-index="index"
                            v-for="(item, index) in selectRegionList"
                            :key="index"
                        >
                            {{ item.name }}
                        </view>
                    </view>
                    <view :class="'done ' + (selectRegionDone ? '' : 'disabled')" style="color: #d77958;" @tap="doneSelectRegion">确定</view>
                </view>
                <view class="bd">
                    <scroll-view scroll-y class="region-list">
                        <view :class="'item ' + (item.selected ? 'selected' : '')" @tap="selectRegion" :data-region-index="index" v-for="(item, index) in regionList" :key="index">
                            {{ item.name }}
                        </view>
                    </scroll-view>
                </view>
            </view>
        </view>
        <view class="bg-mask" @tap="cancelSelectRegion" v-if="openSelectRegion"></view>
    </view>
</template>

<script>
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var check = require('../../../utils/check.js');
var area = require('../../../utils/area.js');
var map = require('../../../utils/map.js');
const chooseLocation = requirePlugin('chooseLocation');
var app = getApp();
import {Dialog} from "@vant/weapp/lib/dialog/index.js"
export default {
    data() {
        return {
            address: {
                id: 0,
                areaCode: 0,
                address: '',
                name: '',
                tel: '',
                isDefault: 0,
                province: '',
                city: '',
                county: '',
                lat: '',
                lng: '',
                addressDetail: '',
                detail: '',
                addressName: ''
            },

            addressId: 0,
            openSelectRegion: false,

            selectRegionList: [
                {
                    code: 0,
                    name: '省份'
                },
                {
                    code: 0,
                    name: '城市'
                },
                {
                    code: 0,
                    name: '区县'
                }
            ],

            regionType: 1,
            regionList: [],
            selectRegionDone: false,
            selectAddress: '',
			showDeleteDialog:false,
			addressIId:0
        };
    },
    onLoad: function (options) {
        // 页面初始化 options为页面跳转所带来的参数
        //console.log(options)
        if (options.id && options.id != 0) {
            this.setData({
                addressId: options.id
            });
            this.getAddressDetail();
        }
        //初始化area
        //area.init();
    },


    onShow: function () {
        let that = this;
        if (app.globalData.mapSelectFinish) {
            let poi = app.globalData.mapSelectPoi;
            let location = poi.location;
            let address = that.address;
            address.lng = location.split(',')[0];
            address.lat = location.split(',')[1];
            address.addressName = poi.name;
            address.address = poi.address;
            address.areaCode = poi.areaCode;
            address.province = poi.province;
            address.city = poi.city;
            address.county = poi.county;
			console.log("address",address);
            if (!address.city) {
                that.getAreaCode(address.lat, address.lng)
                    .then((res) => {
                        address.areaCode = res.areaCode;
                        address.province = res.province;
                        address.city = res.city;
                        address.county = res.county;
                        that.setData({
                            address: address,
                            selectAddress: poi.address
                        });
                    })
                    .catch(() => {
                        uni.showToast({
                            title: '获取地区码失败',
                            icon: 'none',
                            duration: 3000
                        });
                    });
            } else {
                that.setData({
                    address: address,
                    selectAddress: poi.address
                });
            }
        } else {
            //这里分2种情况 1，有城市 标识选中原有地址进来 保持不变
            //2，新增地址 初始化进入此页面时 需要调用getlocation2
            if (that.addressId) {
                return;
            } //从已有地址进入

            // map.getLocation2().then(() => {
            //     that.getAreaCode(app.globalData.lat, app.globalData.lng)
            //         .then((res) => {
            //             res.isDefault = that.address.isDefault;
            //             // console.log('globalData',app.globalData.lat,app.globalData.lng)
            //             // console.log('areaCode',res)
            //             that.setData({
            //                 address: res,
            //                 selectAddress: res
            //             });
            //         })
            //         .catch((err) => {
            //             uni.showToast({
            //                 title: '获取地区码失败',
            //                 icon: 'none',
            //                 duration: 3000
            //             });
            //         });
            // });
        }
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
        chooseLocation.setLocation(null);
    },
    methods: {
        bindinputMobile(event) {
            let address = this.address;
            address.tel = event.detail.value;
            this.setData({
                address: address
            });
        },

        bindinputName(event) {
            let address = this.address;
            address.name = event.detail.value;
            this.setData({
                address: address
            });
        },

        bindinputAddress(event) {
            let address = this.address;
            address.detail = event.detail.value.replace(/[,，]/g, '');
            this.setData({
                address: address
            });
        },

        bindIsDefault() {
            let address = this.address;
            address.isDefault = !address.isDefault;
            this.setData({
                address: address
            });
        },

        getAddressDetail() {
            let that = this;
            util.request(api.AddressDetail, {
                id: that.addressId
            }).then(function (res) {
                if (res.errno === 0) {
                    if (res.data) {
                        that.setData({
                            address: res.data
                        });
                        let addressDetailList = res.data.addressDetail.split(',');
                        let address = that.address;
                        address.address = addressDetailList[0];
                        address.detail = addressDetailList.length > 1 ? addressDetailList[1] : '';
                        that.setData({
                            address: address
                        });
                    }
                }
            });
        },

        setRegionDoneStatus() {
            let that = this;
            let doneStatus = that.selectRegionList.every((item) => {
                return item.code != 0;
            });
            that.setData({
                selectRegionDone: doneStatus
            });
        },

        cancelAddress() {
            uni.navigateBack();
        },

        saveAddress() {
            console.log(this.address);
            let address = this.address;
            if (address.name == '') {
                util.showErrorToast('请输入姓名');
                return false;
            }
            if (address.tel == '') {
                util.showErrorToast('请输入手机号码');
                return false;
            }
            if (address.areaCode == 0) {
                util.showErrorToast('请输入省市区');
                return false;
            }
            if (address.address == '') {
                util.showErrorToast('请选择地址');
                return false;
            }
            if (!check.isValidPhone(address.tel)) {
                util.showErrorToast('手机号不正确');
                return false;
            }
            let that = this;
            let addressString = address.detail == '' ? address.address : address.address + ',' + address.detail;
            util.request(
                api.AddressSave,
                {
                    shopId: app.globalData.shopId ? app.globalData.shopId : '',
                    id: address.id,
                    name: address.name,
                    tel: address.tel,
                    province: address.province,
                    city: address.city,
                    county: address.county,
                    areaCode: address.areaCode,
                    addressDetail: addressString,
                    addressName: address.addressName,
                    isDefault: address.isDefault,
                    lat: Number(address.lat).toFixed(5),
                    lng: Number(address.lng).toFixed(5)
                },
                'POST'
            ).then(function (res) {
                if (res.errno === 0) {
                    //返回之前，先取出上一页对象，并设置addressId
                    var pages = getCurrentPages();
                    var prevPage = pages[pages.length - 2];
                    console.log(prevPage);
                    if (prevPage.route == 'pages/index/index') {
                        var city = address.city.indexOf('市') < 0 ? address.province : address.city;
                        var addresInfo = {
                            city: city,
                            lng: res.data.lng,
                            lat: res.data.lat,
                            shopId: res.data.shopId,
                            address: res.data.addressDetail
                        };
                        uni.setStorageSync('addressInfo', address);
                    } else if (prevPage.route == 'pages/ucenter/serviceDetail/serviceDetail') {
                        uni.setStorageSync('addressInfo', addresInfo);
                    } else if (prevPage.route == 'pages/checkout/checkout') {
                        prevPage.setData({
                            addressId: res.data.id
                        });
                        try {
                            uni.setStorageSync('addressId', res.data);
                        } catch (e) {
                            console.log('CatchClause', e);
                        }
                        console.log('set address');
                    }
                    uni.navigateBack();
                } else {
                    uni.showModal({
                        title: '提醒',
						confirmColor:"#d77958",
                        showCancel: false,
                        content: res.errmsg
					
                    });
                }
            });
        },

        deleteAddress(event) {
           console.log(event.target);
            let that = this;
            uni.showModal({
                title: '',
                content: '确定要删除地址？',
				 confirmColor: '#d77958',
                success: function (res) {
                    if (res.confirm) {
                        let addressId = event.target.dataset.addressId;
                        util.request(
                            api.AddressDelete,
                            {
                                id: addressId
                            },
                            'POST'
                        ).then(function (res) {
                            if (res.errno === 0) {
                                uni.navigateBack({
                                    delta: 1,
                                    success: function () {}
                                });
                            }
                        });

                        console.log('用户点击确定');
                    }
                }
            });
            return false;
		this.setData({
		   // showDeleteDialog:true,
		   addressIId:event.target.dataset.addressId
		});
			
        },
		cancelDelete(){
			this.setData({
			   showDeleteDialog:false
			});
		},
		confirmDelete(){
			util.request(
			    api.AddressDelete,
			    {
			        id: this.addressIId
			    },
			    'POST'
			).then(function (res) {
			    if (res.errno === 0) {
			        uni.navigateBack({
			            delta: 1,
			            success: function () {}
			        });
					console.log("shanchuchenggong");
			    }
			});
		},

        goMapOld() {
            // const key = "JA2BZ-XGOEU-UNZVD-46G64-S6MYJ-6BBF4";
            //使用在腾讯位置服务申请的key
            const key = '6TRBZ-XXC6F-BWWJB-N75ME-BQNOF-YKFQY';
            const referer = '鲸致生活LifePlus'; //调用插件的app的名称

            const category = '小区,生活服务,娱乐休闲';
            if (this.address.lat) {
                const location = JSON.stringify({
                    latitude: Number(this.address.lat),
                    longitude: Number(this.address.lng)
                });
                uni.navigateTo({
                    url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&category=' + category + '&location=' + location
                });
            } else {
                uni.navigateTo({
                    url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&category=' + category
                });
            }
        },

        goMap() {
            app.globalData.mapSelectFinish = false;
            if (this.address.lng && this.address.lat) {
                let city = this.address.city == '市辖区' ? this.address.province : this.address.city;
                uni.navigateTo({
                    url: '/pages/map/mapContent/mapContent?lng=' + this.address.lng + '&lat=' + this.address.lat + '&addressname=' + this.address.address + '&city=' + city
                });
            } else {
                uni.navigateTo({
                    url: '/pages/map/mapContent/mapContent'
                });
            }
        },

        getAreaCodeOld() {
            let param = {
                location: this.address.lng + ',' + this.address.lat,
                extensions: 'all',
                key: api.gdKey,
                radius: 3000
            };
            uni.request({
                url: api.gdUrl,
                data: param,
                method: 'GET',
                header: {
                    'Content-Type': 'application/json'
                },
                success: (res) => {
                    console.log(res);
                    if (res.data.infocode == '10000') {
                        if (res.data.info == 'OK') {
                            // let ad_info = res.data.result.ad_info;
                            // let areaCode = res.data.result.ad_info.adcode;
                            // this.setData({
                            //   ['address.areaCode']: areaCode,
                            //   ['address.province']: ad_info.province,
                            //   ['address.city']: ad_info.city,
                            //   ['address.county']: ad_info.district,
                            // });
                            let regeocode = res.data.regeocode.addressComponent;
                            let cityName = regeocode.city == null || regeocode.city.length == 0 ? regeocode.province : regeocode.city;
                            let district = regeocode.district == null || regeocode.district.length == 0 ? '' : regeocode.district;
                            this.setData({
                                ['address.areaCode']: regeocode.adcode,
                                ['address.province']: regeocode.province,
                                ['address.city']: cityName,
                                ['address.county']: district
                            });
                        } else {
                            uni.showToast({
                                title: '获取地区码失败',
                                icon: 'none',
                                duration: 3000
                            });
                        }
                    } else {
                        uni.showToast({
                            title: '获取地区码失败',
                            icon: 'none',
                            duration: 3000
                        });
                    }
                },
                fail: function (err) {
                    reject(err);
                }
            });
        },

        getAreaCode(lat, lng) {
            return new Promise(function (resolve, reject) {
                let param = {
                    location: lng + ',' + lat,
                    extensions: 'all',
                    key: api.gdKey,
                    radius: 3000
                };
                uni.request({
                    url: api.gdUrl,
                    data: param,
                    method: 'GET',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    success: (res) => {
                        console.log(res);
                        if (res.data.infocode == '10000') {
                            if (res.data.info == 'OK') {
                                // console.info(res.data)
                                let regeocode = res.data.regeocode.addressComponent;
                                let cityName = regeocode.city == null || regeocode.city.length == 0 ? regeocode.province : regeocode.city;
                                let district = regeocode.district == null || regeocode.district.length == 0 ? '' : regeocode.district;
                                let address = {
                                    lat: lat,
                                    lng: lng,
                                    areaCode: regeocode.adcode,
                                    province: regeocode.province,
                                    city: cityName,
                                    county: district,
                                    address: res.data.regeocode.formatted_address,
                                    addressName: regeocode.township //纯粹做显示
                                };

                                console.log(address);
                                resolve(address);
                            } else {
                                reject(false);
                            }
                        } else {
                            reject(false);
                        }
                    },
                    fail: function (err) {
                        reject(false);
                    }
                });
            });
        },

        selectRegionType() {
            console.log('占位：函数 selectRegionType 未声明');
        },

        doneSelectRegion() {
            console.log('占位：函数 doneSelectRegion 未声明');
        },

        selectRegion() {
            console.log('占位：函数 selectRegion 未声明');
        },

        cancelSelectRegion() {
            console.log('占位：函数 cancelSelectRegion 未声明');
        }
    }
};
</script>
<style>
page {
    height: 100%;
    background: #f4f4f4;
}

.add-address .add-form {
    background: #fff;
    width: 100%;
    height: auto;
    overflow: hidden;
}

.add-address .form-item {
    height: 116rpx;
    padding-left: 31.25rpx;
    display: flex;
    align-items: center;
    padding-right: 31.25rpx;
}

.add-address .input {
    flex: 1;
    height: 44rpx;
    line-height: 44rpx;
    overflow: hidden;
   margin-top: 10rpx;
}
.add-address .input1 {
   color: #999999;
}
.custom-placeholder {
  font-size: 28rpx;
  color: #d77958;
  letter-spacing: 2rpx;
  font-weight: 500;
}
.add-address .label {
    font-size: 32rpx;
    font-weight: bold;
    margin-right: 50rpx;
    width: 170rpx;
    text-align: center;
}
.add-address .content {
    border-bottom: 1px solid #d9d9d9;
    height: 116rpx;
    line-height: 116rpx;
    align-content: center;
    width: 100%;
    display: flex;
    align-items: center;
}

.add-address .form-default {
    border-bottom: 1px solid #d9d9d9;
    height: 136rpx;
    background: #fff;
    padding-top: 28rpx;
    font-size: 28rpx;
    padding-left: 31.25rpx;
    margin-top: 30rpx;
    display: flex;
    justify-content: space-between;
}

.add-address .form-default .title {
    font-size: 32rpx;
    font-weight: bold;
}
.add-address .form-default .des {
    color: #b2b2b2;
    line-height: 46rpx;
    height: 40rpx;
}

.add-address .form-default .van-checkbox .van-icon {
    color: #fff;
}

.add-address .btns {
    position: fixed;
    bottom: 0rpx;
    left: 0;
    overflow: hidden;
    width: 100%;
    margin-bottom: 25rpx;
}

.add-address .cannel,
.add-address .save {
	width: 650rpx;
    height: 81rpx;
    text-align: center;
    line-height: 81rpx;
    font-size: 36rpx;
    color: #fff;
    border: none;
    border-radius: 60rpx;
	margin-left: 50rpx;
	
}

.add-address .cannel {
	margin-top: 20rpx;
    background: #EAD2C1;
    color: #999;
}

.add-address .save {
    background: #d77958;
}

.region-select {
    width: 100%;
    height: 600rpx;
    background: #fff;
    position: fixed;
    z-index: 10;
    left: 0;
    bottom: 0;
}

.region-select .hd {
    height: 108rpx;
    width: 100%;
    border-bottom: 1px solid #f4f4f4;
    padding: 46rpx 30rpx 0 30rpx;
}

.region-select .region-selected {
    float: left;
    height: 60rpx;
    display: flex;
}

.region-select .region-selected .item {
    max-width: 140rpx;
    margin-right: 30rpx;
    text-align: left;
    line-height: 60rpx;
    height: 100%;
    color: #333;
    font-size: 28rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.region-select .region-selected .item.disabled {
    color: #999;
}

.region-select .region-selected .item.selected {
    color: #b4282d;
}

.region-select .done {
    float: right;
    height: 60rpx;
    width: 60rpx;
    border: none;
    background: #fff;
    line-height: 60rpx;
    text-align: center;
    color: #333;
    font-size: 28rpx;
}

.region-select .done.disabled {
    color: #999;
}

.region-select .bd {
    height: 492rpx;
    width: 100%;
    padding: 0 30rpx;
}

.region-select .region-list {
    height: 492rpx;
}

.region-select .region-list .item {
    width: 100%;
    height: 104rpx;
    line-height: 104rpx;
    text-align: left;
    color: #333;
    font-size: 28rpx;
}

.region-select .region-list .item.selected {
    color: #b4282d;
}

.bg-mask {
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.4);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 8;
}
</style>
