<template>
	<div class="w100">
		<el-row>
			<el-col :span="18">
				<el-tree-select
					v-model="internalValue"
					lazy
					:load="loadNode"
					:props="{
						label: 'hotSpotFullName',
						children: 'children',
						isLeaf: 'hasChild',
					}"
					node-key="id"
					:default-expanded-keys="externalArr"
					ref="treeRef"
					filterable
					class="w100"
					:placeholder="props.placeholder"
					@node-click="nodeClick"
					:clearable="props.clearable"
					highlight-current
					@clear="clear"
					:check-strictly="props.checkStrictly"
				>
				</el-tree-select>
			</el-col>
			<el-col :span="5" :offset="1">
				<el-button @click="dialogVisible = true"><SvgIcon name="ele-Search" class="mr3" />快捷查询</el-button>
			</el-col>
		</el-row>
	</div>
	<el-drawer v-model="dialogVisible" title="热点快速查找" destroy-on-close append-to-body>
		<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
			<el-form-item label="" prop="name">
				<el-input v-model="state.queryParams.name" placeholder="请输入热点名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
			</el-form-item>
			<el-form-item label="">
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">重置</el-button>
			</el-form-item>
		</el-form>
		<el-scrollbar class="border-box">
			<el-tree
				ref="treeRef"
				:data="tableData"
				:props="{
					label: 'hotSpotFullName',
					children: 'children',
					isLeaf: 'hasChild',
				}"
				default-expand-all
				v-loading="state.loading"
				highlight-current
				@node-click="nodeClickDialog"
				:check-strictly="props.checkStrictly"
				:expand-on-click-node="false"
			>
			</el-tree>
		</el-scrollbar>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false" class="default-button">取 消</el-button>
				<el-button type="primary" :disabled="!tableRadio" @click="onSave" :loading="state.loading">确定</el-button>
			</span>
		</template>
	</el-drawer>
</template>
<script setup lang="ts">
import { computed, PropType, reactive, ref, watch } from 'vue';
import { removeDuplicate } from '@/utils/arrayOperation';
import { hotSpotSearch, hotSpotType } from '@/api/business/order';
import { ElMessage, FormInstance } from 'element-plus';

const props = defineProps({
	modelValue: {
		type: [String, Array, null, undefined] as PropType<string | null | Array<object> | undefined>,
		default: () => null,
	},
	disabled: {
		type: Boolean,
		default: false,
	},
	placeholder: {
		type: String,
		default: '请选择热点分类',
	},
	externalArr: {
		// 外部传入的父级id数组 懒加载时使用
		type: Array,
		default: () => [],
	},
	clearable: {
		type: Boolean,
		default: false,
	},
	checkStrictly: {
		// 选择任意一级
		type: Boolean,
		default: false,
	},
	isYB:{
		// 是否是宜宾 并且是市工单 需要排除掉人社行业热点
		type: Boolean,
		default: false,
	}
} as any);
const emit = defineEmits(['update:modelValue', 'update:externalArr', 'change', 'getCurrentData']);
const internalValue = computed({
	get: () => props.modelValue,
	set: (val) => emit('update:modelValue', val),
});
watch(
	() => props.modelValue,
	(val) => {
		internalValue.value = val;
	},
	{ immediate: true }
);
const externalArr = computed({
	get: () => props.externalArr,
	set: (val) => emit('update:externalArr', val),
});
watch(
	() => props.externalArr,
	(val) => {
		externalArr.value = val;
	},
	{ immediate: true }
);

const nodeClick = async (val: any, node: any) => {
	externalArr.value = [];
	if (node.isLeaf) {
		internalValue.value = val.id;
		externalArr.value = getParentId(node, externalArr.value);
		emit('change', val, node, externalArr.value);
	}
};
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return removeDuplicate(arr);
};
const treeRef = ref();
const loadNode = async (node: any, resolve: any) => {
	if (node.isLeaf) return resolve([]);
	try {
		const { result } = await hotSpotType({ id: node.data.id ? node.data.id : null });
		let resultHotspot = result;
		if(props.isYB){
			resultHotspot = resultHotspot.filter((item:any)=>item.id !== '20')
		}
		resolve(resultHotspot);
		const currentNode = treeRef.value?.getNode(internalValue.value);
		emit('getCurrentData', currentNode);
	} catch (e) {
		console.log(e);
	}
};
const dialogVisible = ref(false);
const tableData = ref([]);
const state = reactive({
	queryParams: {
		name: '',
	},
	loading: false,
});
const handleQuery = async () => {
	if (!state.queryParams.name) {
		ElMessage.warning('请输入热点名称以进行查询');
		return;
	}
	state.loading = true;
	try {
		const { result } = await hotSpotSearch(state.queryParams.name);
		let resultHotspot = result;
		if(props.isYB){
			resultHotspot = resultHotspot.filter((item:any)=>item.id !== '20')
		}
		tableData.value = resultHotspot;
		state.loading = false;
	} catch (e) {
		console.log(e);
	} finally {
		state.loading = false;
	}
};
/** 重置按钮操作 */
const ruleFormRef = ref<RefType>(); // 表单ref
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
};
const tableRadio = ref();
const nodeClickDialog = (val: any, node: any) => {
	if (props.checkStrictly) {
		// 可以选择任意一级
		tableRadio.value = val.id;
		externalArr.value = getParentId(node, externalArr.value);
		emit('change', val, node, externalArr.value);
	} else {
		if (node.isLeaf) {
			tableRadio.value = val.id;
			externalArr.value = getParentId(node, externalArr.value);
			emit('change', val, node, externalArr.value);
		} else {
			tableRadio.value = null;
			externalArr.value = [];
		}
	}
};
const onSave = () => {
	internalValue.value = tableRadio.value;
	dialogVisible.value = false;
};
const clear = () => {
	internalValue.value = null;
	emit('change', null, null, []);
};
defineExpose({});
</script>
<style scoped lang="scss">
.border-box {
	border: var(--el-border);
	border-radius: var(--el-border-radius-base);
	padding: 15px;
	max-height: calc(100% - 100px);
}
:deep(.el-tree) {
	.el-tree-node {
		/*设置横向滚动条*/
		min-width: 100% !important;
		display: block !important;
		float: left;
	}
}
</style>
