<template>
	<view class="">
		<l-label :title="title">
			<picker mode="multiSelector" @columnchange="bindMultiPickerColumnChange" :value="multiIndex" :range="multiArray" @change="locationChange">
				<view class="picker">{{ multiArray[0][multiIndex[0]] }}-{{ multiArray[1][multiIndex[1]] }}-{{ multiArray[2][multiIndex[2]] }}</view>
			</picker>
		</l-label>
	</view>
</template>

<script>
import city from '@/common/js/city.js';
export default {
	name: 'location-picker',
	props: {
		multiIndex: { 
			type: Array, 
			default() {
				return [0, 0, 0]
			},
		},
		code:{}
	},
	data() {
		return {
			title: '省市区',
			multiArray: [[], [], []],
			codeArr: null
		};
	},
	methods:{
		init(){
			var _this = this;
			//根据code回显
			if(this.code != ''){
				this.codeArr = this.code.split(',');
				this.Feedback(city.cityData, 0);
			}
			this.cityCl(city.cityData, 0);
			this.locationChange()
			// console.log(this.code)
			// console.log(this.codeArr)
			// console.log(this.multiIndex)
		},
		Feedback(data, num) {
			let _this = this;
			data.forEach((n, i) => {
				if(n.value == _this.codeArr[num]){
					_this.multiIndex[num] = i;
					if (n.children) {
						let number = num + 1;
						_this.Feedback(n.children, number);
					}
				}
			});
		},
		locationChange() {
			let province = city.cityData[this.multiIndex[0]];
			let citys = province.children[this.multiIndex[1]];
			let area = citys.children[this.multiIndex[2]];

			// console.log(`province.value , citys.value , area.value`)
			this.$emit('input', province.value + ',' + citys.value + ',' + area.value)
			this.$emit('change', province.value + ',' + citys.value + ',' + area.value)
		},
		bindMultiPickerColumnChange: function(e) {
			// console.log(e);
			// console.log('修改的列为：' + e.detail.column + '，值为：' + e.detail.value);
			let _this = this;
			this.multiIndex[e.detail.column] = e.detail.value;
			if (e.detail.column == 0) {
				_this.multiArray[1].length = 0;
				_this.multiArray[2].length = 0;
				_this.multiIndex[1] = 0;
				_this.multiIndex[2] = 0;
				this.cityCl(city.cityData[_this.multiIndex[0]].children, 1);
			} else if (e.detail.column == 1) {
				_this.multiArray[2].length = 0;
				_this.multiIndex[2] = 0;
				this.cityCl(city.cityData[_this.multiIndex[0]].children[_this.multiIndex[1]].children, 2);
			}
			this.$forceUpdate();
		},
		cityCl(data, num) {
			let _this = this;
			data.forEach((n, i) => {
				if (i == _this.multiIndex[num] && n.children) {
					let number = num + 1;
					_this.cityCl(n.children, number);
				}
				_this.multiArray[num].push(n.text);
			});
		},
		watch: {
		  value() {
		    this.locationChange()
		  }
		}
	},
	mounted() {
		this.init()
	}
};
</script>

<style lang="less" scoped></style>
