import { 
	AddReq, 
	CreateCrudOptionsProps, 
	CreateCrudOptionsRet, 
	DelReq,
	dict, 
	EditReq,
	FormWrapperContext,
	ScopeContext,
	UserPageQuery,
	UserPageRes,
	utils
 } from '@fast-crud/fast-crud';
import * as api from './api';
import { BorrowingReview, Switchspost } from './api';
import { ElMessage , ElInput, ElDialog, ElButton } from 'element-plus';
import dayjs from 'dayjs';
import { h, ref, computed ,inject,defineAsyncComponent, Ref} from "vue";
// import ItemsList from './ItemsList/index.vue';

// 审批状态处理工具函数
const getApprovalStatusText = (adminApproverInfo: any) => {
	if (!adminApproverInfo) return '无审批流程';
	
	const { approval_status, current_step, total_steps, is_approved, is_rejected, is_pending } = adminApproverInfo;
	
	// 优先使用布尔状态标识
	if (is_approved) return '审批通过';
	if (is_rejected) return '审批拒绝';
	if (is_pending) return '审批中';
	
	// 回退到文本状态
	let statusText = approval_status || '未知状态';
	
	// 添加进度信息
	if (current_step && total_steps) {
		statusText += ` (${current_step.step_order}/${total_steps})`;
	}
	
	// 添加当前审批人信息
	if (current_step && current_step.approver_name) {
		statusText += ` - 待${current_step.approver_name}审批`;
	}
	
	return statusText;
};

// 审批进度详情处理函数
const getApprovalProgressText = (adminApproverInfo: any) => {
	if (!adminApproverInfo || !adminApproverInfo.approval_records) {
		return '无审批记录';
	}
	
	const records = adminApproverInfo.approval_records;
	
	// 按审批人分组，只保留每个审批人的最新状态
	const approverMap = new Map();
	
	records.forEach((record: any) => {
		const approverName = record.approver_name;
		const existingRecord = approverMap.get(approverName);
		
		// 如果没有记录，或者当前记录更新（按创建时间或审批时间）
		if (!existingRecord || 
			(record.approve_time && (!existingRecord.approve_time || 
			new Date(record.approve_time) > new Date(existingRecord.approve_time)))) {
			approverMap.set(approverName, record);
		}
	});
	
	// 转换为显示文本${timeText}
	return Array.from(approverMap.values()).map((record: any) => {
		const statusIcon = record.status === 1 ? '✓' : record.status === 0 ? '⏳' : '✗';
		const statusText = record.status_label || (record.status === 1 ? '已通过' : record.status === 0 ? '待审核' : '已拒绝');
		const timeText = record.approve_time ? ` (${dayjs(record.approve_time).format('MM-DD HH:mm')})` : '';
		return `${statusIcon} ${record.approver_name} (${statusText})`;
	}).join(' | ');
};

export const createCrudOptions = function ({ crudExpose ,context, showRejectDialog, rejectReason, currentFormId,expose, showWarehouseDialog, currentApprovalFormId }: CreateCrudOptionsProps& {
	showRejectDialog: Ref<boolean>,
	rejectReason: Ref<string>,
	currentFormId: Ref<number | null>,
	showWarehouseDialog: Ref<boolean>,
	currentApprovalFormId: Ref<number | null>
  }): CreateCrudOptionsRet {

/* ${statusIcon} ${record.step_name}: */




	const pageRequest = async (query: UserPageQuery) => {
		try {
			const res = await api.GetList(query);
			console.log("res::::",res)
			return {
				...res,
				records: res.data,
				total: res.total,
			};
		} catch (error) {
			return {
				code: 2000,
				msg: 'success',
				records: [],
				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(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};
	//切换合作商
	const res = Switchspost(1);		



	return {
		crudOptions: {
			request: {
				// switchspost,
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			form: {
				labelWidth: computed(() => {
					return context.labelWidthRef?.value ? context.labelWidthRef.value + "px" : "100px";
				}),
				wrapper: {
					buttons: {
					ok: {
						text: "通过", 
						click: async (ctx: FormWrapperContext) => {
							// 检查是否为续借待审批状态（状态值为9）
							if (ctx.form.status === 9) {
								// 续借审批不需要选择仓库，直接审批通过
								await BorrowingReview(ctx.form.id, "approve", "同意续借");
								ElMessage.success("续借审批通过");
								crudExpose.doRefresh();
							} else {
								// 检查审批流程状态
								const adminApproverInfo = ctx.form.admin_approver_info;
								if (adminApproverInfo && adminApproverInfo.current_step) {
									// 显示当前审批步骤信息
									const currentStep = adminApproverInfo.current_step;
									const stepInfo = `当前步骤：${currentStep.step_name} (${currentStep.step_order}/${adminApproverInfo.total_steps})`;
									console.log(stepInfo);
									
									// 检查是否还有后续审批步骤
									if (currentStep.step_order < adminApproverInfo.total_steps) {
										// 还有后续步骤，需要选择仓库
										currentApprovalFormId.value = ctx.form.id;
										showWarehouseDialog.value = true;
									} else {
										// 最后一步审批，直接通过
										await BorrowingReview(ctx.form.id, "approve", "同意申请");
										ElMessage.success("审批通过");
										crudExpose.doRefresh();
									}
								} else {
									// 没有审批流程信息，按原逻辑处理
									currentApprovalFormId.value = ctx.form.id;
									showWarehouseDialog.value = true;
								}
							}
							ctx.close();
						}
					},
					reject: {
						text: "拒绝",
						type: "danger",
						click: async (context: FormWrapperContext) => {
							currentFormId.value = context.form.id;
							showRejectDialog.value = true;
							context.close();
							crudExpose.doRefresh();
						} 
					},			  
				
				}
			}
			},
			search:{
				show:true,
			},
			pagination: {
				show: true,
				pageSize: 10,
			},
			toolbar:{show: false},
			actionbar:{show:false},		  
			rowHandle:{
				fixed:'right',
				width: 100,
				show: true,
				buttons: {
					view: { 
						show: true,
						order:1,
						click: ({ row }) => {
							// eslint-disable-next-line no-console
							// console.log("row:::",row);
							window.dispatchEvent(new CustomEvent('approve-view', { detail: row }));
						},
					},
					edit: { show: false },
					remove: { show: false },
				// custom: {
				// 	text: "审批",
				// 	order: 5,
				// 	size: "small",
				// 	show: true,
				// 	click({row}) {
				// 			// eslint-disable-next-line no-console
				// 		// console.log("click", context);
				// 		// alert(context);
				// 		try{
				// 			// approvalDialogRef.value.openApprovalDialog(row);
				// 			// BorrowingReview(context.row.id,'approve','同意借用');
				// 			// ElMessage.success('审批通过');
				// 		}catch(err){
				// 			// eslint-disable-next-line no-console
				// 			console.log("error:::::", err);
				// 			ElMessage.error("系统错误!");
				// 		}
				// 	}
				// }

				// customView: {
				// 	text: '审批',
				// 	type: 'primary',
				// 	size: 'small',
				// 	order: 1,
				// 	show: true,
				// }



				}

			},
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						align: 'center',
						width: '70px',
						columnSetDisabled: true,
						formatter: (context) => {
							let index = context.index ?? 1;
							let pagination = crudExpose!.crudBinding.value.pagination;
							return ((pagination!.currentPage ?? 1) - 1) * pagination!.pageSize + index + 1;


						},
					},
				},
					search:{
					title: '关键字搜索',
					search: { show: true,type: 'input', },
					type: 'input',
					form: {
						component: { placeholder: '请输入' },
						show:false},
					column: {show:false}
				},
				application_no: {
					title: '借用单编号',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '请输入借用编号' },
						rules: [{ required: false, message: '请输入借用编号' }],
					},
				},
				borrower_type_label: { title: '借用人角色', column: { minWidth: 100 } },
				borrow_type_label: {
					title: '借用性质',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '请输入借用性质' },
						rules: [{ required: false, message: '请输入借用性质' }],
					},
				},
				user_code:{
					title: '学号/工号',
					search: { show: true },
					type: 'input',
					column: { show:false, minWidth: 120 },
					form: {
						show: false,
						component: { placeholder: '请输入学号/工号' },
						rules: [{ required: false, message: '' }],
					},
				},
				borrower_name:{
				title: '借用人',
					search: { show: true },
					type: 'input',
					column: { show:false, minWidth: 120 },
					form: {
						show: false,
						component: { placeholder: '请输入借用人' },
						rules: [{ required: false, message: '' }],
					},
				},
				"borrower_info.user_code": {
					title: '学号/工号',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					},
				},
				"borrower_info.name": {
					title: '借用人',
					search: { show: false },
					type: 'input',
					column: { show:true, minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					},
				},
				emergency_contact: {
					title: '借用人',
					search: { show: false },
					type: 'input',
					column: { show:false, minWidth: 120 },
					form: {
						show: false,
						component: { placeholder: '请输入借用人' },
						rules: [{ required: false, message: '请输入借用人' }],
					},
				},
				"borrower_info.mobile": {
					title: '联系方式',
					search: { show: false },
					type: 'input',
					column: {
						minWidth: 120
					},
					form: {
						show: true,
						component: { placeholder: '请输入联系方式' },
						rules: [{ required: false, message: '请输入联系方式' }],
					}

				},
				team_type_label: {
					title: '个人/团队',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '请输入个人/团队' },
						rules: [{ required: false, message: '请输入个人/团队' }],
					},
				},
				team_members: { title: '团队成员', column: { show:false,minWidth: 120 } },
				team_members_count: { title: '团队人数', column: { show:false,minWidth: 80 }},
				create_datetime: {
					title: '创建时间',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '请输入创建时间' },
						rules: [{ required: false, message: '请输入创建时间' }],
					},
				},
				status_label: { title: '当前状态', column: { minWidth: 80 } },
				actual_start_time: {
					title: '借出时间',
					column: { minWidth: 140, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '') },
				},
				expected_end_time: {
					title: '预计归还',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '请输入预计归还时间' },
						rules: [{ required: false, message: '请输入预计归还时间' }],
					},
				},
				actual_end_time: {
					title: '完结时间',
					column: { minWidth: 140, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '') },
				},
				/* return_location: { title: '存放仓库', column: { minWidth: 120 } }, */
				purpose: { title: '借用目的', column: { minWidth: 150 ,show:false} },
				/* expected_start_time: {
					title: '预计开始',
					
					column: { minWidth: 140,show:true, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '') },
				}, */
			
				
				approve_time: {
					title: '审批时间',
					column: { show:false,minWidth: 140, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '') },
					from:{show:false}
				},
				approve_remark: { title: '审批备注', column: {show:false, minWidth: 120 } ,from:{show:false}},
				// applicant_remark: { title: '审批备注', column: {show:true, minWidth: 120 } ,from:{show:false}},
				total_items: { title: '设备数量', column: { show:false,minWidth: 80 } },
				
				
				applicant_remark: { title: '申请备注', column: { show:false, minWidth: 120 } ,from:{show:false}},
				
				update_datetime: {
					title: '更新时间',
					column: { show:false,minWidth: 160, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '') },
					
				},
				

				approver_name: {
					title: '当前审批人',	
					search: { show: true },
					type: 'input',
					column: { 
						minWidth: 120,
						formatter: ({ row }: any) => {
							// 优先从 admin_approver_info 获取当前待审批人
							if (row.admin_approver_info && row.admin_approver_info.current_step) {
								return row.admin_approver_info.current_step.approver_name || '未知审批人';
							}
							
							// 回退到原有的 approver_name 字段
							return row.approver_name || '无审批人';
						}
					},
					form: {
						show: false,
						component: { placeholder: '请输入审批人' },
						rules: [{ required: false, message: '' }],
					},
				},
				// 审批流程状态显示
				/* admin_approver_info: {
					title: '审批状态',
					search: { show: false },
					type: 'input',
					column: { 
						minWidth: 200,
						formatter: ({ value }: any) => getApprovalStatusText(value)
					},
					form: { show: false }
				}, */
				// 审批进度详情
				/* approval_progress: {
					title: '审批进度',
					search: { show: false },
					type: 'input',
					column: { 
						minWidth: 300,
						formatter: ({ row }: any) => getApprovalProgressText(row.admin_approver_info)
					},
					form: { show: false }
				}, */
				"items[0].device_category_name": {
					title: '设备分类',
					search: { show: false },
					type: 'input',
					column: { show:false,minWidth: 120 },
					form: {
						show: true,
						component: { placeholder: '' },
						// rules: [{ required: false, message: '请输入当前审批人' }],
					},
				},
				// "items[0].quantity": {
				// 	title: '借用数量',
				// 	search: { show: false },
				// 	type: 'input',
				// 	column: {show:false, minWidth: 120 },
				// 	form: {
				// 		show: true,
				// 		component: { placeholder: '' },
				// 		// rules: [{ required: false, message: '请输入当前审批人' }],
				// 	},
				// },
				// items: {
				// 	title: '设备列表',
				// 	type: 'input', // 必须是 component 类型
				// 	form: {
				// 	  show: true, // 确保表单中显示
				// 	  slot: 'ItemsList',
				// 	}
				//   },
				
				
				  
			
		
		
		
		},
		},
	};
};
