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

<script>
const req = require('../../utils/request.js');
// import AllAddress from './data.js';
let selectVal = ['', '', ''];

export default {
	data() {
		return {
			value: [0, 0, 0],
			ids: [],
			array: [],
			index: 0,
			allAddressData: []
		};
	},
	created() {
		this.getReqAreaList();
	},
	methods: {
		getReqAreaList() {
			let areaList = req.getStorage('areaList');
			if (areaList && areaList.length > 0) {
				this.allAddressData = areaList;
				this.initSelect();
			} else {
				req.getRequest(
					'/area/list',
					{},
					data => {
						req.setStorage('areaList', data);
						this.allAddressData = data;
						this.initSelect();
					},
					true
				);
			}
		},
		// 初始化地址选项
		initSelect() {
			this.updateSourceDate() // 更新源数据
				.updateAddressDate() // 更新结果数据
				.updateIdsDate()
				.$forceUpdate(); // 触发双向绑定
		},
		// 地址控件改变控件
		columnchange(d) {
			this.updateSelectIndex(d.detail.column, d.detail.value) // 更新选择索引
				.updateSourceDate() // 更新源数据
				.updateAddressDate()
				.updateIdsDate() // 更新结果数据
				.$forceUpdate(); // 触发双向绑定
		},

		/**
		 * 更新源数据
		 * */
		updateSourceDate() {
			this.array = [];
			this.array[0] = this.allAddressData.map(obj => {
				return {
					name: obj.label,
					id: obj.value
				};
			});
			this.array[1] = this.allAddressData[this.value[0]].nodes.map(obj => {
				return {
					name: obj.label,
					id: obj.value
				};
			});
			this.array[2] = this.allAddressData[this.value[0]].nodes[this.value[1]].nodes.map(obj => {
				return {
					name: obj.label,
					id: obj.value
				};
			});
			return this;
		},

		/**
		 * 更新索引
		 * */
		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() {
			selectVal = [];
			selectVal[0] = this.array[0][this.value[0]].name + ' ';
			selectVal[1] = this.array[1][this.value[1]].name + ' ';
			if (this.array[2].length > 0) {
				selectVal[2] = this.array[2][this.value[2]].name + ' ';
			}
			return this;
		},
		updateIdsDate() {
			this.ids = [];
			this.ids[0] = this.array[0][this.value[0]].id;
			this.ids[1] = this.array[1][this.value[1]].id;
			if (this.array[2].length > 0) {
				this.ids[2] = this.array[2][this.value[2]].id;
			}
			return this;
		},

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

<style></style>
