<template>
	<view class="page">
		<view class="tip">
			<uni-icons type="info" size="20" color="#00a89b"></uni-icons> 
			<text style="margin-left: 10rpx;">若所在省市无法选择，请在省市区选择其他，在详细地址输入即可</text>
		</view>
		<view class="example">
			<!-- 基础表单校验 -->
			<uni-forms ref="valiForm" :modelValue="valiFormData">
				<uni-forms-item label="收货人" labelWidth="168rpx" required name="name">
					<uni-easyinput v-model="valiFormData.name" maxlength="10" placeholder="请输入收货人" />
				</uni-forms-item>
				<uni-forms-item label="手机号码" labelWidth="168rpx" required name="phone">
					<uni-easyinput type="number" v-model="valiFormData.phone"  maxlength="12" placeholder="请输入手机号码" />
				</uni-forms-item>
				<uni-forms-item label="所在区域" labelWidth="168rpx" name="region">
					<view class="usel"  @click="openPicker">
						<view class="txt" v-if="valiFormData.region">{{valiFormData.region}} </view>
						<view class="txt0" v-else>选择所在区域</view>
						<uni-icons type="right" size="18" color="#ddd"></uni-icons> 
					</view>
				</uni-forms-item>
				<uni-forms-item label="详细地址" labelWidth="168rpx" name="address">
					<uni-easyinput type="textarea" v-model="valiFormData.address" autoHeight maxlength="200" placeholder="请输入详细地址" />
				</uni-forms-item>
			</uni-forms>
		</view>
		
		<view class="xcon">
			<view class="xcell">
				<text class="txt">设置默认地址</text>
				<switch :checked="valiFormData.isDefault" @change="switch1Change"  color="#00a89b" style="transform:scale(0.7)"/>
			</view>
			<!-- <view class="xright" @click="delDo" >删除地址</view> -->
		</view>
		
		<view class="submitcon">
			<button type="primary" v-if="type=='add'||type=='edit'" class="btn" @click="submit('valiForm')">保存</button>
		</view>
		
		<cc-selectCity :show="show" :province="province" :city="city" :area="district" @sureSelectArea="onsetCity" @changeClick="changeClick" @hideShow="onhideShow"></cc-selectCity>
		
		<!-- 是否登录 -->
		<openlogin ref="loginId" @getPhoneNumber="getPhoneNumber"></openlogin>
		
	</view>
</template>

<script>
	import { myCache } from '../../utils/utils.js';
	import openlogin from "../components/openlogin.vue";
	export default {
		components: {
			openlogin
		},
		data() {
			return {
				openId:"",
				phone:"",
				userid:"",
				index:0,
				type:'add',
				show:false,
				province:"辽宁省",
				city:"沈阳市",
				district: "沈北新区",
				valiFormData: {// 校验表单数据
				    id: null,
					name: '',
					phone: '',
					province: "",//省
					city: "",// 城市
					district: "", //区域
					region: "", //区域
					address: '',// 地址
					isDefault: false, // 是否默认地址
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请填写联系电话',
						}, {
							validateFunction: function(rule, value, data, callback) {
								let iphoneReg = (
									/^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
								); //手机号码
								if (!iphoneReg.test(value)) {
									callback('手机号码格式不正确，请重新填写')
								}
							}
						}]
					}
				},
				ifselshow:true
			}
		},
		onLoad(options) {
			console.log('onLoad')
			if(options.data){
				var data = JSON.parse(decodeURIComponent(options.data));
				console.log(data);
				this.valiFormData.id= data.id;
				this.valiFormData.name= data.name;
				this.valiFormData.phone= data.phone;
				this.valiFormData.province= data.province;//省
				this.valiFormData.city= data.city; // 城市
				this.valiFormData.district= data.district; //区域
				this.valiFormData.region= data.province+data.city+data.district; //区域
				this.valiFormData.address= data.address.replace(data.province+data.city+data.district, "") ,// 地址
				this.valiFormData.isDefault= data.isDefault?data.isDefault:false; // 是否默认地址
				console.log(this.valiFormData)
				this.province=this.valiFormData.province;
				this.city=this.valiFormData.city;
				this.district=this.valiFormData.district;
				this.ifselshow=true;
				this.$forceUpdate();
			}
			if(options.index){
				this.index=options.index;
			}
			if(options.type){
				this.type=options.type;
				if(this.type=="edit")
				{
					uni.setNavigationBarTitle({
					  title: "收件地址编辑",
					});
				}
				else if(this.type=="add")
				{
					uni.setNavigationBarTitle({
					  title: "添加收件地址",
					});
				}
			}
		},
		onReady() {
			console.log('onReady')
			if(this.ifselshow){
				// 需要在onReady中设置规则
				this.$refs.valiForm.setRules(this.rules);
			}
		},
		onShow(){
			this.openId = myCache('openId');
			var user = myCache('user');
			this.userid = user.userid? user.userid:'';
			this.phone = user.userphone;
			if(this.userid==""||this.userid=="0"){
				uni.navigateTo({
					url: `/pages/login/login`
				});
			}
		},
		create(){
			console.log('create');
		},
		methods: {
			switch1Change: function (e) {
				console.log('switch1 发生 change 事件，携带值为', e.detail.value);
				if(e.detail.value){
					this.valiFormData.isDefault=true
				}
				else{
					this.valiFormData.isDefault=false
				}
				this.$forceUpdate();
			},
			// 打开省市区选择器事件处理
			openPicker() {
			    console.log('执行打开地址选择器')
			    this.show = true;
				this.$forceUpdate();
			},
			//选择器更改省市区事件
			changeClick(value1, value2, value3){
			    console.log('地址选择器 = ' + value1 + value2 + value3);
				this.province=value1;
				this.city=value2;
				this.district=value3;
				this.$forceUpdate();
			},
			// 关闭省市区选择器事件处理
			onhideShow() {
			    this.show = false;
			    console.log('执行了关闭地址选择器')
			},
			//选中省市区
			onsetCity(e) {
				console.log('选中操作',e)
			    let data = e.detail.target.dataset;
			    let address = data.province + data.city + data.area;
			    this.show = false;
			    this.valiFormData.region = address;
				this.valiFormData.province = data.province;
				this.valiFormData.city = data.city;
				this.valiFormData.district = data.area;
				this.$forceUpdate();
			},
			getPhoneNumber(e){
				if(e.phone){
					this.phone = e.phone
				}
				if(e.userid){
					this.userid = e.userid
				}
			},
			async getinfo() {
				uni.showLoading({
					title: '数据加载中...'
				});
				const {data: res} = await uni.$http.post('/patient/'+this.id, null);
				if(res.data){
					this.valiFormData=res.data;
					this.$forceUpdate();
				}
			},
			async delDo(){
				var _this=this;
				try{
					uni.showModal({
						title: '提示',
						content: '确定要删除此收件地址吗？',
						cancelText: '取消',
						confirmText: '确定',
						success: ress => {
							if (ress.confirm) {
								// var myaddresslist=myCache("myaddresslist");
								// if(myaddresslist&&myaddresslist.length>0){
								// 	if(myaddresslist[this.index]){
								// 		 myaddresslist.splice(this.index, 1);
								// 		 myCache("myaddresslist",myaddresslist);
								// 	}
								// }
								// uni.showToast({
								// 	title: '收件地址已删除！',
								// 	icon: 'success',
								// 	duration: 2000
								// }) 
								// setTimeout(() => {
								// 	uni.navigateBack({
								// 		delta: 1
								// 	});
								// }, 2000);
								_this.delDoDo();
							}
						}
					});
					
				}
				catch{
					uni.showToast({
						title: '地址删除失败！',
						icon: 'error',
						duration: 2000
					});
				}
			},
			async delDoDo() {
				uni.showLoading({
					title: '数据删除中...'
				});
				const {data: res} = await uni.$http.post('/Appiso/delAddressByAddressid', {id:this.valiFormData.id});
				if(res){
					uni.showToast({
						title: '地址已删除！',
						icon: 'success',
						duration: 2000
					}) 
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						});
					}, 2000);
				}
				else{
					uni.showToast({
						title: '地址删除失败！请重试',
						icon: 'error',
						duration: 2000
					}) 
				}
			},
			async submit(ref) {
				var that = this;
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					that.savedo();
				}).catch(err => {
					console.log('err', err);
				})
			},
			async savedo(){
				try{
					if(this.type=="edit"){
						var adr={
							id:this.valiFormData.id,
							address:this.valiFormData.address, // this.valiFormData.province+this.valiFormData.city+this.valiFormData.area+this.valiFormData.address,
							district: this.valiFormData.district,
							city: this.valiFormData.city,
							province: this.valiFormData.province,
							name: this.valiFormData.name,
							phone: this.valiFormData.phone,
							isDefault: this.valiFormData.isDefault,
						}
						const {data: res} = await uni.$http.post('/api/address/edit', adr);
						if(res){
							uni.showToast({
								title: '收件地址已修改！',
								icon: 'success',
								duration: 2000
							}) 
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 2000);
						}
						else{
							uni.showToast({
								title: '收件地址修改失败！请重试',
								icon: 'error',
								duration: 2000
							}) 
						}
					}
					else{
						var adr={
							address:this.valiFormData.address, // this.valiFormData.province+this.valiFormData.city+this.valiFormData.area+this.valiFormData.address,
							district: this.valiFormData.district,
							city: this.valiFormData.city,
							province: this.valiFormData.province,
							name: this.valiFormData.name,
							phone: this.valiFormData.phone,
							isDefault: this.valiFormData.isDefault,
						}
						const {data: res} = await uni.$http.post('/api/address/add', adr);
						if(res){
							uni.showToast({
								title: '收件地址已新增！',
								icon: 'success',
								duration: 2000
							}) 
							myCache("ifaddressadd",1);
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 2000);
						}
						else{
							uni.showToast({
								title: '收件地址新增失败！请重试',
								icon: 'error',
								duration: 2000
							}) 
						}
					}
					
				}
				catch(e){
					console.log(e)
					uni.showToast({
						title: '收件地址保存失败！',
						icon: 'error',
						duration: 2000
					});
				}
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page{
		padding: 0;
		position: relative;
		background-image: url('@/static/image/bg.jpg');
		background-attachment: fixed;
		background-size: cover;
		background-position: center center;
		min-height: calc(100vh - var(--window-top) - var(--window-bottom));
	}
	.usel{
		display: flex;
		flex-direction: row;
		flex: 1;
		justify-content: flex-end;
		align-items: center;
		margin-top: 10rpx;
		.txt{
			font-weight: 500;
			font-size: 28rpx;
			color: #606266;
			margin-right: 20rpx;
		}
		.txt0{
			font-weight: 500;
			font-size: 28rpx;
			color: #999;
			margin-right: 20rpx;
		}
	}
	.xcon{
		box-sizing: border-box;
		margin: 24rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		.xcell{
			display: flex;
			flex-direction: row;
			align-items: center;
			padding: 20rpx;
			border-radius: 16rpx;
			background-color: #FFF;
			box-sizing: border-box;
			width: 100%;
			height: 120rpx;
			.txt{
				font-weight: 500;
				font-size: 28rpx;
				color: #303133;
				display: flex;
				flex: 1;
			}
		}
		.xright{
			width: 100%;
			display: flex;
			flex: 1;
			justify-content: flex-end;
			font-weight: 500;
			font-size: 28rpx;
			color: #303133;
			margin-top: 20rpx;
			margin-right: 20rpx;
		}
	}
	.tip{
		background: #e4f9f7;
		padding: 20rpx;
		font-size: 24rpx;
		color: #303133;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.btn{
		margin: 50rpx auto 54rpx;
		font-size: 32rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #FCFCFD;
		width: 660rpx;
		height: 76rpx;
		line-height: 76rpx;
		background: #00a89b;
		box-shadow: 0rpx 12rpx 64rpx 2rpx rgba(137,150,95,0.4);
		border-radius: 10rpx;
		opacity: 1;
		&::after{
			border:none;
		}
	}
	.ftext{
		margin-top: 20rpx;
		font-size: 28rpx;
		line-height: 2.5;
	}
	.example {
		margin: 30rpx 20rpx;
		padding: 30rpx;
		background-color: #FFFFFF;
		border-radius: 16rpx;
	}
	.submitcon{
		margin: 10rpx 20rpx 50rpx;
		position: relative;
		display: block;
		overflow: hidden;
		height: 200rpx;
	}
	.segmented-control {
		margin-bottom: 15px;
	}
	.button-group {
		margin-top: 30rpx;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 60rpx;
		margin-left: 20rpx;
	}
</style>
