import * as api from './api';
import { dict, UserPageQuery, AddReq, DelReq, EditReq, compute, CreateCrudOptionsProps, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import {GetList} from '../contract/api';
import { dictionary } from '/@/utils/dictionary';
import { successMessage, errorMessage } from '/@/utils/message';
import { auth } from '/@/utils/authFunction';
import { useRouter } from 'vue-router';
import { ElMessageBox } from 'element-plus';

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const router = useRouter();
	
	// 缓存已加载的企业数据，用于本地校验
	let cachedCompanyData: any[] = [];
	
	const pageRequest = async (query: UserPageQuery) => {
		const result = await api.GetList(query);
		// 缓存数据用于本地校验
		if (result.data) {
			cachedCompanyData = result.data.results;
		}
		return result;
	};
	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.tenant_id);
	};
	const addRequest = async ({ form }: AddReq) => {
		try {
			// 先使用缓存数据进行快速校验
			const existingInCache = cachedCompanyData.find(item => item.code === form.code);
			if (existingInCache) {
				errorMessage('企业编码已存在，请使用其他编码');
				throw new Error('企业编码重复');
			}
			
			// 如果缓存中没有数据或数据不完整，则通过接口查询
			if (cachedCompanyData.length === 0) {
				const existingData = await api.GetList({
					page: 1,
					page_size: 1000,
					code: form.code
				});
				
				if (existingData.data && existingData.data.length > 0) {
					errorMessage('企业编码已存在，请使用其他编码');
					throw new Error('企业编码重复');
				}
			}
			
			// 编码不重复，执行新增操作
			const result = await api.AddObj(form);
			
			// 新增成功后，将新数据添加到缓存中
			if (result.data) {
				cachedCompanyData.push(result.data);
			}
			
			return result;
		} catch (error: any) {
			// 如果是编码重复错误，不重复提示
			if (error.message === '企业编码重复') {
				throw error;
			}
			
			// 其他错误，显示通用错误信息
			errorMessage('新增企业失败，请稍后重试');
			throw error;
		}
	};
// 删除确认处理函数
	const handleDeleteConfirm = async (opts: any) => {
		try {
			await ElMessageBox.confirm(
				`确定要删除企业"${opts.row.name}"吗？此操作不可撤销。`,
				'删除确认',
				{
					confirmButtonText: '确定删除',
					cancelButtonText: '取消',
					type: 'warning',
					confirmButtonClass: 'el-button--danger'
				}
			);
			// 用户确认后，调用原有的删除逻辑
			await delRequest(opts);
			successMessage('删除成功');
			// 刷新列表
			crudExpose.doRefresh();
		} catch (error) {
			// 用户取消删除，不做任何操作
			if (error !== 'cancel') {
				errorMessage('删除失败');
			}
		}
	};
	return {
		crudOptions: {
			toolbar:{
				buttons:{
					search:{show:false},
					// 刷新按钮
					refresh:{show:false},
					// 紧凑模式
					compact:{show:false},
					// 导出按钮
					export:{
						text: '导出',
						type: 'primary',
						size: 'small',
						icon: 'upload',
						circle: false,
						display: true,
						show:false
					},
					// 列设置按钮
					columns:{
						show:false
					},
				}
			},
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			search: {
				col: { span: 3 },
				show: true,
				autoSearch:false,
				buttons: {
					search: {
						size: 'small', // 设置查询按钮大小为small
					},
					reset: {
						size: 'small', // 设置重置按钮大小为small
					}
				}
			},
			actionbar: {
				buttons: {
					add: {
						size: 'small',
						show: true//auth('company:Create'),
					},
				},
			},
			rowHandle: {
				//固定右侧
				fixed: 'right',
				width: 260,
				buttons: {
					view: {
						size: 'small',
						text: '详细信息',
						iconRight: 'View',
						type: 'text',
						show: true,//auth('company:Detail'),
					},
					viewContract: {
						size: 'small',
						text: '查看合约',
						iconRight: '',
						type: 'text',
						show: true,//auth('company:ViewContract'),
						click: async ({ row }) => {
							const res = await GetList({
								tenant_id: row.id,
								page: 1,
								page_size: 10
							});
							// TODO: 实现查看合约逻辑，例如导航到合约页面
							res.data.forEach((item: any) => {
								console.log(item.tenant,row.tenant_id);
								if(item.tenant==row.tenant_id){
									console.log(item);
									router.push({
										path: '/system/contract/preview',
										query: {
											file: item.document_link,
											contractName: item.contract_name
										}
									});
								}
							});
						}
					},
					edit: {
						size: 'small',
						type: 'text',
						show: true,
					},
					remove: {
						iconRight: 'Delete', 
						size: 'small',
						type: 'text',
						show: true,
						click: handleDeleteConfirm
					},
				},
			},
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				code:{
					title: '企业编码',
					type: 'input',
					search: { show: true },
					form: { 
						rules: [{ required: true, message: '企业编码必填' }],
						component: { placeholder: '请输入企业编码' },
					},
					column: { minWidth: 120 },
				},
				name: {
					title: '企业名称',
					search: {
						show: true,
					},
					type: 'input',
					form: {
						rules: [{ required: true, message: '企业名称必填' }],
						component: { placeholder: '请输入企业名称' },
					},
					column: { minWidth: 120 },
				},
				company_size: {
					title: '企业规模',
					type: 'dict-select',
					search: { show: true },
					form: { 
						component: { 
							placeholder: '请选择企业规模',
						} 
					},
					column: { minWidth: 100 },
					dict: dict({
						data: [
							{ value: 1, label: '1-10人' },
							{ value: 2, label: '11-50人' },
							{ value: 3, label: '51-200人' },
							{ value: 4, label: '201-500人' },
							{ value: 5, label: '501-1000人' },
							{ value: 6, label: '1000人以上' }
						]
					}),
				},
				company_address: {
					title: '企业地址',
					type: 'input',
					search: { show: false },
					form: { component: { placeholder: '请输入企业地点' } },
					column: { minWidth: 120 },
				},
				industry: {
					title: '行业',
					type: 'dict-select',
					search: { show: true },
					form: { 
						component: { 
							placeholder: '请选择行业',
						} 
					},
					column: { minWidth: 100 },
					dict: dict({
						data: [
							{ value: 1, label: '互联网/软件' },
							{ value: 2, label: '金融/保险' },
							{ value: 3, label: '制造业' },
							{ value: 4, label: '教育培训' },
							{ value: 5, label: '医疗健康' },
							{ value: 6, label: '房地产/建筑' },
							{ value: 7, label: '零售/电商' },
							{ value: 8, label: '餐饮/酒店' },
							{ value: 9, label: '物流/运输' },
							{ value: 10, label: '咨询服务' },
							{ value: 11, label: '媒体/广告' },
							{ value: 12, label: '能源/化工' },
							{ value: 13, label: '政府机构' },
							{ value: 14, label: '非营利组织' },
							{ value: 15, label: '其他' }
						]
					}),
				},
				status: {
					title: '状态',
					search: { show: true },
					type: 'dict-select',
					form: { component: { placeholder: '请选择状态' } },
					column: { minWidth: 120 },
					dict: dict({
						data: [
							{ value: 1, label: '服务中' },
							{ value: 2, label: '试用中' },
							{ value: 0, label: '已停用' }
						]
					}),
				},
				published_jobs_count: {
					title: '岗位数',
					type: 'number',
					column: { minWidth: 90 },
					form: {
						component: {
							// 限制为整数输入
							step: 1,
							precision: 0,
							min: 0,
							// 根据企业规模动态限制最大值
							max: compute(({ form }) => {
								const map: Record<string, number> = {
									'1': 10,
									'2': 50,
									'3': 200,
									'4': 500,
									'5': 1000,
									'6': 999999
								};
								return map[form.company_size as string] ?? 999999;
							})
						},
						rules: [
							{ required: true, message: '岗位数必填' },
							{
								validator: (_rule: any, value: any, callback: any, _model: any) => {
									if (value === undefined || value === null || value === '') {
										return callback();
									}
									// 必须为整数
									if (!Number.isInteger(value)) {
										return callback(new Error('岗位数必须为整数'));
									}
									callback();
								}
							}
						]
					},
				},
				/* usageCount: {
					title: '使用次数',
					type: 'number',
					column: { minWidth: 100 },
				}, */
				update_datetime: {
					title: '数据更新时间',
					type: 'datetime',
					column: { minWidth: 150 },
					form:{
						show:false
					}
				},
			},
		},
	};
}; 