<template>
	<view>
		<!-- 顶部操作条 -->
		<cu-custom :bgColor="'bg-main-color'" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">产品分类</block>
		</cu-custom>
		<vertical-nav v-if="categoryList" :containerHeight="containerHeight" :navList="level0CategoryList" :list="categoryList" :isClick2ShowProducts="true"></vertical-nav>
	</view>
</template>

<script>
	import verticalNav from '@/components/multi-level-nav/vertical-nav.vue';
	
	export default {
		components: {
			verticalNav
		},
		data() {
			return {
				containerHeight: '100vh - ' + this.CustomBar + 'px - 46px',
				level0CategoryList: [],
				categoryList: []
			}
		},
		onLoad() {
			this.loadData();
			this.bindEvent();
		},
		onUnload() {
			this.offBindEvent();
		},
		methods: {
			async loadData(params = {}, type = 1) {
				let res0 = await this.$request.listByStep({
					level: 0
				});
				this.level0CategoryList = res0.data;
				this.loadTargetTypeCategoryList(params, type);
			},
			async loadTargetTypeCategoryList(params = {}, type = 1) {
				this.categoryList = [];
				// this.categoryList = await this.$api.data('categoryList');
				let res = await this.$request.getProductCategories({
					...params,
					type: type
				});
				res = res[1].data.data;
				res.forEach(firstCategory => {
					if (firstCategory.child && firstCategory.child.length) {
						this.categoryList = this.categoryList.concat(firstCategory.child)
					}
				})
			},
			bindEvent() {
				uni.$on(this.$globalFun.VERTICAL_NAV_GET_ITEM, this.chooseSubType);
				uni.$on(this.$globalFun.VERTICAL_NAV_SEARCH, this.searchType);
				uni.$on(this.$globalFun.VERTICAL_NAV_CHANGE_MAIN_NAV_ITEM, this.changeLevel0Category);
			},
			offBindEvent() {
				uni.$off(this.$globalFun.VERTICAL_NAV_GET_ITEM);
				uni.$off(this.$globalFun.VERTICAL_NAV_SEARCH);
				uni.$off(this.$globalFun.VERTICAL_NAV_CHANGE_MAIN_NAV_ITEM);
			},
			chooseSubType(item) {
				let params = {
					category: item
				};
				uni.navigateTo({
					url: '/pages/product/filtered-products?params=' + encodeURIComponent(JSON.stringify(params))
				})
			},
			searchType(keyWords) {
				this.loadData({
					goodsCategoryName: keyWords
				});
			},
			changeLevel0Category(category) {
				this.loadTargetTypeCategoryList({}, category.type);
			}
		}
	}
</script>

<style>
</style>
