<template>
	<div class="system-role-container">
		<el-card shadow="hover">
			<!-- 搜索和操作区域 -->
			<div class="system-user-search mb15">
				<el-form :inline="true">
					<el-form-item>
						<el-button size="default" type="success" @click="handleAdd">
							<el-icon><FolderAdd /></el-icon>
							新增话术
						</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 数据表格 -->
			<el-table :data="tableData.data" v-loading="tableData.loading" style="width: 100%">
				<el-table-column type="index" label="序号" width="60" align="center" />
				<el-table-column prop="tag" label="标签" show-overflow-tooltip min-width="120" />
				<el-table-column prop="creator" label="创建人" show-overflow-tooltip min-width="100" />
				<el-table-column prop="modifier" label="修改人" show-overflow-tooltip min-width="100" />
				<el-table-column prop="createdAt" label="创建时间" show-overflow-tooltip min-width="140" />
				<el-table-column prop="updatedAt" label="修改时间" show-overflow-tooltip min-width="140" />
				<el-table-column label="操作" width="200" align="center" fixed="right">
					<template #default="{ row }">
						<el-button size="small" text type="primary" @click="handleEdit(row)">
							<el-icon><EditPen /></el-icon>修改
						</el-button>
						<el-button size="small" text type="danger" @click="handleDelete(row)">
							<el-icon><DeleteFilled /></el-icon>删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

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

		<!-- 编辑组件 -->
		<EditRole ref="editRoleRef" @success="handleSuccess" />
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { FolderAdd, EditPen, DeleteFilled } from '@element-plus/icons-vue';
import EditRole from './component/editRole.vue';
import Pagination from '/@/components/pagination/index.vue';
import { getscriptList, deletescript } from '/@/api/customerService/script';

// ==================== 类型定义 ====================
interface ScriptItem {
	id: string;
	tag: string;
	creator: string;
	modifier: string;
	createdAt: string;
	updatedAt: string;
	content?: string;
}

interface TableParams {
	pageNum: number;
	pageSize: number;
}

interface TableState {
	data: ScriptItem[];
	total: number;
	loading: boolean;
	param: TableParams;
}

// ==================== 响应式数据 ====================
const editRoleRef = ref<InstanceType<typeof EditRole>>();
const tableData = reactive<TableState>({
	data: [],
	total: 0,
	loading: false,
	param: {
		pageNum: 1,
		pageSize: 10,
	},
});

// ==================== 方法定义 ====================

/**
 * 加载表格数据
 */
const loadTableData = async () => {
	try {
		tableData.loading = true;

		const response = await getscriptList(tableData.param);
		const { list = [], total = 0 } = response.data || {};

		tableData.data = list;
		tableData.total = total;
	} catch (error) {
		console.error('加载数据失败:', error);
		ElMessage.error('数据加载失败');
		tableData.data = [];
		tableData.total = 0;
	} finally {
		tableData.loading = false;
	}
};

/**
 * 新增话术
 */
const handleAdd = () => {
	editRoleRef.value?.openDialog();
};

/**
 * 编辑话术
 */
const handleEdit = (row: ScriptItem) => {
	editRoleRef.value?.openDialog(row);
};

/**
 * 删除话术
 */
const handleDelete = async (row: ScriptItem) => {
	try {
		await ElMessageBox.confirm(`确定要删除话术「${row.tag}」吗？此操作不可恢复。`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		});
		console.log(row, 'row');
		await deletescript({ id: row.id }).then((res) => {});
		ElMessage.success('删除成功');

		// 重新加载数据
		await loadTableData();
	} catch (error) {
		if (error !== 'cancel') {
			console.error('删除失败:', error);
			ElMessage.error('删除失败');
		}
	}
};

/**
 * 操作成功回调
 */
const handleSuccess = () => {
	loadTableData();
};

/**
 * 处理分页变化
 */
const handleSizeChange = (size: number) => {
	tableData.param.pageSize = size;
	tableData.param.pageNum = 1; // 重置到第一页
	loadTableData();
};

const handleCurrentChange = (current: number) => {
	tableData.param.pageNum = current;
	loadTableData();
};

// ==================== 生命周期 ====================
onMounted(() => {
	loadTableData();
});

// ==================== 暴露方法（可选） ====================
defineExpose({
	reload: loadTableData,
});
</script>

<style scoped lang="scss">
.system-role-container {
	.system-user-search {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.mb15 {
		margin-bottom: 15px;
	}
}

// 响应式适配
@media (max-width: 768px) {
	.system-user-search {
		flex-direction: column;
		align-items: flex-start;

		.el-form-item {
			margin-bottom: 10px;
		}
	}
}
</style>
