<template>
	<!-- 选择公司 -->
	<view>
		<u-navbar title="选择公司" autoBack placeholder></u-navbar>
		<view class="card_company" v-if="treeList.length > 0">
			<view class="hint_title">请选择燃气公司</view>
			<firm-tree v-for="item in treeList" :key="item.id" :item="item" @confirm="confirm"></firm-tree>
		</view>
		<view style="margin-top: 30%;" v-else>
			<u-empty mode="list" text="该区/县暂无商家入驻"></u-empty>
		</view>
	</view>
</template>

<script>
	import firmTree from '@/components/firmTree.vue';
	import {
		urbanArea
	} from '@/static/js/districtCode.js'
	export default {
		components: {
			firmTree
		},
		data() {
			return {
				src: 'https://cdn.uviewui.com/uview/album/1.jpg',
				treeList: [],
				areaData: urbanArea(), //原始数据
			}
		},
		mounted() {
			this.getList()
		},
		methods: {
			getList() {
				var city1 = this.$cache.getCache('city')
				var district2 = this.$cache.getCache('district')
				let params = {
					city: '',
					district: ''
				}
				if (city1) {
					params.city = this.cityScreening(city1, this.areaData)
				} else if (district2) {
					params.district = this.cityScreening(district2, this.areaData)
				}
				this.$api.get('/api/applet/store', params).then(res => {
					if (res.code == 200) {
						if (res.data) {
							this.treeList = res.data
						}
					}
				})
			},
			// 城市筛选
			cityScreening(value, list) {
				function getChildById(parentArray, id) {
					for (let i = 0; i < parentArray.length; i++) {
						if (parentArray[i].label === id) { // 如果当前元素的ID与目标ID相等，则返回该元素
							return parentArray[i];
						} else if (parentArray[i].children && Array.isArray(parentArray[i]
								.children)) { // 判断当前元素是否有子节点且类型为数组
							const result = getChildById(parentArray[i].children, id); // 对子节点进行递归调用
							if (result !== null) { // 若子节点存在结果，则返回该结果
								return result;
							}
						}
					}
					return null; // 没有找到符合条件的元素时返回null
				}
				var name = getChildById(list, value)
				if (name != null) {
					return name.value
				}
			},
			// 选择门店\去订气
			confirm(cmpCode) {
				this.$cache.setCache('orderList', {})
				uni.navigateTo({
					url: '/pages/order/booking?companyId=' + cmpCode
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.card_company {
		display: flex;
		flex-direction: column,
	}

	.hint_title {
		padding-left: 30rpx;
		margin-top: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid transparent;
		border-image: linear-gradient(to bottom, transparent 50%, #e7e6e4 50%) 0 0 100% 0;
		font-size: 26rpx;
		color: #909399;
	}
</style>