import * as api from './api';
import { dict, UserPageQuery, AddReq, DelReq, EditReq, compute, CreateCrudOptionsProps, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as companyApi from '../company/api';
import { dictionary } from '/@/utils/dictionary';
import { successMessage } from '/@/utils/message';
import { auth } from '/@/utils/authFunction';
import { Md5 } from 'ts-md5';
import { ref, computed } from 'vue';

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	// 用于跟踪当前企业下是否有账号数据
	const hasAccountData = ref(false);
	
	const pageRequest = async (query: any) => {
		console.log(query)
		const response = await api.GetList(query);
		console.log('API返回的完整响应:', response);
		
		// 过滤掉 platform_admin、platform2_admin 以及 name 为"平台管理员"的账号
		// 处理不同的数据结构
		let dataArray: any[] = [];
		let countKey = 'count';
		
		if (response?.data?.results && Array.isArray(response.data.results)) {
			dataArray = response.data.results;
			countKey = 'count';
		} else if (response?.data?.items && Array.isArray(response.data.items)) {
			dataArray = response.data.items;
			countKey = 'total';
		} else if (Array.isArray(response?.data)) {
			dataArray = response.data;
			countKey = 'total';
		} else if (Array.isArray(response?.records)) {
			dataArray = response.records;
			countKey = 'total';
		}
		
		if (dataArray.length > 0) {
			const originalCount = dataArray.length;
			console.log('过滤前数据:', dataArray.map((item: any) => ({ username: item.username, name: item.name })));
			
			const filteredArray = dataArray.filter((item: any) => {
				// 过滤掉 username 为 platform_admin、platform2_admin 或 name 为"平台管理员"的账号
				const isPlatformAdmin = item.username === 'platform_admin' || item.username === 'platform2_admin';
				const isPlatformAdminName = item.name === '平台管理员';
				
				// 前端二次过滤：如果查询参数中有 tenant_id，则过滤掉不匹配的数据
				let isMismatchTenant = false;
				if (query.tenant_id) {
					const recordTenantId = item.tenant_id ?? item.tenant?.id;
					if (recordTenantId && String(recordTenantId) !== String(query.tenant_id)) {
						isMismatchTenant = true;
					}
				}

				// 如果匹配任一条件，则过滤掉
				const shouldFilter = isPlatformAdmin || isPlatformAdminName || isMismatchTenant;
				if (shouldFilter) {
					console.log('过滤掉账号:', { username: item.username, name: item.name });
				}
				return !shouldFilter;
			});
			
			const filteredCount = filteredArray.length;
			console.log('过滤后数据数量:', filteredCount, '原始数量:', originalCount);
			
			// 更新对应的数据结构
			if (response?.data?.results) {
				response.data.results = filteredArray;
				if (response.data.count !== undefined) {
					response.data.count = Math.max(0, response.data.count - (originalCount - filteredCount));
				}
			} else if (response?.data?.items) {
				response.data.items = filteredArray;
				if (response.data.total !== undefined) {
					response.data.total = Math.max(0, response.data.total - (originalCount - filteredCount));
				}
			} else if (Array.isArray(response?.data)) {
				response.data = filteredArray;
				if (response.total !== undefined) {
					response.total = Math.max(0, response.total - (originalCount - filteredCount));
				}
			} else if (Array.isArray(response?.records)) {
				response.records = filteredArray;
				if (response.total !== undefined) {
					response.total = Math.max(0, response.total - (originalCount - filteredCount));
				}
			}
			
			// 更新是否有账号数据的状态（过滤后的数据）
			hasAccountData.value = filteredArray.length > 0;
		} else {
			// 如果没有数据，设置为 false
			hasAccountData.value = false;
		}
		
		return response;
	};
	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: {
			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
					},
				}
			},
			search: {
				col: { span: 3 },
				show: true,
				autoSearch:true,
				buttons: {
					search: {
						size: 'small', // 设置查询按钮大小为small
					},
					reset: {
						size: 'small', // 设置重置按钮大小为small
					}
				}
			},
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,
			},
			actionbar: {
				buttons: {
					add: {
						show: computed(() => !hasAccountData.value), // 如果没有数据则显示，有数据则隐藏
					},
				},
			},
			rowHandle: {
				fixed: 'right',
				width: 230,
				buttons: {
					view: { show: true,size:'small' },
					edit: { type: 'primary', show: true,size:'small' },//auth('account:Update')
					remove: {type: 'danger', show: true,size:'small' },//auth('account:Delete')
				},
			},
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: { type: 'index', align: 'center', width: '70px', columnSetDisabled: true },
				},
				username: {
					title: '用户名',
					type: 'text',
					search: { show: true },
					form: {
						component: { placeholder: '请输入用户名' },
						rules: [{ required: true, message: '请输入用户名' }]
					},
					column: { minWidth: 120 },
				},
				password: {
					title: '密码',
					type: 'password',
					search: { show: false },
					column: { show: false },
					addForm: {
						component: { placeholder: '请输入密码' },
						rules: [{ required: true, message: '请输入密码' },
							{
								validator: (rule: any, value: string, callback: Function) => {
									if (!value) {
										callback();
										return;
									}
									// 检查密码长度不少于8位
									if (value.length < 8) {
										callback(new Error('密码长度不能少于8位'));
										return;
									}
									// 检查是否包含字母
									const hasLetter = /[a-zA-Z]/.test(value);
									// 检查是否包含数字
									const hasNumber = /[0-9]/.test(value);
									
									if (!hasLetter || !hasNumber) {
										callback(new Error('密码必须包含字母和数字'));
										return;
									}
									callback();
								},
								trigger: 'blur'
							}
						],
						show: true,
						column: { show: false }
					},
					valueResolve({ form }) {
                        if (form.password) {
                            form.password = Md5.hashStr(form.password)
                        }
                    }
				},
				name: {
					title: '姓名',
					type: 'text',
					search: { show: false },
					form: {
						component: { placeholder: '请输入姓名' },
						rules: [{ required: true, message: '请输入姓名' }]
					},
					column: { minWidth: 120 },
				},
				mobile: {
					title: '手机号',
					type: 'text',
					search: { show: true },
					form: {
						component: { placeholder: '请输入手机号' },
						rules: [{ required: true, message: '请输入手机号' }]
					},
					column: { minWidth: 120 },
				},
				email: {
					title: '邮箱',
					type: 'text',
					search: { show: true },
					form: {
						component: { placeholder: '请输入邮箱' },
						rules: [{ required: true, message: '请输入邮箱' }]
					},
					column: { minWidth: 180 },
				},
				tenant_id: {
					title: '商户',
					search: { show: true },
					type: 'dict-select',
					dict: dict({
						url: '/api/platform-admin/tenants/',
						value: 'id',
						label: 'name',
						/* getData: (url) => {
							return companyApi.GetList({ page: 1, limit: 20 }).then((res:any) => {
								return res.data.results;
							});
						} */
					}),
				},
				is_active: {
					title: '账号状态',
					search: { show: true },
					type: 'dict-select',
					form: { show:true, component: { placeholder: '请选择账号状态' } },
					column: { minWidth: 120 },
					dict: dict({
						data: [
							{ value: true, label: '启用' },
							{ value: false, label: '禁用' }
						]
					}),
				},
				create_datetime: {
					title: '开通时间',
					type: 'datetime',
					search: { show: false },
					form: { component: { placeholder: '请选择开通时间' },show:false },
					column: { minWidth: 150 },
				},
				account_expiry_days: {
					title: '截至天数',
					type: 'number',
					search: { show: false },
					form: { 
						component: { 
							placeholder: '请输入截至天数',
							min: 1,
							max: 365
						}, 
						show: true 
					},
					column: { minWidth: 150,show:false },
				},
				account_expiry:{
					title: '账号到期时间',
					type: 'datetime',
					search: { show: false },
					form: { component: { placeholder: '请选择账号到期时间' },show:false  },
					column: { minWidth: 150 },
				},
				last_login: {
					title: '最后登录时间',
					type: 'datetime',
					search: { show: false },
					form: { component: { placeholder: '请选择最后登录时间' },show:false  },
					column: { minWidth: 150 },
				},
				
			},
		},
	};
}; 