import * as api from './api';
import { updateTenantStatus } 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 } from '/@/utils/message';
import { auth } from '/@/utils/authFunction';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

export const createCrudOptions = function ({ crudExpose }: CreateCrudOptionsProps): CreateCrudOptionsRet {
	const router = useRouter();
	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);
	};

	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:true,
				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: '查看',
						/* type: 'primary', */
						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',
						show: true,
					},
					remove: {
						show: false,
					},
					changeStatus: {
						size: 'small',
						text: '修改状态',
						iconRight: 'Edit',
						/* type: 'text', */
						show: true,
						click: async ({ row }) => {
							const statusMap: Record<string, string> = {
								'0': '试用',
								'1': '正式',
								'2': '暂停',
								'3': '过期',
								'4': '禁用'
							};
							
							const { value: status } = await ElMessageBox.prompt('请选择状态：\n0: 试用\n1: 正式\n2: 暂停\n3: 过期\n4: 禁用', '修改状态', {
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								inputPattern: /^[0-4]$/,
								inputErrorMessage: '请输入有效的状态值（0-4）'
							});
							
							if (status !== undefined) {
								try {
									await updateTenantStatus(row.id, parseInt(status));
									ElMessage.success(`状态已更新为：${statusMap[status]}`);
									// 刷新表格数据
									crudExpose.doRefresh();
								} catch (error) {
									ElMessage.error('状态更新失败');
								}
							}
						}
					},
				},
			},
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				search:{
					title: '关键字搜索',
					search: { show: true,type: 'input', },
					type: 'input',
					form: {
						component: { placeholder: '请输入' },
						show:false},
					column: {show:false}
				},
				schema_name: {
					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 },
				},
				
				contact_name: {
					title: '联系人',
					type: 'input',
					search: { show: true },
					form: {
						rules: [{ required: true, message: '联系人必填' }],
						component: { placeholder: '请输入联系人姓名' },
					},
					column: { minWidth: 100 },
				},
				contact_phone: {
					title: '联系电话',
					type: 'input',
					search: { show: true },
					form: {
						rules: [
							{ required: true, message: '联系电话必填' },
							{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
						],
						component: { placeholder: '请输入联系电话' },
					},
					column: { minWidth: 120 },
				},
				contact_email: {
					title: '联系邮箱',
					type: 'input',
					search: { show: true },
					form: {
						rules: [
							{ required: true, message: '联系邮箱必填' },
							{ type: 'email', message: '请输入正确的邮箱地址' }
						],
						component: { placeholder: '请输入联系邮箱' },
					},
					column: { minWidth: 150 },
				},
				/* domain_name: {
					title: '域名',
					type: 'input',
					search: { show: true },
					form: {
						rules: [
							{ required: false, message: '域名必填' },
							{ pattern: /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/, message: '请输入正确的域名格式' }
						],
						component: { placeholder: '请输入域名' },
					},
					column: { minWidth: 180 },
				}, */
				admin_user: {
					title: '管理员信息',
					type: 'group',
					form: {
						show:false,
						group: false,
					},
					column: { show: false },
					children: {
						'admin_user.username': {
							title: '管理员账号',
							type: 'input',
							form: {
								show:false,
								rules: [{ required: true, message: '管理员账号必填' }],
								component: { placeholder: '请输入管理员账号' },
							},
						},
						'admin_user.password': {
							title: '管理员密码',
							type: 'password',
							form: {
								show:false,
								rules: [
									{ required: true, message: '管理员密码必填' },
									{ min: 6, message: '密码长度不能小于6位' }
								],
								component: { 
									placeholder: '请输入管理员密码',
									showPassword: true,
								},
							},
						},
						'admin_user.name': {
							title: '管理员姓名',
							type: 'input',
							form: {
								show:false,
								rules: [{ required: true, message: '管理员姓名必填' }],
								component: { placeholder: '请输入管理员姓名' },
							},
						},
						'admin_user.email': {
							title: '管理员邮箱',
							type: 'input',
							form: {
								show:false,
								rules: [
									{ required: true, message: '管理员邮箱必填' },
									{ type: 'email', message: '请输入正确的邮箱地址' }
								],
								component: { placeholder: '请输入管理员邮箱' },
							},
						},
					},
				},
				/* 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: '试用中' },
							{value:3,label:'已停用'},
							{value:4,label:'禁用'}
						]
					}),
				},
				/* published_jobs_count: {
					title: '岗位数',
					type: 'number',
					column: { minWidth: 90 },
					
				}, */
				/* usageCount: {
					title: '使用次数',
					type: 'number',
					column: { minWidth: 100 },
				}, */
				update_datetime: {
					title: '数据更新时间',
					type: 'datetime',
					column: { minWidth: 150,show:false },
					form:{
						show:false
					}
				},
				description: {
					title: '商户描述',
					type: 'textarea',
					form: {
						component: { 
							placeholder: '请输入商户描述',
							rows: 3,
						},
					},
					column: { minWidth: 180 },
				},
			},
		},
	};
}; 