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}
				},
				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: false, 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: 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: false, message: '' }],
					}
				},
				maintenance_content:{
					title: '维护内容',
					type: 'input',
					column: {
						show:false,
						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,
						formatter: ({ value }) => {
							if (!value) return '';
							// 支持后端返回的字符串或 Date
							if (typeof value === 'string') return value;
							return dayjs(value).isValid() ? dayjs(value).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: false, message: '' }],
					},
					valueBuilder({ form, value }) {
						if (!value) { form.planned_start_time = null; return; }
						// 统一使用字符串以匹配 valueFormat: 'HH:mm:ss'
						if (value instanceof Date) {
							form.planned_start_time = dayjs(value).format('HH:mm:ss');
							return;
						}
						if (typeof value === 'string') {
							// 校验字符串是否为有效时间格式
							const parsed = dayjs(value, 'HH:mm:ss', true);
							form.planned_start_time = parsed.isValid() ? value : null;
							return;
						}
						form.planned_start_time = null;
					},
					valueResolve({ form, value }) {
						if (!value) { form.planned_start_time = null; return; }
						// 提交时同样保持为字符串
						if (value instanceof Date) {
							form.planned_start_time = dayjs(value).format('HH:mm:ss');
							return;
						}
						if (typeof value === 'string') {
							form.planned_start_time = value;
							return;
						}
						form.planned_start_time = null;
					},
				},
				
				planned_end_time:{
					title: '维护结束时间',
					type: 'time',
					column: {
						show:true,
						minWidth: 120,
						formatter: ({ value }) => {
							if (!value) return '';
							if (typeof value === 'string') return value;
							return dayjs(value).isValid() ? dayjs(value).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: false, message: '' }],
					},
					valueBuilder({ form, value }) {
						if (!value) { form.planned_end_time = null; return; }
						// 统一使用字符串以匹配 valueFormat: 'HH:mm:ss'
						if (value instanceof Date) {
							form.planned_end_time = dayjs(value).format('HH:mm:ss');
							return;
						}
						if (typeof value === 'string') {
							const parsed = dayjs(value, 'HH:mm:ss', true);
							form.planned_end_time = parsed.isValid() ? value : null;
							return;
						}
						form.planned_end_time = null;
					},
					valueResolve({ form, value }) {
						if (!value) { form.planned_end_time = null; return; }
						// 提交时保持为字符串
						if (value instanceof Date) {
							form.planned_end_time = dayjs(value).format('HH:mm:ss');
							return;
						}
						if (typeof value === 'string') {
							form.planned_end_time = value;
							return;
						}
						form.planned_end_time = 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: false, message: '' }],
					}
				},
			},
		},
	};
};
