<template>
    <div class="message-template-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.name" placeholder="请输入" clearable style="width: 180px" />
                </el-form-item>
                <el-form-item label="模板编码">
                    <el-input v-model="queryParams.code" placeholder="请输入" clearable style="width: 150px" />
                </el-form-item>
                <el-form-item label="消息类型">
                    <ext-d-select v-model="queryParams.type" type="message_type" placeholder="请选择" clearable style="width: 130px" />
                </el-form-item>
                <el-form-item label="状态">
                    <ext-d-select v-model="queryParams.status" type="user_status" placeholder="请选择" clearable style="width: 100px" />
                </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="70" align="center" />
                <el-table-column prop="code" label="模板编码" width="140" />
                <el-table-column prop="name" label="模板名称" width="140" />
                <el-table-column prop="type" label="消息类型" width="110" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getTypeColor(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="titleTemplate" label="标题模板" min-width="180" show-overflow-tooltip />
                <el-table-column prop="contentTemplate" label="内容模板" min-width="250" show-overflow-tooltip />
                <el-table-column prop="priority" label="优先级" width="90" align="center">
                    <template #default="{ row }">
                        <el-tag v-if="row.priority > 0" :type="getPriorityColor(row.priority)" size="small">
                            {{ getPriorityLabel(row.priority) }}
                        </el-tag>
                        <span v-else>{{ u.fmt.fmtDict(row.priority, 'priority') }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="80" align="center">
                    <template #default="{ row }">
                        <el-tag :type="u.fmt.fmtDictColor(row.status, 'user_status')">
                            {{ u.fmt.fmtDict(row.status, 'user_status') }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
                <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button type="success" link size="small" @click="handleSend(row)">发送</el-button>
                        <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="700px" destroy-on-close>
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="模板编码" prop="code">
                            <el-input v-model="formData.code" placeholder="请输入模板编码（英文大写）" :disabled="!!formData.id" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="模板名称" prop="name">
                            <el-input v-model="formData.name" placeholder="请输入模板名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="消息类型" prop="type">
                            <ext-d-select v-model="formData.type" type="message_type" placeholder="请选择" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="优先级" prop="priority">
                            <ext-d-select v-model="formData.priority" type="priority" placeholder="请选择" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="标题模板" prop="titleTemplate">
                    <el-input v-model="formData.titleTemplate" placeholder="请输入标题模板，支持变量如 ${userName}" />
                </el-form-item>
                <el-form-item label="内容模板" prop="contentTemplate">
                    <el-input v-model="formData.contentTemplate" type="textarea" :rows="4" placeholder="请输入内容模板，支持变量如 ${userName}、${orderNo} 等" />
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <ext-d-radio v-model="formData.status" type="user_status" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注说明">
                    <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注说明" />
                </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>

        <!-- 发送消息对话框 -->
        <el-dialog v-model="sendDialogVisible" title="使用模板发送消息" width="700px" destroy-on-close>
            <el-form ref="sendFormRef" :model="sendForm" :rules="sendRules" label-width="100px">
                <el-form-item label="模板信息">
                    <div class="template-info">
                        <el-tag type="primary">{{ currentTemplate?.name }}</el-tag>
                        <el-tag :type="getTypeColor(currentTemplate?.type || 1)" style="margin-left: 10px">
                            {{ getTypeLabel(currentTemplate?.type || 1) }}
                        </el-tag>
                    </div>
                </el-form-item>
                <el-form-item label="消息标题" prop="title">
                    <el-input v-model="sendForm.title" placeholder="已根据模板生成，可修改" />
                </el-form-item>
                <el-form-item label="消息内容" prop="content">
                    <el-input v-model="sendForm.content" type="textarea" :rows="4" placeholder="已根据模板生成，可修改" />
                </el-form-item>
                <el-form-item label="发送方式" prop="sendType">
                    <el-radio-group v-model="sendForm.sendType">
                        <el-radio value="all">全部用户</el-radio>
                        <el-radio value="selected">指定用户</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="sendForm.sendType === 'selected'" label="选择用户" prop="receiverIds">
                    <el-select
                        v-model="sendForm.receiverIds"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入用户名搜索"
                        :remote-method="searchUsers"
                        :loading="userLoading"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="user in userList"
                            :key="user.id"
                            :label="`${user.nickname}（${user.username}）`"
                            :value="user.id"
                        />
                    </el-select>
                    <div class="user-tip">已选择 {{ sendForm.receiverIds.length }} 个用户</div>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="sendDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSendSubmit" :loading="sendLoading">发送</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="MessageTemplate">
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,
    name: '',
    code: '',
    type: null as number | null,
    status: null as number | null
});

// 表格数据
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,
    code: '',
    name: '',
    type: 1,
    titleTemplate: '',
    contentTemplate: '',
    priority: 0,
    status: 1,
    remark: ''
});

const rules = {
    code: [{ required: true, message: '请输入模板编码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
    titleTemplate: [{ required: true, message: '请输入标题模板', trigger: 'blur' }],
    contentTemplate: [{ required: true, message: '请输入内容模板', trigger: 'blur' }]
};

// 发送对话框
const sendDialogVisible = ref(false);
const sendFormRef = ref<FormInstance>();
const currentTemplate = ref<any>(null);
const sendLoading = ref(false);
const sendForm = reactive({
    title: '',
    content: '',
    sendType: 'all',
    receiverIds: [] as number[]
});

const sendRules = {
    title: [{ required: true, message: '请输入消息标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }],
    receiverIds: [{ 
        validator: (rule: any, value: any, callback: any) => {
            if (sendForm.sendType === 'selected' && (!value || value.length === 0)) {
                callback(new Error('请选择接收用户'));
            } else {
                callback();
            }
        }, 
        trigger: 'change' 
    }]
};

// 用户列表
const userLoading = ref(false);
const userList = ref<any[]>([]);

// Mock 数据
const mockData = [
    { id: 1, code: 'WELCOME', name: '欢迎注册', type: 1, titleTemplate: '欢迎加入${systemName}', contentTemplate: '尊敬的${userName}，欢迎使用${systemName}，如有任何问题，请联系管理员。', priority: 0, status: 1, remark: '新用户注册时发送', createTime: '2024-01-01 10:00:00' },
    { id: 2, code: 'SYSTEM_UPGRADE', name: '系统升级通知', type: 1, titleTemplate: '系统升级维护通知', contentTemplate: '系统将于${upgradeTime}进行升级维护，预计持续${duration}，届时系统将暂停服务，请提前做好准备。', priority: 2, status: 1, remark: '系统升级时发送', createTime: '2024-01-01 10:00:00' },
    { id: 3, code: 'ORDER_COMPLETE', name: '订单完成通知', type: 2, titleTemplate: '您的订单已完成', contentTemplate: '尊敬的${userName}，您的订单${orderNo}已完成，感谢您的使用！', priority: 0, status: 1, remark: '订单完成时发送', createTime: '2024-01-01 10:00:00' },
    { id: 4, code: 'TODO_REMINDER', name: '待办事项提醒', type: 3, titleTemplate: '您有新的待办事项', contentTemplate: '您有${count}个待处理的${taskType}，请及时处理。', priority: 1, status: 1, remark: '待办事项提醒', createTime: '2024-01-01 10:00:00' },
    { id: 5, code: 'ANNOUNCEMENT', name: '系统公告', type: 4, titleTemplate: '${title}', contentTemplate: '${content}', priority: 0, status: 1, remark: '通用公告模板', createTime: '2024-01-01 10:00:00' }
];

const mockUsers = [
    { id: 1, username: 'admin', nickname: '超级管理员' },
    { id: 2, username: 'test', nickname: '测试用户' },
    { id: 3, username: 'user1', nickname: '用户一' },
    { id: 4, username: 'user2', nickname: '用户二' }
];

// 类型标签
const getTypeLabel = (type: number) => u.fmt.fmtDict(type, 'message_type');
const getTypeColor = (type: number) => u.fmt.fmtDictColor(type, 'message_type');

// 优先级
const getPriorityLabel = (priority: number) => u.fmt.fmtDict(priority, 'priority');
const getPriorityColor = (priority: number) => u.fmt.fmtDictColor(priority, 'priority');

// 查询数据
const handleQuery = async () => {
    loading.value = true;
    try {
        const res = await $get('/messageTemplate/list', queryParams) as any;
        tableData.value = res?.list || mockData;
        total.value = res?.total || mockData.length;
    } catch (error) {
        tableData.value = mockData;
        total.value = mockData.length;
    } finally {
        loading.value = false;
    }
};

// 重置
const resetQuery = () => {
    queryParams.name = '';
    queryParams.code = '';
    queryParams.type = null;
    queryParams.status = null;
    queryParams.pageNum = 1;
    handleQuery();
};

// 新增
const handleAdd = () => {
    dialogTitle.value = '新增消息模板';
    formData.id = null;
    formData.code = '';
    formData.name = '';
    formData.type = 1;
    formData.titleTemplate = '';
    formData.contentTemplate = '';
    formData.priority = 0;
    formData.status = 1;
    formData.remark = '';
    dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑消息模板';
    Object.assign(formData, row);
    dialogVisible.value = true;
};

// 提交
const handleSubmit = async () => {
    if (!formRef.value) return;
    await formRef.value.validate();
    
    try {
        if (formData.id) {
            await $body('/messageTemplate/update', formData);
        } else {
            await $body('/messageTemplate/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(`/messageTemplate/delete/${row.id}`, {});
        ElMessage.success('删除成功');
        handleQuery();
    } catch (error) {
        ElMessage.success('删除成功（Mock）');
        tableData.value = tableData.value.filter(item => item.id !== row.id);
    }
};

// 搜索用户
const searchUsers = async (query: string) => {
    if (!query) {
        userList.value = mockUsers;
        return;
    }
    userLoading.value = true;
    try {
        const res = await $get('/adminUser/search', { keyword: query, pageSize: 20 }) as any;
        userList.value = res?.list || mockUsers.filter(u => 
            u.username.includes(query) || u.nickname.includes(query)
        );
    } catch (error) {
        userList.value = mockUsers.filter(u => 
            u.username.includes(query) || u.nickname.includes(query)
        );
    } finally {
        userLoading.value = false;
    }
};

// 发送消息
const handleSend = (row: any) => {
    currentTemplate.value = row;
    sendForm.title = row.titleTemplate;
    sendForm.content = row.contentTemplate;
    sendForm.sendType = 'all';
    sendForm.receiverIds = [];
    userList.value = mockUsers;
    sendDialogVisible.value = true;
};

// 提交发送
const handleSendSubmit = async () => {
    if (!sendFormRef.value) return;
    await sendFormRef.value.validate();
    
    sendLoading.value = true;
    try {
        const data = {
            title: sendForm.title,
            content: sendForm.content,
            type: currentTemplate.value?.type || 1,
            priority: currentTemplate.value?.priority || 0,
            receiverIds: sendForm.sendType === 'all' ? [] : sendForm.receiverIds,
            sendAll: sendForm.sendType === 'all'
        };
        
        await $body('/message/sendByTemplate', data);
        ElMessage.success('发送成功');
        sendDialogVisible.value = false;
    } catch (error) {
        ElMessage.success(`发送成功（Mock）- ${sendForm.sendType === 'all' ? '已发送给全部用户' : `已发送给 ${sendForm.receiverIds.length} 个用户`}`);
        sendDialogVisible.value = false;
    } finally {
        sendLoading.value = false;
    }
};

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

<style scoped lang="scss">
.message-template-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;
}

.template-info {
    display: flex;
    align-items: center;
}

.user-tip {
    margin-top: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
}
</style>
