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';

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,
					click: ({ row }) => {
						window.dispatchEvent(new CustomEvent('workflow-view', { detail: row }));
					},
				},
				edit: {
					show: true,
					click: ({ row }) => {
						window.dispatchEvent(new CustomEvent('workflow-edit', { detail: row }));
					},
				},
				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: true, message: '请输入已借出' }],

					}
				},
				warehouse:{
					title:'库存仓库',
					type:"dict-select",
					column: { minWidth: 150 },
					dict: dict({
						url: '/api/system/warehouse/',
						value: 'id', 
						label: 'name'
					}),
					form: {
						component: { placeholder: '请选择库存仓库' }
					}
				},
				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'),
					}),

				},
				
				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: true, 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: true, message: '请输入设备购入价格' }],
					},
				},
				warranty_expiration: {
					title: '保质期',
					type: 'date',
					search: { show: false },
					column: { minWidth: 120 ,
						formatter: ({ value }) => (value ? dayjs(value).format('YYYY-MM-DD') : ''),
					},
					form: {
						component: { placeholder: '请选择购买日期' },
						rules: [{ required: true, message: '请选择购买日期' }],
					},
					valueResolve({ form, value }) {
						form.warranty_expiration = value ? dayjs(value).format('YYYY-MM-DD') : null;
					},
					valueBuilder({ form, value }) {
						form.warranty_expiration = 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'); 
									// eslint-disable-next-line no-console
									console.log("token:::",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: "上传设备图片",
					// },
	
					
				},
				tenant_id:{
					title: '租户id',
					type: 'dict-select',
					column: {
						show:false,
						minWidth: 120,
					},
					dict: dict({
						url: '/api/system/tenant/list/',
						value: 'id', 
						label: 'name'
					}),
					form: {
						component: { placeholder: '请填租户id' },
						rules: [{ required: false, message: '请填租户id' }],
					},
				},
				category:{
					show: false,
					title: '类别id',
					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: '请输入类别id' }
					}
				},
				quantity:{
					show: false,
					title: '库存数量',
					search: { show: false },
					type: 'input',
					column: { show: false,minWidth: 120 },
					form: {
						component: { placeholder: '请输入库存数量' }
					}
				},
				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'
					}),
					form: {
						component: { placeholder: '请选择设备标签' },
						valueResolve({ form, value }) {
							form.tags = Array.from(String(value), Number);
						},
						valueBuilder({ form, value }) {
							form.tags =Array.from(String(value), Number);
						},
					}
				},
				// 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","image","tenant_id","category","quantity","tags"]
					},
					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: []
					},





					}
				}
			},
		},
	};
};
