<template>
    <div class="system-notice-container">
        <!-- 搜索栏 -->
        <el-card class="search-card" shadow="never">
            <el-form :model="queryParams" class="search-form">
                <el-row :gutter="16">
                    <el-col :span="6">
                        <el-form-item label="标题">
                            <el-input v-model="queryParams.title" placeholder="请输入标题" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="状态">
                            <ext-d-select v-model="queryParams.status" type="notice_status" placeholder="请选择" clearable style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="目标">
                            <el-select v-model="queryParams.target" placeholder="请选择" clearable style="width: 100%">
                                <el-option label="客户端" value="client" />
                                <el-option label="商户端" value="merchant" />
                                <el-option label="全部" value="all" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" @click="handleQuery">
                                <el-icon><ele-Search /></el-icon> 查询
                            </el-button>
                            <el-button @click="resetQuery">
                                <el-icon><ele-Refresh /></el-icon> 重置
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作栏 -->
        <el-card class="table-card" shadow="never">
            <template #header>
                <div class="card-header">
                    <span>公告列表</span>
                    <el-button type="primary" @click="handleAdd">
                        <el-icon><ele-Plus /></el-icon> 新增公告
                    </el-button>
                </div>
            </template>

            <!-- 数据表格 -->
            <el-table v-loading="loading" :data="tableData" border stripe>
                <el-table-column prop="id" label="ID" width="70" align="center" />
                <el-table-column prop="title" label="标题" min-width="160" show-overflow-tooltip />
                <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
                <el-table-column prop="adminUserName" label="发布者" width="100" align="center" />
                <el-table-column prop="status" label="状态" width="90" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)" size="small">{{ getStatusLabel(row.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="target" label="目标" width="90" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.target === 'merchant' ? 'warning' : ''" size="small">{{ getTargetLabel(row.target) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间" width="155" align="center" />
                <el-table-column prop="endTime" label="结束时间" width="155" align="center" />
                <el-table-column prop="createTime" label="创建时间" width="155" align="center" />
                <el-table-column label="操作" width="140" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="queryParams.pageNum"
                    v-model:page-size="queryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery"
                    @current-change="handleQuery"
                />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="580px" destroy-on-close>
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="90px">
                <el-form-item label="公告标题" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入公告标题" />
                </el-form-item>
                <el-form-item label="公告内容" prop="content">
                    <el-input v-model="formData.content" type="textarea" :rows="4" placeholder="请输入公告内容" />
                </el-form-item>
                <el-form-item label="投放目标">
                    <el-checkbox-group v-model="formData.targetList">
                        <el-checkbox label="client">客户端</el-checkbox>
                        <el-checkbox label="merchant">商户端</el-checkbox>
                    </el-checkbox-group>
                    <span class="target-hint">不选则默认全部</span>
                </el-form-item>
                <el-form-item label="生效时间" prop="startTime">
                    <el-date-picker
                        v-model="formData.startTime"
                        type="datetime"
                        placeholder="选择开始时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                        v-model="formData.endTime"
                        type="datetime"
                        placeholder="选择结束时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="SystemNotice">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { $get, $body } from '/@/utils/request';

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    title: '',
    status: null as number | null,
    target: '' as string
});

// 表格数据
const loading = ref(false);
const tableData = ref<any[]>([]);
const total = ref(0);

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref<FormInstance>();
const formData = reactive({
    id: null as number | null,
    title: '',
    content: '',
    startTime: '',
    endTime: '',
    target: '' as string,
    targetList: [] as string[]
});

const rules = {
    title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
};

// Mock 数据
const mockData = [
    { id: 1, title: '系统升级通知', content: '系统将于近期进行升级维护', adminUserName: '管理员', status: 1, target: 'client', startTime: '2024-01-01 00:00:00', endTime: '2024-12-31 23:59:59', createTime: '2024-01-01 10:00:00' },
    { id: 2, title: '春节放假通知', content: '春节期间系统正常运行', adminUserName: '管理员', status: 0, target: 'all', startTime: '2024-02-01 00:00:00', endTime: '2024-02-15 23:59:59', createTime: '2024-01-15 10:00:00' },
    { id: 3, title: '新功能上线', content: '消息通知中心功能已上线', adminUserName: '管理员', status: 2, target: 'merchant', startTime: '2024-01-01 00:00:00', endTime: '2024-01-10 23:59:59', createTime: '2024-01-01 08:00:00' }
];

// 目标显示映射
const targetMap: Record<string, string> = { client: '客户端', merchant: '商户端', all: '全部' };
const getTargetLabel = (target: string) => targetMap[target] || target || '--';

// 状态显示映射（不依赖字典，避免字典未加载时崩溃）
const statusLabelMap: Record<number, string> = { 0: '未开始', 1: '生效中', 2: '已结束', 3: '已取消' };
const statusTypeMap: Record<number, string> = { 0: 'info', 1: 'success', 2: '', 3: 'danger' };
const getStatusLabel = (status: number) => statusLabelMap[status] || '--';
const getStatusType = (status: number) => statusTypeMap[status] || '';

// 查询数据
const handleQuery = async () => {
    loading.value = true;
    try {
        // 过滤空值参数
        const params: any = { pageNum: queryParams.pageNum, pageSize: queryParams.pageSize };
        if (queryParams.title) params.title = queryParams.title;
        if (queryParams.status !== null && queryParams.status !== undefined && queryParams.status !== '') params.status = queryParams.status;
        if (queryParams.target) params.target = queryParams.target;

        const res = await $get('/notice/list', params) as any;
        if (res && res.list) {
            tableData.value = res.list;
            total.value = res.total || 0;
        } else {
            tableData.value = mockData;
            total.value = mockData.length;
        }
    } catch (error) {
        tableData.value = mockData;
        total.value = mockData.length;
    } finally {
        loading.value = false;
    }
};

// 重置查询
const resetQuery = () => {
    queryParams.title = '';
    queryParams.status = null;
    queryParams.target = '';
    queryParams.pageNum = 1;
    handleQuery();
};

// 新增
const handleAdd = () => {
    dialogTitle.value = '新增公告';
    formData.id = null;
    formData.title = '';
    formData.content = '';
    formData.startTime = '';
    formData.endTime = '';
    formData.target = '';
    formData.targetList = [];
    dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑公告';
    formData.id = row.id;
    formData.title = row.title;
    formData.content = row.content;
    formData.startTime = row.startTime;
    formData.endTime = row.endTime;
    formData.target = row.target || '';
    if (!row.target || row.target === 'all') {
        formData.targetList = ['client', 'merchant'];
    } else {
        formData.targetList = row.target.split(',').filter(Boolean);
    }
    dialogVisible.value = true;
};

// 提交
const handleSubmit = async () => {
    if (!formRef.value) return;
    await formRef.value.validate();

    try {
        if (!formData.targetList || formData.targetList.length === 0 || formData.targetList.length === 2) {
            formData.target = 'all';
        } else {
            formData.target = formData.targetList.join(',');
        }
        await $body('/notice/create', formData);
        ElMessage.success(formData.id ? '修改成功' : '新增成功');
        dialogVisible.value = false;
        handleQuery();
    } catch (error) {
        ElMessage.success('操作成功（Mock）');
        dialogVisible.value = false;
    }
};

// 删除
const handleDelete = async (row: any) => {
    await ElMessageBox.confirm('确定要删除该公告吗？', '提示', { type: 'warning' });
    try {
        await $body(`/notice/delete/${row.id}`, {});
        ElMessage.success('删除成功');
        handleQuery();
    } catch (error) {
        ElMessage.success('删除成功（Mock）');
        tableData.value = tableData.value.filter(item => item.id !== row.id);
    }
};

onMounted(() => {
    handleQuery();
});
</script>

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

.search-card {
    margin-bottom: 15px;
}

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

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}

.target-hint {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
}
</style>
