import * as api from './api';
import { dict, UserPageQuery, AddReq, DelReq, EditReq, compute, CreateCrudOptionsProps, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as companyApi from '../company/api';
import { dictionary } from '/@/utils/dictionary';
import { successMessage, errorMessage } from '/@/utils/message';
import { auth } from '/@/utils/authFunction';
import { Md5 } from 'ts-md5';
import { ElMessageBox } from 'element-plus';

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	// 轮询任务状态的函数
	const pollTaskStatus = async (taskId: string, maxAttempts: number = 60): Promise<void> => {
		let attempts = 0;
		
		const poll = async (): Promise<void> => {
			try {
				attempts++;
				const response = await api.GetCopyTaskStatus(taskId);
				
				console.log(`任务状态检查 (${attempts}/${maxAttempts}):`, response);
				
				// 根据任务状态决定下一步操作
				if (response.data && response.data.status) {
					const status = response.data.status;
					
					if (status === 'completed' || status === 'success') {
						console.log('配置复制任务完成');
						successMessage('配置复制任务已完成');
						return;
					} else if (status === 'failed' || status === 'error') {
						console.error('配置复制任务失败:', response.data.message || '未知错误');
						errorMessage('配置复制任务失败: ' + (response.data.message || '未知错误'));
						return;
					} else if (status === 'running' || status === 'in_progress' || status === 'pending') {
						// 任务仍在进行中，继续轮询
						if (attempts < maxAttempts) {
							setTimeout(poll, 5000); // 5秒后再次检查
						} else {
							console.warn('轮询超时，任务可能仍在进行中');
							errorMessage('配置复制任务超时，请稍后手动检查任务状态');
						}
					} else {
						// 未知状态，继续轮询
						if (attempts < maxAttempts) {
							setTimeout(poll, 5000);
						} else {
							console.warn('轮询超时，未知任务状态');
							errorMessage('配置复制任务状态未知，请稍后手动检查');
						}
					}
				} else {
					// 响应格式异常
					if (attempts < maxAttempts) {
						setTimeout(poll, 5000);
					} else {
						console.error('任务状态响应格式异常');
						errorMessage('无法获取任务状态，请稍后手动检查');
					}
				}
			} catch (error) {
				console.error('检查任务状态时出错:', error);
				if (attempts < maxAttempts) {
					setTimeout(poll, 5000);
				} else {
					errorMessage('检查任务状态失败，请稍后手动检查');
				}
			}
		};
		
		// 开始轮询
		poll();
	};

	const pageRequest = async (query: any) => {
		console.log(query)
		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 handleDeleteConfirm = async (opts: any) => {
		try {
			await ElMessageBox.confirm(
				`确定要删除用户"${opts.row.username}"吗？此操作不可撤销。`,
				'删除确认',
				{
					confirmButtonText: '确定删除',
					cancelButtonText: '取消',
					type: 'warning',
					confirmButtonClass: 'el-button--danger'
				}
			);
			// 用户确认后，调用原有的删除逻辑
			await delRequest(opts);
			successMessage('删除成功');
			// 刷新列表
			crudExpose.doRefresh();
		} catch (error) {
			// 用户取消删除，不做任何操作
			if (error !== 'cancel') {
				errorMessage('删除失败');
			}
		}
	};
	const addRequest = async ({ form }: AddReq) => {
		const result = await api.AddObj(form);
		
		// 添加成功后异步调用copy-from-base接口，不阻塞UI响应
		if (result && form.tenant_id) {
			// 使用Promise.resolve().then()确保在下一个微任务中执行，不阻塞当前操作
			Promise.resolve().then(async () => {
				try {
					const copyResponse = await api.CopyFromBase(form.tenant_id);
					console.log('Copy from base response:', copyResponse);
					
					// 检查响应是否包含task_id
					if (copyResponse && copyResponse.data && copyResponse.data.task_id) {
						const taskId = copyResponse.data.task_id;
						console.log('开始轮询任务状态，task_id:', taskId);
						
						// 显示任务已启动的消息
						successMessage('用户添加成功，配置复制任务已启动');
						
						// 开始轮询任务状态
						pollTaskStatus(taskId);
					} else {
						console.warn('Copy from base响应中未找到task_id');
						successMessage('用户添加成功，但无法获取配置复制任务ID');
					}
				} catch (error) {
					console.error('Copy from base failed:', error);
					errorMessage('用户添加成功，但启动配置复制任务失败');
				}
			});
		}
		
		return result;
	};

	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
					},
				}
			},
			search: {
				col: { span: 3 },
				show: true,
				autoSearch:false,
				buttons: {
					search: {
						size: 'small', // 设置查询按钮大小为small
					},
					reset: {
						size: 'small', // 设置重置按钮大小为small
					}
				}
			},
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			actionbar: {
				buttons: {
					add: {
						show: true,//auth('account:Create'),
					},
				},
			},
			rowHandle: {
				fixed: 'right',
				width: 200,
				buttons: {
					view: { iconRight: 'View', type: 'text',show: true },
					edit: { iconRight: 'Edit', type: 'text', show: false },//auth('account:Update')
					remove: { 
						iconRight: 'Delete', 
						type: 'text', 
						show: true,
						click: handleDeleteConfirm
					},//auth('account:Delete')
				},
			},
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: { type: 'index', align: 'center', width: '70px', columnSetDisabled: true },
				},
				username: {
					title: '用户名',
					type: 'text',
					search: { show: true },
					form: {
						component: { placeholder: '请输入用户名' },
						rules: [{ required: true, message: '请输入用户名' }]
					},
					column: { minWidth: 120 },
				},
				password: {
					title: '密码',
					type: 'password',
					search: { show: false },
					column: { show: false },
					form: {
						component: { placeholder: '请输入密码' },
						rules: [{ required: true, message: '请输入密码' }],
						show: true,
						column: { show: false }
					},
					valueResolve({ form }) {
                        if (form.password) {
                            form.password = Md5.hashStr(form.password)
                        }
                    }
				},
				name: {
					title: '姓名',
					type: 'text',
					search: { show: false },
					form: {
						component: { placeholder: '请输入姓名' },
						rules: [{ required: true, message: '请输入姓名' }]
					},
					column: { minWidth: 120 },
				},
				mobile: {
					title: '手机号',
					type: 'text',
					search: { show: true },
					form: {
						component: { placeholder: '请输入手机号' },
						rules: [{ required: true, message: '请输入手机号' }]
					},
					column: { minWidth: 120 },
				},
				email: {
					title: '邮箱',
					type: 'text',
					search: { show: false },
					form: {
						component: { placeholder: '请输入邮箱' },
						rules: [{ required: true, message: '请输入邮箱' }]
					},
					column: { minWidth: 180 },
				},
				tenant_id: {
					title: '商户ID',
					search: { show: true },
					type: 'dict-select',
					form: {
						component: { placeholder: '请选择商户' },
						rules: [{ required: true, message: '请选择商户' }]
					},
					column: { minWidth: 120 },
					dict: dict({
						url: '/api/platform/tenants/',
						value: 'tenant_id',
						label: 'name',
						getData: (url) => {
							return companyApi.GetList({ page: 1, limit: 20 }).then((res:any) => {
								return res.data.results;
							});
						}
					}),
				},
				is_active: {
					title: '账号状态',
					search: { show: true },
					type: 'dict-select',
					form: { show:false, component: { placeholder: '请选择账号状态' } },
					column: { minWidth: 120 },
					dict: dict({
						data: [
							{ value: true, label: '启用' },
							{ value: false, label: '禁用' }
						]
					}),
				},
				date_joined: {
					title: '开通时间',
					type: 'datetime',
					search: { show: false },
					form: { component: { placeholder: '请选择开通时间' },show:false },
					column: { minWidth: 150 },
				},
				last_login: {
					title: '最后登录时间',
					type: 'datetime',
					search: { show: false },
					form: { component: { placeholder: '请选择最后登录时间' },show:false  },
					column: { minWidth: 150 },
				},
				permission_level: {
					title: '权限等级',
					search: { show: false },
					type: 'dict-select',
					form: { component: { placeholder: '请选择权限等级' },show:false  },
					column: { minWidth: 120 },
					dict: dict({
						data: [
							{ value: 'admin', label: '管理员' },
							{ value: 'user', label: '普通用户' },
							{ value: 'guest', label: '访客' }
						]
					}),
				},
				account_status_display:{
					title: '账号状态',
				}
				/* job_count: {
					title: '岗位数量',
					type: 'number',
					column: { minWidth: 100 },
				},
				report_count: {
					title: '报告数量',
					type: 'number',
					column: { minWidth: 100 },
				}, */
			},
		},
	};
}; 