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, ElDialog, ElButton, ElUpload } from 'element-plus';
import { ref } from 'vue';
import { Session } from '/@/utils/storage';

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const router = useRouter(); // 添加这行来获取router实例
	const pageRequest = async (query: any) => {
		// 确保查询参数正确传递
		console.log(query);
		
		// 基础参数
		const baseParams = {
			...query,
			limit: 100,
			tenant_id: Session.get('tenant_id'),
			question_category: (query.form && query.form.category) || query.category || '',
			question_tags: (query.form && query.form.tag) || query.tag || '',
		};

		// 缓存搜索参数
		sessionStorage.setItem('cacheSearchData', JSON.stringify(baseParams));

		// 根据是否有tag或category来选择不同的接口和参数
		if (baseParams.question_category || baseParams.question_tags) {
			if(baseParams.question_category==5){
				baseParams.question_form = '4';
			}
			return api.GetPublicList(baseParams);
		} else {
			// 只有在不是tag和category查询时才添加job_id
			return api.GetDocumentList({
				...baseParams,
				question_form: query.question_form,
				job_id: query.form?.job_id || query.job_id || 1,
			});
		}
	};

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

	// 修改绑定parent_question_id的请求函数，使用现有的API
	const updateParentQuestionRequest = async (id: number, parentQuestionId: number) => {
		// 使用现有的UpdateDocument API而不是不存在的UpdateInterviewQuestion
		return await api.UpdateDocument({
			id: id,
			parent_question_id: parentQuestionId
		});
	};

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

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

	return {
		crudOptions: {
			toolbar:{
				buttons:{
					search:{show:false},
					// 刷新按钮
					refresh:{show:false},
					// 紧凑模式
					compact:{show:false},
					// 导出按钮
					export:{
						text: '导出',
						type: 'primary',
						size: 'small',
						icon: 'upload',
						circle: false,
						display: true,
						show:false
					},
					// 列设置按钮
					columns:{
						show:false
					},
				}
			},
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			pagination:{
				show:false,
   				pageSize: 100, //默认pageSize
				pageSizes: [50, 100], // 可选的分页大小选项
				showSizePicker: true // 显示分页大小选择器
			},
			// 添加工具栏配置
			actionbar: {
				buttons: {
					add: {
						show: false,
						text: '新增职位问题',
						icon: 'Plus',
						size: 'small',
						click: () => {
							// 触发自定义事件，让父组件处理弹窗显示
							const event = new CustomEvent('openPositionQuestionDialog');
							window.dispatchEvent(event);
						}
					}
				}
			},
			search: {
				show: true,
				autoSearch:false,
				buttons: {
					search: {
						size: 'small', // 设置查询按钮大小为small
					},
											reset: {
							size: 'small', // 设置重置按钮大小为small
							click: () => {
								// 从sessionStorage获取缓存的搜索参数
								const cacheSearchData = sessionStorage.getItem('cacheSearchData');
								if (cacheSearchData) {
									const searchParams = JSON.parse(cacheSearchData);
									// 只保留 job_id 和 question_form 参数
									const resetParams = {
										job_id: searchParams.job_id || searchParams.form?.job_id,
										question_form: searchParams.question_form
									};
									// 执行搜索
									crudExpose.doSearch({
										form: resetParams
									});
								}
							}
						}
				},
				onSearch: (params: any) => {
				},
				columns: {
					category: {
						title: "分类",
						search: { show: true, value: '' },
						type: 'text',
						column: { show: false } // 表格中不显示此列
					}
				}
			},
			rowHandle: {
				width: 350, // 增加宽度以容纳新按钮
				buttons: {
					view: {
						size: 'small',
						icon:"View",
						type: 'text',
						show:false,
						click: ({ row }: any) => {
							const event = new CustomEvent('viewDocumentDetail', { detail: row });
							window.dispatchEvent(event);
						}
					},
					uploadVideo: {
						text: '上传视频',
						type: 'text',
						icon:"upload",
						show:false,
						size: 'small',
						click: ({ row }: any) => {
							// 触发自定义事件，让父组件处理弹窗显示
							const event = new CustomEvent('openVideoUploadDialog', { detail: row });
							window.dispatchEvent(event);
						}
					},
					// 添加绑定中文释义按钮
					bindParentQuestion: {
						text: '绑定开放问题',
						type: 'text',
						icon: "Link",
						size: 'small',
						show:false,
						click: async ({ row }: any) => {
							// 打开选择开放问题的对话框
							const event = new CustomEvent('openBindParentQuestionDialog', { detail: row });
							window.dispatchEvent(event);
						}
					},
					edit: {
						show:false,
						type: 'text',
						icon:"Edit",
						size: 'small',
					},
					remove: {
						type: 'text',
						icon:"Delete",
						size: 'small',
					},
					sort: {
						type: 'text',
						icon:"sort",
						size: 'small',
						text: '修改排序',
						click: ({ row }: any) => {
							// 触发自定义事件，让父组件处理弹窗显示
							const event = new CustomEvent('openSortDialog', { detail: row });
							window.dispatchEvent(event);
						}
					}
				}
			},
			form: {
				view: {
					disabled: true,
					display: 'text'
				}
			},
			columns: {
				/* _index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				}, */
				id: {
					title: 'ID',
					column: { show: true ,width:80, },
					search: { show: false },
					form: { show: false },
				},
				position_id: {
					title: '职位',
					search: { show: false,
						size: 'small',
						col:{ span:3},
					 },
					type: 'dict-select',
					dict:dict({
                        url({form}){
                            return  '/api/system/job/list?tenant_id='+Session.get('tenant_id')
                        },
                        label:'title',
                        value:'id'
                        }),
					column: {
						value: '1',
						minWidth: 120,
						show: false,
					},
					form: { show: true },
				},
				question_id: {
					title: '职位问题',
					search: { show: false },
					type: 'dict-select',
					dict:dict({
						url: '/api/categories', // 获取数据的接口
						// 或者使用方法
						getData: async () => {
						  const res = await api.GetInterviewQuestions({page:1,limit:200,tenant_id:Session.get('tenant_id'),});
						  return res.data.items;
						},
						label: 'question',
						value: 'id'
					}),
					column: {
						value: '1',
						show: false
					},
					form: { 
						show: true,
						component: {
							props: {
								filterable: true,
								clearable: true,
								placeholder: '请选择职位问题',
							}
						}
					},
				},
			
				question: {
					title: '题目内容',
					search: { show: true,
						size: 'small',
						col:{ span:3},
					 },
					column: {
						
						sortable: 'custom',
						showOverflowTooltip: true, // 超出显示提示
						width: 300 // 固定列宽
					},
					form: {
						rules: [{ required: true, message: '题目内容必填' }],
						component: {
							placeholder: '请输入题目内容',
						},
						show: false
					},
				},
				
				// 添加 parent_question_id 字段
				parent_question_id: {
					title: '关联开放问题',
					search: { show: false,
						size: 'small',
						col:{ span:3},
					},
					type: 'dict-select',
					dict: dict({
						//url: '/api/open-questions', // 获取开放问题的接口
						// 或者使用方法
						getData: async () => {
							const res = await api.GetInterviewQuestions({
								page: 1,
								limit: 200,
								tenant_id: Session.get('tenant_id'),
								question_form: 0, // 开放问题类型
							});
							return res.data.items;
						},
						label: 'question',
						value: 'id'
					}),
					column: {
						minWidth: 150,
						showOverflowTooltip: true,
						formatter: ({ row }: any) => {
							// 如果有关联问题，显示关联问题的内容
							if (row.parent_question && row.parent_question.question) {
								return row.parent_question.question;
							} else if (row.parent_question_id) {
								return `${row.parent_question_id}`;
							}
							return '无关联问题';
						}
					},
					form: {
						show: true,
						component: {
							props: {
								filterable: true,
								clearable: true,
								placeholder: '请选择关联的开放问题',
							}
						},
						helper: '关联到对应的开放问题，用于中文释义'
					},
				},
				/* 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: '选择问题的类型分类',
						show: false
					},
				}, */
				question_form: {
					title: '题目形式',
					search: { show: false,
						size: 'small',
						col:{ span:3},
					 },
					type: 'dict-select',
					column: {
						minWidth: 100,
					},
					dict: dict({
						// 使用API方式获取数据
						getData: async () => {
							const res = await api.GetQuestionTypeList();
							// 返回question_forms数组
							return res.data.question_forms || [];
						},
						label: 'label',
						value: 'value'
					}),
					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: '选择题目的形式：开放问题、单选题或多选题',
						show: false
					},
				},
				/* position_types: {
					title: '适用职位',
					search: { show: true },
					type: 'dict-select',
					column: {
						minWidth: 120,
					},
					dict: dict({
						data: [
							{ value: '0', label: '技术' },
							{ value: '1', label: '管理' },
						]
					}),
					form: {
						component: {
							props: {
								multiple: true,
								filterable: true,
								placeholder: '请选择适用职位类型',
							}
						},
						helper: '选择题目适用的职位类型，可多选',
						show: false
					}
				},
				recommended_duration: {
					title: '建议时长(秒)',
					search: { show: false },
					column: {
						minWidth: 100,
					},
					form: {
						component: {
							name: 'el-input-number',
							props: {
								min: 10,
								max: 600,
								step: 10
							}
						},
						helper: '建议回答此题目的时长，单位为秒',
						show: false
					}
				}, */
				difficulty: {
					title: '难度等级',
					search: { show: false,
						size: 'small',
						col:{ span:3},
					 },
					type: 'dict-select',
					column: {
						minWidth: 80,
					},
					dict: dict({
						data: [
							{ value: 1, label: '初级' },
							{ value: 2, label: '中级' },
							{ value: 3, label: '高级' }
						]
					}),
					form: {
						rules: [{ required: true, message: '难度等级必填' }],
						helper: '选择题目的难度级别',
						show: false
					},
				},
				/* is_system: {
					title: '系统题目',
					search: { show: true },
					dict: dict({
						data: [
							{ value: 0, label: '停用' },
							{ value: 1, label: '启用' }
						]
					}),
					column: {
						width: 120,
					},
					form: {
						component: {
							name: 'el-switch',
							props: {
								activeText: '是',
								inactiveText: '否'
							}
						},
						helper: '是否为系统预设题目',
						show: false
					}
				}, */
				/* status: {
					title: '状态',
					search: { show: true },
					type: 'dict-select',
					column: {
						width: 80,
					},
					dict: dict({
						data: [
							{ value: 0, label: '停用' },
							{ value: 1, label: '启用' }
						]
					}),
					form: {
						rules: [{ required: true, message: '状态必填' }],
						component: {
							placeholder: '请选择状态',
						},
						helper: '题目的启用状态',
						show: false
					},
				},
				sort: {
					title: '排序',
					search: { show: false },
					column: {
						width: 80,
					},
					form: {
						component: {
							name: 'el-input-number',
							props: {
								min: 1,
								max: 999
							}
						},
						helper: '题目的排序值，值越小排序越靠前',
						show: false
					}
				}, */
				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 }: { form: any }) => {
									// 确保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>
									)
								}
							}
						},
						show: false,
						helper: compute(({ form }) => {
							if (form.question_form === 1) {
								return '添加单选题的选项，并标记正确答案（只能有一个正确答案）';
							} else if (form.question_form === 2) {
								return '添加多选题的选项，并标记正确答案（可以有多个正确答案）';
							}
							return '';
						})
					}
				},
				sequence_number: {
					title: '排序',
					search: { show: false },
					column: { show: true },
					form: { show: true },
				},
				answer_explanation: {
					title: '答案解析',
					search: { show: false },
					column: { show: false },
					form: {
						component: {
							name: 'el-input',
							type: 'textarea',
							rows: 4,
							placeholder: '请输入答案解析'
						},
						show:false
					},
				},
				// 添加视频相关字段
				digital_human_video_url: {
					title: '视频链接',
					search: { show: false },
					column: { 
						show: true,
						width: 120,
						formatter: ({ row }: any) => {
							return row.digital_human_video_url ? '已上传' : '未上传';
						}
					},
					form: { show: false },
				},
				digital_human_video_subtitle: {
					title: '字幕',
					search: { show: false },
					column: { 
						show: true,
						width: 120,
						formatter: ({ row }: any) => {
							return row.digital_human_video_subtitle ? '已上传' : '未上传';
						}
					},
					form: { show: false },
				},
			},
		},
		// 不需要导出这些状态
		// videoUploadDialogVisible,
		// currentRow
	};
}; 