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, warningMessage } from '../../../utils/message';
import { auth } from '/@/utils/authFunction';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

/**
 *
 * @param crudExpose：index传递过来的示例
 * @param context：index传递过来的自定义参数
 * @returns
 */
export const createCrudOptions = function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const pageRequest = async (query: any) => {
		return await api.GetList(query);
	};
	const editRequest = async ({ form, row }: EditReq) => {
		form.id = row.id;
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.DelObj(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};

/* 	// 修改分类和标签数据获取方式
	const categoryOptions = ref<Array<{value: number, label: string}>>([]);
	const tagOptions = ref<Array<{value: number, label: string}>>([]);
	
	// 获取分类数据
	const fetchCategories = async () => {
		try {
			const res = await api.GetcategoryList({page:1, limit:1000, tenant_id:1});
			if (res.code === 0 && res.data && res.data.items) {
				categoryOptions.value = res.data.items;
			}
		} catch (error) {
			console.error('获取分类数据失败', error);
		}
	};
	
	// 获取标签数据
	const fetchTags = async (categoryId?: number) => {
		try {
			const params = {
				page: 1,
				limit: 1000,
				tenant_id: 1
			};
			if (categoryId) {
				params.category_id = categoryId;
			}
			const res = await api.GetTagList(params);
			if (res.code === 0 && res.data && res.data.items) {
				tagOptions.value = res.data.items;
			}
		} catch (error) {
			console.error('获取标签数据失败', error);
		}
	}; */
	
	// 初始化时获取分类数据
/* 	onMounted(() => {
		fetchCategories();
		fetchTags();
	}); */

	// 添加批量更新标签的方法
	const batchUpdateTags = async (questionIds: number[], tagIds: number[]) => {
		try {
			const res = await api.BatchUpdateTags({
				question_ids: questionIds,
				tag_ids: tagIds,
				tenant_id: 1
			});
			if (res.code === 0) {
				successMessage('批量更新标签成功');
				// 刷新列表
				crudExpose.doRefresh();
			}
		} catch (error) {
			console.error('批量更新标签失败', error);
		}
	};

	return {
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			pagination: {
				show: true,
			},
			actionbar: {
				buttons: {
					add: {
						show: auth('role:Create'),
					},
					// 添加批量绑定标签按钮
					/* batchBindTags: {
						text: '批量绑定标签',
						type: 'primary',
						show: true,
						order: 2,
						click: () => {
							// 尝试不同的方式获取选中行
							const selection = crudExpose.getSelection?.() || crudExpose.selectedRows || [];
							console.log('选中的行:', selection);
							
							if (!selection || selection.length === 0) {
								warningMessage('请先选择要操作的题目');
								return;
							}
							// 打开批量绑定标签对话框
							context.openBatchTagsDialog(selection);
						},
					}, */
				},
			},
			rowHandle: {
				//固定右侧
				fixed: 'right',
				width: 320,
				buttons: {
					view: {
						show: true,
					},
					edit: {
						show: auth('role:Update'),
					},
					remove: {
						show: auth('role:Delete'),
					},
					/* permission: {
						type: 'primary',
						text: '权限配置',
						show: auth('role:Permission'),
						click: (clickContext: any): void => {
							const { row } = clickContext;
							context.RoleDrawer.handleDrawerOpen(row);
							context.RoleMenuBtn.setState([]);
							context.RoleMenuField.setState([]);
						},
					}, */
				},
			},
			form: {
				col: { span: 24 },
				labelWidth: '100px',
				wrapper: {
					is: 'el-dialog',
					width: '600px',
				},
			},
			columns: {
				_selection: {
					title: '选择',
					form: { show: false },
					column: {
						type: 'selection',
						align: 'center',
						width: 50,
						fixed: 'left',
						columnSetDisabled: true,
					},
				},
				id: {
					title: 'ID',
					column: { show: true ,width:80,},
					search: { show: false },
					form: { show: false },
				},
				question: {
					title: '题目内容',
					search: { show: true },
					column: {
						showOverflowTooltip: true, // 超出显示提示
						width: 300 ,// 固定列宽
						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 }: { 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>
									)
								}
							}
						},
						helper: compute(({ form }) => {
							if (form.question_form === 1) {
								return '添加单选题的选项，并标记正确答案（只能有一个正确答案）';
							} else if (form.question_form === 2) {
								return '添加多选题的选项，并标记正确答案（可以有多个正确答案）';
							}
							return '';
						})
					}
				},
				scoring_reference : {
					title: '备注',
					search: { show: false },
					column: { show: false },
					form: {
						component: {
							name: 'el-input',
							type: 'textarea',
							rows: 4,
							placeholder: '请输入答案解析'
						},
					},
				},
				category_id: {
					title: '题目分类',
					search: { show: true },
					type: 'dict-select',
					column: {
						minWidth: 120,
					},
					dict: dict({
						// 使用API方式获取数据
						getData: async () => {
							const res = await api.GetcategoryList({page:1, limit:1000, tenant_id:1});
							return res.data.items;
						},
						label: 'name',
						value: 'id'
					}),
					form: {
						rules: [{ required: true, message: '题目分类必填' }],
						component: {
							placeholder: '请选择题目分类',
							/* onChange: ({ value }: { value: number }) => {
								// 当分类变化时，重新获取对应的标签
								fetchTags(value);
							} */
						},
						helper: '选择题目所属的分类'
					},
				},
				tag_ids: {
					title: '题目标签',
					search: { show: true },
					type: 'dict-select',
					column: {
						minWidth: 150,
						component: {
							name: 'fs-dict-label',
							props: {
								multiple: true
							}
						}
					},
					dict:  dict({
						// 使用API方式获取数据
						getData: async () => {
							const res = await api.GetTagList({page:1, limit:1000, tenant_id:1});
							return res.data.items;
						},
						label: 'name',
						value: 'id'
					}),
					form: {
						component: {
							props: {
								multiple: true,
								filterable: true,
								placeholder: '请选择题目标签'
							}
						},
						helper: '选择题目关联的标签，可多选'
					}
				},
			},
			// 确保表格配置正确
			table: {
				selection: true,
			},
		},
	};
};

// 导出批量更新标签方法，供组件使用
export const useBatchUpdateTags = (crudExpose: any) => {
	const batchUpdateTags = async (questionIds: number[], tagIds: number[]) => {
		try {
			const res = await api.BatchUpdateTags({
				question_ids: questionIds,
				tag_ids: tagIds,
				tenant_id: 1
			});
			if (res.code === 0) {
				successMessage('批量更新标签成功');
				// 刷新列表
				crudExpose.doRefresh();
			}
		} catch (error) {
			console.error('批量更新标签失败', error);
		}
	};
	
	return { batchUpdateTags };
};
