<template>
	<view class="container">
		<view class="address-info ">
			<u--form labelPosition="left" ref="uForm">
				<u-form-item required label="联系人" prop="addressInfo.name" labelWidth="120" borderBottom>
					<u--input v-model="addressInfo.name" placeholder="请输入联系人姓名" placeholderStyle="text-align:right;color:#AAA" border="none"  inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item required label="手机号码" prop="addressInfo.phone" labelWidth="120" borderBottom>
					<u--input v-model="addressInfo.phone" placeholder="请输入手机号码" placeholderStyle="text-align:right;color:#AAA"  border="none"  inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="应急联络" prop="addressInfo.emergencyPhone" labelWidth="120" borderBottom>
					<u--input v-model="addressInfo.emergencyPhone" placeholder="请输入应急联络号码" placeholderStyle="text-align:right;color:#AAA" border="none"  inputAlign="right"></u--input>
				</u-form-item>
				
				<!-- <u-form-item label="所在城市" prop="addressInfo.city" labelWidth="120" borderBottom>
					<picker mode="multiSelector" @columnchange="columnchange" @change="bindMultiPickerColumnChange" :value="multiIndex"
						:range="multiArray">
						<view style="display: flex;justify-content: space-between;">
							<u--input :value="addressInfo.city? (addressInfo.city +'  '+ addressInfo.district):''" 
								disabled disabledColor="#ffffff" placeholder="请选择所在城市"  
								placeholderStyle="text-align:right;color:#AAA" border="none"  inputAlign="right">
							</u--input>
							
							<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
						</view>
					</picker>
				</u-form-item> -->
				
				<u-form-item label="所在地区" prop="addressInfo.city" labelWidth="120" borderBottom>
					<view style="display: flex;justify-content: space-between;" @click="selectAddress">
						<u--input :value="addressInfo.city" 
							disabled disabledColor="#ffffff" placeholder="请选择所在地区"  
							placeholderStyle="text-align:right;color:#AAA" border="none"  inputAlign="right">
						</u--input>
						<u-icon slot="right" name="arrow-right" color="#AAA"></u-icon>
					</view>
				</u-form-item>
				
				<u-form-item label="详细地址" prop="addressInfo.detailAddress" labelWidth="120" borderBottom>
					<u--input v-model="addressInfo.detailAddress" placeholder="如楼栋、门牌号" placeholderStyle="text-align:right;color:#AAA;" border="none"  inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="设为默认地址" prop="addressInfo.isDefault" labelWidth="120">
					<view>
						<u-radio-group :value="addressInfo.isDefault?'默认':''" placement="column"  @change="groupChange">
							<u-radio name="默认" activeColor="#ffbf60" labelColor="#ffbf60" label="默认"></u-radio>
						</u-radio-group>
					</view>
				</u-form-item>
			</u--form>
		</view>
		<view class="address-save">
			<button class="address-save-btn" @click="save" :loading="loading">保存并使用</button>
		</view>
	</view>
	
</template>

<script>
	import {
		getCity
	} from '@/api/system/user.js'
	import {
		getAddressDetails,addAddress,updateAddress
	} from '@/api/system/address.js'
	export default{
		data(){
			return{
				loading:false,
				addressInfo:{
					name:"",
					phone:"",
					emergencyPhone:"",
					province:"",
					city:"",
					district:'',
					detailAddress:"",
					openId:"",
					isDefault:0
				},
				multiArray: [],
				cityList:[],
				multiIndex: [0, 0],
				addressId:'',
			}
		},
		onLoad(option) {
			this.optionType=option.optionType;
			if(this.optionType=='edit'){
				this.addressId=option.addressId;
				this.getAddressDetails(option.addressId);
			}
		},
		mounted() {
			this.getCityList()
		},
		methods:{
			getAddressDetails(id){
				getAddressDetails(id).then(res=>{
					if(res&& res.id){
						const { 
							name,
							phone,
							emergencyPhone,
							province,
							city,
							district,
							detailAddress,
							openId,
							isDefault
						} = res;
						this.addressInfo = {
								name,
								phone,
								emergencyPhone,
								province,
								city,
								district,
								detailAddress,
								openId,
								isDefault
							};
					}else{
						this.$modal.showToast('获取地址详情失败')
					}
				})
			},
			
			// 选择地区
			selectAddress(){
				uni.chooseLocation({
					success: res => {
						this.addressInfo.latitude = res.latitude
						this.addressInfo.longitude = res.longitude
                        
						var reg = /.+?(省|市|自治区|自治州|县|区)/g;
						
						let arr = res.address.match(reg)
                        
						this.addressInfo.province = arr[0]
						this.addressInfo.city = arr[1]
						this.addressInfo.district = arr[2]
						
						if (!res.address && res.name) { //用户直接选择城市的逻辑
							return this.addressInfo.selectAddress = res.name
						}
						if (res.address || res.name) {
							return this.addressInfo.selectAddress = res.address + res.name
						}
						this.addressInfo.selectAddress = '' //用户啥都没选就点击勾选
					},
					fail(e) {
						console.log("获取位置信息失败!", e)
					}
				})
			},
			save(){
				let params = this.addressInfo
				if(params.phone){
					if(!(/^1[3456789]\d{9}$/.test(params.phone))){ 
						this.$modal.showToast('手机号码有误')
						return false; 
					}
				} else {
					this.$modal.showToast('请输入手机号')
					return false;
				}
				if(params.emergencyPhone){
					if(!(/^1[3456789]\d{9}$/.test(params.emergencyPhone))){ 
						this.$modal.showToast('手机号码有误')
						return false; 
					}
				}
				if(!params.name){
					this.$modal.showToast('请输入联系人')
					return false;
				}
				this.loading=true
				if(this.optionType=='edit'){
					params.id = this.addressId;
					updateAddress(params).then(res=>{
						if(res&&res==1){
							this.$globalData.newOrderData.currentAddress={
								id:params.id,
								name:params.name,
								phone:params.phone,
								province:params.province,
								city:params.city,
								district:params.district,
								detailAddress:params.detailAddress,
							}
							this.loading=false
							uni.redirectTo({
								url: `/pages/newOrder/serviceNew`
							});
						}else {
							this.loading=false
							this.$modal.showToast('更新地址失败')
						}
					})
				} else if(this.optionType=='add'){
					addAddress(params).then(res=>{
						if(res&&res>0){
							this.$globalData.newOrderData.currentAddress={
								id:res,
								name:params.name,
								phone:params.phone,
								province:params.province,
								city:params.city,
								district:params.district,
								detailAddress:params.detailAddress,
							}
							this.loading=false
							uni.redirectTo({
								url: `/pages/newOrder/serviceNew`
							});
						}else {
							this.loading=false
							this.$modal.showToast('新增地址失败')
						}
					})
				}
			},
			getCityList() {
				getCity().then(res => {
					if (res.code == 200) {
						console.log('city', JSON.parse(res.msg));
						this.cityList = JSON.parse(res.msg)
						const cityLabels = this.cityList.map(item =>item.city)
						this.multiArray[0] = cityLabels
						this.multiArray[1] = this.cityList[0].region.map(e=> e.region)
			
					} else {
						this.$modal.showToast('获取城市失败，请联系系统管理员！');
					}
			
			
				})
			},
			columnchange(e){
				console.log(e)
				// 当滚动切换一级分类时，为当前的一级分类添加它的子类
				if (e.detail.column == 0) {
					const currentCity = this.cityList[e.detail.value]
					// #ifdef H5
					// 在小程序中直接赋值无效  H5 可直接赋值
					this.multiArray[1] = currentCity.region.map(e=>e.region)
					// #endif
					// #ifdef MP-WEIXIN
					// 在 H5 环境下 $set 会导致一级分类无法滚动， 小程序正常运行
					this.$set(this.multiArray, 1, currentCity.region.map(e=>e.region))
					// #endif
					this.multiIndex=[e.detail.value,0]
				}
			},
			bindMultiPickerColumnChange(e) {
				console.log('值为：' + e.detail.value)
				this.multiIndex = e.detail.value
				this.addressInfo.province = this.multiArray[0][this.multiIndex[0]]
				this.addressInfo.city = this.multiArray[0][this.multiIndex[0]]
				this.addressInfo.district = this.multiArray[1][this.multiIndex[1]]
				this.isSelected = true
				this.$forceUpdate()
			},
			 groupChange(n) {
				console.log('groupChange', n);
				this.addressInfo.isDefault=+(!this.addressInfo.isDefault)
			  },
		}
	}
</script>

<style lang="scss">
	.container {
		position: relative;
		height: 100%;
		padding-bottom: 90px;
		.address-save {
			background-color: #FFFFFF;
			padding: 10px 20px 40px;
			width: 100%;
			height: 90px;
			position: fixed;
			bottom: 0;
			z-index: 100;
		
			.address-save-btn {
				width: 100%;
				border-radius: 6px;
				background: #FFB13F;
				font-size: 16px;
				color: #FFFFFF;
			}
		}
	}
	.address-info{
		background-color: #fff;
		padding: 10px 20px;
		.u-radio-group{
			float: right;
		}
	}
</style>