import { AddReq, 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'

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: 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}
				},
				record_no: {
					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: '' }],
					}
				},
				maintenance_title: {
					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: '' }],
					}
				},
				maintenance_plan:{
					title: '维护计划',
					type: 'dict-select',
					column: {
						show:true,
						minWidth: 120,
					},
					dict: dict({
						url: '/api/system/maintenance/plan/',
						value: 'id',
						label: 'plan_name',
					}),
					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: 'dict-select',
					column: {
						show:false,
						minWidth: 120,
					},
					dict: dict({
						url: '/api/system/device/?has_inventory=1',
						value: 'id',
						label: 'name',
					}),
					form: {
						show:true,
						component: { placeholder: '请选择设备名称',
							filterable: true,
						 },
						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: false, message: '' }],
					}
				},
				/* device_code:{
					title: '设备编码',
					type: 'input',
					column: {
						
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写设备编码' },
						rules: [{ required: false, message: '请填写设备编码' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				}, */
				maintenance_items:{
					title: '维护项目',
					type: 'input',
					column: {
						show:true,
						minWidth: 120,
					},
					form: {
						show:true,
						component: { placeholder: '请输入维护项目' },
						rules: [{ required: true, message: '请输入维护项目' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
					valueBuilder({ form, value }) {
						// form.maintenance_items = Array.isArray(value) ? value : []
						form.maintenance_items = value;
					},
					valueResolve({ form, value }) {
						// console.log('valueResolve:', typeof value, value);
						if (Array.isArray(value)) {
							form.maintenance_items = value;
						} else if (typeof value === 'string') {
						form.maintenance_items = value
							.split(',')
							.map(v => v.trim())
							.filter(Boolean);
						} else {
						form.maintenance_items = [];
						}
					},
					
				},
				maintenance_team:{
					title: '维护团队',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
						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: '' }],
					}
				},
				planned_date:{
					title: '维护日期',
					type: 'date',
					column: {
						minWidth: 120,
						// formatter: ({ value }) => (value ? dayjs(value).format('YYYY-MM-DD') : ''),
					},
					form: {
						show:true,
						component: { placeholder: '请填写维护日期' },
						rules: [{ required: true, message: '请填写维护日期' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
					valueResolve({ form, value }) {
						form.planned_date = value ? dayjs(value).format('YYYY-MM-DD') : null;
					},
					valueBuilder({ form, value }) {
						form.planned_date =  value ;
					},
				},
				planned_start_time:{
					title: '维护开始时间',
					type: 'time',
					column: {
						show:true,
						minWidth: 120,
						// format: 'HH:mm:ss',  
						
					},
					form: {
						show:true,
						component: { 
							placeholder: '请填写维护开始时间',
							format: 'HH:mm:ss',  
							valueFormat: 'HH:mm:ss', 
						},
						rules: [{ required: false, message: '请填写维护开始时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
					valueBuilder({ form, value }) {
						form.planned_start_time = value
								? dayjs(value, 'HH:mm:ss').toDate()
								: null;
					},
				},
				
				planned_end_time:{
					title: '维护结束时间',
					type: 'time',
					column: {
						show:true,
						minWidth: 120,
					},
					form: {
						show:true,
						component: { 
							placeholder: '请填写维护结束时间',
							format: 'HH:mm:ss',  
							valueFormat: 'HH:mm:ss', 
						},
						rules: [{ required: false, message: '请填写维护结束时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
					valueBuilder({ form, value }) {
						form.planned_end_time = value
								? dayjs(value, 'HH:mm:ss').toDate()
								: null;
					},
				},
				status:{
					title: '维护状态',
					type: 'dict-select',
					column: {
						show:false,
						minWidth: 120,
					},
					dict: dict({
						data: [
							{ label: '计划中', value: 0},
							{ label: '进行中', value: 1},
							{ label: '已完成', value: 2},
							{ label: '已取消', value: 3 },
							{ label: '延期', value: 4 },

						],
					}),
					form: {
						show:true,
						component: { placeholder: '请选择维护状态' },
						rules: [{ required: true, message: '请选择维护状态' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				status_display:{
					title: '维护状态',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写维护状态' },
						rules: [{ required: false, message: '请填写维护状态' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
			},
		},
	};
};
