import { AddReq, compute,useCrud ,useExpose, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, dict, EditReq, uiContext, UserPageQuery, } from '@fast-crud/fast-crud';
import dayjs from 'dayjs';
import * as api from './api';
import { uploadFile } from './api';
import { auth } from '/@/utils/authFunction';
import {request} from '/@/utils/service';
import {getBaseURL} from '/@/utils/baseUrl';
import Cookies from 'js-cookie';
import { successMessage } from '/@/utils/message';
import { dictionary } from '/@/utils/dictionary';
import { APIResponseData } from '../columns/types';
import { computed, h,defineComponent, ref, onMounted, watch  } from 'vue';
import { ElTable, ElTableColumn, ElLoading } from 'element-plus';
import { nextTick } from 'vue';
import XEUtils from 'xe-utils';




const BorrowRecords = defineComponent({
	props: { form: Object },
	setup(props) {
		try {
			const records = ref([]);
			const loading = ref(false);
			const filteredRecords = computed(() =>
				(records.value || [])/* .filter((item: any) => item?.record_type === 0) */
			);
			const loadData = async () => {
				if (!props.form?.id) return;
				loading.value = true;
				try {
					const res = await api.getBorrowRecords(props.form.id);
					records.value = res.data || [];
				} finally {
					loading.value = false;
				}
			};

			watch(() => props.form?.id, loadData, { immediate: true });

			return () => (
			<ElTable data={filteredRecords.value} v-loading={loading.value} style="width: 100%">
				<ElTableColumn prop="application_no" label="借用编号" />
				<ElTableColumn prop="borrower_name" label="借用人" />
				<ElTableColumn prop="borrower_code"  label="学号/工号"/>
				<ElTableColumn prop="record_type_label" label="状态" />
				<ElTableColumn prop="borrow_type_display" label="借用类型" />
				
			</ElTable>
			);
		} catch (e) {
			console.error("BorrowRecords setup error:", e);
			return () => <div>组件加载失败</div>;
		}
	}
  });
  
  const MaintenanceHistory = defineComponent({
	props: { form: Object },
	setup(props) {
		try {
		const records = ref([]);
		const loading = ref(false);
		const loadData = async () => {
		if (!props.form?.id) return;
		loading.value = true;
		try {
			const res = await api.getMaintenanceHistory(props.form.id);
			records.value = res.data || [];
		} finally {
			loading.value = false;
		}
		};

		watch(() => props.form?.id, loadData, { immediate: true });

		return () => (
		<ElTable data={records.value} v-loading={loading.value} style="width: 100%">
			<ElTableColumn prop="damage_no" label="维修编号" />
			<ElTableColumn prop="device_name" label="设备名称" />
			<ElTableColumn prop="damage_reason" label="损坏原因" />
			<ElTableColumn prop="estimated_loss" label="损失价格" />
		</ElTable>
		);
	} catch (e) {
		console.error("MaintenanceHistory setup error:", e);
		return () => <div>组件加载失败</div>;
	}

	}
  });

const MaintenanceRecords = defineComponent({
	props: { form: Object },
	setup(props) {
		try {
			const records = ref([]);
			const loading = ref(false);
			const loadData = async () => {
				if (!props.form?.id) return;
				loading.value = true;
				try {
					const res = await api.getMaintenanceRecords(props.form.id);
					records.value = res.data || [];
				} finally {
					loading.value = false;
				}
			};

			watch(() => props.form?.id, loadData, { immediate: true });

			return () => (
			<ElTable data={records.value} v-loading={loading.value} style="width: 100%">
				<ElTableColumn prop="record_no" label="保养编号" />
				<ElTableColumn prop="plan_name" label="保养计划" />
				<ElTableColumn prop="planned_date" label="保养日期" />
				<ElTableColumn prop="maintenance_person" label="保养人员" />
				<ElTableColumn prop="maintenance_content" label="保养内容" />
		
			</ElTable>
			);
		} catch (e) {
			console.error("MaintenanceRecords setup error:", e);
			return () => <div>组件加载失败</div>;
		}
	}
});

const DeviceStatistics = defineComponent({
	props: { form: Object },
	setup(props) {
		try {
			const statistics = ref<any>({});
			const loading = ref(false);
			const loadData = async () => {
				if (!props.form?.id) return;
				loading.value = true;
				try {
					const res = await api.getDeviceStatistics(props.form.id);
					statistics.value = res.data || {};
					console.log(statistics.value)
				} finally {
					loading.value = false;
				}
			};

			watch(() => props.form?.id, loadData, { immediate: true });

			return () => (
			<div v-loading={loading.value} style={{ padding: '20px' }}>
				<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px' }}>
					<div style={{ background: '#f5f7fa', padding: '20px', borderRadius: '8px', textAlign: 'center' }}>
						<div style={{ fontSize: '24px', fontWeight: 'bold', color: '#409eff' }}>{statistics.value.borrow_count || 0}</div>
						<div style={{ color: '#606266', marginTop: '8px' }}>总借用次数</div>
					</div>
					<div style={{ background: '#f5f7fa', padding: '20px', borderRadius: '8px', textAlign: 'center' }}>
						<div style={{ fontSize: '24px', fontWeight: 'bold', color: '#67c23a' }}>{statistics.value.maintenance_records_count || 0}</div>
						<div style={{ color: '#606266', marginTop: '8px' }}>维护次数</div>
					</div>
					<div style={{ background: '#f5f7fa', padding: '20px', borderRadius: '8px', textAlign: 'center' }}>
						<div style={{ fontSize: '24px', fontWeight: 'bold', color: '#e6a23c' }}>{statistics.value.maintenance_history_count || 0}</div>
						<div style={{ color: '#606266', marginTop: '8px' }}>维修次数</div>
					</div>
					<div style={{ background: '#f5f7fa', padding: '20px', borderRadius: '8px', textAlign: 'center' }}>
						<div style={{ fontSize: '24px', fontWeight: 'bold', color: '#f56c6c' }}>{statistics.value.total_borrow_hours || 0}</div>
						<div style={{ color: '#606266', marginTop: '8px' }}>借用时长</div>
					</div>
				</div>
				{statistics.value.recent_activities && (
					<div style={{ marginTop: '30px' }}>
						<h3 style={{ marginBottom: '20px', color: '#303133' }}>最近活动</h3>
						<ElTable data={statistics.value.recent_activities} style={{ width: '100%' }}>
							<ElTableColumn prop="activity_type" label="活动类型" />
							<ElTableColumn prop="activity_date" label="活动日期" />
							<ElTableColumn prop="description" label="描述" />
						</ElTable>
					</div>
				)}
			</div>
			);
		} catch (e) {
			console.error("DeviceStatistics setup error:", e);
			return () => <div>组件加载失败</div>;
		}
	}
});

  
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);
	};

    // 跨页累积选择的行集合
    const selectedRows = ref<any[]>([]);
    const selectedIds = ref<any[]>([]);

    const onSelectionChange = (changed: any[]) => {
        // 当前页数据
        const tableData = crudExpose.getTableData();
        const unChanged = tableData.filter((row: any) => !changed.includes(row));
        // 合并当前页已选择的行
        XEUtils.arrayEach(changed, (item: any) => {
            const ids = XEUtils.pluck(selectedRows.value, 'id');
            if (!ids.includes(item.id)) {
                selectedRows.value = XEUtils.union(selectedRows.value, [item]);
            }
        });
        // 移除当前页未勾选的行
        XEUtils.arrayEach(unChanged, (unItem: any) => {
            selectedRows.value = XEUtils.remove(selectedRows.value, (it: any) => it.id !== unItem.id);
        });
        // 同步导出所需的 id 列表
        selectedIds.value = XEUtils.pluck(selectedRows.value, 'id');
    };

    const toggleRowSelection = () => {
        // 翻页/刷新后回显已选择项
        const tableRef = crudExpose.getBaseTableRef();
        const tableData = crudExpose.getTableData();
        const selected = XEUtils.filter(tableData, (item: any) => {
            const ids = XEUtils.pluck(selectedRows.value, 'id');
            return ids.includes(item.id);
        });
        nextTick(() => {
            XEUtils.arrayEach(selected, (item: any) => {
                tableRef.toggleRowSelection(item, true);
            });
        });
    };

    // 对外暴露选中ID集合（稳定引用）
    (crudExpose as any).selectedIds = selectedIds;

	return {
		// selectedIds,
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
            table: {
                rowKey: "id", 
                onSelectionChange,
                onRefreshed: () => toggleRowSelection(),
            },
			toolbar:{
				show:false,
			},
			rowHandle: {
				fixed: 'right',
				width: 220,
				view: {
					show: true,
				
				},
				edit: {
					show: true,
				},
				remove: {
					show: true,
				},
			},
			actionbar: {
                buttons: {
                    add: {
                        show: auth('user:Create')
                    },
					// batchimport:{
					// 	text: "批量导入",
                    //     title: "导入",
                    //     // show: auth('user:batchimport'),
					// },
                    // export: {
                    //     text: "导出",
                    //     title: "导出",
                    //     show: auth('user:Export'),
                    // },
					// downloadtemplate: {
                    //     text: "下载模板",
                    //     title: "下载模板",
                    //     // show: auth('user:Export'),
                    // },
					// batchdelete: {
                    //     text: "批量删除",
                    //     title: "批量删除",
                    //     // show: auth('user:Export'),
                    // },
                }
            },
			columns: {
				$checked: {
					title: "选择",
					form: { show: false },
					column: {
					type: "selection",
					align: "center",
					width: "55px",
					columnSetDisabled: true, //禁止在列设置中选择
					selectable(row: any, index: any) {
						// return row.id !== 1; //设置第一行不允许选择
						return row.id;
					}
				}
				},
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						align: 'center',
						width: '70px',
						columnSetDisabled: true,
						formatter: (context) => {
							let index = context.index ?? 1;
							let pagination = crudExpose!.crudBinding.value.pagination;
							return ((pagination!.currentPage ?? 1) - 1) * pagination!.pageSize + index + 1;
						},
					},
				},
				search:{
					title: '关键字搜索',
					search: { show: true,type: 'input', },
					type: 'input',
					form: {
						component: { placeholder: '请输入' },
						show:false},
					column: {show:false}
				},
				code: {
					title: '设备编号',
					search: { show: true },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						component: { placeholder: '请输入设备编号' },
						rules: [{ required: true, message: '请输入设备编号' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
				},
				
				category_name: {
					title: '设备分类',
					search: { show: true },
					type: 'dict-select',
					dict: dict({
						url: '/api/system/device/category/?page=1&limit=100',
						value: 'id',
						label: 'name',
					}),
					column: { minWidth: 100 },
					form: {
						show:false,
						component: { placeholder: '请选择设备分类' },
						rules: [{ required: true, message: '请选择设备分类' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				name: {
					title: '设备名称',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						component: { placeholder: '请输入设备名称' },
						rules: [{ required: true, message: '请输入设备名称' }]
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				status_list:{
					title: '设备状态',
					type: 'dict-select',
					search: { show: false },
					column: {
						show: false,
						minWidth: 100,
					},
					dict: dict({
						data: [
							{ value: 0, label: '停用' },
							{ value: 1, label: '正常' },
							{ value: 2, label: '维修中' },
							{ value: 3, label: '报废' }
						]
					}),
					form: {
						show:false,
						component: { placeholder: '请选择设备状态' },
						rules: [{ required: true, message: '请选择设备状态' }],
					},
					viewForm:{
						show:false,
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				"inventory.borrowed_quantity":{
						title: '设备状态',
						type: 'text',
						search: { show: false },
						column: {
							show: true,
							minWidth: 130,
							formatter: ({ row }) => {
								const isBorrowed = row.inventory.borrowed_quantity > 0;
								const isMaintenance = row.inventory.maintenance_quantity > 0 && row.inventory.maintenance_quantity === row.inventory.total_quantity;
								const isDamaged = row.inventory.damaged_quantity > 0 &&  row.inventory.total_quantity==row.inventory.damaged_quantity;
								
								let label, color;
								console.log(isDamaged);
								if (isDamaged) {
									label = '报废';
									color = '#F56C6C';
								} else if (isMaintenance) {
									label = '维修';
									color = '#E6A23C';
								} else if (isBorrowed) {
									label = row.total_quantity - row.borrowed_quantity === 0 ? '在借' : '在借';
									color = '#FFA500';
								} else {
									label = row.total_quantity === 0 ? '在借' : '空闲';
									color = '#4CAF50';
								}
								return h(
									'span',
									{
										style: {
										display: 'inline-block',
										padding: '2px 8px',
										border: `1px solid ${color}`,
										borderRadius: '4px',
										backgroundColor: color,
										color: 'white',
										fontWeight: 'bold',
										}
									},
									label
									);
							},
							filters: [
								{ text: "空闲", value: "idle" },
								{ text: "在借", value: "borrowed" },
								{ text: "维修", value: "maintenance" },
								{ text: "报废", value: "scrapped" }
							  ],
							  filterMethod: (value: string, row: any) => {
								const inv = row.inventory;
								const isBorrowed = inv.borrowed_quantity > 0;
								const isMaintenance = inv.maintenance_quantity > 0 && inv.maintenance_quantity === inv.total_quantity;
								const isDamaged = inv.damaged_quantity > 0 && inv.total_quantity === 0;
								
								if (value === "scrapped") {
									return isDamaged;
								} else if (value === "maintenance") {
									return isMaintenance;
								} else if (value === "borrowed") {
									return isBorrowed;
								} else if (value === "idle") {
									return !isBorrowed && !isMaintenance && !isDamaged;
								}
								return false;
							  },
							  sortable: true
						},
						form: {
							show:false,
							component: { placeholder: '请选择设备状态' },
							rules: [{ required: true, message: '请选择设备状态' }],
						},
				},
				borrowed_quantity:{
					title:"已借出",
					type:'input',
					search:{show:false},
					column: { minWidth: 100 },
					form: {
						show:false,
						component: { placeholder: '请输入已借出' },
						rules: [{ required: true, message: '请输入已借出' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				brand:{
					title:'品牌',
					type:"input",
					column: { minWidth: 100 },
					form: {
						component: { placeholder: '请输入品牌' }
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					},
				},	
				specification: {
					title: '规格型号',
					search: { show: false },
					type: 'input',
					column: { minWidth: 100 },
					form: {
						component: { placeholder: '请输入规格型号' }
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					},
				},
				serial_number:{
					title:'序列号',
					type:"input",
					column: { minWidth: 100 },
					form: {
						component: { placeholder: '请输入序列号' }
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					},
				},
				available_quantity:{
					title:'可用库存',
					type:"input",
					column: { minWidth: 100 },
					addForm:{
						show:false,
					},
					viewForm:{
						show:false,
					},
					editForm:{show:false},
					from:{ 
						show:false,
						component: { placeholder: '请输入库存数量' },
						rules: [{ required: false, message: '请输入库存数量' }],

					}
				},
				total_quantity:{
					title:'库存数量',
					type:"input",
					column: { minWidth: 100 },
					addForm:{
						show:false,
					},
					viewForm:{
						show:false,
					},
					editForm:{show:false},
					from:{ 
						show:false,
						component: { placeholder: '请输入库存数量' },
						rules: [{ required: false, message: '请输入库存数量' }],

					}
				},
				warehouse:{
					title:'存放仓库',
					search: { show: true },
					type:"dict-select",
					column: { minWidth: 150 },
					dict: dict({
						url: '/api/system/warehouse/',
						value: 'id', 
						label: 'name'
					}),
					form: {
						component: { placeholder: '请选择存放仓库' },
						rules: [{ required: true, message: '请选择存放仓库' }],
					}
				},
				status:{
					title:'是否可见',
					type: 'dict-switch',
					search: { show: true },
					column: {
						show:true,
						minWidth: 90,
						component: {
							name: 'fs-dict-switch',
							activeText: '',
							inactiveText: '',
							style: '--el-switch-on-color: var(--el-color-primary); --el-switch-off-color: #dcdfe6',
							onChange: compute((context) => {
								let isInitialized = false;
								// 延迟设置初始化完成标志，避免初始化时触发
								setTimeout(() => {
									isInitialized = true;
								}, 100);
								
								return () => {
									// 只有在初始化完成后才执行API调用
									if (isInitialized) {
										api.UpdateObjStatus(context.row).then((res:APIResponseData) => {
											successMessage(res.msg as string);
										});
									}
								};
							}),
						},
					},
					dict: dict({
						data: [{ label: '可见', value: 1 }, { label: '不可见', value: 0 }],
					}),
					form: {
						show:false,
						rules: [{ required: true, message: '请选择是否可见' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}


				},
				/* status_label:{
					title: '当前状态',
					search: { show: false },
					form: {
						show:false,
					}

				}, */
				department: {
					title: '所属部门',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						component: { placeholder: '请输入所属部门' }
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				purchase_date: {
					title: '采购时间',
					type: 'date',
					search: { show: false },
					column: {
						minWidth: 120,
						formatter: ({ value }) => (value ? dayjs(value).format('YYYY-MM-DD') : ''),
					},
					form: {
						component: { placeholder: '请选择采购时间' },
						rules: [{ required: false, message: '请选择采购时间' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					},
					
					valueResolve({ form, value }) {
						form.purchase_date = value ? dayjs(value).format('YYYY-MM-DD') : null;
					},
					valueBuilder({ form, value }) {
						form.purchase_date = value;
					},
				},
				
				supplier: {
					title: '供应商',
					type: 'dict-select',
					search: { show: true  },
					column: { 
						minWidth: 120,				
					},
					dict: dict({
						url: '/api/system/supplier/',
						value: 'id', 
						label: 'name'
					}),
					form: {
						component: { placeholder: '请输入供应商' },
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				price: {
					title: '价格',
					type: 'number',
					search: { show: false },
					column: { minWidth: 100 },
					form: {
						component: { placeholder: '请输入设备购入价格' },
						rules: [{ required: false, message: '请输入设备购入价格' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				warranty_expiration: {
					title: '质保到期',
					type: 'date',
					search: { show: false },
					column: { minWidth: 120 ,
						formatter: ({ value }) => (value ? dayjs(value).format('YYYY-MM-DD') : ''),
					},
					viewForm: {
						title: '质保到期',
						component: {
							render({ value }) {
								// eslint-disable-next-line no-console
								console.log("valuevaluevalue:::",value);
								if (!value) return '';
								const formatted = dayjs(value).format('YYYY-MM-DD');
								const isExpired = dayjs(value).isBefore(dayjs(), 'day');
								return h(
									'span',
									{
										style: {
										color: isExpired ? 'red' : 'inherit',
										fontWeight: isExpired ? 'bold' : 'normal'
										}
									},
									isExpired ? `${formatted}（已过期）` : formatted
									);
							},
							showHtml: true,
						},
						rules: [{ required: false, message: '请选择质保到期' }]
					},
					form: {
						component: { placeholder: '请选择质保到期' },
						rules: [{ required: false, message: '请选择质保到期' }],
					},
					valueResolve({ form, value }) {
						form.warranty_expiration = value ? dayjs(value).format('YYYY-MM-DD') : null;
					},
					valueBuilder({ form, value }) {
						form.warranty_expiration = value;
					},
				},
				tenant_id:{
					title: '租户id',
					type: 'input',
					value: 1,
					column: {
						show:false,
						minWidth: 120,
					},
					// dict: dict({
					// 	url: '/api/system/tenant/list/',
					// 	value: 'id', 
					// 	label: 'name'
					// }),
					form: {
						value:1,
						show:false,
						component: { placeholder: '请填租户id' },
						rules: [{ required: false, message: '请填租户id' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				category:{
					show: false,
					title: '设备类别',
					search: { show: false },
					type: 'dict-select',
					column: { show: false,minWidth: 120 },
					dict: dict({
						url: '/api/system/device/category/?page=1&limit=100',
						value: 'id', 
						label: 'name'
					}),
					form: {
						component: { 
							placeholder: '请输入设备类别',
							filterable: true 
						},
						rules: [{ required: true, message: '请输入设备类别' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				quantity:{
					show: false,
					title: '库存数量',
					search: { show: false },
					type: 'input',
					column: { show: false,minWidth: 120 },
					viewForm:{
						component:{placeholder:""}
					},
					form: {
						component: { placeholder: '请输入库存数量' },
						rules: [{ required: true, message: '请输入库存数量' }],
						valueResolve({ form, value }) {
							form.quantity = Number(value ?? 0);
						},		  
						valueBuilder({ form, value }) {
							// form.tags =Array.from(String(value), Number);
							form.quantity = form.total_quantity;

						}
						
					}
				},
				tags:{
					show: false,
					title: '设备标签',
					search: { show: true },
					type: 'dict-select',
					column: { show: true,minWidth: 120 },
					dict: dict({
						url: '/api/system/device_tags/?page=1&limit=100',
						value: 'id', 
						label: 'name'
					}),
					viewForm:{
						component:{placeholder:""}
					},
					form: {
						component: { placeholder: '请选择设备标签',
							filterable: true 
						 },
						rules: [{ required: true, message: '请选择设备标签' }],
						valueResolve({ form, value }) {
							form.tags =  [parseInt(value, 10)]//Array.from(String(value), Number);
							console.log(form.tags)
						},
						valueBuilder({ form, value }) {
							if(value){
								form.tags = Array.isArray(value)? value.length > 0 ? Number(value[0]) : '': Number(value);
								console.log(form.tags)
							}

						},
					}
				},
				image:{			
					title: '设备图片',
					type: 'image-uploader',
					column: { 
						minWidth: 120,
						show:false,				
					},
					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];
					}
					
				},

				id: {
					title: 'deviceid',
					search: { show: false },
					type: 'input',
					column: { show:false,minWidth: 120 },
					form: {
						show:false,
						component: { placeholder: '请输入维修' }
					},
					viewForm:{
						show:true,
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},

			},
			viewForm: {
				wrapper: {
					buttons: {
						ok:{
							text:'提交',
							show:false
						}
					}
				},
				row: { gutter: 20 },
				group: {
				groupType: "tabs", 
				groups: {
					base: {
						slots: {
							label: (scope) => {
							return (
								<span style={{ color: scope.hasError ? "red" : "#409eff" }}>
									
									基础信息
								</span>
							);
						}
					},
						icon: "el-icon-goods",
						columns: ["code","category_name", "name", "status","borrowed_quantity","brand","specification","serial_number","warehouse","is_visible","department","purchase_date","supplier","price","warranty_expiration","tenant_id","category","quantity","tags","image"]
					},
					borrow: {
						show:true,
						label: "借用记录",
						icon: "el-icon-price-tag",
						columns: ["id"],
						slots: {
							default: (scope) => {
								const currentRow = crudExpose.getFormData();
								console.log("currentRow::",currentRow);
								return <BorrowRecords form={currentRow || {}}/>;
							}
						}
					},
					maintenance: {
						show:true,
						label: "维修记录",
						icon: "el-icon-warning-outline",
						columns: ["id"],
						slots: {
							default: (scope) => {
								const currentRowwx = crudExpose.getFormData();
								console.log("currentRowwx::",currentRowwx);
								return <MaintenanceHistory form={currentRowwx || {}} />
							}
						}
					},
					maintain: {
						show: true,
						label: "保养记录",
						icon: "el-icon-warning-outline",
						columns: ["id"],
						slots: {
							default: (scope) => {
								const currentRowMaintain = crudExpose.getFormData();
								console.log("currentRowMaintain::",currentRowMaintain);
								return <MaintenanceRecords form={currentRowMaintain || {}} />
							}
						}
					},
					datastatis: {
						show: true,
						label: "数据统计",
						icon: "el-icon-data-analysis",
						columns: ["id"],
						slots: {
							default: (scope) => {
								const currentRowStats = crudExpose.getFormData();
								console.log("currentRowStats::",currentRowStats);
								return <DeviceStatistics form={currentRowStats || {}} />
							}
						}
					},





					}
				}
			},
		},
	};
};
