<template>
	<view>
		<u-picker ref="uPicker" :show="areaShow" :defaultIndex="[1, 0, 0]" :columns="columns" @change="changeHandler"
			@confirm="confirm" @cancel="cancel" keyName="areaName"></u-picker>
	</view>
</template>

<script>
	import $http from '@/utils/request.js'
	export default {
		name: "area-picker",
		props: {
			areaShow: {
				type: [Boolean],
				default: false
			},
		},
		data() {
			return {
				columns: []
			};
		},
		methods: {
			async getArea() {
				const picker = this.$refs.uPicker
				let provinceRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: 0
				})
				let cityRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: provinceRes && provinceRes.data && provinceRes.data[1].areaId
				})
				let areaRes = await $http.post('/api/v1/mp/area/listByPid', {
					pid: cityRes && cityRes.data && cityRes.data[0].areaId
				})
				picker.setColumnValues(0, provinceRes.data)
				picker.setColumnValues(1, cityRes.data)
				picker.setColumnValues(2, areaRes.data)
			},

			async changeHandler(e) {
				const {
					columnIndex,
					index,
					value,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				if (columnIndex === 0) {
					let cityRes = await $http.post('/api/v1/mp/area/listByPid', {
						pid: value && value[0].areaId
					})
					let areaRes = await $http.post('/api/v1/mp/area/listByPid', {
						pid: cityRes && cityRes.data && cityRes.data[0].areaId
					})
					picker.setColumnValues(1, cityRes.data)
					picker.setColumnValues(2, areaRes.data)
				}
				if (columnIndex === 1) {
					let areaRes = await $http.post('/api/v1/mp/area/listByPid', {
						pid: value && value[1].areaId
					})
					picker.setColumnValues(2, areaRes.data)
				}


			},

			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				const picker = this.$refs.uPicker
				const {
					value
				} = e
				// console.log(value);
				let confirmObj = {
					province: value[0].areaName,
					provinceId: value[0].areaId,
					city: value[1].areaName,
					cityId: value[1].areaId,
					area: value[2].areaName,
					areaId: value[2].areaId,
					cityShow: value.map(item => item.areaName).join('-')
				}
				this.$emit('confirmArea', confirmObj)
			},

			cancel() {
				this.$emit('cancel')
			},
		},
		mounted() {
			this.getArea()
		}
	}
</script>

<style lang="scss">

</style>
