<template>
	<picker @change="bindPickerChange" @columnchange="columnchange" :range="array" range-key="name" :value="value" mode="multiSelector"><slot></slot></picker>
</template>

<script>
import AllAddress from './city-picker.data.js';
let selectVal = [
	{
		name: '安徽省',
		code: '340000'
	},
	{
		name: '合肥市',
		code: '340100'
	},
	{
		name: '瑶海区',
		code: '340102'
	}
];
export default {
	data() {
		return {
			value: [0, 0, 0],
			code:['340000','340100','340102'],
			array: [],
			index: 0
		};
	},
	created() {
		this.initSelect();
	},
	methods: {
		// 初始化地址选项
		initSelect() {
			this.updateSourceDate() // 更新源数据
				.updateAddressDate() // 更新结果数据
				.$forceUpdate(); // 触发双向绑定
		},
		// 地址控件改变控件
		columnchange(d) {
			this.updateSelectIndex(d.detail.column, d.detail.value)// 更新选择索引
			.updateAddressDate(d.detail.column) // 更新结果数据
			.updateSourceDate() // 更新源数据
			.$forceUpdate(); // 触发双向绑定
		},

		/**
		 * 更新源数据
		 * */
		updateSourceDate() {
			let obj = this;
			obj.array = [[], [], []];
			for (let i in AllAddress[86]) {
				// 循环对象中的数组数据
				AllAddress[86][i].forEach(e => {
					obj.array[0].push({
						name: e.address,
						code: e.code
					});
				});
			}
			for (let i in AllAddress[selectVal[0].code]) {
				// 循环对象中的数组数据
				obj.array[1].push({
					name: AllAddress[selectVal[0].code][i],
					code: i
				});
			}
			for (let i in AllAddress[selectVal[1].code]) {
				// 循环对象中的数组数据
				obj.array[2].push({
					name: AllAddress[selectVal[1].code][i],
					code: i
				});
			}
			return obj;
		},

		/**
		 * 更新索引
		 * */
		updateSelectIndex(column, value) {
			let arr = JSON.parse(JSON.stringify(this.value));
			arr[column] = value;
			if (column === 0) {
				arr[1] = 0;
				arr[2] = 0;
			}
			if (column === 1) {
				arr[2] = 0;
			}
			this.value = arr;
			return this;
		},

		/**
		 * 更新结果数据
		 * */
		updateAddressDate(column) {
			// 保存一级对象数据
			selectVal[0] = this.array[0][this.value[0]];
			if (column === 0) {
				// 查询二级对象数据
				let arr1 = AllAddress[selectVal[0].code];
				for(let i in arr1){
					selectVal[1] = {
							name: arr1[i],
							code: i
					};
					break
				}
				// 查询三级对象数据
				let arr2 = AllAddress[selectVal[1].code];
				for(let i in arr2){
					selectVal[2] = {
							name: arr2[i],
							code: i
					};
					break
				}
				
			}
			if (column === 1) {
				// 保存当前选中的二级对象数据
				selectVal[1] = this.array[1][this.value[1]]
				// 查询三级数据
				let arr2 = AllAddress[selectVal[1].code];
				for(let i in arr2){
					selectVal[2] = {
							name: arr2[i],
							code: i
					};
					break
				}
			}
			return this;
		},

		/**
		 * 点击确定
		 * */
		bindPickerChange(e) {
			console.log(this.value,'++++++++++++++++',selectVal)
			this.$emit('change', {
				index: this.value,
				data: selectVal
			});
			return this;
		}
	}
};
</script>

<style></style>
