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

<script>
	import AllAddress from './data.js'
	let selectVal = ['', '', '']
	let codeVal = ['','','']
	export default {
		data() {
			return {
				value: [0, 0, 0],
				array: [],
				codeArray:[],
				index: 0
			}
		},
		created() {
			this.getAllRegion()
		},
		methods: {
			//获取地址
			getAllRegion() {
				this.$api.my.allRegion().then(res => {
					this.AllAddress = res.data
					this.initSelect()
				})
			},
			// 初始化地址选项
			initSelect() {
				this.updateSourceDate() // 更新源数据
					.updateAddressDate() // 更新结果数据
					.$forceUpdate() // 触发双向绑定
			},
			// 地址控件改变控件
			columnchange(d) {
				this.updateSelectIndex(d.detail.column, d.detail.value) // 更新选择索引
					.updateSourceDate() // 更新源数据
					.updateAddressDate() // 更新结果数据
					.$forceUpdate() // 触发双向绑定
			},

			/**
			 * 更新源数据
			 * */
			updateSourceDate() {
				this.array = []
				this.array[0] = this.AllAddress.map(obj => {
					return {
						name: obj.full_name
					}
				})
				this.array[1] = this.AllAddress[this.value[0]].city_list.map(obj => {
					return {
						name: obj.full_name
					}
				})
				this.array[2] = this.AllAddress[this.value[0]].city_list[this.value[1]].area_list.map(obj => {
					return {
						name: obj.full_name
					}
				})
				this.codeArray = []
				this.codeArray[0] = this.AllAddress.map(obj => {
					return {
						code: obj.code
					}
				})
				this.codeArray[1] = this.AllAddress[this.value[0]].city_list.map(obj => {
					return {
						code: obj.code
					}
				})
				this.codeArray[2] = this.AllAddress[this.value[0]].city_list[this.value[1]].area_list.map(obj => {
					return {
						code: obj.code
					}
				})
				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[0] = this.array[0][this.value[0]].name
				selectVal[1] = this.array[1][this.value[1]].name
				selectVal[2] = this.array[2][this.value[2]].name
				codeVal[0] = this.codeArray[0][this.value[0]].code
				codeVal[1] = this.codeArray[1][this.value[1]].code
				codeVal[2] = this.codeArray[2][this.value[2]].code
				
				
				return this
			},

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

<style>
</style>
