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 { ja } from 'element-plus/es/locale';
import {getBaseURL} from '/@/utils/baseUrl';
import Cookies from 'js-cookie';
import {request} from '/@/utils/service';
import {Ref, shallowRef} from 'vue';
import dayjs from 'dayjs';
import deviceSelector from '/@/components/deviceSelector/index.vue';

export const createCrudOptions = function ({ crudExpose,  dialogId,
	dialogVisible }: CreateCrudOptionsProps & { dialogId: Ref<number | null>; dialogVisible: Ref<boolean> }): 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:{
					remove:{
						show:true,
					},
					edit:{
						show:compute(({ row }) => {
							return row.status !== 3;
						}),
					},
					updateStatus: {
						text: '修改状态',
						show: false,
						order: 99,
						type: 'primary',
						click({ row }) {
							dialogId.value = row.id
							dialogVisible.value = 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}
				},
				damage_no: {
					title: '编号',
					search: {
						show: false,
					},
					treeNode: true,
					type: 'input',
					column: {
						show:false,
						minWidth: 120,
					},
					form: {
						show:false,
						// rules: [
						// 	// 表单校验规则
						// 	// { required: true, message: '名称必填项' },
						// ],
						component: {
							placeholder: '请输入编号',
							onChange: async (context: any) => {
								// 当选择设备时，自动回填设备编号和设备名称
								console.log("onChange context:", context);
							}
						},
					},
					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);
								}
							}
						 },
						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: {
						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: '请填写设备名称' }],
					},
					editForm:{
						component: { disabled: true },
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				
				
				device_name:{
					title: '设备名称',
					type: 'input',
					column: {
						show:true,
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写设备名称' },
						rules: [{ required: true, message: '请填写设备名称' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				quantity:{
					title: '维修数量',
					type: 'number',
					column: {
						minWidth: 120,
					},
					form: {
						component: { 
							placeholder: '请填写维修数量',
							min: 0,
							precision: 0
						},
						rules: [
							{ required: true, message: '请填写维修数量' },
							{ 
								type: 'number', 
								min: 0, 
								message: '维修数量不能为负数',
								trigger: 'blur'
							},
							{
								validator: (rule: any, value: any, callback: any) => {
									if (value !== null && value !== undefined && value !== '') {
										if (!Number.isInteger(Number(value)) || Number(value) < 0) {
											callback(new Error('维修数量必须为正整数'));
										} else {
											callback();
										}
									} else {
										callback();
									}
								},
								trigger: 'blur'
							}
						],
					},
					editForm:{
						component: { disabled: true },
					},
					valueResolve({ form, value }) {
						form.quantity = Number(value);
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				damage_type:{
					title: '维修类型',
					type: 'dict-select',
					dict: dict({
						data: [
							// { label: '报废', value: 0 },
							{ label: '维修', value: 1 },
						],
					}),
					column: {
						show:false,
						minWidth: 120,
					},
					form: {
						value:1,
						show:false,
						component: { placeholder: '请填写排序'},
						rules: [{ required: false, message: '请填写排序' }],
					},
					editForm:{
						component: { disabled: true },
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				
				estimated_loss:{
					title: '维修费用(元)',
					type: 'number',
					column: {
						minWidth: 120,
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.damage_type === 1;
						})
					},
					form: {
						show:false,
						component: { 
							placeholder: '请填写维修费用',
							min: 0,
							precision: 2
						},
						rules: [
							{ required: false, message: '请填写维修费用' },
							{ 
								type: 'number', 
								min: 0, 
								message: '维修费用不能为负数',
								trigger: 'blur'
							},
							{
								validator: (rule: any, value: any, callback: any) => {
									if (value !== null && value !== undefined && value !== '') {
										const numValue = Number(value);
										if (isNaN(numValue) || numValue < 0) {
											callback(new Error('维修费用必须为有效的正数'));
										} else if (numValue > 999999.99) {
											callback(new Error('维修费用不能超过999999.99元'));
										} else {
											callback();
										}
									} else {
										callback();
									}
								},
								trigger: 'blur'
							}
						],
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.damage_type === 1;
						})
					},
					editForm:{
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.status == 3;
						}),
						component: { 
							placeholder: '请填写维修费用',
							min: 0,
							precision: 2
						},
						rules: [
							{ required: false/* compute(({ form }) => {
								return form && form.status === 3;
							}) */, message: '请填写维修费用' },
							{ 
								type: 'number', 
								min: 0, 
								message: '维修费用不能为负数',
								trigger: 'blur'
							},
							{
								validator: (rule: any, value: any, callback: any) => {
									if (value !== null && value !== undefined && value !== '') {
										const numValue = Number(value);
										if (isNaN(numValue) || numValue < 0) {
											callback(new Error('维修费用必须为有效的正数'));
										} else if (numValue > 999999.99) {
											callback(new Error('维修费用不能超过999999.99元'));
										} else {
											callback();
										}
									} else {
										callback();
									}
								},
								trigger: 'blur'
							}
						],
					},
					addForm:{
						show:false,
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.damage_type === 1;
						})
					},
					valueResolve({ form, value }) {
						form.estimated_loss = Number(value);
					}
				},
				responsible_person:{
					title: '维修人',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写维修人姓名' },
						rules: [
							{ required: false, message: '请填写维修人' },
							{ min: 2, max: 20, message: '维修人姓名长度应在2-20个字符之间', trigger: 'blur' },
							{
								validator: (rule: any, value: any, callback: any) => {
									if (value && value.trim()) {
										const nameRegex = /^[\u4e00-\u9fa5a-zA-Z\s]+$/;
										if (!nameRegex.test(value.trim())) {
											callback(new Error('维修人姓名只能包含中文、英文字母和空格'));
										} else {
											callback();
										}
									} else {
										callback();
									}
								},
								trigger: 'blur'
							}
						],
					},
					editForm:{
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.status == 3;
						}),
						component: { placeholder: '请填写维修人姓名' },
						rules: [
							{ required:true /* compute(({ form }) => {
								return form && form.status === 2;
							}) */, message: '请填写维修人' },
							{ min: 2, max: 20, message: '维修人姓名长度应在2-20个字符之间', trigger: 'blur' },
							{
								validator: (rule: any, value: any, callback: any) => {
									if (value && value.trim()) {
										const nameRegex = /^[\u4e00-\u9fa5a-zA-Z\s]+$/;
										if (!nameRegex.test(value.trim())) {
											callback(new Error('维修人姓名只能包含中文、英文字母和空格'));
										} else {
											callback();
										}
									} else {
										callback();
									}
								},
								trigger: 'blur'
							}
						],
					},
					viewForm:{
						show:true,
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				responsible_phone:{
					title: '维修人电话',
					type: 'input',
					column: {
						show:true,
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写维修人电话' },
						rules: [
							{ required: false, message: '请填写维修人电话' },
							{
								validator: (rule: any, value: any, callback: any) => {
									if (value && value.trim()) {
										const phoneRegex = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$|^400-?\d{3}-?\d{4}$/;
										if (!phoneRegex.test(value.trim())) {
											callback(new Error('请输入正确的手机号码或固定电话号码'));
										} else {
											callback();
										}
									} else {
										callback();
									}
								},
								trigger: 'blur'
							}
						],
					},
					editForm:{
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.status == 3;
						}),
						component: { placeholder: '请填写维修人电话' },
						rules: [
							{ required: compute(({ form }) => {
								return form && form.status === 2;
							}), message: '请填写维修人电话' },
							{
								validator: (rule: any, value: any, callback: any) => {
									if (value && value.trim()) {
										const phoneRegex = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$|^400-?\d{3}-?\d{4}$/;
										if (!phoneRegex.test(value.trim())) {
											callback(new Error('请输入正确的手机号码或固定电话号码'));
										} else {
											callback();
										}
									} else {
										callback();
									}
								},
								trigger: 'blur'
							}
						],
					},
					viewForm:{
						show:true,
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				reporter_name:{
					title: '负责人',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
						component: { placeholder: '请填写负责人' },
						rules: [{ required: false, message: '请填写负责人' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				status:{
					search:{
						show:true
					},
					title: '维修状态',
					type: 'dict-select',
					column: {
						show:true,
						minWidth: 120,
					},
					dict: dict({
						data: [
							{ label: '待维修', value: 1 ,color: "warning"},
							{ label: '维修中', value: 2 ,color: "primary"},
							{ label: '维修完成', value: 3,color: "success" },
						],
					}),
					form: {
						show:false,
						component: { placeholder: '请选择维修状态' },
						rules: [{ required: false, message: '请选择维修状态' }],
					},
					editForm:{
						show:true,
						component: { placeholder: '请选择维修状态' },
						rules: [{ required: true, message: '请选择维修状态' }],
					},
					viewForm:{
						show:true,
						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: '' }],
					}
				}, */
				remark:{
					title: '备注',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
						component: { placeholder: '请填写备注' },
						rules: [{ required: false, message: '请填写备注' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				damage_reason:{
					title: '维修原因',
					type: 'textarea',
					column: {
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写维修原因' },
						rules: [{ required: true, message: '请填写维修原因' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				repair_result:{
					title: '维修结果',
					type: 'textarea',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写维修结果' },
						rules: [{ required: false, message: '请填写维修结果' }],
					},
					editForm:{
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.status == 3;
						}),
						component: { placeholder: '请填写维修结果' },
						rules: [{ required: true, message: '请填写维修结果' }],
					},
					viewForm:{
					show:true,
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				damage_images:{
					title: '附件',
					type: 'image-uploader',
					column: {
						minWidth: 120,
					},
					form: {
						show: auth('image:upload'),
						component: {
							uploader: {
								type: 'form',
								limit: 1,
								action: '/api/system/device/upload-image/',
								accept: ".jpg,.png",
								uploadRequest: async ({ action, file, onProgress }) => {
									const token = Cookies.get('token'); 
									const data = new FormData();
									data.append("image", file);
									return await request({
										url: action,
										method: "post",
										timeout: 60000,
										headers: {
										"Content-Type": "multipart/form-data",
										"Authorization": token ? `JWT ${token}` : ''
										},
										data,
										onUploadProgress: (p) => {
										onProgress({ percent: Math.round((p.loaded / p.total) * 100) });
										}
									});
								},
								successHandle(ret) {
									// eslint-disable-next-line no-console
									// console.log("ret.data.image_url:::",ret.data.image_url);

									return {
										url: getBaseURL(ret.data.image_url), 
										key: ret.data.id,
										...ret.data
									};
								},
							
								

								
							}
						},
						
					},
					valueBuilder({ row, key }) {
						return row[key] ? [row[key]] : [];
					},
					valueResolve({ form, key }) {
						// eslint-disable-next-line no-console
						console.log("form[key]:::",form[key]);
						form[key] = Array.isArray(form[key]) ? form[key][0] : form[key];
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				
				repair_start_time:{
					title: '维修开始时间',
					type: 'input',
					column: {
						minWidth: 160,
						formatter: ({ value }: { value: unknown }) => {
							if (value == null || value === '') return '';
							const d = dayjs(value as string);
							return d.isValid() ? d.format('YYYY-MM-DD HH:mm:ss') : String(value);
						},
					},
					form: {
						show:false,
						component: { placeholder: '维修开始时间' },
						rules: [{ required: false, message: '维修开始时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				repair_end_time:{
					title: '维修完成时间',
					type: 'input',
					column: {
						minWidth: 160,
						formatter: ({ value }: { value: unknown }) => {
							if (value == null || value === '') return '';
							const d = dayjs(value as string);
							return d.isValid() ? d.format('YYYY-MM-DD HH:mm:ss') : String(value);
						},
					},
					form: {
						show:false,
						component: { 
							placeholder: '创建时间',
							valueFormat: "YYYY-MM-DD HH:mm:ss",
						},
						rules: [{ required: false, message: '创建时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				report_time:{
					title: '创建时间',
					type: 'input',
					column: {
						minWidth: 160,
						formatter: ({ value }: { value: unknown }) => {
							if (value == null || value === '') return '';
							const d = dayjs(value as string);
							return d.isValid() ? d.format('YYYY-MM-DD HH:mm:ss') : String(value);
						},
					},
					form: {
						show:false,
						component: { placeholder: '创建时间' },
						rules: [{ required: false, message: '创建时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},









			},
		},
	};
};
