<template>
    <div class="system-notice-container">
        <!-- 搜索栏 -->
        <el-card class="search-card" shadow="never">
            <el-form :inline="true" :model="queryParams" class="search-form">
                <el-form-item label="标题">
                    <el-input v-model="queryParams.title" placeholder="请输入标题" clearable style="width: 200px" />
                </el-form-item>
                <el-form-item label="状态">
                    <ext-d-select v-model="queryParams.status" type="notice_status" placeholder="请选择" clearable style="width: 150px" />
                </el-form-item>
                <el-form-item label="目标">
                    <ext-d-select v-model="queryParams.target" type="notice_target" placeholder="请选择" clearable style="width: 150px" />
                </el-form-item>
                <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-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="80" align="center" />
                <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
                <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
                <el-table-column prop="adminUserName" label="发布者" width="120" align="center" />
                <el-table-column prop="status" label="状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="target" label="目标" width="100" align="center">
                    <template #default="{ row }">
                        {{ getTargetLabel(row.target) }}
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间" width="170" align="center" />
                <el-table-column prop="endTime" label="结束时间" width="170" align="center" />
                <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
                <el-table-column label="操作" width="150" 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="600px" destroy-on-close>
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
                <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="5" placeholder="请输入公告内容" />
                </el-form-item>
                <el-form-item label="目标" prop="target">
                    <el-checkbox-group v-model="formData.targetList">
                        <el-checkbox label="client">客户端</el-checkbox>
                        <el-checkbox label="merchant">商户端</el-checkbox>
                    </el-checkbox-group>
                    <span style="color: #999; font-size: 12px; margin-left: 10px;">不选则默认全部</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';
import u from '/@/utils/u';

// 查询参数
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: '',
    stationIdList: [] as number[],
    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, 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, 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, startTime: '2024-01-01 00:00:00', endTime: '2024-01-10 23:59:59', createTime: '2024-01-01 08:00:00' }
];

// 获取状态标签
const getStatusLabel = (status: number) => u.fmt.fmtDict(status, 'notice_status');
const getStatusType = (status: number) => u.fmt.fmtDictColor(status, 'notice_status');
const getTargetLabel = (target: string) => u.fmt.fmtDict(target, 'notice_target');

// 查询数据
const handleQuery = async () => {
    loading.value = true;
    try {
        const res = await $get('/notice/list', queryParams) as any;
        tableData.value = res?.list || mockData;
        total.value = res?.total || mockData.length;
    } catch (error) {
        // 使用 Mock 数据
        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 {
        // 将 targetList 转为 target 字符串
        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 {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

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

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