import * as api from './api';
import { dict, UserPageQuery, AddReq, DelReq, EditReq, compute, CreateCrudOptionsProps, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import { dictionary } from '/@/utils/dictionary';
import { successMessage } from '/@/utils/message';
import { auth } from '/@/utils/authFunction';
import tableSelector from '/@/components/tableSelector/index.vue';
import { shallowRef, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

interface DigitalHumanForm {
	id?: number;
	name: string;
	description?: string;
	avatar_url: string;
	template_video_url?: string;
	status: number;
	config: {
		style: string;
		voice_id: string;
	} | string;
	creator_name?: string;
	create_datetime?: string;
	update_datetime?: string;
}

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);
	};

	/**
	 * 生成预览视频
	 */
	const generatePreviewVideo = async (row: DigitalHumanForm) => {
		try {
			ElMessageBox.confirm('确定要生成预览视频吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'info',
			}).then(async () => {
				const loading = ElMessage({
					message: '正在生成预览视频，请稍候...',
					type: 'info',
					duration: 0
				});
				
				try {
					const result = await api.createDemo({
						digital_human_id: row.id,
						text: '您好，我是您的数字人助手，很高兴为您服务！'
					});
					
					loading.close();
					console.log(result);
					if (result.code === 2000) {
						ElMessage.success('数字人演示视频生成任务已提交！');
						// 刷新列表
						crudExpose.doRefresh();
					} else {
						ElMessage.error(result.msg || '生成预览视频失败');
					}
				} catch (error) {
					loading.close();
					ElMessage.error('生成预览视频失败，请稍后重试');
					console.error('生成预览视频错误:', error);
				}
			}).catch(() => {
				// 用户取消操作
			});
		} catch (error) {
			console.error('生成预览视频错误:', error);
		}
	};

	/**
	 * 懒加载
	 * @param row
	 * @returns {Promise<unknown>}
	 */
	const loadContentMethod = (tree: any, treeNode: any, resolve: Function) => {
		pageRequest({ pcode: tree.code }).then((res: APIResponseData) => {
			resolve(res.data);
		});
	};

	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,
			},
			actionbar: {
				buttons: {
					add: {
						show: true,
						size: 'small',
						click: () => {
							if (crudExpose && typeof crudExpose.openAdd === 'function') {
								crudExpose.openAdd();
							}
						}
					},
				},
			},
			rowHandle: {
				//固定右侧
				fixed: 'right',
				width: 350,
				buttons: {
					generatePreview: {
						text: '生成预览视频',
						size: 'small',
						type: 'text',
						show: true,
						click: ({ row }) => {
							generatePreviewVideo(row);
						}
					},
					view: {
						iconRight: 'view',
						show: false,
						type: 'text',
						click: ({ row }) => {
							// 查看数字人详情
							// router.push({
							// 	path: '/digitalHuman/detail',
							// 	query: { id: row.id }
							// });
						}
					},
					edit: {
						iconRight: 'Edit',
						type: 'text',
						show: false,
						/* click: ({ row }) => {
							console.log(crudExpose);
					
							//crudExpose.emit('edit-digital-human', row);
						} */
					},
					remove: {
						iconRight: 'Delete',
						type: 'text',
						show: false//	auth('digitalHuma:Delete'),
					},
					
				},
			},
			pagination: {
				show: true,
			},
			table: {
				rowKey: 'id',
			},
			search: {
				show: true,
				layout: 'auto',
				autoSearch:false,
				buttons: {
					search: {
						size: 'small', // 设置查询按钮大小为small
					},
					reset: {
						size: 'small', // 设置重置按钮大小为small
					}
				}
			},
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				name: {
					title: '数字人名称',
					search: {
						show: true,
						component: {
							placeholder: '请输入数字人名称',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'input',
					column: {
						minWidth: 150,
					},
					form: {
						rules: [
							{ required: true, message: '数字人名称为必填项' },
						],
					},
				},
				avatar_url: {
					title: '头像',
					type: 'cropper-uploader',
					form: {
						component: {
							uploader: {
								action: '/api/system/admin_upload/',
								multiple: false,
								limit: 1,
								accept: '.jpg,.png,.jpeg',
								headers: () => {
									return {
										'Authorization': `JWT ${localStorage.getItem('token') || ''}`
									}
								},
								data: {
									tenant_id: '1'
								},
								onSuccessHandle(res: any) {
									// 返回上传后的URL
									return res.data.url;
								},
								beforeUpload(file: File) {
									const isImage = file.type.startsWith('image/');
									const isLt2M = file.size / 1024 / 1024 < 2;
									
									if (!isImage) {
										this.$message.error('只能上传图片文件!');
										return false;
									}
									if (!isLt2M) {
										this.$message.error('图片大小不能超过 2MB!');
										return false;
									}
									return true;
								}
							},
							slots: {
								default: ({modelValue}) => {
									return modelValue ? 
										<img src={modelValue} class="avatar" style="width:100px;height:100px;"/> : 
										<el-icon class="avatar-uploader-icon"><Plus /></el-icon>
								}
							}
						},
						rules: [
							{ required: true, message: '请上传头像' }
						]
					},
					/* column: {
						component: {
							name: 'fs-image',
							style: {width: '50px', height: '50px'},
							props: {
								src: (row) => row.avatar_url,
								preview: true,
								fit: 'cover'
							}
						}
					} */
				},
				template_video_url: {
					title: '模板视频',
					type: 'file-uploader',
					form: {
						component: {
							uploader: {
								action: '/api/system/admin_upload/',
								multiple: false,
								limit: 1,
								accept: '.mp4,.mov,.avi',
								headers: () => {
									return {
										'Authorization': `JWT ${localStorage.getItem('token') || ''}`
									}
								},
								data: {
									tenant_id: '1'
								},
								onSuccessHandle(res: any) {
									return res.data.url;
								},
								beforeUpload(file: File) {
									const isVideo = file.type.startsWith('video/');
									const isLt50M = file.size / 1024 / 1024 < 50;
									
									if (!isVideo) {
										this.$message.error('只能上传视频文件!');
										return false;
									}
									if (!isLt50M) {
										this.$message.error('视频大小不能超过 50MB!');
										return false;
									}
									return true;
								}
							},
							placeholder: '请上传模板视频'
						}
					},
					column: {
						show: false,
						minWidth: 180,
						
					}
				},
				demo_video_url: {
					title: '演示视频',
					type: 'file-uploader',
					column: {
						
						width: 300,
						
					},
					form: {
						show: false,
					},
				},
				status: {
					title: '状态',
					search: {
						show: true,
						component: {
							placeholder: '请选择状态',
						},
						size: 'small',
						col:{ span:3},
					},
					type: 'dict-select',
					column: {
						minWidth: 100,
					},
					dict: dict({
						data: [
							{ value: 1, label: '启用' },
							{ value: 0, label: '禁用' },
						],
					}),
				},
				description: {
					title: '描述',
					search: {
						show: false,
						size: 'small',
						col:{ span:3},
					},
					type: 'textarea',
					column: {
						minWidth: 200,
						showOverflowTooltip: true,
					},
					form: {
						component: {
							span: 24,
						},
					},
				},
				/* config: {
					title: '配置信息',
					type: 'text',
					column: {
						minWidth: 150,
						formatter: (row) => {
							if (row.config) {
								try {
									const config = typeof row.config === 'string' ? JSON.parse(row.config) : row.config;
									return `风格: ${config.style || '-'}, 语音ID: ${config.voice_id || '-'}`;
								} catch (e) {
									return '配置格式错误';
								}
							}
							return '-';
						},
						showOverflowTooltip: true,
					},
					form: {
						component: {
							name: 'el-card',
							header: '配置信息',
							children: {
								style: {
									title: '风格设置',
									value: 'professional',
									component: {
										name: 'el-select',
										options: [
											{ value: 'professional', label: '专业' },
											{ value: 'friendly', label: '友好' },
											{ value: 'serious', label: '严肃' },
											{ value: 'casual', label: '随意' }
										]
									}
								},
								voice_id: {
									title: '语音设置',
									value: 'xiaoming_voice_premium',
									component: {
										name: 'el-select',
										options: [
											{ value: 'xiaoming_voice_premium', label: '小明(高级)' },
											{ value: 'xiaohong_voice_premium', label: '小红(高级)' },
											{ value: 'xiaohong_voice', label: '小红' }
										]
									}
								}
							}
						},
						valueResolve: (form: DigitalHumanForm) => {
							// 将配置对象转换为JSON字符串
							if (form.config && typeof form.config === 'object') {
								form.config = JSON.stringify(form.config);
							}
							return form;
						},
						valueBuilder: (form: DigitalHumanForm) => {
							// 将JSON字符串转换为对象
							if (form.config && typeof form.config === 'string') {
								try {
									form.config = JSON.parse(form.config);
								} catch (e) {
									console.error('配置解析错误:', e);
									form.config = { style: 'professional', voice_id: 'xiaoming_voice_premium' };
								}
							} else if (!form.config) {
								form.config = { style: 'professional', voice_id: 'xiaoming_voice_premium' };
							}
						}
					}
				}, */
				creator_name: {
					title: '创建人',
					type: 'text',
					column: {
						
						minWidth: 120,
					},
					form: {
						show: false,
					},
				},
				create_datetime: {
					title: '创建时间',
					type: 'datetime',
					column: {
						show: false,
						minWidth: 160,
					},
					form: {
						show: false,
					},
				},
				update_datetime: {
					title: '更新时间',
					type: 'datetime',
					column: {
						show: false,
						minWidth: 160,
					},
					form: {
						show: false,
					},
				},
			/* 	operation: {
					title: '操作',
					type: 'button',
					width: '200px',
					buttons: {
						edit: {
							show: false
						},
					},
					columnSlot: true
				} */
			},
		},
	};
};
