<template>
	<div class="system-role-container">
		<el-card shadow="hover">
			<!-- 搜索区域 -->
			<div class="system-user-search mb15">
				<el-form :inline="true">
					<el-form-item label="产品名称">
						<el-input size="default" v-model="tableData.param.name" placeholder="请输入产品名称" class="w-50 m-2" clearable />
					</el-form-item>
					<el-form-item>
						<el-button size="default" type="primary" class="ml10" @click="handleSearch">
							<el-icon>
								<Search />
							</el-icon>
							查询
						</el-button>
						<el-button size="default" type="success" class="ml10" @click="onOpenAddRole">
							<el-icon>
								<FolderAdd />
							</el-icon>
							新增产品
						</el-button>
						<!-- 导入导出按钮 -->
						<el-button size="default" type="warning" class="ml10" @click="onOpenImport">
							<el-icon>
								<Upload />
							</el-icon>
							导入
						</el-button>
						<el-button size="default" type="info" class="ml10" @click="onOpenExport" style="background-color: deeppink; border: 0">
							<el-icon>
								<Download />
							</el-icon>
							导出
						</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 产品表格 -->
			<el-table :data="tableData.data" style="width: 100%" v-loading="tableData.loading">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="name" label="产品名称" show-overflow-tooltip />
				<el-table-column prop="rag_doc_id" label="已上传知识库" show-overflow-tooltip>
					<template #default="{ row }">
						<el-tag :type="row.rag_doc_id ? 'success' : 'info'" effect="light">
							{{ row.rag_doc_id ? '是' : '否' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="creator" label="创建人" show-overflow-tooltip />
				<el-table-column prop="updater" label="修改人" show-overflow-tooltip />
				<el-table-column prop="createdAtString" label="创建时间" show-overflow-tooltip>
					<template #default="{ row }">
						{{ formatTime(row.createdAt) }}
					</template>
				</el-table-column>
				<el-table-column prop="updatedAtString" label="修改时间" show-overflow-tooltip>
					<template #default="{ row }">
						{{ formatTime(row.updatedAt) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220">
					<template #default="scope">
						<el-button size="small" text type="primary" class="op-btn-add" @click="onTrainProduct(scope.row)">
							<el-icon><Mic /></el-icon>上传
						</el-button>
						<el-button size="small" text type="primary" class="op-btn-edit" @click="onOpenEditRole(scope.row)">
							<el-icon><EditPen /></el-icon>修改
						</el-button>
						<el-button size="small" text type="primary" class="op-btn-del" @click="onRowDel(scope.row)">
							<el-icon><Delete /></el-icon>删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页组件 -->
			<pagination
				v-show="tableData.total > 0"
				:total="tableData.total"
				v-model:page="tableData.param.pageNum"
				v-model:limit="tableData.param.pageSize"
				@pagination="getProductList"
			/>
		</el-card>

		<!-- 编辑对话框组件 -->
		<EditRole ref="editRoleRef" @refresh="getProductList" />

		<!-- 导入导出对话框组件 -->
		<ImportDialog ref="importDialogRef" @refresh="getProductList" />
		<ExportDialog ref="exportDialogRef" />
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Search, FolderAdd, Upload, Download, Mic, EditPen, Delete } from '@element-plus/icons-vue';
import EditRole from '/@/views/customerService/product/component/editRole.vue';
import ImportDialog from '/@/views/customerService/product/component/importDialog.vue';
import ExportDialog from '/@/views/customerService/product/component/exportDialog.vue';
import { deleteProduct, getList } from '/@/api/customerService/product';

/**
 * 产品数据接口
 */
interface ProductData {
	id: number;
	status: number;
	listOrder: number;
	name: string;
	creator: string;
	updater: string;
	remark: string;
	dataScope: number;
	createdAt: string;
	updatedAt: string;
	rag_doc_id?: string; // 添加缺失的属性
	description?: string; // 产品详情
}

/**
 * 查询参数接口
 */
interface QueryParam {
	name: string;
	roleStatus: string;
	pageNum: number;
	pageSize: number;
}

/**
 * 表格状态接口
 */
interface TableState {
	data: ProductData[];
	total: number;
	loading: boolean;
	param: QueryParam;
}

// 响应式状态
const tableData = reactive<TableState>({
	data: [],
	total: 0,
	loading: false,
	param: {
		name: '',
		roleStatus: '',
		pageNum: 1,
		pageSize: 10,
	},
});

// 组件引用
const editRoleRef = ref<InstanceType<typeof EditRole>>();
const importDialogRef = ref<InstanceType<typeof ImportDialog>>();
const exportDialogRef = ref<InstanceType<typeof ExportDialog>>();

/**
 * 获取产品列表
 */
const getProductList = async () => {
	try {
		tableData.loading = true;
		const res = await getList(tableData.param);

		if (res.data?.list) {
			tableData.data = res.data.list;
			tableData.total = res.data.total;
		}
	} catch (error) {
		console.error('获取产品列表失败:', error);
		// 错误已由请求拦截器统一处理，此处不再重复提示
	} finally {
		tableData.loading = false;
	}
};

/**
 * 格式化时间显示
 */
const formatTime = (time: string | number | Date): string => {
	if (!time) return '-';

	try {
		let date: Date;

		if (time instanceof Date) {
			date = time;
		} else if (typeof time === 'string') {
			date = new Date(time);
		} else {
			let timestamp = time;
			if (timestamp > 1000000000000) {
				// 已经是毫秒时间戳
			} else if (timestamp > 1000000000) {
				// 秒时间戳，转换为毫秒
				timestamp = timestamp * 1000;
			}
			date = new Date(timestamp);
		}

		if (isNaN(date.getTime())) {
			return String(time);
		}

		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	} catch (error) {
		console.error('时间格式化错误:', error);
		return String(time);
	}
};

/**
 * 训练产品
 */
const onTrainProduct = async (row: ProductData) => {
	try {
		await ElMessageBox.confirm(`确定要训练产品："${row.name}"吗？`, '训练确认', {
			confirmButtonText: '开始训练',
			cancelButtonText: '取消',
			type: 'warning',
		});

		ElMessage.success(`产品"${row.name}"训练任务已开始，请稍后查看训练结果`);
	} catch (error) {
		// 用户取消操作
		console.log('用户取消训练操作');
	}
};

/**
 * 处理搜索
 */
const handleSearch = () => {
	tableData.param.pageNum = 1;
	getProductList();
};

/**
 * 打开新增产品对话框
 */
const onOpenAddRole = () => {
	editRoleRef.value?.openDialog();
};

/**
 * 打开编辑产品对话框
 */
const onOpenEditRole = (row: ProductData) => {
	editRoleRef.value?.openDialog(row);
};

/**
 * 打开导入对话框
 */
const onOpenImport = () => {
	importDialogRef.value?.openDialog();
};

/**
 * 打开导出对话框
 */
const onOpenExport = () => {
	exportDialogRef.value?.openDialog(tableData.param.name);
};

/**
 * 删除产品
 */
const onRowDel = async (row: ProductData) => {
	try {
		await ElMessageBox.confirm(`此操作将永久删除产品："${row.name}"，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		});

		await deleteProduct({ id: row.id });
		ElMessage.success('删除成功');
		await getProductList();
	} catch (error) {
		// 用户取消操作
		console.log('用户取消删除操作');
	}
};

// 页面加载时初始化数据
onMounted(() => {
	getProductList();
});
</script>

<style scoped lang="scss">
.system-role-container {
	padding: 20px;
}

.system-user-search {
	margin-bottom: 15px;

	:deep(.el-form-item) {
		margin-bottom: 0;
	}
}

.mb15 {
	margin-bottom: 15px;
}

.ml10 {
	margin-left: 10px;
}

.w-50 {
	width: 240px;
}

:deep(.el-table) {
	.el-button {
		margin: 0 2px;

		&.el-button--small {
			padding: 6px 8px;
		}
	}
}

:deep(.pagination-container) {
	margin-top: 15px;
	padding: 10px 0;
}
</style>
