import { AddReq, EditReq, DelReq, CreateCrudOptionsProps, dict,CreateCrudOptionsRet, UserPageQuery,compute } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from '/@/utils/authFunction';
import dayjs from 'dayjs';
import { request } from '/@/utils/service';
import { shallowRef } from 'vue';
import deviceSelector from '/@/components/deviceSelector/index.vue';
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;
		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,

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

				}

			},
			pagination: {
				show: true,
			},		
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						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}
				},
				plan_code: {
					title: '计划编码',
					search: {
						show: false,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						rules: [
							// 表单校验规则
							{ required: true, message: '名称必填项' },
						],
						component: {
							placeholder: '请输入名称',
						},
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				plan_name: {
					title: '计划名称',
					search: {
						show: true,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						rules: [
							// 表单校验规则
							{ required: true, message: '名称必填项' },
						],
						component: {
							placeholder: '请输入计划名称',
						},
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				description:{
					title: '计划描述',
					type: 'input',
					column: {
						show:true,
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写计划描述' },
						rules: [{ required: false, message: '请填写计划描述' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				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: '设备名称',
					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: '请选择设备名称' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				device_name:{
					title: '设备名称',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写标签描述' },
						rules: [{ required: false, message: '请填写标签描述' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				/* device_code:{
					title: '设备编码',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写设备编码' },
						rules: [{ required: false, message: '请填写设备编码' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				}, */
				cycle_type:{
					title: '维护类型',
					type: 'dict-select',
					column: {
						show:false,
						minWidth: 120,
					},
					dict: dict({
						data: [
							{ label: '每月', value: 2 },
							{ label: '每季度', value: 3 },
							{ label: '每年', value: 5 },

						],
					}),
					form: {
						show:true,
						component: { placeholder: '请选择维护类型' },
						rules: [{ required: true, message: '请选择维护类型' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				cycle_type_display:{
					title: '维护类型',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写排序' },
						rules: [{ required: false, message: '请填写排序' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				maintenance_content:{
					title: '维护内容',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
						component: { placeholder: '请填写维护内容' },
						rules: [{ required: true, message: '请填写维护内容' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				maintenance_person:{
					title: '维护人',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
						component: { placeholder: '请填写维护人' },
						rules: [{ required: true, message: '请填写维护人' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				start_date:{
					title: '维护开始时间',
					type: 'date',
					column: {
						minWidth: 120,
						// formatter: ({ value }) => (value ? dayjs(value).format('YYYY-MM-DD') : ''),
					},
					form: {
						show:true,
						component: { 
							placeholder: '请填写维护开始时间',
							disabledDate: (time: Date) => {
								return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
							}
						},
						rules: [{ required: true, message: '请填写维护开始时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
					valueResolve({ form, value }) {
						form.start_date = value ? dayjs(value).format('YYYY-MM-DD') : null;
					},
					valueBuilder({ form, value }) {
						form.start_date =  value ;
					},
				},
				next_maintenance_date:{
					title: '下次维护开始时间',
					type: 'date',
					column: {
						minWidth: 120,
						formatter: ({ value }) => (value ? dayjs(value).format('YYYY-MM-DD') : ''),
					},
					form: {
						show:false,
						component: { placeholder: '请填写维护开始时间' },
						rules: [{ required: false, message: '请填写维护开始时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
					valueResolve({ form, value }) {
						form.purchase_date = value ? dayjs(value).format('YYYY-MM-DD') : null;
					},
					valueBuilder({ form, value }) {
						form.purchase_date = value;
					},
				},
				status_display:{
					title: '维护状态',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写维护状态' },
						rules: [{ required: false, message: '请填写维护状态' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
			},
		},
	};
};
