import { AddReq, compute, 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 { commonCrudConfig } from '/@/utils/commonCrud';
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 { h } from '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);
	};

	

	const ui = uiContext.get();

	return {
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			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: {
				_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;
						},
					},
				},
				code: {
					title: '设备编号',
					search: { show: true },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						component: { placeholder: '请输入设备编号' },
						rules: [{ required: true, message: '请输入设备编号' }],
					},
				},
				
				category_name: {
					title: '设备分类',
					search: { show: true },
					type: 'dict-select',
					dict: dict({
						url: '/api/system/device/category/',
						value: 'id',
						label: 'name',
					}),
					column: { minWidth: 100 },
					form: {
						show:false,
						component: { placeholder: '请选择设备分类' },
						rules: [{ required: true, message: '请选择设备分类' }],
					},
				},
				name: {
					title: '设备名称',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						component: { placeholder: '请输入设备名称' },
						rules: [{ required: true, message: '请输入设备名称' }]
					}
				},
				// statusss: {
				// 	title: '设备状态',
				// 	type: 'dict-select',
				// 	search: { show: false },
				// 	dict: dict({
				// 		data: [
				// 			{ label: '在借', value: 1 },
				// 			{ label: '空闲', value: 2 },
				// 		],
				// 	}),
				// 	column: { minWidth: 100 },
				// 	form: {
				// 		component: { placeholder: '请选择设备状态' },
				// 		rules: [{ required: true, message: '请选择设备状态' }],
				// 	},
				// },
				"inventory.borrowed_quantity":{
						title: '设备状态',
						type: 'dict-select',
						search: { show: false },
						dict: dict({
							data: [
								{ label: '在借', value: 1 },
								{ label: '空闲', value: 0 },
							],
							getData: (dict) => {
								return (value) => {
									return value > 0 ? '在借' : '空闲';
								}
							}
						}),
						column: { show:true, minWidth: 100 },
						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: '请输入已借出' }],
					},
				},
				brand:{
					title:'品牌',
					type:"input",
					column: { minWidth: 100 },
				},	
				specification: {
					title: '规格型号',
					search: { show: false },
					type: 'input',
					column: { minWidth: 100 },
					form: {
						component: { placeholder: '请输入规格型号' }
					}
				},
				serial_number:{
					title:'序列号',
					type:"input",
					column: { minWidth: 100 },
				},
				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:'存放仓库',
					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',
					column: {
						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) => {
								return () => {
									api.UpdateObjStatus(context.row).then((res:APIResponseData) => {
										successMessage(res.msg as string);
									});
								};
							}),
						},
					},
					dict: dict({
						data: dictionary('device_button_status_bool'),
					}),
					form: {
						rules: [{ required: true, message: '请选择是否可见' }],
					}

				},
				
				department: {
					title: '所属部门',
					search: { show: false },
					type: 'input',
					column: { minWidth: 120 },
					form: {
						component: { placeholder: '请输入所属部门' }
					}
				},
				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: '请选择采购时间' }],
					},
					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: false },
					column: { 
						minWidth: 120,				
					},
					dict: dict({
						url: '/api/system/supplier/',
						value: 'id', 
						label: 'name'
					}),
					form: {
						component: { placeholder: '请输入供应商' },
					},
				},
				price: {
					title: '价格',
					type: 'number',
					search: { show: false },
					column: { minWidth: 100 },
					form: {
						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,
						}
					},
					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' }],
					},
				},
				category:{
					show: false,
					title: '设备类别',
					search: { show: false },
					type: 'dict-select',
					column: { show: false,minWidth: 120 },
					dict: dict({
						url: '/api/system/device/category/',
						value: 'id', 
						label: 'name'
					}),
					form: {
						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: false },
					type: 'dict-select',
					column: { show: false,minWidth: 120 },
					dict: dict({
						url: '/api/system/device_tags/',
						value: 'id', 
						label: 'name'
					}),
					viewForm:{
						component:{placeholder:""}
					},
					form: {
						component: { placeholder: '请选择设备标签' },
						rules: [{ required: true, message: '请选择设备标签' }],
						valueResolve({ form, value }) {
							form.tags = Array.from(String(value), Number);
						},
						valueBuilder({ form, value }) {
							if(value){
								form.tags = Array.isArray(value)? value.length > 0 ? Number(value[0]) : '': Number(value);
							}

						},
					}
				},
				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];
					}
					// form: {
					// 	// component: { placeholder: '请上传图片' },
					// 	component: {
					// 		limit: 1,
					// 		uploader: {
					// 		type: "form"
					// 	}
					// 	},
					// 	rules: createUploaderRules([{ required: true, message: "此项必传", trigger: "change" }]),
					// 	change:()=>{

					// 	},
					// 	helper: "上传设备图片",
					// },
	
					
				},
				// maintenancename: {
				// 	title: '维修名称',
				// 	type: 'input',
				// 	search: { show: false },
				// 	column: { show:false,minWidth: 100 },
				// 	form: {
				// 		component: { placeholder: '请输入设备购入价格' },
				// 		rules: [{ required: true, message: '请输入设备购入价格' }],
				// 	},
				// },
				// ...commonCrudConfig({
				// 	create_datetime: { search: false },
				// 	update_datetime: { search: false },
				// }),
			},
			form: {
				row: { gutter: 20 },
				group: {
				groupType: "tabs", //collapse， tabs
				accordion: false,
				groups: {
					base: {
						slots: {
						label: (scope) => {
						return (
							<span style={{ color: scope.hasError ? "red" : "green" }}>
								<fs-icon icon={"ion:checkmark-circle"} />
								基础信息
							</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: {
						label: "借用记录",
						icon: "el-icon-price-tag",
						columns: []
					},
					maintenance: {
						label: "维修记录",
						collapsed: true, //默认折叠
						icon: "el-icon-warning-outline",
						columns: [""]
					},
					maintain: {
						label: "保养记录",
						collapsed: true, //默认折叠
						icon: "el-icon-warning-outline",
						columns: []
					},
					datastatis: {
						label: "数据统计",
						collapsed: true, //默认折叠
						icon: "el-icon-warning-outline",
						columns: []
					},





					}
				}
			},
		},
	};
};
