import { CreateCrudOptionsProps, CreateCrudOptionsRet, AddReq, DelReq, EditReq, dict, compute } from '@fast-crud/fast-crud';
import * as api from './api';
import { dictionary } from '/@/utils/dictionary';
import { successMessage } from '../../../utils/message';
import { auth } from '/@/utils/authFunction';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const router = useRouter(); // 添加这行来获取router实例
	const pageRequest = async (query: any) => {
		// 确保查询参数正确传递
		api.GetDocumentTree({}).then((ret: any) => {
			// 构建请求参数，确保category参数被正确传递
		const params = {
			...query,
			tenant_id: '1',
			// 如果 query.form 中有 category，使用它，否则使用 query.category
			category: (query.form && query.form.category) || query.category || '',
			job_id: ret.data[0].id
		};

		console.log('Request params:', params); // 添加日志以便调试

		return  api.GetDocumentList(params);
		});
		
	};

	const editRequest = async ({ form, row }: any) => {
		return await api.UpdateDocument({
			...form,
			id: row.id
		});
	};

	const delRequest = async ({ row }: any) => {
		return await api.DelDocument(row.id);
	};

	const addRequest = async ({ form }: any) => {
		return await api.AddDocument(form);
	};

	return {
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			search: {
				show: true,
				onSearch: (params: any) => {
					console.log('Search params:', params);
					return params;
				},
				columns: {
					category: {
						title: "分类",
						search: { show: true, value: '' },
						type: 'text',
						column: { show: false } // 表格中不显示此列
					}
				}
			},
			rowHandle: {
				width: 250,
				buttons: {
					view: {
						size: 'small',
						click: ({ row }: any) => {
							const event = new CustomEvent('viewDocumentDetail', { detail: row });
							window.dispatchEvent(event);
						}
					},
					preview: {
						text: '预览',
						type: 'success',
						size: 'small',
						click: (row) => {
							// 检查文件路径是否存在
							if (!row.row || !row.row.file_path) {
								ElMessage.error('文件路径无效');
								return;
							}

							const filePath = row.row.file_path;
							// 获取文件扩展名
							const fileType = row.row.file_type;

							// 支持的文件类型列表
							const supportedTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

							if (!supportedTypes.includes(fileType)) {
								ElMessage.warning(`暂不支持预览该文件类型: ${fileType}`);
								return;
							}

							// 使用window.open在新窗口中打开预览页面
							const previewUrl = `/#/preview?url=${encodeURIComponent(filePath)}&type=${fileType}`;
							window.open(previewUrl, '_blank');
						}
					},
					edit: {
						type: 'primary',
						size: 'small',
					},
					remove: {
						type: 'danger',
						size: 'small',
					}
				}
			},
			form: {
				view: {
					disabled: true,
					display: 'text'
				}
			},
			columns: {
				/* _index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				}, */
				position_id: {
					title: '职位',
					search: { show: true },
					type: 'dict-select',
					column: {
						value: '1',
						minWidth: 120,
						show: false,
					},
					form: { show: false },
				},
				question_id: {
					title: 'ID',
					search: { show: false },
					column: {
						value: '1',
						show: false
					},
					form: { show: false },
				},
				id: {
					title: 'ID',
					column: { show: false },
					search: { show: false },
					form: { show: false },
				},
				question: {
					title: '题目内容',
					search: { show: true },
					column: {
						minWidth: 120,
						sortable: 'custom',
					},
					form: {
						rules: [{ required: true, message: '题目内容必填' }],
						component: {
							placeholder: '请输入题目内容',
						},
					},
				},
				question_type: {
					title: '问题类型',
					search: { show: true },
					type: 'dict-select',
					column: {
						minWidth: 100,
					},
					dict: dict({
						data: [
							{ value: 1, label: '专业技能' },
							{ value: 2, label: '通用能力' },
							{ value: 3, label: '个人特质' }
						]
					}),
					form: {
						rules: [{ required: true, message: '问题类型必填' }],
						component: {
							placeholder: '请选择问题类型',
						},
						helper: '选择问题的类型分类',
					},
				},
				question_form: {
					title: '题目形式',
					search: { show: true },
					type: 'dict-select',
					column: {
						minWidth: 100,
					},
					dict: dict({
						data: [
							{ value: 0, label: '开放问题' },
							{ value: 1, label: '单选题' },
							{ value: 2, label: '多选题' }
						]
					}),
					form: {
						rules: [{ required: true, message: '题目形式必填' }],
						component: {
							placeholder: '请选择题目形式',
							onChange: ({ form }: { form: any }) => {
								// 重置相关字段
								if (form.question_form === 1) {
									// 单选题
									form.options = [{ option_text: '', is_correct: false, sort: 1 }, { option_text: '', is_correct: false, sort: 2 }];
								} else if (form.question_form === 2) {
									// 多选题
									form.options = [{ option_text: '', is_correct: false, sort: 1 }, { option_text: '', is_correct: false, sort: 2 }];
								} else {
									// 开放问题
									form.options = [];
								}
							}
						},
						helper: '选择题目的形式：开放问题、单选题或多选题',
					},
				},
				position_types: {
					title: '适用职位',
					search: { show: true },
					type: 'dict-select',
					column: {
						minWidth: 120,
					},
					dict: dict({
						data: [
							{ value: '0', label: '技术' },
							{ value: '1', label: '管理' },
						]
					}),
					form: {
						component: {
							/* 	name: 'el-select', */
							props: {
								multiple: true,
								filterable: true,
								placeholder: '请选择适用职位类型',
								/* options: [
									{ value: '0', label: '技术' },
									{ value: '1', label: '管理' },
								] */
							}
						},
						helper: '选择题目适用的职位类型，可多选'
					}
				},
				recommended_duration: {
					title: '建议时长(秒)',
					search: { show: false },
					column: {
						minWidth: 100,
					},
					form: {
						component: {
							name: 'el-input-number',
							props: {
								min: 10,
								max: 600,
								step: 10
							}
						},
						helper: '建议回答此题目的时长，单位为秒'
					}
				},
				difficulty: {
					title: '难度等级',
					search: { show: true },
					type: 'dict-select',
					column: {
						minWidth: 80,
					},
					dict: dict({
						data: [
							{ value: 1, label: '初级' },
							{ value: 2, label: '中级' },
							{ value: 3, label: '高级' }
						]
					}),
					form: {
						rules: [{ required: true, message: '难度等级必填' }],
						helper: '选择题目的难度级别'
					},
				},
				is_system: {
					title: '系统题目',
					search: { show: true },
					column: {
						width: 80,
						component: {
							name: 'el-switch'
						}
					},
					form: {
						component: {
							name: 'el-switch',
							props: {
								activeText: '是',
								inactiveText: '否'
							}
						},
						helper: '是否为系统预设题目'
					}
				},
				status: {
					title: '状态',
					search: { show: true },
					type: 'dict-select',
					column: {
						width: 80,
						/* component: {
							name: 'fs-dict-label',
							props: {
								dict: dict({
									data: [
										{ value: 0, label: '停用' },
										{ value: 1, label: '启用' }
									]
								})
							}
						} */
					},
					dict: dict({
						data: [
							{ value: 0, label: '停用' },
							{ value: 1, label: '启用' }
						]
					}),
					form: {
						rules: [{ required: true, message: '状态必填' }],
						component: {
							placeholder: '请选择状态',
						},
						helper: '题目的启用状态'
					},
				},
				sort: {
					title: '排序',
					search: { show: false },
					column: {
						width: 80,
					},
					form: {
						component: {
							name: 'el-input-number',
							props: {
								min: 1,
								max: 999
							}
						},
						helper: '题目的排序值，值越小排序越靠前'
					}
				},
				option_items: {
					title: '选项列表',
					search: { show: false },
					column: { show: false },
					form: {
						show: compute(({ form }) => {
							return form && (form.question_form === 1 || form.question_form === 2);
						}),
						component: {
							name: 'el-card',
							children: {
								default: ({ form }) => {
									// 确保options数组已初始化
									if (!form.options) {
										form.options = [];
									}

									return (
										<div>
											<div class="option-header" style="display: flex; margin-bottom: 10px; font-weight: bold;">
												<span style="flex: 1;">选项内容</span>
												<span style="width: 80px; text-align: center;">是否正确</span>
											</div>
											{form.options.map((option: any, index: number) => (
												<div class="option-item" key={index} style="display: flex; align-items: center; margin-bottom: 10px;">
													<el-input
														v-model={option.option_text}
														placeholder="请输入选项内容"
														style="flex: 1; margin-right: 10px;"
													/>
													<el-tooltip
														content="设置为正确答案"
														placement="top"
														effect="light"
													>
														<div
															onClick={() => {
																if (form.question_form === 1) {
																	// 单选题：只能有一个正确答案
																	form.options.forEach((item: any, idx: number) => {
																		item.is_correct = (idx === index);
																	});
																} else {
																	// 多选题：可以有多个正确答案
																	option.is_correct = !option.is_correct;
																}
															}}
															style="cursor: pointer; width: 80px; text-align: center;"
														>
															{form.question_form === 1 ? (
																// 单选题使用单选按钮
																<el-radio
																	modelValue={option.is_correct}
																	label={true}
																/>
															) : (
																// 多选题使用复选框
																<el-checkbox
																	modelValue={option.is_correct}
																/>
															)}
														</div>
													</el-tooltip>
												</div>
											))}
											<div style="display: flex; justify-content: space-between; margin-top: 10px;">
												<el-button
													type="primary"
													onClick={() => {
														// 确保options数组已初始化
														if (!form.options) {
															form.options = [];
														}
														// 添加新选项时自动设置排序值
														const sort = form.options.length > 0 ?
															Math.max(...form.options.map((o: any) => o.sort || 0)) + 1 : 1;
														form.options.push({ option_text: '', is_correct: false, sort });
													}}
												>
													添加选项
												</el-button>

												{form.options.length > 2 && (
													<el-button
														type="danger"
														onClick={() => {
															form.options.pop();
														}}
													>
														删除最后一项
													</el-button>
												)}
											</div>
										</div>
									)
								}
							}
						},
						helper: compute(({ form }) => {
							if (form.question_form === 1) {
								return '添加单选题的选项，并标记正确答案（只能有一个正确答案）';
							} else if (form.question_form === 2) {
								return '添加多选题的选项，并标记正确答案（可以有多个正确答案）';
							}
							return '';
						})
					}
				},
				answer_explanation: {
					title: '答案解析',
					search: { show: false },
					column: { show: false },
					form: {
						component: {
							name: 'el-input',
							type: 'textarea',
							rows: 4,
							placeholder: '请输入答案解析'
						},
					},
				},

			},
		}
	};
}; 