<template>
	<div class="home">
		<div class="title">创建问卷模版</div>
		<div>
			<el-row>
				<el-col :span="8" style=" background-color: #ffffff;">
					<div class="demo-tabs">
						<el-tabs style=" background-color: #ffffff;" :stretch="true" v-model="activeName">
							<el-tab-pane label="题型" name="first">
								<div class="wrap1">
									<el-card class="topicCard">
										<template #header>
											<div class="card-header">
												<span>题型</span>
											</div>
										</template>
										<div class="surveyItem" @click="handleAdd('单选')"><el-icon class="iconEle">
												<CirclePlus />
											</el-icon>单选题</div>
										<div class="surveyItem" @click="handleAdd('多选')"><el-icon class="iconEle">
												<CirclePlus />
											</el-icon>多选题</div>
										<div class="surveyItem" @click="handleAdd('问答')"><el-icon class="iconEle">
												<CirclePlus />
											</el-icon>问答题</div>
										<div class="surveyItem" @click="handleAdd('排序')"><el-icon class="iconEle">
												<CirclePlus />
											</el-icon>排序</div>
									</el-card>

									<el-card class="topicCardTit">
										<div class="surveyTitle" v-for="(o, i) in surverTitData" :key="i">{{ `${i+ 1}. ${o}` }}</div>
									</el-card>
								</div>
							</el-tab-pane>
							<!-- <el-tab-pane label="大纲" name="second">
								<div class="wrap2">
									<el-tree default-expand-all style="max-width: 600px" :data="surverTreeData"
										:props="defaultProps" @node-click="handleNodeClick" />
								</div>
							</el-tab-pane> -->
							<el-tab-pane label="总分设置" name="three">
								<!-- <div class="wrap2 mb-4"> -->
								<div class="mb-4 p-4 max-h-[calc(100vh-200px)] overflow-y-auto">
									<div class="text-gray-700 mb-2">总分设置</div>
									<div class="mb-4">
										<div class="flex items-center gap-2 mb-2">
											<span class="text-sm text-gray-500">预警标签</span>
											<el-select v-model="warningLabel" placeholder="请选择预警标签" class="flex-1"
												@change="handleWarningLabelChange">
												<el-option v-for="(range, index) in scoreRanges" :key="index"
													:label="range.labelName" :value="range.tagSign">
													<div class="flex items-center">

														<div :style="{ backgroundColor: range.color }"
															class="w-3 h-3 rounded-full mr-2"></div>
														<span>{{range.labelName }} ({{ range.min }}-{{ range.max
															}}分)</span>
													</div>
												</el-option>
											</el-select>
										</div>
									</div>
									<div v-for="(range, index) in scoreRanges" :key="index"
										class="mb-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
										<div class="flex items-center justify-between mb-4">
											<span class="text-sm text-gray-600">分值区间 {{ index + 1 }}</span>
											<el-button type="text" @click="removeScoreRange(index)"
												class="!rounded-button">
												<el-icon>
													<Delete />
												</el-icon>
											</el-button>
										</div>
										<div class="grid grid-cols-2 gap-4 mb-3">

											<div class="flex flex-col gap-2">
												<span class="text-sm text-gray-500">最低分</span>
												<el-input-number v-model="range.min" :min="0" :max="100" class="w-full"
													:controls="false" />
											</div>
											<div class="flex flex-col gap-2">
												<span class="text-sm text-gray-500">最高分</span>
												<el-input-number v-model="range.max" :min="0" :max="100" class="w-full"
													:controls="false" />
											</div>
										</div>
										<div class="flex items-center gap-2">
											<span class="text-sm text-gray-500">标签</span>
											<!-- <el-input v-model="range.labelName" placeholder="请输入标签" class="flex-1" /> -->
											<el-cascader ref="labelCascaderRef" class="flex-1" v-model="range.label"
                                :props="{ label: 'dictLabel', value: 'dictValue' }" placeholder="请选择标签" :options="labels" filterable
                                @change="labelChange($event, range, index)" />
											<!-- <el-color-picker v-model="range.color" class="!w-8 !h-8" /> -->
										</div>
									</div>
									<el-button type="primary" class="w-full mt-2 !rounded-button"
										@click="addScoreRange">
										<el-icon class="mr-1">
											<Plus />
										</el-icon>
										添加分值范围
									</el-button>
								</div>
								<!-- </div> -->
							</el-tab-pane>
						</el-tabs>
					</div>

				</el-col>
				<el-col :span="16" style=" background-color: #ffffff;">
					<right-add ref="surveyAdd" @postSurverData="getSurverData" @postSurverClassData="getSurverClassData"
						@submit="submit" @initData="setData"></right-add>
				</el-col>
			</el-row>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import leftTopic from './cpns/leftTopic';
import leftOutline from './cpns/leftOutline';
import rightAdd from './cpns/rightAdd';
import { ElMessage } from 'element-plus';
import { createPageData, getPageListData } from '@/api/main/system/system'
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const { proxy } = getCurrentInstance();

const surveyAdd = ref(rightAdd);
const activeName = ref('first')

function handleAdd (type) {
	surveyAdd.value.addTitle(type)
}
const handleNodeClick = (data) => {
	console.log(data)
}
const addSurverData = ref([])
const surverTitData = ref([])
const surverClassData = ref([])
const surverTreeData = ref([])
function getSurverData (data) {
	surverTitData.value = []
	surverTreeData.value = []
	surverTitData.value = getHandleSurverData('title', data)
	// surverClassData.value = getHandleSurverData('class',data)
	data.questionlist.forEach(ele => {
		if (ele.classificationName) {
			if (surverClassData.value.indexOf(ele.classificationName) === -1) {
				surverClassData.value.push(ele.classificationName)
			}
		}
	});
	surverClassData.value.forEach((eleClass) => {
		const obj = {}
		obj.label = eleClass
		obj.children = []
		surverTreeData.value.push(obj)
	})
	data.questionlist.forEach(ele => {
		if (ele.classificationName && ele.title) {
			if (surverClassData.value.indexOf(ele.classificationName) !== -1) {
				surverTreeData.value.forEach((eleTree) => {
					if (eleTree.label === ele.classificationName) {
						const obj = {}
						obj.label = ele.title
						eleTree.children.push(obj)
					}
				})
			}
		}
	});
}
function getHandleSurverData (type, data) {
	const resultData = []
	data.questionlist.forEach(ele => {
		if (ele.title && type === 'title') {
			resultData.push(ele.title)
		}
	});
	return resultData
}


const defaultProps = {
	children: 'children',
	label: 'label',
}

const warningLabel = ref("");
const scoreRanges = ref([
	//   { min: 0, max: 10, labelName: "高危", color: "#ff4d4f", checkin: false },
	//   { min: 11, max: 50, labelName: "中危", color: "#faad14", checkin: false },
]);
const validateScoreRanges = () => {
	for (let i = 0; i < scoreRanges.value.length; i++) {
		const current = scoreRanges.value[i];
		for (let j = 0; j < scoreRanges.value.length; j++) {
			if (i !== j) {
				const other = scoreRanges.value[j];
				if (
					(current.min >= other.min && current.min <= other.max) ||
					(current.max >= other.min && current.max <= other.max)
				) {
					return false;
				}
			}
		}
	}
	return true;
};
const addScoreRange = () => {
	scoreRanges.value.push({
		min: 0,
		max: 100,
		labelName: "",
		checkin: false,
		color: "#1890ff",
	});
};

const setData = (data, type) => {
	console.log(data, 'data');
	if (!data?.scoreRanges?.length) return;

	let ranges = data.scoreRanges;
	if (type === 'copy') {
		ranges = data.scoreRanges.map((item) => {
			delete item.id;
			const label = getLabelLevel(item.tagSign);
			return {
				...item,
				label,
			}
		})
	} else {
		ranges = data.scoreRanges.map((item) => {
			const label = getLabelLevel(item.tagSign);
			return {
				...item,
				label,
			}
		})
	}

	scoreRanges.value = ranges;
	warningLabel.value = data.yjTagSign;//getLabelLevel(data.yjTagSign);
	console.log(ranges, 'ranges');
	getSurverData(data);
}

const getLabelLevel = (val) => {
	console.log(val, labels.value, 'getLabelLevel');
	const parentId = labels.value.find((item) => item.children.find((child) => child.dictValue === val));
	if (parentId) {
		return [parentId.dictValue, val];
	}

	return '';
}

const watchScoreRanges = (data) => {

	if (!validateScoreRanges()) {
		ElMessage.error("分值范围不能有交集");
		return false;
	}
	return true;
};
watch(
	scoreRanges,
	() => {
		// watchScoreRanges();
	},
	{ deep: true },
);

const handleWarningLabelChange = (val) => {
	console.log(val, 'handleWarningLabelChange');
	for (let i = 0; i < scoreRanges.value.length; i++) {
		if (i === val) {
			scoreRanges.value[i].checkin = true;
		} else {
			scoreRanges.value[i].checkin = false;
		}
	}
}

const removeScoreRange = (index) => {
	scoreRanges.value.splice(index, 1);
};

// 提交保存问卷
const submit = (data, type) => {
	if (!validateScoreRanges()) {
		ElMessage.error("分值范围不能有交集");
		return false;
	}

	const params = {
		...data,
		scoreRanges: [],
		yjTagSign: warningLabel.value || '',
		// surveyScoreLabel: warningLabel.value || '',
	}

	if (scoreRanges.value?.length) {
		const ranges = scoreRanges.value.map((item) => {
			return {
				min: item.min,
				max: item.max,
				// label: item.label,
				labelName: item.labelName,
				color: item.color,
				tagSign: item.tagSign || '',
			}
		});

		params.scoreRanges = ranges;
	}

	console.log(type, params, 'params');

	createPageData('/survey/survey', params).then(() => {
		const msg = type === 'add' ? '新增成功！' : type === 'copy' ? '复制成功！' : '编辑成功！';
		proxy.$modal.msgSuccess(msg);
		router.back();
	})
}

const labels = ref([]);
const labelCascaderRef = ref(null);
const getLabelsTree = () => {
    getPageListData('/patient/tag/getdata').then(({ data }) => {
        labels.value = data;
    });
}

const labelChange = (value, range, ind) => {
	// 判断是否重复选择
	if (scoreRanges.value.length > 0) {
		const index = scoreRanges.value.findIndex((item, i) => item.label[1] === value[1] && ind !== i);
		if (index !== -1) {
			ElMessage.error("标签不能重复选择");
			range.label = [];
			return false;
		}
	}
	


    // 查找匹配的标签对象
    const typeInfo = labels.value.find((item) => item.dictValue === value[0]);
	if (typeInfo.children.length) {
		const labelName = typeInfo.children.find((item) => item.dictValue === value[1]).dictLabel;
		if (labelName) {
			range.labelName = `${typeInfo.dictLabel}/${labelName}`;
			range.color = typeInfo.children.find((item) => item.dictValue === value[1]).color;
			if (!range.color) {
				range.color = '#1890ff';
			}
			range.tagSign = range.label[1];
		}
	}
}

onMounted(() => {
	getLabelsTree();
})

</script>

<style lang="scss" scoped>
.home {
	padding: 15px;
	background-color: #EFEFEF;

	.title {
		background: #ffffff;
		height: 50px;
		line-height: 50px;
		padding-left: 30px;
	}

	.demo-tabs {
		background-color: #EFEFEF;
		margin: 10px;
		padding: 15px;

		.wrap {
			padding: 15px;
			height: calc(100vh - 251px);
			background: #ffffff;
		}
	}

}

.wrap2 {
	height: calc(100vh - 270px);
}

.wrap1 {
	padding: 15px;
	height: calc(100vh - 270px);
	background: #ffffff;

	.topicCard {
		margin-bottom: 15px;

		.surveyItem {
			line-height: 30px;
			cursor: pointer;

			.iconEle {
				vertical-align: -10%;
				color: #409EFF;
				margin-right: 8px;
			}
		}

		.surveyTitle {
			line-height: 30px;
		}
	}

	.topicCardTit {
		height: calc(100vh - 510px);
		scrollbar-width: none;
		/* firefox */
		-ms-overflow-style: none;
		/* IE 10+ */
		overflow-x: hidden;
		overflow-y: auto;
		line-height: 30px;
	}
}
</style>