<template>
	<view class="pages">
		<view class="addrs">
			<view class="addrs-item" :class="item.defaultStatus==1?'default':''" v-for="(item,index) in addrsList" :key="index" @click="editAddr(item)">
				<view class="addrs-item-content">
					<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">
					<text class="iconfont iconGroup" v-if="item.defaultStatus == 1"></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 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';
	const defaultparams= {
		token: '',
		name: '',
		phoneNumber: "",
		defaultStatus: "0",
		postCode: "",
		province: "",
		city: "",
		region: "",
		detailAddress: "",
		latitude: '',
		longitude: ''
	};
	export default {
		components: {
			BaiduMap,
			BmNavigation,
			BmView,
			BmGeolocation,
			BmCityList,
			uniPopup,
			uniPopupDialog,
		},
		data() {
			return {
				isedit: 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);
				}
			});
			

		},
		methods: {
			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.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.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();
						// 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();
			},
			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;
			},
			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>
