<template>
    <div class="app-container">
        <el-card>
            <el-tabs v-model="state.activeTab" @tab-click="handleTabChange">
                <el-tab-pane label="发送邮件" name="send">
                    <el-form
                        ref="formRef"
                        :model="state.form"
                        :rules="state.rules"
                        label-width="100px"
                        style="max-width: 700px"
                    >
                        <el-form-item label="用户UID" prop="memberId">
                            <el-input
                                v-model="state.form.memberId"
                                placeholder="请输入用户UID，多个UID用分号;隔开"
                                clearable
                            />
                        </el-form-item>
                        <el-form-item label="邮件主题" prop="subject">
                            <el-input
                                v-model="state.form.subject"
                                placeholder="请输入邮件主题"
                                clearable
                            />
                        </el-form-item>
                        <el-form-item label="邮件内容" prop="content">
                            <el-input
                                v-model="state.form.content"
                                type="textarea"
                                :rows="10"
                                placeholder="请输入邮件内容（支持HTML）"
                                show-word-limit
                                maxlength="10000"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button
                                type="primary"
                                :loading="state.loading"
                                @click="handleSubmit"
                            >
                                发送邮件
                            </el-button>
                            <el-button @click="handlePreview">预览邮件</el-button>
                            <el-button @click="handleReset">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="发送记录" name="record">
                    <el-form :inline="true" :model="state.queryParams" class="search-form">
                        <el-form-item label="用户UID">
                            <el-input
                                v-model="state.queryParams.memberId"
                                placeholder="请输入用户UID"
                                clearable
                                style="width: 200px"
                                @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="主题关键字">
                            <el-input
                                v-model="state.queryParams.subject"
                                placeholder="请输入主题关键字"
                                clearable
                                style="width: 200px"
                                @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleQuery">查询</el-button>
                            <el-button @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>

                    <el-table
                        v-loading="state.recordLoading"
                        border
                        :data="state.tableData"
                        style="width: 100%"
                    >
                        <el-table-column align="center" label="ID" prop="id" width="80" />
                        <el-table-column align="center" label="用户UID" prop="memberId" width="120" />
                        <el-table-column align="center" label="邮箱" prop="email" min-width="180" />
                        <el-table-column align="center" label="邮件主题" prop="subject" min-width="160" />
                        <el-table-column align="center" label="发送状态" prop="status" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                                    {{ scope.row.status === 1 ? "成功" : "失败" }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="失败原因" prop="failReason" min-width="120" />
                        <el-table-column align="center" label="发送时间" prop="sendTime" width="180" />
                        <el-table-column align="center" label="操作" width="100">
                            <template #default="scope">
                                <el-button type="primary" link @click="viewContent(scope.row)">
                                    查看内容
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination-container">
                        <el-pagination
                            v-if="state.total > 0"
                            background
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="state.total"
                            :page-sizes="[15, 30, 50]"
                            v-model:current-page="state.queryParams.pageNo"
                            v-model:page-size="state.queryParams.pageSize"
                            @size-change="handleQuery"
                            @current-change="handleQuery"
                        />
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 邮件内容弹窗 -->
        <el-dialog v-model="state.contentVisible" title="邮件内容" width="600px">
            <div class="email-content-preview" v-html="state.currentContent"></div>
        </el-dialog>

        <!-- 邮件预览弹窗 -->
        <el-dialog v-model="state.previewVisible" title="邮件预览" width="800px">
            <div class="email-preview-wrapper">
                <div class="preview-label">邮件主题：</div>
                <div class="preview-subject">{{ state.form.subject }}</div>
                <div class="preview-label" style="margin-top: 12px">邮件内容：</div>
                <div class="email-content-preview" v-html="state.previewHtml"></div>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts">
name: "sendEmail";
</script>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import { sendEmail, emailSendRecordList } from "@/api/messageCenter/index";
import { ElMessage } from "element-plus";

const formRef = ref();

const state = reactive({
    activeTab: "send" as string,
    loading: false,
    recordLoading: false,
    form: {
        memberId: "" as number | string,
        subject: "",
        content: "",
    },
    rules: {
        memberId: [{ required: true, message: "请输入用户UID", trigger: "blur" }],
        subject: [{ required: true, message: "请输入邮件主题", trigger: "blur" }],
        content: [{ required: true, message: "请输入邮件内容", trigger: "blur" }],
    },
    queryParams: {
        memberId: "",
        subject: "",
        pageNo: 1,
        pageSize: 15,
    },
    tableData: [] as any[],
    total: 0,
    contentVisible: false,
    currentContent: "",
    previewVisible: false,
    previewHtml: "",
});

const handleSubmit = () => {
    formRef.value.validate((valid: boolean) => {
        if (!valid) return;

        // Support multiple UIDs separated by semicolons
        const memberIds = String(state.form.memberId)
            .split(";")
            .map((id: string) => id.trim())
            .filter((id: string) => id.length > 0);

        if (memberIds.length === 0) {
            ElMessage.error("请输入有效的用户UID");
            return;
        }

        state.loading = true;

        const promises = memberIds.map((memberId: string) =>
            sendEmail({
                memberId: Number(memberId),
                subject: state.form.subject,
                content: state.form.content,
            })
        );

        Promise.all(promises)
            .then((results: any[]) => {
                const successCount = results.filter((r: any) => r.code === 0).length;
                const failCount = results.length - successCount;

                if (failCount === 0) {
                    ElMessage.success(`邮件发送成功，共发送 ${successCount} 封`);
                } else {
                    ElMessage.warning(`已发送 ${successCount} 封，${failCount} 封失败`);
                }

                handleReset();
                state.activeTab = "record";
                handleQuery();
            })
            .catch(() => {
                ElMessage.error("发送失败");
            })
            .finally(() => {
                state.loading = false;
            });
    });
};

const handleReset = () => {
    state.form.memberId = "";
    state.form.subject = "";
    state.form.content = "";
    formRef.value?.clearValidate();
};

const handleQuery = () => {
    state.recordLoading = true;
    const params: Record<string, any> = {
        pageNo: state.queryParams.pageNo,
        pageSize: state.queryParams.pageSize,
    };
    if (state.queryParams.memberId) {
        params.memberId = Number(state.queryParams.memberId);
    }
    if (state.queryParams.subject) {
        params.subject = state.queryParams.subject;
    }
    emailSendRecordList(params)
        .then((res: any) => {
            if (res.code == 0 && res.data) {
                state.tableData = res.data.content || [];
                state.total = res.data.totalElements || 0;
            }
        })
        .finally(() => {
            state.recordLoading = false;
        });
};

const resetQuery = () => {
    state.queryParams.memberId = "";
    state.queryParams.subject = "";
    state.queryParams.pageNo = 1;
    handleQuery();
};

const handleTabChange = (tab: any) => {
    if (tab.props.name === "record") {
        handleQuery();
    }
};

const handlePreview = () => {
    formRef.value.validate((valid: boolean) => {
        if (!valid) return;
        // Use the same newline-to-br conversion as the backend template
        const htmlContent = state.form.content.replace(/\r\n/g, "<br>").replace(/\n/g, "<br>");
        state.previewHtml = htmlContent;
        state.previewVisible = true;
    });
};

const viewContent = (row: any) => {
    state.currentContent = (row.content || "").replace(/\n/g, "<br>");
    state.contentVisible = true;
};
</script>

<style lang="scss" scoped>
.search-form {
    margin-bottom: 16px;
}
.pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}
.email-content-preview {
    max-height: 500px;
    overflow-y: auto;
    padding: 16px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}
.preview-label {
    font-weight: 600;
    color: #606266;
}
.preview-subject {
    font-size: 16px;
    color: #303133;
    margin-top: 4px;
}
</style>
