import { AddReq,useCompute, CreateCrudOptionsProps, CreateCrudOptionsRet, UserPageQuery,EditReq ,DelReq,dict} from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from '/@/utils/authFunction';
import {request} from '/@/utils/service';
import {getBaseURL} from '/@/utils/baseUrl';
import {Ref, shallowRef} from 'vue';
import { ElMessage } from 'element-plus';
import Cookies from 'js-cookie';
import deviceSelector from '/@/components/deviceSelector/index.vue';

const { compute } = useCompute();

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const pageRequest = async (query: UserPageQuery) => {
		return await api.GetList(query);
	};
	const editRequest = async ({ form, row }: EditReq) => {
		form.id = row.id;
		form.device_id=Number(form.device);
		form.title=form.article_title;
		form.content=form.article_content;
		// PDF文件字段保持不变，直接传递
		if (form.device_operation_manual==null) {
			api.DeleteAttachment(form.id);
		}
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		// console.log("delform:::",row)
		return await api.DelObj(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		form.device_id=Number(form.device);
		form.title=form.article_title;
		form.content=form.article_content;
		// PDF文件字段保持不变，直接传递
		// console.log("sdfsdfsdfform::::",form);
		
		return await api.AddObj(form);
	};

	return {
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,

			},
			actionbar: {
				buttons: {
					add: {
						show: true//auth('area:Create'),
					},
				},
			},
			form:{
				wrapper: {
					buttons: {
						ok:{
							text:'提交',
							show:compute((row) => {
								return row.mode !=='view'
							})
						}
					}
				}
			},
			toolbar:{
				show:false,
			},
			rowHandle:{
				buttons:{
					remove:{
						show:true,
					},
					edit:{
						show:true,
					}

				}

			},
			pagination: {
				show: true,
			},		
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						show:false,
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
					search:{
					title: '关键字搜索',
					search: { show: true,type: 'input', },
					type: 'input',
					form: {
						component: { placeholder: '请输入' },
						show:false},
					column: {show:false}
				},
				device_code:{
					title: '设备编号',
					type: 'input',
					column: {
						show:true,
						minWidth: 120,
					},
					form: {
						show:true,
						component: { 
							placeholder: '请填写设备编号',
							onBlur: async (event: any) => {
								// 当输入框失去焦点时，根据编号搜索设备信息
								const deviceCode = event.target.value?.trim();
								console.log("onBlur deviceCode:", deviceCode);
								
								if (!deviceCode) return;
								
								try {
									// 调用API搜索设备信息
									const response = await request({
										url: `/api/system/device/?code=${encodeURIComponent(deviceCode)}`,
										method: 'get'
									});
									
									console.log("设备搜索响应:", response);
									
									if (response.code === 2000 && response.data && response.data.length > 0) {
										const deviceData = response.data[0]; // 取第一个匹配的设备
										console.log("找到设备:", deviceData);
										
										// 使用 crudExpose 来设置表单数据
										const formData = crudExpose.getFormData();
										formData.device = deviceData.id; // 设置设备ID
										formData.device_code = deviceData.code; // 设置设备编号
										formData.device_name = deviceData.name; // 设置设备名称
										crudExpose.setFormData(formData);
									} else {
										console.log("未找到匹配的设备");
										// 可以在这里显示提示信息
									}
								} catch (error) {
									console.error("搜索设备信息失败:", error);
								}
							}
							/* disabled: true  */ // 新增时也禁用，因为会自动回填
						},
						rules: [{ required: true, message: '请填写设备编号' }],
					},
					editForm:{
						component: { disabled: true },
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				device:{
					title: '设备名称',
					search: {
						show: false,
					},
					treeNode: true,
					type: 'table-selector',
					column: {
						show:false,
						minWidth: 120,
					},
					form: {
						show:true,
						component: {
							name: shallowRef(deviceSelector),
							vModel: 'modelValue',
							displayLabel: compute(({ row }) => {
								if (row && row.device_name) {
									return row.device_name;
								}
								return null;
							}),
							tableConfig: {
								url: '/api/system/device/',
								label: 'name',
								value: 'id',
								columns: [
									{
										prop: 'name',
										label: '设备名称',
										width: 150,
									},
									{
										prop: 'code',
										label: '设备编号',
										width: 120,
									},
								],
							},
							onChange: async (selectedDeviceId: any) => {
								// 当选择设备时，自动回填设备编号和设备名称
								console.log("onChange selectedDeviceId:", selectedDeviceId);
								
								if (!selectedDeviceId) return;
								
								try {
									// 通过API获取设备详情
									const response = await request({
										url: `/api/system/device/${selectedDeviceId}/`,
										method: 'get'
									});
									console.log("response::::",response)
									if (response.code==2000) {
										const deviceData = response.data;
										console.log("设备数据:", deviceData);
										
										// 使用 crudExpose 来设置表单数据
										const formData = crudExpose.getFormData();
										formData.device_code = deviceData.code;
										formData.device_name = deviceData.name;
										crudExpose.setFormData(formData);
									}
								} catch (error) {
									console.error("获取设备信息失败:", error);
								}
							}
						},
						rules: [{ required: true, message: '请选择设备名称' }],
					},
				},
				article:{
					title: '文章id',
					search: {
						show: false,
					},
					type: 'input',
					column: {
						show:false,
						minWidth: 120,
					},
					form: {
						show:false,
					}

				},
				/* device_code: {
					title: '设备编号',
					search: {
						show: false,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
					},
				}, */
				
				
				device_name:{
					title: '设备名称',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填设备名称' },
						rules: [{ required: false, message: '请填写设备名称' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				article_title: {//article_title
					title: '手册标题',//'设备名称',
					search: {
						show: false,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
						rules: [
							// 表单校验规则
							{ required: true, message: '手册标题必填项' },
						],
						component: {
							placeholder: '请输入手册标题',
						},
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				article_content:{
					title: '内容',
					// type: 'textarea',
					type: 'editor-wang5',
					column: {
						show:false,
						minWidth: 120,
						formatter: ({ row, value }: { row: any; value: any }) => {
							// 去除HTML标签，只显示纯文本内容
							if (!value) return '';
							const text = value.replace(/<[^>]*>/g, '').trim();
							console.log('原始内容:', value);
							console.log('处理后内容:', text);
							return text;
						},
					},
					form: {
						show:true,
						col: {
							span: 24
						},
						// component: { showWordLimit: true, maxlength: 200 ,placeholder: '请填写内容' },
						rules: [{ 
							required: true,
								message: '内容为必填项',
							}],
						component: {
							disabled: false,
							id: '1', // 当同一个页面有多个editor时，需要配置不同的id
							editorConfig: {
								// 是否只读
								readOnly: compute((context) => {
									const { mode } = context;
									if (mode === 'add') {
										return false;
									}
									return true;
								}),
							},
							uploader: {
								type: 'form',
								buildUrl(res: any) {
									console.log("res::::",res)
									return res.url;
								},
							},
							},

					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				device_operation_manual: {
					title: 'PDF手册',
					type: 'file-uploader',
					column: {
						show: false,
						minWidth: 120,
						formatter: ({ row, value }: { row: any; value: any }) => {
							if (!value) return '无';
							return value.split('/').pop() || 'PDF文件';
						},
					},
					form: {
						show: true,
						component: {
							limit: 1,
							// 保持可点击，通过 beforeUpload + uploadRequest 做前置校验与提示
							helpMessage: '请先选择设备名称或填写设备编号后再上传PDF',
							uploader: {
								type: 'form',
								accept: 'application/pdf,.pdf',
								beforeUpload: (file: File) => {
									try {
										const formData = crudExpose.getFormData();
										if (!formData || !formData.device) {
											ElMessage.warning('请先选择设备或填写设备编号');
											return false;
										}
									} catch (e) {
										ElMessage.error('无法获取表单数据，请重试');
										return false;
									}
									const isPdf = file.type === 'application/pdf' || /\.pdf$/i.test(file.name);
									if (!isPdf) {
										ElMessage.error('仅支持上传 PDF 文件');
										return false;
									}
									return true;
								},
								uploadRequest: async (params: any) => {
									const { action, file, onProgress } = params;
									
									// 动态获取设备ID
									let deviceId = '';
									try {
										const formData = crudExpose.getFormData();
										deviceId = formData.device;
									} catch (error) {
										console.warn('获取表单数据失败:', error);
									}
									
									if (!deviceId) {
										ElMessage.warning('请先选择设备或填写设备编号');
										throw new Error('请先选择设备');
									}
									
									const uploadUrl = `/api/system/device/${deviceId}/upload_manual/`;
									const token = Cookies.get('token'); 
									const data = new FormData();
									data.append("file", file);
									return await request({
										url: uploadUrl,
										method: "post",
										timeout: 60000,
										headers: {
										"Content-Type": "multipart/form-data",
										"Authorization": token ? `JWT ${token}` : ''
										},
										data,
										onUploadProgress: (p: any) => {
										onProgress({ percent: Math.round((p.loaded / p.total) * 100) });
										}
									});
								},
									successHandle(ret: any) {
									// eslint-disable-next-line no-console
									// console.log("ret.data.image_url:::",ret.data.image_url);

										return {
										url: getBaseURL(ret.data.manual_url), 
										key: ret.data.id,
										...ret.data
									};
									},
									onError: (error: any) => {
										ElMessage.error('PDF 上传失败，请重试');
										// eslint-disable-next-line no-console
										console.error('PDF上传失败:', error);
									},
									onExceed: () => {
										ElMessage.warning('只允许上传 1 个文件');
									},
								/* buildUrl(res: any) {
									console.log("PDF上传响应:", res);
									// 根据返回的数据结构，提取manual_url
									if (res && res.code === 2000 && res.data && res.data.manual_url) {
										return res.data.manual_url;
									}
									return res.url || '';
								},
								onSuccess: (response: any, file: any) => {
									console.log("PDF上传成功:", response);
									// 根据返回的数据结构，提取manual_url并设置到表单
									if (response && response.code === 2000 && response.data && response.data.manual_url) {
										// 将manual_url设置到pdf_file字段
										const formData = crudExpose.getFormData();
										formData.pdf_file = response.data.manual_url;
										crudExpose.setFormData(formData);
										console.log("PDF文件路径已设置:", response.data.manual_url);
										return response.data.manual_url;
									}
									return response.url || '';
								},
								onError: (error: any) => {
									console.error("PDF上传失败:", error);
								} */
							}
						},
						rules: [{ 
							required: false, 
							message: 'PDF手册为可选项' 
						}],
						helper: {
							text: "请先选择设备名称或填写设备编号后再上传PDF"
						  },
					},
					
					viewForm: {
						component: { 
							placeholder: '',
							disabled: true 
						},
						rules: [{ required: false, message: '' }],
					}
				},
				publisher_name:{
					title: '发布人',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写发布人' },
						rules: [{ required: false, message: '请填写发布人' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				create_datetime:{
					title: '发布时间',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写发布时间' },
						rules: [{ required: false, message: '请填写发布时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				is_default:{
					title: '状态',
					type: 'input',
					column: {
						show:false,
						minWidth: 120,
					},
					form: {
						value:true,
						show:false,
						component: { placeholder: '请填写状态' },
						rules: [{ required: false, message: '请填写状态' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				// device_id:{
				// 	title: '设备id',
				// 	type: 'input',
				// 	column: {
				// 		show:false,
				// 		minWidth: 120,
				// 	},
				// 	form: {
				// 		show:true,
				// 		component: { placeholder: '请填写状态' },
				// 		rules: [{ required: false, message: '请填写状态' }],
				// 	},
				// },
				// title:{
				// 	title: '设备标题',
				// 	type: 'input',
				// 	column: {
				// 		show:false,
				// 		minWidth: 120,
				// 	},
				// 	form: {
				// 		show:true,
				// 		component: { placeholder: '请填写设备标题' },
				// 		rules: [{ required: false, message: '请填写设备标题' }],
				// 	},
				// },
				// content:{
				// 	title: '设备内容',
				// 	type: 'input',
				// 	column: {
				// 		show:false,
				// 		minWidth: 120,
				// 	},
				// 	form: {
				// 		show:true,
				// 		component: { placeholder: '请填写设备内容' },
				// 		rules: [{ required: false, message: '请填写设备内容' }],
				// 	},
				// },



			},
		},
	};
};
