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,warningMessage } from '/@/utils/message';
import { auth } from '/@/utils/authFunction';
import tableSelector from '/@/components/tableSelector/index.vue';
import { shallowRef, h, createVNode, render } from 'vue';
import { useRouter } from 'vue-router';
import { ElDialog, ElDescriptions, ElDescriptionsItem, ElTabs, ElTabPane, ElTable, ElTableColumn, ElButton } from 'element-plus';
import axios from 'axios';
import { Session } from '/@/utils/storage';

export const createCrudOptions = function ({ crudExpose, context}: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const router = useRouter();
	
	const pageRequest = async (query: UserPageQuery) => {
		console.log(query.status);
		if(query.status==undefined){
			query.status='6,7'
		}
		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);
	};

	/**
	 * 懒加载
	 * @param row
	 * @returns {Promise<unknown>}
	 */
	const loadContentMethod = (tree: any, treeNode: any, resolve: Function) => {
		pageRequest({ pcode: tree.code }).then((res: APIResponseData) => {
			resolve(res.data);
		});
	};

	// 修改获取用户信息的方法
	const getUserProfile = async (userId: number) => {
		try {
			const response = await axios.get(`${import.meta.env.VITE_API_URL}/api/system/wechat/user/profile/get?user_id=${userId}&tenant_id=${Session.get('tenant_id')}`);
			return response.data;
		} catch (error) {
			console.error('获取用户信息失败:', error);
			return null;
		}
	};

	// 显示用户信息弹窗
	const showUserProfileDialog = async (userId: number) => {
		const profileData = await getUserProfile(userId);
		if (!profileData || profileData.code !== 2000) {
			warningMessage('获取用户信息失败');
			return;
		}

		// 创建弹窗内容
		const { user_info, profile, educations, family_members, trainings, work_experiences } = profileData.data;

		// 创建一个容器元素
		const container = document.createElement('div');
		
		// 创建对话框内容
		const dialogContent = createVNode(
			ElDialog,
			{
				title: '个人信息详情',
				width: '70%',
				modelValue: true,
				'onUpdate:modelValue': (val: boolean) => {
					if (!val) {
						// 关闭对话框时销毁组件
						render(null, container);
						document.body.removeChild(container);
					}
				},
				beforeClose: () => {
					render(null, container);
					document.body.removeChild(container);
				}
			},
			{
				default: () => createVNode(ElTabs, { type: 'border-card' }, {
					default: () => [
						// 基本信息标签页
						createVNode(ElTabPane, { label: '基本信息' }, {
							default: () => createVNode(ElDescriptions, { column: 3, border: true }, {
								default: () => [
									createVNode(ElDescriptionsItem, { label: '姓名' }, { default: () => user_info?.name || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '电话' }, { default: () => user_info?.phone || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '年龄' }, { default: () => user_info?.age || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '出生日期' }, { default: () => user_info?.birth_date || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '性别' }, { default: () => user_info?.gender_name || '未知' }),
									createVNode(ElDescriptionsItem, { label: '身份证号' }, { default: () => user_info?.id_card || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '政治面貌' }, { default: () => profile?.political_status || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '民族' }, { default: () => profile?.ethnicity || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '身高' }, { default: () => profile?.height ? `${profile.height}cm` : '未填写' }),
									createVNode(ElDescriptionsItem, { label: '体重' }, { default: () => profile?.weight ? `${profile.weight}kg` : '未填写' }),
									createVNode(ElDescriptionsItem, { label: '籍贯' }, { default: () => profile?.native_place || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '户口所在地' }, { default: () => profile?.household_location || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '现居地址' }, { default: () => profile?.current_address || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '婚姻状况' }, { default: () => profile?.marital_status_name || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '是否有子女' }, { default: () => profile?.has_children !== undefined ? (profile.has_children ? '是' : '否') : '未填写' }),
									createVNode(ElDescriptionsItem, { label: '期望薪资' }, { default: () => profile?.expected_salary || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '紧急联系人' }, { default: () => profile?.emergency_contact || '未填写' }),
									createVNode(ElDescriptionsItem, { label: '紧急联系电话' }, { default: () => profile?.emergency_phone || '未填写' }),
								]
							})
						}),
						
						// 教育经历标签页 - 只在有数据时显示
						educations && educations.length > 0 ? createVNode(ElTabPane, { label: '教育经历' }, {
							default: () => createVNode(ElTable, { data: educations, border: true, stripe: true }, {
								default: () => [
									createVNode(ElTableColumn, { prop: 'education_type_name', label: '学历类型' }),
									createVNode(ElTableColumn, { prop: 'degree_name', label: '学位' }),
									createVNode(ElTableColumn, { prop: 'school_name', label: '学校名称' }),
									createVNode(ElTableColumn, { prop: 'major', label: '专业' }),
									createVNode(ElTableColumn, { prop: 'start_date', label: '开始日期' }),
									createVNode(ElTableColumn, { prop: 'end_date', label: '结束日期' }),
								]
							})
						}) : null,
						
						// 家庭成员标签页 - 只在有数据时显示
						family_members && family_members.length > 0 ? createVNode(ElTabPane, { label: '家庭成员' }, {
							default: () => createVNode(ElTable, { data: family_members, border: true, stripe: true }, {
								default: () => [
									createVNode(ElTableColumn, { prop: 'relation', label: '关系' }),
									createVNode(ElTableColumn, { prop: 'name', label: '姓名' }),
									createVNode(ElTableColumn, { prop: 'workplace', label: '工作单位' }),
									createVNode(ElTableColumn, { prop: 'position', label: '职位' }),
									createVNode(ElTableColumn, { prop: 'phone', label: '联系电话' }),
								]
							})
						}) : null,
						
						// 工作经历标签页 - 只在有数据时显示
						work_experiences && work_experiences.length > 0 ? createVNode(ElTabPane, { label: '工作经历' }, {
							default: () => createVNode(ElTable, { data: work_experiences, border: true, stripe: true }, {
								default: () => [
									createVNode(ElTableColumn, { prop: 'company_name', label: '公司名称' }),
									createVNode(ElTableColumn, { prop: 'department', label: '部门' }),
									createVNode(ElTableColumn, { prop: 'position', label: '职位' }),
									createVNode(ElTableColumn, { prop: 'start_date', label: '开始日期' }),
									createVNode(ElTableColumn, { prop: 'end_date', label: '结束日期' }),
									createVNode(ElTableColumn, { prop: 'monthly_salary', label: '月薪' }),
									createVNode(ElTableColumn, { prop: 'company_size', label: '公司规模' }),
									createVNode(ElTableColumn, { prop: 'supervisor_name', label: '主管姓名' }),
									createVNode(ElTableColumn, { prop: 'supervisor_phone', label: '主管电话' }),
									createVNode(ElTableColumn, { prop: 'resignation_reason', label: '离职原因' }),
								]
							})
						}) : null,
						
						// 培训经历标签页 - 只在有数据时显示
						trainings && trainings.length > 0 ? createVNode(ElTabPane, { label: '培训经历' }, {
							default: () => createVNode(ElTable, { data: trainings, border: true, stripe: true }, {
								default: () => [
									createVNode(ElTableColumn, { prop: 'training_name', label: '培训名称' }),
									createVNode(ElTableColumn, { prop: 'institution', label: '培训机构' }),
									createVNode(ElTableColumn, { prop: 'start_date', label: '开始日期' }),
									createVNode(ElTableColumn, { prop: 'end_date', label: '结束日期' }),
									createVNode(ElTableColumn, { prop: 'description', label: '描述' }),
									createVNode(ElTableColumn, { prop: 'certificate', label: '证书' }),
								]
							})
						}) : null,
					].filter(Boolean) // 过滤掉null值
				}),
				footer: () => createVNode(ElButton, {
					onClick: () => {
						render(null, container);
						document.body.removeChild(container);
					}
				}, { default: () => '关闭' })
			}
		);

		// 将容器添加到body
		document.body.appendChild(container);
		
		// 渲染对话框到容器
		render(dialogContent, container);
	};

	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:true,
						click: async () => {
							try {
								const response = await api.exportData({
									tenant_id: Session.get('tenant_id'),
									status: '6,7',
								});
								if (response.code === 2000) {
									const downloadUrl = response.data.minio_url;
									let fileName = response.data.file_name;

									// 处理文件名中的特殊字符
									fileName = decodeURIComponent(fileName).replace(/[<>:"/\\|?*]+/g, '_');

									// 使用 Blob 处理下载
									try {
										const blob = await fetch(downloadUrl).then(res => res.blob());
										
										// 根据文件扩展名设置正确的 MIME 类型
										const fileExtension = fileName.split('.').pop()?.toLowerCase();
										let mimeType = 'application/octet-stream'; // 默认类型
										
										if (fileExtension === 'xlsx' || fileExtension === 'xls') {
											mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
										} else if (fileExtension === 'csv') {
											mimeType = 'text/csv';
										}

										const blobUrl = window.URL.createObjectURL(new Blob([blob], { type: mimeType }));
										
										// 创建下载链接
										const link = document.createElement('a');
										link.href = blobUrl;
										link.download = fileName;
										link.style.display = 'none';
										
										// 兼容不同浏览器的下载方式
										if (window.navigator.msSaveOrOpenBlob) {
											// IE10+
											window.navigator.msSaveOrOpenBlob(blob, fileName);
										} else {
											// 其他现代浏览器
											document.body.appendChild(link);
											
											if (link.click) {
												link.click();
											} else {
												// 触发点击的备选方案
												const event = document.createEvent('MouseEvents');
												event.initEvent('click', true, true);
												link.dispatchEvent(event);
											}
											
											document.body.removeChild(link);
										}
										
										// 清理 Blob URL
										setTimeout(() => {
											window.URL.revokeObjectURL(blobUrl);
										}, 100);

										successMessage('导出成功，文件开始下载');
									} catch (fetchError) {
										console.error('下载文件失败:', fetchError);
										warningMessage('下载文件失败，请检查网络连接');
									}
								} else {
									warningMessage('导出失败：' + (response.msg || '未知错误'));
								}
							} catch (error) {
								console.error('导出失败:', error);
								warningMessage('导出失败，请稍后重试');
							}
						}
					},
					// 列设置按钮
					columns:{
						show:false
					},
				}
			},
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			actionbar: {
				buttons: {
					add: {
						show: false,//auth('area:Create'),
					},
					// 添加批量操作按钮
					batchBindTags: {
						text: '批量绑定标签',
						type: 'primary',
						show: true,
						order: 2,
						click: () => {
							const selection = context.selectedRows?.value || [];
							if (!selection || selection.length === 0) {
								warningMessage('请先选择要操作的记录');
								return;
							}
							context.openBatchTagsDialog(selection);
						},
					},
					batchStatus: {
						text: '批量修改状态',
						type: 'primary',
						show: true,
						order: 1,
						click: () => {
							const selection = context.selectedRows?.value || [];
							if (!selection || selection.length === 0) {
								warningMessage('请先选择要操作的记录');
								return;
							}
							context.openBatchStatusDialog(selection);
						},
					},
				},
			},
			rowHandle: {
				//固定右侧
				fixed: 'right',
				width: 280, // 增加宽度以容纳新按钮
				buttons: {
					view: {
						text: '查看个人信息',
						iconRight: 'User',
						show: true,
						type: 'text',
						click: ({ row }) => {
							showUserProfileDialog(row.user.id);
						}
						
					},
					profile: { // 添加查看个人信息按钮
						text: '查看报告',
						iconRight: 'view',
						type: 'text',
						show: true,
						order: 1,
						click: ({ row }) => {
							// 在新窗口中打开报告详情页面
							console.log(row)
							const baseUrl = window.location.origin;
							const url = `${baseUrl}/#/JobApplication/report/report?id=${row.original_application}&tenant_id=${Session.get('tenant_id')}&application_id=${row.original_application}`;
							
							window.open(url, '_blank');
						}
					},
					edit: {
						text: '编辑',
						iconRight: 'Edit',
						type: 'text',
						show: false,//auth('area:Update'),
					},
					remove: {
						text: '删除',
						iconRight: 'Delete',
						type: 'text',
						show: false,//auth('area:Delete'),
					},
				},
			},
			pagination: {
				show: true,
			},
			table: {
				selection: true,
				onSelectionChange: (selection: any[]) => {
					if (context && context.selectedRows) {
						context.selectedRows.value = selection;
					}
				},
			},
			search: {
				show: true,
				layout: 'auto',
				autoSearch:false,
				buttons: {
					search: {
						size: 'small', // 设置查询按钮大小为small
					},
					reset: {
						size: 'small', // 设置重置按钮大小为small
					}
				},		
				resetBtn: {
					show: true,
					click: () => {
						// 重置搜索时，也重置树的选中状态
						const treeRef = document.querySelector('.el-tree');
						if (treeRef) {
							// 尝试清除当前高亮
							const highlightNode = treeRef.querySelector('.is-current');
							if (highlightNode) {
								highlightNode.classList.remove('is-current');
							}
						}
					}
				}
			},
			columns: {
				_selection: {
					title: '选择',
					form: { show: false },
					column: {
						type: 'selection',
						align: 'center',
						width: 50,
						fixed: 'left',
						columnSetDisabled: true,
					},
				},
				id: {
					title: 'ID',
					search: {
						show: false,
						component: {
							placeholder: '请输入ID',
						},
					},
					type: 'number',
					column: {
						width: 80,
					},
					form: {
						show: false,
					},
				},
				keyword: {
					title: '姓名',
					search: {
						show: true,
						component: {
							placeholder: '请输入姓名',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						show: false,
						minWidth: 100,
						formatter: ({ row }) => {
							return row.user.name || row.user.nikename || '未填写';
						}
					},
				},

				'user.name': {
					title: '姓名',
					search: {
						show: false,
						component: {
							placeholder: '请输入姓名',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 100,
						formatter: ({ row }) => {
							return row.user.name || row.user.nikename || '未填写';
						}
					},
				},
				tags: {
					title: '标签',
					type: 'dict-select',
					column: {
						minWidth: 180,
						component: {
							name: 'fs-component',
							render: ({ row }: { row: any }) => {
								if (!row.tags || row.tags.length === 0) return <span>-</span>;
								
								const displayTags = row.tags.slice(0, 2); // 只显示前两个标签
								const remainingCount = row.tags.length - 2; // 计算剩余标签数量
								
								return (
									<div style="display: flex; gap: 4px; align-items: center;">
										{displayTags.map((tag: any) => (
											<el-tag
												key={tag.id}
												type="warning"
												effect="plain"
												size="mini"
												style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
												title={tag.name}
											>
												{tag.name.length > 4 ? tag.name.slice(0, 4) + '...' : tag.name}
											</el-tag>
										))}
										{remainingCount > 0 && (
											<el-tooltip
												placement="top"
												effect="light"
												popper-class="tag-tooltip"
											>
												{{
													default: () => (
														<el-tag
															type="info"
															effect="plain"
															size="mini"
														>
															+{remainingCount}
														</el-tag>
													),
													content: () => (
														<div>
															<div style="font-weight: bold; margin-bottom: 5px">剩余{remainingCount}个标签:</div>
															{row.tags.slice(2).map((tag: any) => (
																<div key={tag.id} style="margin: 3px 0">{tag.name}</div>
															))}
														</div>
													)
												}}
											</el-tooltip>
										)}
									</div>
								);
							}
						}
					},
				},
				phone: {
					title: '手机号',
					search: {
						show: true,
						component: {
							placeholder: '请输入电话',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
						formatter: ({ row }) => {
							return row.user.phone || '未填写';
						}
					},
				},
				'user.phone': {
					title: '电话',
					search: {
						show: false,
						component: {
							placeholder: '请输入电话',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 120,
						formatter: ({ row }) => {
							return row.user.phone || '未填写';
						}
					},
				},
				gender: {
					title: '性别',
					search: {
						show: true,
						/* component: {
							name: 'el-select',
							options: [
								{ value: '男', label: '男' },
								{ value: '女', label: '女' },
								{ value: '未知', label: '未知' },
							]
						}, */
						size: 'small',
						col:{ span:3},
					},
					type: 'dict-select',
					dict: dict({
						data: [
							{ value: '1', label: '男' },
							{ value: '2', label: '女' },
							{ value: '0', label: '未知' },
						
						]
					}),
					column: {
						minWidth: 80,
							

					},
				},
				age: {
					title: '年龄',
					type: 'number',
					column: {
						minWidth: 80,
						/* formatter: ({ row }) => {
							return row.age || '未填写';
						} */
					},
				},
				/* 'profile_summary.political_status': {
					title: '政治面貌',
					type: 'input',
					column: {
						minWidth: 100,
						formatter: ({ row }) => {
							return row.profile_summary?.political_status || '未填写';
						}
					},
				},
				'profile_summary.ethnicity': {
					title: '民族',
					type: 'input',
					column: {
						minWidth: 80,
						formatter: ({ row }) => {
							return row.profile_summary?.ethnicity || '未填写';
						}
					},
				}, 
				'profile_summary.marital_status_name': {
					title: '婚姻状况',
					type: 'input',
					column: {
						minWidth: 100,
						formatter: ({ row }) => {
							return row.profile_summary?.marital_status_name || '未填写';
						}
					},
				},*/
				expected_salary_max: {
					title: '期望薪资',
					type: 'number',
					column: {
						minWidth: 100,
						formatter: ({ row }) => {
							return row.profile_summary?.expected_salary ? `${row.profile_summary.expected_salary}元` : '未填写';
						}
					},
				},
				title: {
					title: '职位',
					search: {
						show: true,
						component: {
							placeholder: '请输入职位',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						show: false,
						minWidth: 120,
						formatter: ({ row }) => {
							return row.suitable_positions[0]?.title || '未填写';
						}
					},
				},
				'suitable_positions.title': {
					title: '职位',
					search: {
						show: false,
						component: {
							placeholder: '请输入职位',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 120,
						formatter: ({ row }) => {
							return row.suitable_positions[0]?.title || '未填写';
						}
					},
				},
				status: {
					title: '状态',
					type: 'dict-select',
					dict: dict({
						data: [
							/* { value: 1, label: '试用期' },
							{ value: 2, label: '考察期' },
							{ value: 3, label: '在职' },
							{ value: 4, label: '已离职' },
							{ value: 5, label: '在职已盘点' }, */
							{ value: 6, label: '曾就职' },
							{ value: 7, label: '具备潜力' },
						
						]
					}),
					search: {
						show: true,
					/* 	component: {
							name: 'el-select',
							options: [
								{ value: 1, label: '试用期' },
								{ value: 2, label: '考察期' },
								{ value: 3, label: '在职' },
								{ value: 4, label: '已离职' },
								{ value: 5, label: '在职已盘点' },
								
							]
						}, */
						size: 'small',
						col:{ span:3},
					},
					
					column: {
						minWidth: 100,
						
						/* formatter: ({ row }) => {
							return row.application_summary?.latest_status || '未填写';
						} */
					},
				},
				interview_score: {
					title: '面试得分',
					type: 'input',
					column: {
						minWidth: 100,
						/* formatter: ({ row }) => {
							return row.application_summary?.highest_score || '';
						} */
					},
				},
				remarks: {
					title: '备注',
					type: 'textarea',
					column: {
						minWidth: 100,
						/* formatter: ({ row }) => {
							return row.application_summary?.latest_status_name || '未填写';
						} */
					},
				},
				/*'application_summary.highest_score': {
					title: '最高评分',
					type: 'number',
					column: {
						minWidth: 100,
						formatter: ({ row }) => {
							return row.application_summary?.highest_score || '未评分';
						}
					},
				},
				'application_summary.total_count': {
					title: '申请次数',
					type: 'number',
					column: {
						minWidth: 100,
						formatter: ({ row }) => {
							return row.application_summary?.total_count || 0;
						}
					},
				},
				 status_name: {
					title: '账号状态',
					type: 'input',
					column: {
						minWidth: 100,
					},
				},
				create_datetime: {
					title: '创建时间',
					type: 'datetime',
					column: {
						minWidth: 160,
					},
					form: {
						show: false,
					},
				}, */
			},
			
		},
	};
};
