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 { ElMessage, ElMessageBox } from 'element-plus'
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: 290,
				buttons:{
					remove:{
						show:true,
					},
					edit:{
						show:true,
					},
					cancelDamage: {
						text: '撤销',
						type: 'danger',
						order: 98,
						show: compute(({ row }) => {
							return row.status !== 5;
						}),
						click({ row }) {
							ElMessageBox.confirm('确认撤销该报损记录？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
							}).then(async () => {
							try {
								const res = await api.UpdateDamageCancel(row);
								console.log("res::::",res)
								if (res.code === 2000) {
								ElMessage.success('撤销成功')
								crudExpose.doRefresh()
								} else {
								ElMessage.error(res.msg || '撤销失败')
								}
							} catch (err) {
								ElMessage.error('请求失败')
							}
							}).catch(() => {
							// 用户取消操作
							})
						}
					}
						

				}

			},
			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: true,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						// rules: [
						// 	// 表单校验规则
						// 	// { required: true, message: '名称必填项' },
						// ],
						component: {
							placeholder: '请输入编号',
						},
					},
					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/',
						value: 'id',
						label: 'name',
					}),
					form: {
						component: { 
							placeholder: '请填写设备名称',
							onChange: async (context: any) => {
								// 当选择设备时，自动回填设备编号和设备名称
								console.log("onChange context:", context);
								
								// 获取选中的设备ID
								const selectedDeviceId = context;
								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: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写报废数量'},
						rules: [{ required: true, message: '请填写报废数量' }],
					},
					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:0,
						show:false,
						component: { placeholder: '请填写报损类型'},
						rules: [{ required: false, message: '请填写报损类型' }],
					},
					editForm:{
						component: { disabled: true },
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				damage_reason:{
					title: '报废原因',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						component: { placeholder: '请填写报废原因' },
						rules: [{ required: false, message: '请填写报废原因' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				estimated_loss:{
					title: '维修费用',
					type: 'input',
					column: {
						minWidth: 120,
						show:false,
						// show:compute(({ form }) => {
						// 	// 只有当选择了胜任力标签时才显示配置
						// 	return form && form.damage_type === 1;
						// })
					},
					form: {
						show:false,
						component: { placeholder: '请填写维修费用' },
						rules: [{ required: false, message: '请填写维修费用' }],
						// show:compute(({ form }) => {
						// 	// 只有当选择了胜任力标签时才显示配置
						// 	return form && form.damage_type === 1;
						// })
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
						show:compute(({ form }) => {
							// 只有当选择了胜任力标签时才显示配置
							return form && form.damage_type === 1;
						})
					}
				},
				reporter_person:{
					title: '负责人',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写负责人' },
						rules: [{ required: false, 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: '' }],
					}
				},
				create_datetime:{
					title: '创建时间',
					type: 'datetime',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
					}
				}








			},
		},
	};
};
