import * as api from './api';
import { dict, UserPageQuery, AddReq, DelReq, EditReq, compute, CreateCrudOptionsProps, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import { dictionary } from '/@/utils/dictionary';
import { successMessage } from '/@/utils/message';
import { auth } from '/@/utils/authFunction';
import tableSelector from '/@/components/tableSelector/index.vue';
import { shallowRef } from 'vue';
import { useRouter } from 'vue-router';
import { Session } from '/@/utils/storage';

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const router = useRouter();
	
	const pageRequest = async (query: any) => {
		try {
			// 如果有职位ID，添加到查询参数中
			if (query.form && query.form.job_id) {
				query.job_id = query.form.job_id;
			}
			return await api.GetList(query);
		} catch (error) {
			console.error('Failed to fetch list:', error);
			return { data: { items: [], total: 0 } }; // 返回空数据而不是抛出错误
		}
	};
	const editRequest = async ({ form, row }: EditReq) => {
		form.id = row.id;
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.DelObj({id:row.id});
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};

	/**
	 * 懒加载
	 * @param row
	 * @returns {Promise<unknown>}
	 */
	const loadContentMethod = (tree: any, treeNode: any, resolve: Function) => {
		pageRequest({ pcode: tree.code }).then((res: APIResponseData) => {
			resolve(res.data);
		}).catch(error => {
			console.error('Failed to load content:', error);
			resolve([]); // 出错时返回空数组
		});
	};

	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,
			},
			actionbar: {
				buttons: {
					add: {
						show: true, // 允许添加标签类别
					},
				},
			},
			rowHandle: {
				//固定右侧
				fixed: 'right',
				width: 200,
				buttons: {
					view: {
						show: false, // 移除查看按钮，因为标签类别不需要详情页
					},
					edit: {
						iconRight: 'Edit',
						type: 'text',
						show: true, // 允许编辑标签类别
					},
					remove: {
						iconRight: 'Delete',
						type: 'text',
						show: true, // 允许删除标签类别
					},
				},
			},
			pagination: {
				show: true,
			},
			table: {
				rowKey: 'id',
			},
			search: {
				show: true,
				autoSearch:false,
				buttons: {
					search: {
						size: 'small', // 设置查询按钮大小为small
					},
					reset: {
						size: 'small', // 设置重置按钮大小为small
					}
				}
			},
			columns: {
				/* _index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				}, */
				id: {
					title: 'ID',
					form: { show: false },
					column: {
						show: true,
					},
				},
				keyword: {
					title: '标签名称',
					search: {
						show: true,
						component: {
							placeholder: '请输入标签名称',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
					},
					form: {
						show: false,
						rules: [
							{ required: true, message: '标签名称为必填项' },
						],
					},
				},
				name: {
					title: '标签名称',
					search: {
						show: false,
						component: {
							placeholder: '请输入标签名称',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						rules: [
							{ required: true, message: '标签名称为必填项' },
						],
					},
				},
				positions: {
					title: '关联职位',
					type: 'dict-select',
					column: {
						minWidth: 150,
						component: {
							vModel: 'modelValue',
							multiple: true,
							// 自定义渲染组件，显示彩色标签
							name: 'fs-component',
							render: ({ row }: { row: any }) => {
								if (!row.positions || row.positions.length === 0) return <span>-</span>;
								
								return (
									<div style="display: flex; flex-wrap: wrap; gap: 4px;">
										{row.positions.map((tag: any) => (
											<el-tag
												key={tag.id}
												type="warning"
												effect="plain"
												size="mini"
											>
												{tag.title}
											</el-tag>
										))}
									</div>
								);
							}
						},
					},
					dict: dict({
						getData: async () => {
							const res = await api.GetPositionList({page:1,limit:100,tenant_id:Session.get('tenant_id')});
							return res.data || [];
						},
						label: 'title',
						value: 'id'
					}),
					form: {
						component: {
							/* multiple: true,
							filterable: true, */
							props: {
								multiple: true, // 在编辑表单中保持多选
								filterable: true,
								placeholder: '请选择关联职位',
								disabled: compute(({ mode }) => mode === 'edit') // 编辑时禁用
							},
							value: compute(({ form }) => {
								if (!form.positions) return [];
								console.log('form.positions', form.positions);
								// 如果是数组但元素是对象，提取id
								if (Array.isArray(form.positions)) {
									const ids = form.positions.map((tag: any) => {
										if (typeof tag === 'object' && tag !== null) {
											// 同时更新 competency_tags_config
											if (!form.competency_tags_config) {
												form.competency_tags_config = [];
												form.positions = [];
											}
											
											// 检查配置是否已存在
											const existingConfig = form.competency_tags_config.find(
												(config: any) => config.id === tag.id
											);
											
											if (!existingConfig) {
												form.competency_tags_config.push({
													id: tag.id,
													competency_name: tag.name,
													weight: tag.weight || 100,
													importance: tag.importance || 1,
													remark: ''
												});
											
												form.positions.push(tag.id);
											}
											
											return tag.id;
										}
										return tag;
									});
									return ids;
								}
								
								return form.positions;
							}),
							/* placeholder: '请选择关联职位', */
						},
						/* rules: [
							{ required: true, message: '关联职位为必填项' },
						], */
					},
				},
				/* icon: {
					title: '图标',
					type: 'input',
					column: {
						minWidth: 100,
					},
					form: {
						component: {
							placeholder: '请输入图标名称',
						},
					},
				},
				color: {
					title: '标签颜色',
					type: 'colorpicker',
					column: {
						minWidth: 100,
						component: {
							name: 'fs-color-block',
						},
					},
					form: {
						value: '#52c41a', // 默认颜色
					},
				}, */
				sort: {
					title: '排序',
					type: 'number',
					column: {
						minWidth: 80,
					},
					form: {
						value: 1, // 默认排序值
					},
				},
				
				/* questions_count: {
					title: '问题数量',
					type: 'number',
					column: {
						minWidth: 100,
					},
					form: {
						show: false, // 表单中不显示，由系统自动计算
					},
				}, */
				create_datetime: {
					title: '创建时间',
					type: 'datetime',
					column: {
						show:false,
						minWidth: 160,
					},
					form: {
						show: false, // 表单中不显示，由系统自动生成
					},
				},
				update_datetime: {
					title: '更新时间',
					type: 'datetime',
					column: {
						show:false,
						minWidth: 160,
					},
					form: {
						show: false, // 表单中不显示，由系统自动更新
					},
				},
				is_general: {
					title: '通用胜任力',
					type: 'dict-select',
					column: {
						minWidth: 90,
						component:{
							render: ({ row }: { row: any }) => {
								return <span>{row.is_general ? '通用' : '非通用'}</span>;
							}
						}
					},
					dict: dict({
						data: [
							{ value: true, label: '通用' },
							{ value: false, label: '非通用' },
						],
					}),
					form: {
						value: true, // 默认启用
						component: {
							name: 'el-switch',
						},
					},
				},
				description: {
					title: '描述',
					search: {
						show: false,
						component: {
							placeholder: '请输入描述',
						},
					},
					type: 'textarea',
					column: {
						minWidth: 150,
						showOverflowTooltip: true,
					},
					form: {
						component: {
							span: 24,
							placeholder: '请输入标签描述',
						},
					},
				},
			},
		},
	};
};
