<template>
	<view class="pages">
		<view class="addrs">
			<view class="addrs-item" :class="item.defaultStatus==1?'default':''" v-for="(item,index) in addrsList" :key="index">
				<view class="addrs-item-content" @click="selectDefault(item)">
					<view class="addrs-item-upwrap">
						<view class="addrs-item-name">收货人：{{item.name}}</view>
						<view class="addrs-item-phoneNumber">{{item.phoneNumber}}</view>
					</view>
					<view class="addrs-item-addr">收货地址：{{item.province}}{{item.city}}{{item.region}}{{item.detailAddress}}</view>
				</view>
				<view class="addrs-item-icon-wrap" @click="editAddr(item)">
					<!-- <text class="iconfont iconGroup" v-if="item.defaultStatus == 1"></text> -->
					<text>编辑</text>
				</view>
			</view>
		</view>
		<view class="new-btn-wrap">
			<view class="new-btn" @click="newAddr">添加新地址</view>
		</view>
		<!-- 地址编辑 -->
		<view class="newaddr-page fix-content translate" :class="{ 'open': fixPageOpen }">
			<view class="fix-content-nav"><text @click="closeFixPage" class="iconfont iconhoutui"></text></view>

			<!-- <view class="form-item required">
				<view class="form-item-til">所在省</view>
				<view class="form-item-con">
					<input type="text" placeholder="请选择/输入" v-model="params.province" value="" />
				</view>
			</view>
			<view class="form-item required">
				<view class="form-item-til">所在市</view>
				<view class="form-item-con">
					<input type="text" placeholder="请选择/输入" v-model="params.city" value="" />
				</view>
			</view>
			<view class="form-item required">
				<view class="form-item-til">所在地区</view>
				<view class="form-item-con">
					<input type="text" placeholder="请选择/输入" v-model="params.region" value="" />
				</view>
			</view> -->
			
			<view class="form-item select-addr required" @click="addressShow = true">
				<view class="form-item-til">选择地址</view>
				<view class="form-item-con">
					<text v-if="address==''">请选择地址</text>
					{{address}}
					<pickerAddress v-model="addressShow" @confirm="addresspick" />
				</view>
			</view>
			<view class="form-item required">
				<view class="form-item-til">详细地址</view>
				<view class="form-item-con">
					<input type="text" placeholder="请输入详细地址" v-model="params.detailAddress" value="" />
				</view>
			</view>
			<view class="form-item required">
				<view class="form-item-til">联系人</view>
				<view class="form-item-con">
					<input type="text" placeholder="请输入联系人" v-model="params.name" value="" />
				</view>
			</view>
			<view class="form-item required">
				<view class="form-item-til">联系电话</view>
				<view class="form-item-con">
					<input type="text" placeholder="请输入联系电话" v-model="params.phoneNumber" value="" />
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-til">邮政编码</view>
				<view class="form-item-con">
					<input type="text" placeholder="请输入邮政编码" v-model="params.postCode" value="" />
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-til">设为默认收货地址</view>
				<view class="form-item-con" style="min-width: auto;">
					<switch :checked="params.defaultStatus==1?true:false" @change="switchDefaultStatus" />
				</view>
			</view>
			<view class="form-item" v-if="isedit">
				<view class="form-item-til" style="color: red;" @click="delAddr">删除收货地址</view>
			</view>
			<view class="form-item save-addr">
				<view class="form-item-til" @click="saveAddr">保存收货地址</view>
			</view>

			<!-- <baidu-map class="map" :center="center" :zoom="zoom" @ready="handlermap" :scroll-wheel-zoom="true" @click="clickEvent"
			 ak="BSf4i2bljmxl8R0x28cjOy8KMVrCVzev">
				<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
				<bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
				<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true" @locationSuccess="getLoctionSuccess"></bm-geolocation>
				<bm-view :style="{width:'100%',height: '400px'}"></bm-view>
			</baidu-map> -->

		</view>
		<!-- 地址编辑 -->
		<uni-popup ref="popup" type="dialog">
		    <uni-popup-dialog type="info"  content="确认删除此地址吗?" :duration="2000" :before-close="true" @close="closepopup" @confirm="confirmpopup"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	// import {
	// 	BaiduMap,
	// 	BmNavigation,
	// 	BmView,
	// 	BmGeolocation,
	// 	BmCityList
	// } from 'vue-baidu-map';
	import uniPopup from '@/components/uni-popup/uni-popup.vue';
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue';
	import pickerAddress from '@/components/liudx-pickerAddress/index.vue'
	const defaultparams= {
		token: '',
		name: '',
		phoneNumber: "",
		defaultStatus: "0",
		postCode: "",
		province: "",
		city: "",
		region: "",
		detailAddress: "",
		latitude: '',
		longitude: ''
	};
	export default {
		// beforeRouteEnter(to, from, next){
		// 	console.log('from',from);
		// 	next(vm =>{
		// 		console.log('22222222',from) // 上一页面的路由信息
		// 	})
		// },
		// beforeRouteLeave(to, from, next) {
		// 	console.log(' beforeRouteLeave !', this)
		// 	const answer = window.confirm('确认离开？')
		// 	answer ? next() : next(false)
		//   },
		components: {
			// BaiduMap,
			// BmNavigation,
			// BmView,
			// BmGeolocation,
			// BmCityList,
			uniPopup,
			uniPopupDialog,
			pickerAddress
		},
		data() {
			return {
				addressShow: false,
				form: {
					province: '',
					city: '',
					area: '',
				},
				address: '',
								
				isedit: false,
				isselectAddr:false,
				addrsList: [],
				token:'',
				params: Object.assign({},defaultparams),
				ruleItems:{
					name: '',
					phoneNumber: "",
					province: "",
					city: "",
					region: "",
					detailAddress: "",					
				},
				rules: {
					name: {rule: /^[\u4E00-\u9FA5]{2,4}$/,msg: "姓名2到4位汉字"},
					province: {rule: /\S/,msg: "请填写必要内容"},
					city: {rule: /\S/,msg: "请填写必要内容"},
					region: {rule: /\S/,msg: "请填写必要内容"},
					detailAddress: {rule: /\S/,msg: "请填写详细地址"},
					phoneNumber: {rule: /(^1[3|4|5|7|8|9]\d{9}$)|(^09\d{8}$)/,msg: "请填写正确手机号"},
				},
				fixPageOpen: false,
				center: {
					lng: 106.632713,
					lat: 26.653157
				},
				zoom: 12,
			}
		},
		onShow() {			
			let serf = this;
			this.getAddrList();

		},
		onLoad() {
			
			let self = this;
			uni.getStorage({
				key:'token',
				success: function (res) {
					self.token = res.data;
				   // console.log(res.data);
				}
			});
			uni.getStorage({
				key:'selectAddr',
				success: function (res) {
					self.isselectAddr = true;
				   // console.log(res.data);
				},
				fail:function(){
					self.isselectAddr = false;
				}
			});
			

		},
		onUnload() {
			console.log('1111111111111');
			this.isselectAddr = false;
			uni.setStorage({
				key:'selectAddr',
				data:false
			});
		},
		methods: {
			addresspick(obj) {
				console.log('addresspick',obj);
				this.params.province = obj.province.areaName;
				this.params.city = obj.city.areaName;
				this.params.region = obj.area.areaName||'';
				this.concatAddr();
			},
			concatAddr(){
				this.address = this.params.province + this.params.city +this.params.region;
			},
			getAddrList() {
				let thetoken = 'Bearer ' + this.token;
				this.$api.http.get(this.config.apiBaseurl + '/member/address/list',{header: {Authorization:thetoken}}).then(res => {
					// console.log('getAddrList', res);
					this.addrsList = res.data.data;					
					if(this.addrsList.length == 1 && this.addrsList[0].defaultStatus!=1){
						// console.log('getAddrListlength', this.addrsList[0]);
						// setTimeout(function(){console.log(this)},5000);
						setTimeout(this.setDefault(this.addrsList[0].id),1000);
						// this.setDefault(this.addrsList[0].id);
					}
				}).catch(err => {
					// console.log('err', err)
				})
			},
			newAddr() {
				this.fixPageOpen = true;
			},
			closeFixPage(){
				this.fixPageOpen = false;
				this.params = Object.assign({},defaultparams);
				this.isedit = false;
				this.address = '';
				this.getAddrList();
				
			},
			//是否默认
			switchDefaultStatus(e) {
				if (e.target.value) {
					this.params.defaultStatus = 1;
				} else {
					this.params.defaultStatus = 0;
				}
				// console.log('this.params',this.params);
			},
			editAddr(item){
				this.isedit = true;
				this.params = Object.assign(this.params,item);
				this.concatAddr();
				this.fixPageOpen = true;
			},
			saveAddr(){
				console.log(this.isedit);				
				for (let x in this.ruleItems) {
					// console.log('x',x)
					if(!this.validate(x)) return;
				}
				console.log('this.params',this.params);
				// var saveApi;
				if(this.isedit){
					// saveApi = this.config.apiBaseurl + '/member/address/update';
					// console.log(this.params);
					this.$api.http.put(this.config.apiBaseurl + '/member/address/update/'+this.params.id,this.params,{
						header: {
						Accept:'application/json',
						Authorization: 'Bearer '+ this.token, //注意Bearer后面有一空格
					},
					}).then(res => {
						this.closeFixPage();
						// console.log('res',res)
					}).catch(err =>{
						console.log('err',err)
					});
				}else{
					// saveApi = this.config.apiBaseurl + '/member/address/add';
					if(this.addrsList.length == 0 ){this.params.defaultStatus = 1}
					this.$api.http.post(this.config.apiBaseurl + '/member/address/add',this.params,{
						header: {
						Accept:'application/json',
						Authorization: 'Bearer '+ this.token, //注意Bearer后面有一空格
					},
					}).then(res => {
						this.closeFixPage();						
						//产品跳转
						uni.getStorage({
							key:'productID',
							success: res => {
								console.log('productID',res.data);
								this.jumpProduct(res.data);
								uni.removeStorage({
									key:'productID'
								});
							}
						});
						//产品跳转
						// console.log('res',res)
					}).catch(err =>{
						console.log('err',err)
					});
				}
				
				
			},
			closepopup(done){
				done()
			},
			confirmpopup(done,value){
				this.$api.http.delete(this.config.apiBaseurl + '/member/address/delete/'+this.params.id,{},{
					header: {
					Accept:'application/json',
					Authorization: 'Bearer '+ this.token, //注意Bearer后面有一空格
				},
				}).then(res => {					
					this.closeFixPage();					
					// console.log('res',res)
				}).catch(err =>{
					console.log('err',err)
				});	
				done()
			},
			delAddr(item){
				this.$refs.popup.open();
			},
			selectDefault(item){
				// console.log('item',item);
				if(item.defaultStatus != 1){
					this.setDefault(item.id);
				}
				console.log(this.$router);
				console.log(this.$router.history.current.fullPath);
				if(this.isselectAddr){this.$router.go(-1);}
			},			
			setDefault(id){
				this.$api.http.put(this.config.apiBaseurl + '/member/address/default/'+id,{},{
					header: {
					Accept:'application/json',
					Authorization: 'Bearer '+ this.token, //注意Bearer后面有一空格
				},
				}).then(res => {
					// this.closeFixPage();
					console.log('res',res)
				}).catch(err =>{
					console.log('err',err)
				});				
			},
			//判断验证是否符合要求
			validate(key) {
				let bool = true;
				if (!this.rules[key].rule.test(this.params[key])) {
					//提示信息
					uni.showToast({
						icon:"none",
						title: this.rules[key].msg,
					})
					//取反
					bool = false;
					return false;
				}
				return bool;
			},			
			//产品跳转链接
			jumpProduct(id){
				uni.navigateTo({
					url:`/pages/product/product?id=${id}`,
					fail(err) {
						console.log(err)
					}
				})				
			},
			// handlermap({
			// 	BMap,
			// 	map
			// }) {
			// 	let _this = this;
			// 	var geolocation = new BMap.Geolocation();
			// 	geolocation.getCurrentPosition(function(r) {
			// 		// console.log(r);
			// 		_this.center = {
			// 			lng: r.longitude,
			// 			lat: r.latitude
			// 		}; // 设置center属性值
			// 		// console.log('_this.center',_this.params);
			// 		if (_this.params.latitude && _this.params.longitude) {
			// 			let transqq = qqMapTransBMap(_this.params.longitude, _this.params.latitude);
			// 			// console.log('transqq',transqq);
			// 			_this.center = {
			// 				lng: transqq.lng,
			// 				lat: transqq.lat
			// 			};
			// 		};
			// 		let Icon_0 = new BMap.Icon("static/img/zuobiao.gif", new BMap.Size(64, 64), {
			// 			anchor: new BMap.Size(18, 32),
			// 			imageSize: new BMap.Size(36, 36)
			// 		});
			// 		let myMarker = new BMap.Marker(new BMap.Point(_this.params.longitude, _this.params.latitude), {
			// 			icon: Icon_0
			// 		});
			// 		// map.addOverlay(myMarker);
			// 		_this.autoLocationPoint = {
			// 			lng: r.longitude,
			// 			lat: r.latitude
			// 		}; // 自定义覆盖物
			// 		_this.initLocation = true;
			// 	}, {
			// 		enableHighAccuracy: true
			// 	})
			// 	window.map = map;
			// },
			//点击地图监听
			// clickEvent(e) {
			// 	map.clearOverlays();
			// 	let Icon_0 = new BMap.Icon("static/img/zuobiao.gif", new BMap.Size(64, 64), {
			// 		anchor: new BMap.Size(18, 32),
			// 		imageSize: new BMap.Size(36, 36)
			// 	});
			// 	var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat), {
			// 		icon: Icon_0
			// 	});
			// 	map.addOverlay(myMarker);
			// 	//用所定位的经纬度查找所在地省市街道等信息
			// 	var point = new BMap.Point(e.point.lng, e.point.lat);
			// 	var gc = new BMap.Geocoder();
			// 	let _this = this;
			// 	gc.getLocation(point, function(rs) {
			// 		var addComp = rs.addressComponents;
			// 		console.log(rs); //地址信息
			// 		_this.params.province = rs.addressComponents.province;
			// 		_this.params.city = rs.addressComponents.city;
			// 		_this.params.region = rs.addressComponents.district;
			// 		uni.showToast({
			// 		 	title:"选择成功!",
			// 		 	icon:"none",
			// 		 	duration:800
			// 		});
			// 		// _this.params.detailAddress = rs.address;
			// 	});
			// 	//转为高德坐标
			// 	// let transGaode = bMapTransQQMap(e.point.lng, e.point.lat);
			// },

		}
	}
</script>

<style scoped>
	@import url("./addrs.css");
</style>
