<!--
 * @Author: ch
 * @Date: 2022-03-29 16:05:06
 * @LastEditors: ch
 * @LastEditTime: 2022-05-21 20:04:47
 * @Description: file content
-->
<template>
	<view>
		<UiCell title="所在区域" @click="show = true">
			<template slot="value">
				<input class="cityInput" disabled :value="valueText" placeholder="请选择省市区" />
			</template>
		</UiCell>
		<u-picker
			:show="show"
			ref="picker"
			keyName="name"
			:columns="columnsData"
			:defaultIndex="defaultIndex"
			@cancel="show = false"
			@change="changeCity"
			@confirm="confirm"
		/>
	</view>
</template>
<script>
import UiCell from "./UiCell";
import Province from '@/common/dicts/area.json';
const DefaultCityColumn = Province[0].children;
const DefaultAreaColumn = DefaultCityColumn[0].children;
export default {
	components: { UiCell },
	props: {
		value : {
			type : Array,
			default : []
		}
	},
	data() {
		return {
			show: false,
			columnsData : [],
			defaultIndex : []
		};
	},
	computed:{
		valueText(){
			return this.value.map(i => i.name).join('/');
		},
		
	},
	watch:{
		value(val){
			this.setColumAndDefalut(val);
		}
	},
	mounted(){
		this.setColumAndDefalut(this.value);

	},
	methods: {
		/**
		 * 设置列数据和默认选中值
		 */
		setColumAndDefalut(val){

			if(val.length){
				// 省选中值下标
				const provinceIndex =  Province.findIndex(item => val[0].code === item.code) || 0;

				// 市选数据
				const city = Province[provinceIndex].children;
				const cityIndex = city.findIndex(item => val[1].code === item.code) || 0;
				
				// 区数据
				const area = city[cityIndex].children;
				const areaIndex = area.findIndex(item => val[2].code === item.code) || 0;

				this.columnsData = [Province, city, area];
				this.defaultIndex = [provinceIndex, cityIndex, areaIndex]
			}else{
				this.columnsData = [Province, DefaultCityColumn, DefaultAreaColumn];
			}
		},
		changeCity(val) {
			if(val.columnIndex == 2){
				return;
			}
			let newIndexs = val.indexs;
			if(val.columnIndex == 0){
				newIndexs[1] = 0;
			}
			newIndexs[2] = 0;
			this.defaultIndex = newIndexs;

			const city = val.value[0].children;
			const area = city[newIndexs[1]].children;
			
			this.$refs.picker.setColumnValues(1, city);
			this.$refs.picker.setColumnValues(2, area);
		},
		confirm(value) {
			this.show = false;
			this.$emit('input', value.value)
			this.$emit('change', value.value)
		},
	},
};
</script>
<style lang="scss" scoped>
.cityInput{
	flex: 1;
	font-size: $font-size-base;
	padding-left: 40rpx;
}
</style>