<template>
	<view class="ads" :style="{background:adsList.length == 0?'#fff':'#f9f9fb'}">
		<view class="al" v-if="!isEdit">
			<view class="al_item" v-for="(item, index) in adsList" :key="item.id" @click="selectAds(item)">
				<view class="T">
					<text>{{ item.name }}</text>
					<text>
						<text style="font-size:28rpx;color:#999"
							v-if="item.area_code">{{item.area_code==='+86'?'':item.area_code}}</text>
						<text>{{ item.phone }}</text>
					</text>
				</view>
				<view class="C">
					<view class="C_L">{{ item.province }}{{ item.city }}{{ item.area }}{{ item.address }}</view>
				</view>
				<view class="B flexB">
					<view class="B_L active" @click.stop="setDefault(item.id, item.is_default, index)">
						<text class="iconfont iconxuanzhong" v-if="item.is_default == 1"></text>
						<text class="iconfont iconweixuanzhong" v-else></text>
						<text :class="item.is_default == 1 ? 'default' : ''">设置为默认地址</text>
					</view>
					<view class="B_R">
						<text @click.stop="edit(item)">编辑</text>
						<text @click.stop="delAds(item.id, index)">删除</text>
					</view>
				</view>
			</view>
			<view class="noData" v-if="adsList.length == 0">
				<image src="/static/imgs/default/no_record.png"></image>
				<view>暂无收货地址~</view>
			</view>
			<view class="al_add_btn" @click="addNew">+添加新地址</view>
		</view>
		<view class="edit_ads" v-else>
			<view class="nav">
				<textarea v-model="message" type="text" :placeholder="placeholder" class="discern"
					placeholder-class="discern-placeholder" />
				<view class="flex">
					<view class="nav-clearbutton flexC" @click="message = ''">清空</view>
					<view class="nav-button flexC" @click="text">识别</view>
				</view>
			</view>
			<view class="box">
				<view class="box-top flexS">
					<view class="title">
						<text>收货人</text>
						<text class="star">*</text>
					</view>
					<input v-model="params.name" type="text" class="box-input" placeholder-class="input_placeholder"
						placeholder="请填写真实姓名" />
				</view>
				<view class="box-top">
					<navigator url="../phone-area/phone-area" class="phone-area flexB">
						<view class="flexS">
							<view class="title">
								<text class="text" style="color:#333">国家/地区</text>
								<text class="star">*</text>
							</view>
							<text class="area">{{areaName}}（{{params.areaCode}}）</text>
						</view>
						<text class="icon cuIcon-right"></text>
					</navigator>
				</view>
				<view class="box-top">
					<view class="title">
						<text>手机号</text>
						<text class="star">*</text>
					</view>
					<input v-model="params.phone" type="number" class="box-input" placeholder-class="input_placeholder"
						placeholder="请填写手机号码" maxlength="11" />
				</view>
				<view class="box-top">
					<view class="title">
						<text>省市区</text>
						<text class="star">*</text>
					</view>
					<view class="picker flexB" @tap="choosePicker">
						<view :style="{ color: params.local ? '#333' : '#808080' }" style="font-size:30rpx;">
							{{ params.local ? params.local : '请选择所在地区' }}
						</view>
						<text class="iconfont iconzhcc_xiangxiajiantou"></text>
					</view>
				</view>
				<w-picker ref="Selector" mode="region" themeColor="#F76454" @confirm="onConfirm" />
				<view class="box-bottom">
					<view class="title">
						<text>详细地址</text>
						<text class="star">*</text>
					</view>
					<view class="textbox">
						<textarea v-model="params.address" type="text" placeholder="请填写详细地址" class="box-input"
							placeholder-class="input_placeholder" />
					</view>
				</view>
				<view class="box-changyong flexB">
					<view class="title">设置为常用地址</view>
					<view class="flexS default_btn">
						<view @click="editDefault(0)" class="set-control"
							:class="params.is_default == 0 ? 'active' : 'set-used'">否</view>
						<view @click="editDefault(1)" class="set-control"
							:class="params.is_default == 1 ? 'active' : 'set-used'" style="margin-left:20rpx;">是</view>
					</view>
				</view>
			</view>
			<view class="remind">若自动识别的信息不准确，请手动修改</view>
			<view class="fixed_btn_box flexC">
				<view @click="save" class="flexC">{{ address_id ? '确认修改' : '保存' }}</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		getAllAds,
		setDefault,
		deleteAds,
		addAds,
		updateAds,
		getLocation,
		location,
		discernAdress
	} from '@/apis/shop.js';
	import WPicker from '../../components/w-picker/w-picker.vue';
	import cityPicker from '../../components/citypicker/city-picker.vue';
	import AddressParse from 'address-parse';
	import areaList from '@/common/util/phone-area.js'
	export default {
		data() {
			return {
				placeholder: '请粘贴或输入整段地址，点击“识别”自动拆分姓名、电话和地址。例如：张三，15100001111，河南省郑州市金水区某路和某路交叉口某小区某号楼',
				message: '', //输入的要识别的地址
				adsList: '', //获取的地址列表
				params: {
					name: '',
					phone: '',
					local: '',
					province: '',
					city: '',
					area: '',
					address: '',
					is_default: 0,
					remark: '',
					areaCode: '+86', // 手机号地区代码
				},
				address_id: '',
				pickerDefaultVal: ['河南省', '郑州市', '金水区'],
				isEdit: false,
				user_id: '',
				isMatch: /^[1][3-9]\d{9}$/, //手机号验证
				areaName: '中国大陆', // 手机号地区名称
				codeList: areaList, //手机号区域选择
			};
		},
		onLoad(ops) {
			this.user_id = ops.user_id;
		},
		onShow() {
			this.getList();
		},
		beforeDestroy() {
			clearInterval(this.timer);
		},
		created() {
			uni.$on('CHOOSEPHONECODE', (name, code, reg, phoneReg) => {
				// 监听 chooseArea 事件更新
				this.areaName = name; // 修改选择的手机号地区名称
				this.params.areaCode = code // 修改选择的手机号地区代码
				this.isMatch = phoneReg
			});
		},
		components: {
			WPicker,
			cityPicker
		},

		methods: {
			// 识别地址手机号验证
			checkCode(type, arr) {
				let t = '886'
				let a = '853'
				let x = '852'
				let msg = this.message.replace(/\s*/g, "")
				let index = ''
				let mobile = ''
				let code = ''
				if (msg.indexOf(t) != -1) {
					index = msg.indexOf(t)
					mobile = msg.substring(index + 3, index + 13)
					code = `+${t}`
					this.areaName = '中国台湾'
					this.isMatch = /^[0]{1}[9]{1}\d{8}$/
				} else if (msg.indexOf(a) != -1) {
					index = msg.indexOf(a)
					mobile = msg.substring(index + 3, index + 11)
					code = `+${a}`
					this.areaName = '中国澳门'
					this.isMatch = /^[6]\d{7}$/
				} else if (msg.indexOf(x) != -1) {
					index = msg.indexOf(x)
					mobile = msg.substring(index + 3, index + 11)
					code = `+${x}`
					this.areaName = '中国香港'
					this.isMatch = /^([6|9|5])\d{7}$/
				} else {
					code = '+86'
					this.areaName = '中国大陆'
					mobile = arr.mobile
					this.isMatch = /^[1][3-9]\d{9}$/
				}
				this.params = {
					name: arr.name.replace(/[0-9]/g, ''),
					areaCode: code,
					phone: mobile,
					local: type === 0 ? `${arr.province}-${arr.city}-${arr.area}` : `${arr.province}-${arr.city}`,
					province: arr.province,
					city: arr.city,
					area: arr.area,
					address: arr.details,
					is_default: 0,
					remark: '',
				};
			},
			//识别地址
			text() {
				if (this.message.length < 1) {
					uni.toast('请输入需要识别的内容');
					return;
				}

				this.result = AddressParse.parse(this.message);
				let arr = AddressParse.parse(this.message)[0];
				if (arr.mobile === '') {
					this.checkCode(0, arr)
				} else if (arr.area === '') {
					const params = {
						city: arr.city,
						details: arr.details
					};
					this.checkCode(1, arr)
					discernAdress(params).then(res => {
						if (res.code === 200) {
							if (!res.data.area) {
								uni.showToast({
									title: '有部分信息未能识别或错误，请核实或手动填写',
									icon: 'none'
								})
								return;
							}
							this.params.area = res.data.area
							this.params.local = `${arr.province}-${arr.city}-${res.data.area}`
							// this.params = {
							// 	name: arr.name,
							// 	phone: arr.mobile,
							// 	local: `${arr.province}-${arr.city}-${res.data.area}`,
							// 	province: arr.province,
							// 	city: arr.city,
							// 	area: res.data.area,
							// 	address: arr.details,
							// 	is_default: 0,
							// 	remark: ''
							// };
							// console.log(this.params);
						} else {
							uni.showToast({
								title: '识别失败，请手动填写',
								icon: 'none'
							})
						}
					});
				} else {
					this.params = {
						name: arr.name,
						phone: arr.mobile,
						local: `${arr.province}-${arr.city}-${arr.area}`,
						province: arr.province,
						city: arr.city,
						area: arr.area,
						address: arr.details,
						is_default: 0,
						remark: '',
						areaCode: '+86'
					};
				}
			},
			choosePicker() {
				// 显示地址选择器
				this.$refs.Selector.show();
			},
			onConfirm(e) {
				// 选择地址选择器
				this.params.local = `${e.checkArr[0]}-${e.checkArr[1]}-${e.checkArr[2]}`;
				this.pickerDefaultVal = [e.checkArr[0], e.checkArr[1], e.checkArr[2]];
				this.params.province = e.checkArr[0];
				this.params.city = e.checkArr[1];
				this.params.area = e.checkArr[2];
			},
			/*添加新地址*/
			addNew() {
				this.isEdit = true;
				this.address_id = '';
				this.message = '';
				this.areaName = '中国大陆';
				this.isMatch = /^[1][3-9]\d{9}$/;
				this.params = {
					name: '',
					phone: '',
					local: '',
					province: '',
					city: '',
					area: '',
					address: '',
					is_default: 0,
					remark: '',
					areaCode: '+86', // 手机号地区代码
				}
			},
			//编辑或添加时设置默认地址
			editDefault(type) {
				this.params.is_default = type;
			},
			//保存或者确认修改
			save() {
				if (this.params.name) {
					this.params.name = this.params.name.replace(/\s*/g, '');
				}
				if (!this.params.name.match(/^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/)) {
					// 校验姓名
					uni.showToast({
						title: '姓名不符合要求',
						icon: 'none',
						mask: true
					});
					return;
				}
				if (!this.params.phone) {
					uni.showToast({
						title: '手机号码不能为空',
						icon: 'none',
						mask: true
					});
					return
				}
				if (this.isMatch && !this.params.phone.match(this.isMatch)) {
					uni.showToast({
						title: '手机号所属与区号不一致',
						icon: 'none',
						mask: true
					});
					return
				}
				if (!this.params.local.trim().length) {
					// 校验是否选择地区
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none',
						mask: true
					});
					return;
				}
				if (!this.params.address) {
					// 校验是否填写详细地址
					uni.showToast({
						title: '详细地址不能为空',
						icon: 'none',
						mask: true
					});
					return;
				}
				let data = '';
				let http = '';
				let hint = '';
				//如果有地址id表示是修改  没有表示是添加
				if (this.address_id) {
					this.params.address_id = this.address_id;
					data = this.params;
					http = updateAds;
					hint = '修改地址成功！';
				} else {
					this.params.user_id = this.user_id;
					data = this.params;
					http = addAds;
					hint = '添加地址成功！';
				}
				http(data).then(res => {
					if (res.code == 200) {
						uni.showModal({
							content: hint,
							showCancel: false,
							success: res => {
								if (res.confirm) {
									this.isEdit = false;
									this.getList();
								}
							}
						});
					} else {
						uni.showModal({
							content: res.data,
							showCancel: false
						});
					}
				});
			},
			/*获取地址列表
			 *id 商户帮他下单的用户id
			 */
			getList() {
				getAllAds({
					id: this.user_id
				}).then(res => {
					if (res.code == 200) {
						this.adsList = res.data;
					} else {
						uni.showModal({
							content: res.data,
							showCancel: false
						});
					}
				});
			},
			/*删除地址*/
			delAds(id, idx) {
				uni.showModal({
					content: '确定要删除当前地址吗？',
					success: res => {
						if (res.confirm) {
							deleteAds({
								id
							}).then(res => {
								if (res.code == 200) {
									this.adsList.splice(idx, 1);
									uni.showToast({
										title: '删除地址成功',
										mask: true,
										duration: 3000
									});
								} else {
									uni.showModal({
										content: res.msg,
										showCancel: false
									});
								}
							});
						}
					}
				});
			},
			/*根据数组中某个对象排序*/
			compare(property) {
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return value2 - value1;
				};
			},
			/*设为默认地址*/
			setDefault(id, is_default, idx) {
				let hint = '';
				if (is_default == 1) {
					//已设为默认
					hint = '确定要取消当前地址为默认地址?';
				} else {
					hint = '确定要设置当前地址为默认地址?';
				}
				uni.showModal({
					content: hint,
					success: res => {
						if (res.confirm) {
							setDefault({
								id
							}).then(res => {
								if (res.code == 200) {
									let list = this.adsList;
									for (let i = 0; i < list.length; i++) {
										if (is_default == 1) {
											this.$set(list[i], 'is_default', 0);
											return false;
										}
										if (is_default == 0) {
											if (i == idx) {
												list[idx].is_default = 1;
											} else {
												list[i].is_default = 0;
											}
										}
									}
									this.adsList = list;
									uni.showToast({
										title: '设置成功',
										mask: true,
										duration: 3000
									});
								} else {
									uni.showModal({
										content: res.data || '设置失败',
										showCancel: false
									});
								}
							});
						}
					}
				});
			},
			/*编辑收货地址*/
			edit(item) {
				this.isEdit = true;
				this.params = item;
				this.message = '';
				this.params.local = `${item.province}-${item.city}-${item.area}`;
				this.address_id = item.id;
				this.params.areaCode = item.area_code ? item.area_code : '+86'
				if (this.params.areaCode) {
					let index = this.params.areaCode.indexOf('+')
					let code = this.params.areaCode.substring(index + 1)
					this.codeList[0].list.map(i => {
						if (i.code === Number(code)) {
							this.areaName = i.name
							this.isMatch = i.phoneReg
						}
					})
				}
			},
			//选择地址返回上一页
			selectAds(item) {
				let that = this;
				var pages = getCurrentPages();
				var prevPage = pages[pages.length - 2]; //上一个页面
				let object = item;
				prevPage.$vm.otherFun(object); //重点$vm
				uni.navigateBack();
			}
		}
	};
</script>
<style lang="scss" scoped>
	.ads {
		min-height: 100vh;
		height: 100%;
		width: 100%;
		background: #f9f9fb;
		padding-bottom: 150rpx;
	}

	page {
		display: flex;
		justify-content: flex-start;
		flex-direction: column;
	}

	.default_ads {
		height: 130rpx;
		width: 100%;

		.default_btn {
			view {
				width: 98rpx;
				height: 50rpx;
			}
		}
	}

	.edit_ads {
		width: 690rpx;
		margin: 30rpx auto 0;
		box-sizing: border-box;

		.nav {
			padding: 26rpx 20rpx 30rpx 30rpx;
			background-color: #fff;
			border-radius: 24rpx;
			display: flex;
			flex-direction: column;
			align-items: flex-end;

			.discern {
				width: 100%;
				height: 180rpx;
				font-size: 28rpx;

				&-placeholder {
					color: #c8c8c8;
					font-size: 28rpx;
					line-height: 44rpx;
				}
			}

			.flex {
				display: flex;

				view {
					width: 128rpx;
					height: 64rpx;
					font-size: 28rpx;
					border-radius: 32rpx;
				}
			}

			&-button {
				color: #ffffff;
				background: linear-gradient(90deg, #ff232c 0%, #ff571b 100%);
			}

			&-clearbutton {
				background: #fff4f3;
				border: 2rpx solid $base-color;
				color: $base-color;
				margin-right: 15rpx;
			}
		}

		.box {
			margin: 30rpx 0;
			background-color: #fff;
			border-radius: 24rpx;

			.phone-area {
				width: 100%;

				.area {
					color: #42b983;
					margin-left: 16rpx;
				}

				.icon {
					font-size: 40rpx;
					color: #999;
				}

			}

			&-input {
				font-size: 30rpx;
				min-height: 126rpx;
				width: 75%;
				margin-left: 20rpx;
			}

			&-top {
				min-height: 128rpx;
				padding: 0 30rpx;
				box-sizing: border-box;
				border-bottom: 2rpx solid #eeeeee;
				display: flex;
				justify-content: flex-start;
				align-items: center;

				.title {
					font-size: 34rpx;
					font-weight: bold;

					.star {
						color: $base-color;
						margin-left: 10rpx;
						font-size: 40rpx;
					}
				}

				.picker {
					width: 75%;
					min-height: 128rpx;
					margin-left: 20rpx;
					font-size: 30rpx;

					.iconfont {
						color: #cbcbcb;
					}
				}

				.input_placeholder {
					font-size: 30rpx;
					color: #cbcbcb;
				}
			}

			&-bottom {
				height: 166rpx;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				border-bottom: 2rpx solid #eeeeee;
				display: flex;
				justify-content: flex-start;
				align-items: flex-start;

				.title {
					font-size: 34rpx;
					font-weight: bold;

					.star {
						color: $base-color;
						margin-left: 10rpx;
						font-size: 40rpx;
					}
				}

				.input_placeholder {
					font-size: 30rpx;
					color: #cbcbcb;
				}

				.textbox {
					height: 166rpx;

					.box-input {
						width: 440rpx;
						height: 120rpx;
						font-size: 30rpx;
					}
				}
			}

			&-changyong {
				height: 110rpx;
				padding: 26rpx 20rpx 30rpx 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title {
					font-size: 28rpx;
					font-weight: 400;
					line-height: 29rpx;
					color: #585858;
				}

				.input_placeholder {
					font-size: 28rpx;
					font-weight: 400;
					line-height: 29rpx;
				}

				.set-used {
					margin-right: auto;
					color: $base-color;
					font-size: 30rpx;
				}

				.set-control {
					width: 110rpx;
					height: 55rpx;
					line-height: 55rpx;
					border-radius: 50rpx;
					text-align: center;
					background: #f8f8f8;
					color: #333333;
					font-size: 30rpx;

					&:nth-last-of-type(1) {
						margin-left: 20rpx;
					}

					&.active {
						background: linear-gradient(to right, #F30000, #FE4815) !important;
						color: #ffffff !important;
					}
				}
			}
		}

		.remind {
			text-align: center;
			color: #fb231f;
			font-size: 28rpx;
		}

		.fixed_btn_box {
			position: fixed;
			bottom: 0;
			left: 0;
			height: 100rpx;
			width: 100%;
			background: #fff;

			view {
				width: 690rpx;
				height: 88rpx;
				border-radius: 44px;
				color: #fff;
				font-size: 32rpx;
				font-weight: bold;
				letter-spacing: 6rpx;
				background-color: $base-color;
			}
		}
	}

	.al {
		flex: 1;
		width: 690rpx;
		margin: 0 auto;
		padding-top: 24rpx;


		.al_add_btn {
			margin: 50rpx 110rpx 0 110rpx;
			height: 88rpx;
			border-radius: 88rpx;
			color: #ffffff;
			font-size: 32rpx;
			background: $base-line-bg;
			line-height: 88rpx;
			text-align: center;
		}

		.al_item {
			width: 100%;
			padding: 24rpx;
			box-sizing: border-box;
			background: #ffffff;
			margin-bottom: 30rpx;

			&:nth-last-of-type(1) {
				margin-bottom: 0;
			}

			border-radius: 24rpx;

			.B {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.B_R {
					display: flex;
					align-items: center;

					// justify-content: flex-end;
					text {
						width: 112rpx;
						height: 50rpx;
						line-height: 50rpx;
						text-align: center;
						border-radius: 50rpx;
						background-color: #f8f8f8;
						color: #333333;
						font-size: 28rpx;
						margin-left: 20rpx;
					}
				}

				.B_L {
					display: flex;
					align-items: center;
					justify-content: flex-start;

					// width:50%;
					.iconfont {
						margin-right: 10rpx;
						vertical-align: -2rpx;
					}

					.default {
						color: $base-color;
					}
				}
			}

			.C {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-bottom: 20rpx;
				border-bottom: 2rpx solid #e9e9e9;
				margin-bottom: 26rpx;

				.C_L {
					flex: 1;
					overflow: hidden;
					color: #333333;
					font-size: 28rpx;
					line-height: 40rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}
			}

			.T {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 20rpx;

				text {
					&:nth-of-type(1) {
						color: #333333;
						font-size: 32rpx;
						flex: 1;
						overflow: hidden;
						text-overflow: ellipsis;
						margin-right: 10rpx;
					}

					&:nth-last-of-type(1) {
						width: max-content;
						color: #999999;
						font-size: 28rpx;
					}
				}
			}
		}
	}
</style>
