import * as api from './api';
import { UserPageQuery, AddReq, DelReq, EditReq, CreateCrudOptionsProps, CreateCrudOptionsRet, dict, useCompute } from '@fast-crud/fast-crud';
import dayjs from 'dayjs';

const { compute } = useCompute();

/** 列表请求参数处理过程是否打印到控制台（联调后改为 false 即可关） */
const BORROW_LIST_PAGE_REQUEST_LOG = true;

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const pageRequest = async (query: UserPageQuery) => {
		const q: any = { ...(query as any) };
		const form = q.form && typeof q.form === 'object' ? { ...q.form } : {};
		if (BORROW_LIST_PAGE_REQUEST_LOG) {
			// eslint-disable-next-line no-console
			console.log('[borrow/list] pageRequest 入参 根上字段与 form', {
				根: { status: q.status, status__in: q.status__in },
				form: { ...form },
			});
		}
		/**
		 * 多状态：列 status__in。fast-crud 可能放在 form 里，也可能展到 query 根上（故 q.form 为空时仍可能有 q.status__in）。
		 * 列表接口使用 params.status（与后端一致），不单独传 status__in，避免后端忽略。
		 * 搜索栏「当前状态」单选优先于地址栏/看板注入的 status__in，避免用户改选后请求仍带多状态。
		 */
		const singleStatus =
			form.status != null && String(form.status).trim() !== '' ? String(form.status).trim() : '';
		if (singleStatus) {
			q.status = singleStatus;
			delete q.status__in;
			delete (form as any).status__in;
			delete (form as any).status;
		} else {
			const fromInForm =
				form.status__in != null && String(form.status__in).trim() !== '' ? String(form.status__in).trim() : '';
			const fromInQuery =
				q.status__in != null && String(q.status__in).trim() !== '' ? String(q.status__in).trim() : '';
			const statusInVal = fromInForm || fromInQuery;
			if (statusInVal) {
				q.status = statusInVal;
				delete q.status__in;
				if (fromInForm) {
					delete (form as any).status__in;
				}
			}
		}
		q.form = form;
		if (BORROW_LIST_PAGE_REQUEST_LOG) {
			const { form: f, ...rest } = q;
			// eslint-disable-next-line no-console
			console.log('[borrow/list] pageRequest → 调用 GetList 参数', { ...rest, form: f });
		}
		return await api.GetList(q);
	};

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

	return {
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			pagination: {
				show: true,
				pageSize: 10,
			},
			actionbar: {
				buttons: {
					add: {
						show: false,
						text: '创建借用单',
						click: () => {
							window.dispatchEvent(new CustomEvent('borrow-add'))
						}
					}
				}
			},
			rowHandle: {
				fixed: 'right',
				width: 370,
				buttons: {
					view: {
						show: true,
						order: 1,
						click: ({ row }) => {
							// eslint-disable-next-line no-console
							// console.log("row:::",row);
							window.dispatchEvent(new CustomEvent('borrow-view', { detail: row }));
						},
					},
					edit: {
						show: compute(({ row }) => {
							return row.status == 1 && row.borrow_type !== 0;
						}),
						order: 4,
						disabled: compute(({ row }) => {
							return row.status !== 1;
						}),
						click: ({ row }) => {
							window.dispatchEvent(new CustomEvent('borrow-edit', { detail: row }));
						}
					},
					remove: {
						order: 10,
						show: compute(({ row }) => {
							return row.status !== 5 || row.status === 6;
						}),
					},
					/* 查看结算单 */
					settlement: {
						order: 6,
						show: compute(({ row }) => {
							return row.status === 5 || row.status == 7 || row.status == 8;
						}),
						text: '结算单',
						click: ({ row }) => {
							window.dispatchEvent(new CustomEvent('borrow-settlement', { detail: row }));
						}
					},
					collectEquipment: {
						order: 2,
						show: compute(({ row }) => {
							return row.status === 2;
						}),
						text: '领取',
						click: ({ row }) => {
							window.dispatchEvent(new CustomEvent('borrow-collect', { detail: row }));
						}
					},
					returnEquipment: {
						order: 3,
						show: compute(({ row }) => {
							return row.status === 5 || row.status === 6 || row.status === 8;
						}),
						text: '归还',
						click: ({ row }) => {
							window.dispatchEvent(new CustomEvent('borrow-return', { detail: row }));
						}
					},
					renewdevice: {
						order: 3,
						show: compute(({ row }) => {
							return (row.status === 5 || row.status === 6 || row.status === 8) && row.borrow_type == 2;
						}),
						text: '续借',
						click: ({ row }) => {
							window.dispatchEvent(new CustomEvent('renew-device', { detail: row }));
						}
					}

				},
			},
			search: {
				show: true,
			},
			toolbar: {
				show: false,
			},
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						align: 'center',
						width: '70px',
						columnSetDisabled: true,
						formatter: (context: any) => {
							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: {
					search: { show: false },
					title: '借用单编号',
					column: { minWidth: 140 },
					form: {
						component: { placeholder: '请输入借用单编号' },
						search: {
							component: { placeholder: '请输入借用单编号' },
							rules: [{ required: true, message: '' }],
						}
					}
				},
				borrower_type_label: { title: '借用人角色', column: { minWidth: 120, sortable: true } },
				borrow_type_label: { search: { show: false }, title: '借用性质', column: { minWidth: 100 } },
				user_code: {
					title: '学号/工号',
					search: {
						show: true,
					},
					column: {
						show: false,
						minWidth: 100,
					},
					form: {
						show: false,
						component: { placeholder: '请输入学号/工号' },
					}
				},
				/* "borrower_info.user_code":{
					title:"学号/工号",
					search:{
					show:true,		
				},column: { minWidth: 100 },form:{
					component: { placeholder: '请输入学号/工号' },
				}}, */
				borrower_name: {
					title: '借用人',
					search: {
						show: true,
					},
					column: {
						show: false,
						minWidth: 100,
					},
					form: {
						show: false,
						component: { placeholder: '请输入借用人' },
					}
				},
				borrow_type: {
					title: '借用性质',
					type: 'dict-select',
					search: {
						show: false,


					},
					dict: dict({
						data: [
							{ label: '常规借用', value: 0 },
							{ label: '课堂借用', value: 1 },
							{ label: '特殊借用', value: 2 },
						],
					}),
					column: {
						show: false,
						minWidth: 100,
					},
					form: {
						show: false,
						component: { placeholder: '请选择借用性质' },
					}
				},
				borrower_phone: {
					title: "联系方式",
					search: {
						show: true,
					}, column: { show: false, minWidth: 100 }, form: {
						show: false,
						component: { placeholder: '请输入联系方式' },
					}
				},
				"borrower_info.name": {
					title: '借用人',
					search: {
						show: false,
					},
					column: {
						show: true,
						minWidth: 100,
					}, form: {
						component: { placeholder: '请输入借用人' },
					}
				},
				external_borrower_name: {
					title: '借用人',

					column: { show: false, minWidth: 100 },
					form: {
						component: {
							placeholder: '请输入借用人',
							search: {
								component: { placeholder: '请输入借用人' },

							}
						},
					}
				},

				"borrower_info.mobile": {
					title: '联系方式',
					search: { show: false }, column: { minWidth: 120 }, form: {
						component: { placeholder: '请输入联系方式' },
					}
				},
				team_type_label: { title: '个人/团队', column: { minWidth: 90 } },
				team_members: { title: '团队成员', column: { show: false, minWidth: 120 } },
				team_members_count: { title: '团队人数', column: { show: false, minWidth: 80 } },
				create_datetime: {
					title: '创建时间',
					column: { minWidth: 160, sortable: true, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '') },
				},
				status_label: {
					title: '当前状态',
					column: {
						minWidth: 110,
						sortable: true,
						cellRender: ({ value }: any) => {
							// 根据状态值返回不同颜色的标签
							const getStatusConfig = (status: string) => {
								switch (status) {
									case '待审批':
										return { color: '#909399', bgColor: '#f4f4f5' }
									case '已批准':
										return { color: '#67c23a', bgColor: '#f0f9ff' }
									case '已拒绝':
										return { color: '#f56c6c', bgColor: '#fef0f0' }
									case '已取消':
										return { color: '#909399', bgColor: '#f4f4f5' }
									case '已借出':
										return { color: '#409eff', bgColor: '#ecf5ff' }
									case '已归还':
										return { color: '#67c23a', bgColor: '#f0f9ff' }
									case '部分归还':
										return { color: '#e6a23c', bgColor: '#fdf6ec' }
									case '已逾期':
										return { color: '#e6a23c', bgColor: '#fdf6ec' }
									case '续借待审批':
										return { color: '#909399', bgColor: '#f4f4f5' }
									default:
										return { color: '#606266', bgColor: '#f5f7fa' }
								}
							}

							const config = getStatusConfig(value)

							return (
								<span
									style={{
										color: config.color,
										backgroundColor: config.bgColor,
										padding: '4px',
										borderRadius: '4px',
										fontSize: '12px',

										display: 'inline-block',
										minWidth: '60px',
										textAlign: 'center'
									}}
								>
									{value || '-'}
								</span>
							)
						}
					}
				},
				actual_start_time: {
					title: '借出时间',
					column: { minWidth: 140, sortable: true, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '') },
				},
				expected_end_time: {
					title: '预计归还',
					column: { minWidth: 140, sortable: true, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD') : '') },
				},
				actual_end_time: {
					title: '完结时间',
					column: { minWidth: 140, sortable: true, 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: false, 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') : '') },
				},
				approve_remark: { title: '审批备注', column: { show: false, minWidth: 120 } },
				total_items: { title: '设备数量', column: { show: false, minWidth: 80 } },


				applicant_remark: { title: '申请备注', column: { show: false, minWidth: 120 } },

				update_datetime: {
					title: '更新时间',
					column: { show: false, minWidth: 160, formatter: ({ value }: any) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '') },
				},
				"items.device_code": {
					title: '设备编号',
					search: {
						show: true,
					},
					column: {
						show: false,
						minWidth: 100,
					}, form: {
						show: false,
						component: { placeholder: '请输入设备编号' },
					}
				},
				abnormal_status: {
					title: '异常记录',
					type: 'dict-select',
					search: {
						show: true,
					},
					dict: dict({
						data: [
							{ label: '无异常', value: '无异常', color: '#67c23a', bgColor: '#f0f9ff' },
							{ label: '有损坏', value: '有损坏', color: '#f56c6c', bgColor: '#fef0f0' },
							{ label: '有逾期', value: '有逾期', color: '#e6a23c', bgColor: '#fdf6ec' },
							{ label: '有损坏和逾期', value: '有损坏和逾期', color: '#f56c6c', bgColor: '#fef0f0' },
						],
					}),
					column: {
						show: true,
						minWidth: 110,
						cellRender: ({ value }: any) => {
							// 根据异常状态值返回不同颜色的标签
							const getAbnormalStatusConfig = (status: string) => {
								switch (status) {
									case '无异常':
										return { color: '#67c23a', bgColor: '#f0f9ff' }
									case '有损坏':
										return { color: '#f56c6c', bgColor: '#fef0f0' }
									case '有逾期':
										return { color: '#e6a23c', bgColor: '#fdf6ec' }
									case '有损坏和逾期':
										return { color: '#f56c6c', bgColor: '#fef0f0' }
									default:
										return { color: '#606266', bgColor: '#f5f7fa' }
								}
							}

							const config = getAbnormalStatusConfig(value)

							return (
								<span
									style={{
										color: config.color,
										backgroundColor: config.bgColor,
										padding: '4px',
										borderRadius: '4px',
										fontSize: '12px',
										display: 'inline-block',
										minWidth: '60px',
										textAlign: 'center'
									}}
								>
									{value || '-'}
								</span>
							)
						}
					}, form: {
						show: false,
						component: { placeholder: '请选择异常记录' },
					}
				},
				status: {
					title: '当前状态',
					type: 'dict-select',
					search: {
						show: true,
						/** 用户操作搜索区「当前状态」时清掉残留 status__in，与地址栏/程序化多状态解耦；清空时同理 */
						valueChange: (arg0: any, _arg1?: any, formArg?: any) => {
							const f =
								arg0 && typeof arg0 === 'object' && 'form' in arg0
									? (arg0 as { form: any }).form
									: formArg;
							if (f == null) return;
							delete f.status__in;
						},
					},
					dict: dict({
						data: [
							{ label: '待审批', value: 1 },
							{ label: '已批准', value: 2 },
							{ label: '已拒绝', value: 3 },
							{ label: '已取消', value: 4 },
							{ label: '已借出', value: 5 },
							// { label: '有损坏和逾期', value: 6},
							{ label: '部分归还', value: 6 },
							{ label: '已归还', value: 7 },
							{ label: '已逾期', value: 8 },
							{ label: '续借待审批', value: 9 },
						],
					}),
					column: {
						show: false,
						minWidth: 100,
					}, form: {
						show: false,
						component: { placeholder: '请选择当前状态' },
					}
				},
				/* 程序化传入：看板「已借出」等多状态跳转，不在搜索栏展示 */
				status__in: {
					title: '状态多选',
					type: 'text',
					search: { show: false },
					column: { show: false },
					form: { show: false },
				},




			},
		},
	};
};
