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: 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);
	};

	/**
	 * 懒加载
	 * @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;
		}
		console.log(profileData);

		// 创建弹窗内容
		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 ? '是' : '否') }),
									createVNode(ElDescriptionsItem, { label: '期望薪资' }, { default: () => profile?.expected_salary || '-' }),
									createVNode(ElDescriptionsItem, { label: '紧急联系人' }, { default: () => profile?.emergency_contact || '-' }),
									createVNode(ElDescriptionsItem, { label: '紧急联系电话' }, { default: () => profile?.emergency_phone || '-' }),
									createVNode(ElDescriptionsItem, { label: '特长' }, { default: () => profile?.specialties || '-' }),
									createVNode(ElDescriptionsItem, { label: '人生格言' }, { default: () => profile?.life_motto || '-' }),
									createVNode(ElDescriptionsItem, { label: '招聘来源' }, { default: () => profile?.recruitment_source_name || '-' }),
									createVNode(ElDescriptionsItem, { label: '招聘来源详情' }, { default: () => profile?.recruitment_source_detail || '-' }),
								]
							})
						}),
						
						// 教育经历标签页
						createVNode(ElTabPane, { label: '教育经历' }, {
							default: () => educations && educations.length > 0 
								? 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: '结束日期' }),
									]
								})
								: createVNode('div', { style: 'text-align: center; padding: 20px;' }, { default: () => '暂无教育经历数据' })
						}),
						
						// 家庭成员标签页
						createVNode(ElTabPane, { label: '家庭成员' }, {
							default: () => family_members && family_members.length > 0
								? 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: '联系电话' }),
									]
								})
								: createVNode('div', { style: 'text-align: center; padding: 20px;' }, { default: () => '暂无家庭成员数据' })
						}),
						
						// 工作经历标签页
						createVNode(ElTabPane, { label: '工作经历' }, {
							default: () => work_experiences && work_experiences.length > 0
								? 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: '离职原因' }),
									]
								})
								: createVNode('div', { style: 'text-align: center; padding: 20px;' }, { default: () => '暂无工作经历数据' })
						}),
						
						// 培训经历标签页已被注释掉，保持原样
					]
				}),
				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:false
					},
					// 列设置按钮
					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 || [];
							console.log('选中的行:', selection);
							
							if (!selection || selection.length === 0) {
								warningMessage('请先选择要操作的申请');
								return;
							}
							// 打开批量绑定标签对话框
							context.openBatchTagsDialog(selection);
						},
					}, */
					// 添加批量修改状态按钮
					batchUpdateStatus: {
						text: '批量修改状态',
						type: 'primary',
						show: true,
						order: 1,
						size: 'small',
						click: () => {
							const selection = context.selectedRows || [];
							
							if (!selection || selection.length === 0) {
								warningMessage('请先选择要操作的候选人');
								return;
							}
							// 打开批量修改状态对话框
							context.openBatchStatusDialog(selection);
						},
					},
					//批量短信通知
					SMSnotification:{
						text: '批量短信通知',
						type: 'primary',
						show: true,
						order: 2,
						size: 'small',
						click:()=>{
							console.log(context.selectedRows)
							const selection = context.selectedRows || [];
							
							if (!selection || selection.length === 0) {
								warningMessage('请先选择要操作的候选人');
								return;
							}

							// 检查选中行的状态
							const statusGroups = selection.reduce((acc:any, row:any) => {
								if (!acc[row.status]) {
									acc[row.status] = [];
								}
								acc[row.status].push(row);
								return acc;
							}, {});

							// 获取状态数量
							const statusCount = Object.keys(statusGroups).length;

							if (statusCount > 1) {
								warningMessage('请选择相同状态的申请进行批量短信通知');
								return;
							}

							// 检查是否选择了状态为"已面试待处理"(status=2)的申请
							const hasInterviewedPending = selection.some((row: any) => row.status === 2);
							if (hasInterviewedPending) {
								warningMessage('请先修改为状态后再进行短信通知');
								return;
							}

							// 打开批量短信通知对话框
							context.openSmsNotification(selection);
						}
					}
				},
			},
			rowHandle: {
				//固定右侧
				fixed: 'right',
				width: 280, // 增加宽度以容纳新按钮
				buttons: {
					view: {
						iconRight: 'view',
						show: true,
						type: 'text',
						click: async ({ row }) => {
							console.log(row)
							try {
								// 先请求接口检查面试状态
								const response = await axios.get(`${import.meta.env.VITE_API_URL}/api/job/application_detail`, {
									params: {
										tenant_id: Session.get('tenant_id'),
										application_id: row.id
									}
								});
								
								if (response.data.code === 2000) {
									console.log(response.data.data)
									const analysisStatus = response.data.data?.application?.analysis_status;
									
									if (analysisStatus && analysisStatus.report_ready === true) {
										// 报告已准备好，执行跳转
										console.log(row);
										const baseUrl = window.location.origin;
										const url = `${baseUrl}/#/JobApplication/report/report?id=${row.id}&tenant_id=${Session.get('tenant_id')}&application_id=${row.applicant}&position=${row.position}`;
										window.open(url, '_blank');
									} else {
										// 面试未完成，显示提示
										warningMessage('面试未完成，无法查看报告');
									}
								} else {
									warningMessage('获取面试状态失败');
								}
							} catch (error) {
								console.error('检查面试状态失败:', error);
								warningMessage('检查面试状态失败');
							}
						}
					},
					notification: { // 添加发送短信通知按钮
						text: '发送短信',
						iconRight: 'Message',
						type: 'text',
						show: compute(({ row }) => {
							return row.status === 0; // 只在状态为"待通知"时显示
						}),
						order: 3,
						click: ({ row }) => {
							// 将单个申请转换为数组格式，以复用批量通知的逻辑
							const selection = [row];
							context.openSmsNotification(selection);
						}
					},
					profile: { // 添加查看个人信息按钮
						text: '查看个人信息',
						iconRight: 'User',
						type: 'text',
						show: false,
						order: 1,
						click: ({ row }) => {
							showUserProfileDialog(row.applicant);
						}
					},
					reanalyze: { // 添加重新分析按钮
						text: '重新分析',
						iconRight: 'Refresh',
						type: 'text',
						show:false /* compute(({ row }) => {
							return row.status === 2; // 只在状态为"已面试"时显示
						}) */,
						order: 2,
						click: async ({ row }) => {
							try {
								// 先调用视频分析接口
								const videoAnalysisResponse = await axios.post(`${import.meta.env.VITE_API_URL}/api/system/interview_analysis/analyze_applicant_videos/`, {
									application_id: row.id
								});
								
								if (videoAnalysisResponse.data.code !== 200) {
									warningMessage(videoAnalysisResponse.data.message || '视频分析失败');
									return;
								}
								
								// 视频分析成功后，调用综合分析接口
								const response = await axios.post(`${import.meta.env.VITE_API_URL}/api/system/job/trigger_comprehensive_analysis`, {
									application_id: row.id,
									force_trigger: true
								});
								
								if (response.data.code === 2000) {
									successMessage('已触发重新分析');
									// 刷新当前页面数据
									crudExpose.doRefresh();
								} else {
									warningMessage(response.data.message || '触发重新分析失败');
								}
							} catch (error) {
								console.error('重新分析失败:', error);
								warningMessage('重新分析失败');
							}
						}
					},
					edit: {
						iconRight: 'Edit',
						type: 'text',
						show: false,//auth('area:Update'),
					},
					remove: {
						iconRight: 'Delete',
						type: 'text',
						show: auth('area:Delete'),
					},
					
				},
			},
			pagination: {
				show: true,
			},
			table: {
				selection: true,
				onSelectionChange: (selection: any[]) => {
					// 存储选中的行到一个全局变量中
					context.selectedRows = selection;
				},
			},
			search: {
				show: true,
				layout: 'auto',
				/* immediate: false, // 关闭输入框实时触发
				trigger: 'manual', // 改为手动触发 */
				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,
					},
				},
				/* _index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				}, */
				id:{
					title: 'ID',
					form: { show: false },
					column: {
						show: false,
						align: 'center',
						width: '70px',}
				},
				report_id: {
					title: '报告编号',
					search: {
						show: false,
						component: {
							placeholder: '请输入报告编号',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 150,
					},
					form: {
						rules: [
							{ required: true, message: '报告编号必填项' },
						],
					},
				},
				applicant_name: {
					title: '申请人姓名',
					search: {
						show: true,
						component: {
							placeholder: '请输入申请人姓名',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						rules: [
							{ required: true, message: '申请人姓名必填项' },
						],
					},
				},
				applicant_phone: {
					title: '申请人电话',
					search: {
						show: true,
						component: {
							placeholder: '请输入申请人电话',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 130,
					},
					form: {
						rules: [
							{ required: true, message: '申请人电话必填项' },
						],
					},
				},
				position_title: {
					title: '申请职位',
					search: {
						show: true,
						component: {
							placeholder: '请输入申请职位',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						rules: [
							{ required: true, message: '申请职位必填项' },
						],
					},
				},
				status: {
					title: '申请状态',
					search: {
						show: true,
						placeholder: '请选择申请状态',
						size: 'small',
						col:{ span:3},
						/* component: {
							name: 'el-select',
							
						}, */
					},
					type: 'dict-select',
					column: {
						minWidth: 100,
					},
					dict: dict({
						data: [
							{ value: 0, label: '待通知' },
							{ value: 1, label: '已通知待面试' },
							{ value: 2, label: '已面试待处理' },
							{ value: 3, label: '已录用' },
							{ value: 4, label: '已拒绝' },
							{ value: 5, label: '拒绝并加入人才库' },
						],
					}),
				},
				comprehensive_score: {
					title: '综合评分',
					type: 'number',
					column: {
						align: 'center',
						minWidth: 100,
					},
				},
				hire_recommendation: {
					title: '录用建议',
					type: 'dict-select',
					search: {
						show: true,
						type: 'dict-select',
						
						component: {
							placeholder: '请选择录用建议',
							clearable: true,
						},
						size: 'small',
						col:{ span:3},
					},dict: dict({
						data: [
							{ value: '谨慎录用', label: '谨慎录用' },
							{ value: '推荐录用', label: '推荐录用' },
							{ value: '有条件录用', label: '有条件录用' },
							{ value: '不推荐录用', label: '不推荐录用' },
						],
					}),
					column: {
						minWidth: 150,
						showOverflowTooltip: true,
					},
				},
				/* resume_url: {
					title: '简历链接',
					type: 'link',
					column: {
						minWidth: 100,
						component: {
							name: 'fs-button',
							type: 'primary',
							link: true,
							text: '查看简历',
							click: compute(({ row }) => {
								return () => {
									if (row.resume_url) {
										window.open(row.resume_url);
									}
								};
							}),
						},
						show: compute(({ row }) => {
							return !!row.resume_url;
						}),
					},
				}, */
				create_datetime: {
					title: '创建时间',
					type: 'datetime',
					column: {
						show: false,
						minWidth: 160,
					},
					form: {
						show: false,
					},
				},
				update_datetime: {
					title: '更新时间',
					type: 'datetime',
					column: {
						minWidth: 160,
					},
					form: {
						show: false,
					},
				},
			},
			
		},
	};
};
