<template>
	<fs-page>
		<el-row class="document-el-row">
		<el-col :span="3">
			<div class="document-box document-left-box">
				<TreeList ref="treeListRef" :treeData="documentTreeData"
				@treeClick="handleTreeClick"
				@updateDocument="handleUpdateDocument"
				@deleteDocument="handleDeleteDocument" />
			</div>
		</el-col>
		<el-col :span="21">
			<div class="document-box document-right-box">
				<fs-crud ref="crudRef" :dialog-width="800"  v-bind="crudBinding"> 
					<template #cell-chinese_explanation="scope">
						<el-tooltip
							v-if="scope.row.chinese_explanation"
							:content="scope.row.chinese_explanation"
							placement="top"
							:hide-after="2000"
						>
							<span>{{ scope.row.chinese_explanation }}</span>
						</el-tooltip>
						<span v-else>-</span>
					</template>
					<template #toolbar-right>
						<el-button
							v-if="showScoringButton"
							type="primary"
							size="small"
							@click="handleSetScoring"
						>
							设置评分标准
						</el-button>
					</template>
				</fs-crud>
			</div>
		</el-col>
		</el-row>
		<!-- <TreeList ref="treeListRef" :treeData="treeData" /> -->
		
		<PermissionDrawerCom />
		<BatchTagsDialog ref="batchTagsDialogRef" :crudExpose="crudExpose" />
		<BatchCategoryDialog ref="batchCategoryDialogRef" :crudExpose="crudExpose" />
		<BatchCompetencyTagsDialog ref="batchCompetencyTagsDialogRef" :crudExpose="crudExpose" />
		<ScoringStandardDialog ref="scoringDialogRef" @update="handleScoringUpdate" />
		<el-drawer v-model="drawerVisible" title="添加分类" direction="rtl" size="500px" :close-on-click-modal="false" :before-close="handleDrawerClose">
			<DocumentFormCom
				v-if="drawerVisible"
				:initFormData="drawerFormData"
				:cacheData="documentTreeCacheData"
				:treeData="documentTreeData"
				@drawerClose="handleDrawerClose"
			/>
			</el-drawer>
	</fs-page>
</template>

<script lang="ts" setup name="role">
import { defineAsyncComponent, onMounted, ref } from 'vue';
import { useFs } from '@fast-crud/fast-crud';
import { ElMessageBox, ElMessage } from 'element-plus';
import { createCrudOptions } from './crud';
import { RoleDrawerStores } from './stores/RoleDrawerStores';
import { RoleMenuBtnStores } from './stores/RoleMenuBtnStores';
import { RoleMenuFieldStores } from './stores/RoleMenuFieldStores';
import { RoleUsersStores } from './stores/RoleUsersStores';
import { successMessage } from '../../../utils/message';
import TreeList from './components/treeList.vue';
import { GetDocumentTree, GetCategoryList, GetTagList,DeleteDocumentCategory } from '../positionList/api';
import { successNotification } from '/@/utils/message';
import DocumentFormCom from '../positionList/components/DocumentFormCom/index.vue';

/* import { GetDocumentTree, DeleteDocumentCategory, UpdateDocument ,UpdateSequence, GetInterviewQuestions,AddDocument,
  GetCategoryList, GetTagList
 } from '../positionList/api'; */

const PermissionDrawerCom = defineAsyncComponent(() => import('./components/RoleDrawer.vue'));
const BatchTagsDialog = defineAsyncComponent(() => import('./components/BatchTagsDialog.vue'));
const BatchCategoryDialog = defineAsyncComponent(() => import('./components/BatchCategoryDialog.vue'));
const BatchCompetencyTagsDialog = defineAsyncComponent(() => import('./components/BatchCompetencyTagsDialog.vue'));
const ScoringStandardDialog = defineAsyncComponent(() => import('./components/ScoringStandardDialog.vue'));

const batchTagsDialogRef = ref();
const scoringDialogRef = ref();
const batchCategoryDialogRef = ref();
const batchCompetencyTagsDialogRef = ref();
const drawerVisible = ref(false);
const drawerFormData = ref({});
const documentTreeRef = ref<DocumentTreeRef | null>(null);
	const documentTreeCacheData = ref<any[]>([]);

const RoleDrawer = RoleDrawerStores(); // 角色-抽屉
const RoleMenuBtn = RoleMenuBtnStores(); // 角色-菜单
const RoleMenuField = RoleMenuFieldStores();// 角色-菜单-字段
const RoleUsers = RoleUsersStores();// 角色-用户
const treeListRef = ref();
const treeData = ref([]);

// 添加类型定义
interface DocumentTreeRef {
  treeRef?: {
    currentNode?: {
      parent?: {
        data: any;
      };
    };
  };
}
// 定义树节点的类型
interface TreeNode {
	id: string;
	title: string;
	children?: TreeNode[];
	question_type?: string;
	chinese_explanation?: string;
	name?: string;
	category_id?: string | number;
}

const documentTreeData = ref<TreeNode[]>([]); // 使用定义的类型

const { crudBinding, crudRef, crudExpose } = useFs({
	createCrudOptions,
	context: { 
		RoleDrawer, 
		RoleMenuBtn, 
		RoleMenuField,
		$message: {
			warning: (msg: string) => successMessage(msg)
		},
		openBatchTagsDialog: (selection: any) => {
			batchTagsDialogRef.value.open(selection);
		},
		openBatchCategoryDialog: (selection: any) => {
			batchCategoryDialogRef.value.open(selection);
		},
		openBatchCompetencyTagsDialog: (selection: any) => {
			batchCompetencyTagsDialogRef.value.open(selection);
		},
		selectedRows: [] // 存储选中的行
	},
});

const selectedCategoryId = ref(1);
const showScoringButton = ref(false);

// 处理设置评分标准按钮点击
const handleSetScoring = () => {
  // 打开评分标准设置对话框
  scoringDialogRef.value?.open();
};

// 处理评分标准更新
const handleScoringUpdate = async (data: any) => {
  /* try {
    // 调用API保存评分标准
    const res = await UpdateScoringStandard({
      category_id: selectedCategoryId.value,
      scoring_reference: data.scoring_reference,
      options: data.options
    });

    if (res.code === 2000) {
      // 刷新列表
      await crudExpose.doRefresh();
      ElMessage.success('评分标准更新成功');
    } else {
      ElMessage.error(res.msg || '更新评分标准失败');
    }
  } catch (error) {
    console.error('更新评分标准失败:', error);
    ElMessage.error('更新评分标准失败，请重试');
  } */
};

// 关闭抽屉
const handleDrawerClose = (type: string) => {
  if (type === 'submit') {
    getTreeData();
  }
  drawerVisible.value = false;
  drawerFormData.value = {};
};
// 删除文档分类
const handleDeleteDocument = (id: any, callback: any) => {
  ElMessageBox.confirm('您确认删除该文档分类吗?', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await DeleteDocumentCategory(id);
    callback();
    if (res?.code === 2000) {
      successNotification(res.msg);
      getTreeData();
    }
  });
};

const handleTreeClick = (node: any) => {
	console.log('record', node);
  
  // 获取当前节点ID并处理前缀
  const currentNodeId = node?.currentNode?.id || '';
  const originalId = currentNodeId.replace(/^(open_|prof_|category_|tag_)/, '');
  
  // 保存当前选中的分类ID，如果ID不是数字则使用默认值1
  selectedCategoryId.value = (!isNaN(Number(originalId)) && originalId !== null) ? originalId : 1;
  
  // 根据不同的问题类型设置question_form
  let question_form;
  const firstLevelId = node?.firstLevel?.id;
  const nodeType = currentNodeId.startsWith('open_') ? 'open' : 
                   currentNodeId.startsWith('prof_') ? 'professional' :
                   currentNodeId.startsWith('category_') ? 'category' :
                   currentNodeId.startsWith('tag_') ? 'tag' : 
                   firstLevelId;
  
  // 检查是否是心理测试分类
  const currentNodeName = node?.firstLevel?.title || '';
  console.log('currentNodeName', currentNodeName);
  showScoringButton.value = currentNodeName === '心理测试';
 
  
  if (nodeType === 'open' || firstLevelId === 'root') {
    question_form = '0';  // 职位开放题
  } else if (firstLevelId === 'psychology_questions') {
    question_form = '4';  // 心理题库
  } else if (firstLevelId === 'common_questions') {
    question_form = '1';  // 常识题库
  } else if (nodeType === 'professional' || firstLevelId === 'professional_questions') {
    question_form = '1,2,3,4,6';  // 专业考察题库
  } /*  else {
    question_form = '0';  // 默认为职位开放题
  } */

 /*  // 重置上传文件状态
  uploadedFile.value = null; */
  
  // 构建搜索参数
  const searchParams = {
    form: {
      limit: 20,
      ...(firstLevelId === 'root' || firstLevelId === 'professional_questions' ? { position_types: selectedCategoryId.value } : {}),
      question_form: question_form,
      ...(nodeType === 'category' ? { question_category: originalId } : {}),
      ...(nodeType === 'tag' ? { question_tags: originalId } : {})
    }
  };
  
  // 执行搜索
  crudExpose.doSearch(searchParams);
};

// 处理文档分类的新增或编辑
const handleUpdateDocument = (type: any, record: any) => {
  if (type === 'update' && record) {
    const parentData = documentTreeRef.value?.treeRef?.currentNode?.parent?.data || {};
    documentTreeCacheData.value = [parentData];
    drawerFormData.value = record;
  }
  drawerVisible.value = true;
};

// 关闭抽屉
/* const handleDrawerClose = (type: string) => {
  if (type === 'submit') {
    getTreeData();
  }
  drawerVisible.value = false;
  drawerFormData.value = {};
}; */

// 获取文档树数据
const getTreeData = () => {
	GetDocumentTree({}).then((ret: any) => {
		console.log('ret', ret);
		const responseData = ret.data;
		GetCategoryList({page:1,limit:50}).then((res: any) => {
			console.log('res', res);
			const categoryList = res.data.items.filter((item: any) => 
				!['技术能力', '服务意识', '职业素质','基本常识','色盲检测','内容铺垫','心理测试1'].includes(item.name)
			);
			GetTagList({}).then((res: any) => {
				console.log('res', res);
				const tagList = res.data.items;
			
				// 创建根节点
				const rootNode = [ 
					/* {
						id: 'root',
						title: '职位开放题',
						children: responseData.map((item: any) => ({
							...item,
							id: `open_${item.id}`,
							title: item.name || item.title,
							question_type: 'open',
							chinese_explanation: item.chinese_explanation || ''
						}))
					},
					{
						id: 'professional_questions',
						title: '专业考察题库',
						children: responseData.map((item: any) => ({
							...item,
							id: `prof_${item.id}`,
							title: item.name || item.title,
							question_type: 'professional',
							chinese_explanation: item.chinese_explanation || ''
						}))
					}, */
					...categoryList.map((item: any) => ({
						id: `category_${item.id}`,  
						title: item.name,
						children: tagList.filter((tag: any) => tag.category_id === item.id).map((tag: any) => ({
							id: `tag_${tag.id}`,
							title: tag.name,
							chinese_explanation: tag.chinese_explanation || ''
						})) 
					}))
				];
				documentTreeData.value = rootNode;
			});
		});
	});
};

// 页面打开后获取列表数据
onMounted(async () => {
	getTreeData()
	// 刷新
	crudExpose.doRefresh();
	// 获取全部用户
	RoleUsers.get_all_users();
});
</script>
<style lang="scss" scoped>
.document-el-row {
  height: 100%;
  overflow: hidden;

  .el-col {
    height: 100%;
    padding: 10px 0;
    box-sizing: border-box;
  }
}
.document-box {
  height: 100%;
  padding: 10px;
  background-color: var(--el-fill-color-blank);
  box-sizing: border-box;
}

.document-left-box {
  position: relative;
  border-radius: 0 8px 8px 0;
  margin-right: 10px;
  overflow-y: auto;
}

.document-right-box {
  border-radius: 8px 0 0 8px;
}

/* 添加中文释义相关样式 */
.chinese-explanation {
  color: #666;
  font-size: 14px;
  margin-top: 4px;
  
  &:hover {
    color: #409EFF;
  }
}

.tooltip-content {
  max-width: 300px;
  word-break: break-all;
  white-space: pre-wrap;
}
::v-deep .fs-form-helper{
	height: 100%;
	line-height: 18px;
}
</style>