<template>
	<view>

		<view class="box" @click.stop="openPopup">
			<text class="u-font-28 color-999 u-p-r-16" v-if="selArr[0]===null||selArr[1]===null">请选择</text>
			<text class="u-font-28 color-333 u-p-r-16" v-else>{{returnLabel()}}</text>
			<view class="icon">
				<up-icon name="arrow-down" size="14" color="#999"></up-icon>
			</view>
		</view>
		<up-popup :show="show" placement="bottom" round="18rpx" closeOnClickOverlay @close="close">
			<view class="u-p-30">
				<view class="font-bold color-333 u-font-32">选择行业类目</view>
				<view class="u-m-t-24">
					<up-search v-model="query.bankName" @search="search" @change="bankNameChange" @custom="search"
						@clear="search"></up-search>
				</view>
				<view class="u-flex u-m-t-30 gap-20 u-col-top">
					<view class="u-flex-1">
						<view class="u-p-b-24 font-bold text-center">一级类目</view>
						<scroll-view @scrolltolower="scrolltolower" scroll-with-animation :scroll-into-view="oneSelId"
							class="scroll-view " scroll-y="true" style="max-height :60vh;">
							<view class="u-m-b-10 u-flex item" v-for="(item,index) in list" :key="item.id"
								@click="oneCategoryClick(index)" :id="'cateOne_'+index"
								:class="{active:selArr[0]===index}">
								<view class="checkbox">
									<up-icon name="checkbox-mark" color="#fff"></up-icon>
								</view>
								<view class="u-flex-1">{{item.firstCategory}}</view>
							</view>
							<up-empty v-if="list.length==0" text="暂无相关分类"></up-empty>
						</scroll-view>
					</view>
					<view class="u-flex-1">
						<view class="u-p-b-24 font-bold text-center">二级类目</view>
						<scroll-view @scrolltolower="scrolltolower" scroll-with-animation :scroll-into-view="twoSelId"
							class="scroll-view " scroll-y="true" style="max-height :60vh;">
							<view class="u-m-b-10 u-flex item" v-for="(item,index) in sendList" :key="item.id"
								@click="selArr[1]=index" :id="'cateTwo_'+index" :class="{active:selArr[1]==index}">
								<view class="checkbox">
									<up-icon name="checkbox-mark" color="#fff"></up-icon>
								</view>
								<view class="u-flex-1">{{item.secondCategory}}</view>
							</view>
							<up-empty v-if="list.length==0" text="暂无相关分类"></up-empty>
						</scroll-view>
					</view>

				</view>


				<view class="u-flex gap-20 u-m-t-30">
					<view class="u-flex-1">
						<my-button type="default" @click="close">取消</my-button>
					</view>
					<view class="u-flex-1">
						<my-button type="primary" @click="submit">确定</my-button>
					</view>
				</view>
			</view>
		</up-popup>
	</view>
</template>
<script setup>
	import {
		computed,
		nextTick,
		onMounted,
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		mccCategory
	} from '@/http/api/system/common.js';
	const customStyle = ref({
		marginRight: '20px'
	});

	const show = ref(false);
	const modelValue = defineModel();




	const oneSelId = ref('')
	const twoSelId = ref('')

	const allCategoryArr = computed(() => {
		return list.value.reduce((prve, cur) => {
			prve.push(...cur.child)
			return prve
		}, [])
	})

	function returnLabel() {
		const [index1, index2] = selArr.value
		console.log('selArr', selArr.value);
		if (index1 !== null && index2 !== null) {
			return list.value[index1].firstCategory + '/' + list.value[index1].child[index2].secondCategory
		}
		return ''
	}

	function oneCategoryClick(index) {
		selArr.value[0] = index
		selArr.value[1] = null
	}

	const selItem = ref(null)

	function itemClick(bank) {
		selItem.value = bank;

	}



	function close() {
		show.value = false;
	}

	function submit() {
		if (selArr.value[0] === null || selArr.value[1] === null) {
			return uni.showToast({
				title: '请选择行业类目',
				icon: 'none'
			})
		}
		const [oneIndex, twoIndex] = selArr.value
		const item = list.value[oneIndex].child[twoIndex]
		modelValue.value = item.firstCategoryCode + '_' + item.secondCategoryCode
		show.value = false;

	}

	function search() {
		init()
	}

	const list = ref([]);
	

	function openPopup() {

		show.value = true;

	}

	// --------------- 核心新增：节流函数实现 ---------------
	/**
	 * 节流函数：限制函数在指定时间内只触发一次
	 * @param {Function} fn - 要节流的函数
	 * @param {number} delay - 节流延迟时间（毫秒）
	 * @returns {Function} 节流后的函数
	 */
	function throttle(fn, delay = 300) {
		let timer = null; // 定时器标识
		return function(...args) {
			// 如果已有定时器，直接返回（未到触发时间）
			if (timer) return;
			// 执行函数并设置新定时器
			fn.apply(this, args);
			timer = setTimeout(() => {
				clearTimeout(timer);
				timer = null;
			}, delay);
		};
	}

	// --------------- 核心修改：创建节流后的search方法 ---------------
	// 300ms内只触发一次search，可根据需求调整delay值（如500ms）
	const throttledSearch = throttle(search, 300);

	// --------------- 改造bankNameChange：调用节流后的搜索 ---------------
	function bankNameChange() {
		// 输入变化时，调用节流后的搜索方法
		throttledSearch();
	}

	const query = reactive({
		bankName: ''
	})
	const isEnd = ref(false)

	function scrolltolower() {

	}


	async function init() {
		const res = await mccCategory(query);
		if (res) {
			list.value = res.map(v => {
				return {
					...v,
					firstCategoryCode: v.child[0].firstCategoryCode
				}
			})
			startWatch()
		}
	}

	const selArr = ref([null, null])
	const sendList = computed(() => {
		if (selArr.value[0] !== null) {
			return list.value[selArr.value[0]].child
		}
	})

	function startWatch() {
		watch(() => modelValue.value, (newval) => {
			if (newval) {
				const arr = modelValue.value.split('_')
				const [oneCode, twoCode] = arr
				console.log('oneCode',oneCode);
				console.log('twoCode',twoCode);
				const oneIndex = list.value.findIndex(v => v.firstCategoryCode == oneCode)
				if (oneIndex != -1) {
					selArr.value[0] = oneIndex
					oneSelId.value = 'cateOne_' + oneIndex
					const twoIndex = list.value[oneIndex].child.findIndex(v => v.secondCategoryCode==twoCode)
					if (twoIndex != -1) {
						selArr.value[1] = twoIndex
						twoSelId.value = 'cateTwo_' + twoIndex
					}
				}
				console.log('watch selArr',selArr.value);
			} else {
				selArr.value = [null, null]
			}
		}, {
			immediate: true
		})

	}

	onMounted(init);
</script>
<style lang="scss">
	.box {
		border-radius: 8upx;
		display: flex;
		flex-direction: row;
		align-items: top;
		flex-wrap: wrap;
		padding: 20rpx 24rpx;
		border: 2rpx solid #e5e5e5;
		position: relative;

		.icon {
			position: absolute;
			top: 50%;
			right: 24rpx;
			transform: translateY(-50%);
		}
	}

	.shop-item {
		padding: 4rpx 8rpx 4rpx 16rpx;
		border-radius: 4rpx;
		border: 2rpx solid #f0f0f0;
		background-color: #f5f5f5;
		margin-bottom: 16rpx;
		margin-left: 16rpx;
	}

	.scroll-view {
		.item {
			border: 1px solid #eee;
			padding: 20rpx;
			border-radius: 12rpx;

			&.active {
				border-color: $my-main-color;
			}

		}
	}

	.checkbox {
		margin-right: 10rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 6rpx;
		border: 1px solid #999;

	}

	.item {
		&.active {
			.checkbox {
				background-color: $my-main-color;
				border-color: $my-main-color;
			}
		}
	}
</style>