<template>
	<view class="bg">
		<view class="list-forms">
			<view class="list-item">
				<view class="list-item-title">姓名:</view>
				<view class="list-item-input"><input type="text" v-model="username" placeholder="请输入姓名" /></view>
			</view>
			<view class="list-item">
				<view class="list-item-title">手机号:</view>
				<view class="list-item-input"><input type="number" v-model="mobile" placeholder="请输入手机号" maxlength="11"
						 /></view>
			</view>
			<view class="list-item" style="position: relative;">
				<view class="list-item-title">选择地区:</view>
				<view class="list-item-input" style="flex: 1;">
					<picker mode="multiSelector" :range="newProvinceDataList" range-key="name" @change="changeArea" @columnchange="pickerColumnchange"
					style="position: relative;z-index: 2;">
						<input type="text" readonly style="text-align: right;font-size: 33rpx;position: relative;z-index: -1;"
								v-model="citySeld" disabled="true" placeholder="请选择地区"/>
					</picker>
				</view>
			</view>
			<view class="list-item">
				<view class="list-item-title">详细地址:</view>
				<view class="list-item-input"><input type="text" v-model="detailAddr" placeholder="请输入详细地址" /></view>
			</view>
			<view class="list-item">
				<view class="list-item-title">设为默认:</view>
				<view class="list-item-switch">
					<switch :checked="idDefault" @change="switchChange" color="#6A8A2D"/>
				</view>
			</view>
			<view class="list-item-btn">
				<view class="list-item-post" @click="postSave()">保存</view>
			</view>
		</view>
	</view>
</template>

<script>
	import District from 'ydui-district/dist/jd_province_city_area_id';
	export default {
		data() {
			return {
				username: '',
				mobile: '',
				citySeld: '',
				detailAddr: '',
				idDefault: false,
				title: '新增收货地址',
				show: false,
				district: District, //数据
				ready: false,
				province: null,
				city: null,
				area: '',
				provinceId: null,
				cityId: null,
				areaId: null,
				columns: [],
				id: '',
				newProvinceDataList:[
					[],[],[]
				],
				multiIndex: [0, 0, 0],
			}
		},
		onLoad(option){
			this.id = option.id
			if (option.id > 0) {
			  this.title = '编辑收货地址'
			  this.getDetail()
			}
			else {
			  this.getSeldCityList()
			}
		},
		methods: {
			switchChange(e){
				this.idDefault = e.detail.value
			},
			changeArea(e){
				// 数组内的下标
				this.multiIndex = e.detail.value;
				this.citySeld = this.newProvinceDataList[0][this.multiIndex[0]].name + this.newProvinceDataList[1][this.multiIndex[1]].name + this.newProvinceDataList[2][this.multiIndex[2]].name
				this.provinceId = this.newProvinceDataList[0][this.multiIndex[0]].id
				this.cityId = this.newProvinceDataList[1][this.multiIndex[1]].id
				this.areaId = this.newProvinceDataList[2][this.multiIndex[2]].id
			},
			getSeldCityList() {
			    let that = this;
			    that.Post({}, '/api/uservice/user/getAreas').then(res => {
			        if (res.code === 1) {
			            var data = res.data;
			            var result = {};
			
			            // 处理数据，构建省市区的层级结构
			            for (var i = 0; i < data.length; i++) {
			                var item = data[i];
			                if (item.level === 0) {
			                    continue; // 跳过国家层级
			                }
			                if (item.level === 1) {
			                    // 处理省份
			                    result[item.id.toString()] = {
			                        id: item.id,
			                        name: item.name,
			                        children: []
			                    };
			                } else if (item.level === 2) {
			                    // 处理城市
			                    var provinceId = item.pid.toString();
			                    if (result[provinceId]) {
			                        result[provinceId].children.push({
			                            id: item.id,
			                            name: item.name,
			                            children: []
			                        });
			                    }
			                } else if (item.level === 3) {
			                    // 处理区域
			                    var cityId = item.pid.toString();
			                    for (var j = 0; j < Object.keys(result).length; j++) {
			                        var province = result[Object.keys(result)[j]];
			                        for (var k = 0; k < province.children.length; k++) {
			                            var city = province.children[k];
			                            if (city.id.toString() === cityId) {
			                                city.children.push({
			                                    id: item.id,
			                                    name: item.name
			                                });
			                                break;
			                            }
			                        }
			                    }
			                }
			            }
			
			            // 将 Object 转为 Array
			            var r = [];
			            for (var i in result) {
			                r.push(result[i]);
			            }
			
			            // 将数据赋值给省市区联动选择器
			            that.district = r;
			
			            // 初始化省市区数据
			            let arr = [];
			            let arr1 = [];
			            let arr2 = [];
			
			            that.district.forEach(item => {
			                arr.push(item);
			            });
			
			            if (that.district.length > 0 && that.district[0].children.length > 0) {
			                that.district[0].children.forEach(item => {
			                    arr1.push(item);
			                });
			
			                if (that.district[0].children[0].children.length > 0) {
			                    that.district[0].children[0].children.forEach(item => {
			                        arr2.push(item);
			                    });
			                }
			            }
			
			            that.columns = arr;
			            // 控制异步数据
			            that.ready = true;
			
			            // 填充 newProvinceDataList
			            that.newProvinceDataList[0] = [];
			            that.newProvinceDataList[1] = [];
			            that.newProvinceDataList[2] = [];
			
			            for (let i = 0; i < that.columns.length; i++) {
			                that.newProvinceDataList[0].push({ name: that.columns[i].name, id: that.columns[i].id });
			            }
			
			            if (that.columns.length > 0 && that.columns[0].children.length > 0) {
			                for (let i = 0; i < that.columns[0].children.length; i++) {
			                    that.newProvinceDataList[1].push({ name: that.columns[0].children[i].name, id: that.columns[0].children[i].id });
			                }
			
			                if (that.columns[0].children[0].children.length > 0) {
			                    for (let i = 0; i < that.columns[0].children[0].children.length; i++) {
			                        that.newProvinceDataList[2].push({ name: that.columns[0].children[0].children[i].name, id: that.columns[0].children[0].children[i].id });
			                    }
			                }
			            }
			        }
			    });
			},
			// 滑动
			pickerColumnchange(e){
				// 第几列滑动
				// console.log(e.detail.column);
				// 第几列滑动的下标
				// console.log(e.detail.value)
				// 第一列滑动
				if(e.detail.column === 0){
					this.multiIndex[0] =  e.detail.value
					// console.log('第一列滑动');
					// this.newProvinceDataList[1] = [];
					this.newProvinceDataList[1] = this.columns[this.multiIndex[0]].children.map((item,index)=>{
						// console.log(item)
						return item
					})
					// console.log(this.multiIndex)
					if(this.columns[this.multiIndex[0]].children.length === 1){
						this.newProvinceDataList[2] = this.columns[this.multiIndex[0]].children[0].children.map((item,index)=>{
							// console.log(item)
							return item
						})
					}else{
						this.newProvinceDataList[2] = this.columns[this.multiIndex[0]].children[this.multiIndex[1]].children.map((item,index)=>{
							// console.log(item)
							return item
						})
					}
					// 第一列滑动  第二列 和第三列 都变为第一个
					this.multiIndex.splice(1, 1, 0)
					this.multiIndex.splice(2, 1, 0)
				}
				// 第二列滑动
				if(e.detail.column === 1){
					this.multiIndex[1] =  e.detail.value
					// console.log('第二列滑动');
					// console.log(this.multiIndex)
					this.newProvinceDataList[2] = this.columns[this.multiIndex[0]].children[this.multiIndex[1]].children.map((item,index)=>{
						// console.log(item)
						return item
					})
					// 第二列 滑动 第三列 变成第一个
					this.multiIndex.splice(2, 1, 0)
				}
				// 第三列滑动
				if(e.detail.column === 2){
					this.multiIndex[2] =  e.detail.value
					// console.log('第三列滑动')
					// console.log(this.multiIndex)
				}
			},
			getDetail() {
				this.Post({
					id: this.id
				}, "/api/uservice/user/getContactInfoById").then(res => {
					res = res.data;
					if (res && res.id > 0) {
						this.username = res.name
						this.mobile = res.tel
						this.idDefault = res.is_default == 1 ? true : false
						this.provinceId = res.province_id
						this.cityId = res.city_id
						this.areaId = res.district_id
						this.citySeld = res.seldAdd
						this.detailAddr = res.detail_addr;
						this.getSeldCityList();
					}
				})
			},
			postSave() {
				this.username = this.username.trim()
				this.mobile = this.mobile.trim()
				this.detailAddr = this.detailAddr.trim()
				if (this.username.length < 1) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					})
					return
				}
				if (this.username.length > 6) {
					uni.showToast({
						title: '姓名最多6个字',
						icon: 'none'
					})
					return
				}
				if (!this.IsTel(this.mobile)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return
				}
				if (this.citySeld.length < 1) {
					uni.showToast({
						title: '请选择地区',
						icon: 'none'
					})
					return
				}
				if (this.detailAddr.length < 2) {
					uni.showToast({
						title: '请输入具体地址',
						icon: 'none'
					})
					return
				}
				this.Post({
					username: this.username,
					mobile: this.mobile,
					is_default: this.idDefault ? '1' : '0',
					province_id: this.provinceId,
					city_id: this.cityId,
					district_id: this.areaId,
					detail_addr: this.detailAddr,
					id: this.id || null
				},'/api/uservice/user/' + (this.id > 0 ? 'edit' : 'addNew') + 'Consignee').then(res => {
					if(res.code == 1){
						uni.setStorageSync('addressNow',JSON.stringify(res.data))
						uni.showModal({
							title: '提示',
							content: this.id>0?'编辑成功':'添加成功',
							showCancel: false,
							success: res => {
								if(res.confirm){
									uni.navigateBack({})
								}
							}
						})
					}else{
						uni.showModal({
							title: '提示',
							content: res.msg,
							showCancel: false,
							success: res => {
								
							}
						})
					}
				})
			}
		}
	}
</script>

<style scoped>
	.bg {
		min-height: 100vh;
		background-color: white;
		display: flex;
		flex-direction: column;
	}

	.list-forms {
		display: flex;
		flex-direction: column;
		border-top: 1rpx solid #D8D8D8;
		padding: 20rpx 40rpx;
		box-sizing: content-box
	}

	.list-item {
		display: flex;
		border-bottom: 1rpx solid #D8D8D8;
		padding: 30rpx 0;
		height: 60rpx;
		align-items: center;
		box-sizing: content-box
	}

	.list-item-title {
		width: 150rpx;
		font-size: 31rpx;
		margin-right: 20rpx;
	}

	.list-item-input {
		flex: 1;
	}

	.list-item-input input {
		width: 100%;
		height: 100%;
		padding: 0;
		margin: 0;
		border: 0;
		background-color: transparent;
		line-height: 34rpx;
		font-size: 31rpx;
		text-align: right;
		font-weight: 500;
	}

	.list-item-input input::placeholder {
		font-size: 26rpx;
	}

	.list-item-switch {
		display: flex;
		flex: 1;
		justify-content: flex-end;
	}

	.list-item-btn {
		display: flex;
		justify-content: center;
		margin-top: 20rpx;
	}

	.list-item-post {
		display: flex;
		color: #FFFFFF;
		font-size: 36rpx;
		width: 697rpx;
		height: 73rpx;
		background: #6A8A2D;
		border-radius: 37rpx;
		justify-content: center;
		align-items: center;
		margin-top: 650rpx;
	}
</style>
