<template>
    <div class="page">
        <div class="title">{{ title }}</div>
        <div class="query adfacjb">
            <el-input placeholder="请输入名称" prefix-icon="el-icon-search" v-model="queryParams.name" style="flex: 1;padding-right: 20px;" @keyup.enter.native="getList"></el-input>
            <el-button type="primary" icon="el-icon-plus" @click="handleAddModel">新增</el-button>
            <el-button type="primary" icon="el-icon-setting" @click="handleSetModel">邮件配置</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDeleteMore">删除</el-button>
        </div>
        <div class="content">
            <el-table ref="multipleTable" @selection-change="handleSelectionChange" :data="modelList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无邮件模板" max-height="578px">
                <el-table-column
                    type="selection"
                    width="55">
                </el-table-column>
                <el-table-column label="名称" prop="name"></el-table-column>
                <el-table-column label="主题" prop="subject"></el-table-column>
                <el-table-column label="发送时间" prop="createDate" sortable></el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button link type="text" size="mini" @click="handleEditModel(scope.row)">修改</el-button>
                        <!-- <el-button link type="text" size="mini" @click="handleSendEamil(scope.row)">发送邮件</el-button> -->
                        <el-button link type="text" size="mini" @click="handleDeleteModel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row style="display: flex;justify-content: center;">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryParams.page"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    v-show="total > 0">
                </el-pagination>
            </el-row>
        </div>
        <el-dialog width="60%" :visible.sync="show" :title="modelTitle" @close="cancel">
            <el-form ref="modelRef" :model="modelForm" :rules="modelRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="modelForm.name" placeholder="名称"></el-input>
                </el-form-item>
                <el-form-item label="主题" prop="subject">
                    <el-input v-model="modelForm.subject" placeholder="主题"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <template>
                        <div style="border: 1px solid #ccc;">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editor"
                                :defaultConfig="toolbarConfig"
                                :mode="mode"
                            />
                            <Editor
                                style="height: 500px; overflow-y: hidden;"
                                v-model="modelForm.content"
                                :defaultConfig="editorConfig"
                                :mode="mode"
                                @onCreated="onCreated"
                            />
                        </div>
                    </template>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
                <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog width="50%" :visible.sync="setShow" title="邮件配置" @close="setCancel">
            <el-form ref="setRef" :model="setForm" :rules="setRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="邮件配置" prop="smtp">
                    <el-input v-model="setForm.smtp" placeholder="邮件配置"></el-input>
                </el-form-item>
                <el-form-item label="端口号" prop="port">
                    <el-input v-model="setForm.port" placeholder="端口号"></el-input>
                </el-form-item>
                <el-form-item label="邮箱账号" prop="username">
                    <el-input v-model="setForm.username" placeholder="邮箱账号"></el-input>
                </el-form-item>
                <el-form-item label="邮箱密码" prop="password">
                    <el-input v-model="setForm.password" placeholder="邮箱密码"></el-input>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="setButtonLoading" type="primary" @click="setSubmitForm">保 存</el-button>
                <el-button @click="setCancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="">
    import '@wangeditor/editor/dist/css/style.css'
    import { onBeforeUnmount, ref, getCurrentInstance, onMounted } from 'vue'
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
    import {
        getEmailModelList,
        saveEmailModel,
        updateEmailModel,
        deleteEmailModel,
        getEmailModelById,
        getEmailModelConfig,
        saveEmailModelConfig
    } from '@/api/agent'
    const { proxy } = getCurrentInstance();
    const editor = ref(null)
    const toolbarConfig = {}
    const mode = 'default'
    const editorConfig = { placeholder: '请输入内容...' }
    onBeforeUnmount(() => {
        if (editor.value == null) return
        editor.value.destroy()
    })

    const onCreated = (editor2) => {
        editor.value = Object.seal(editor2)
    }

    const title = proxy.$route.meta.title;
    const queryParams = ref({
        name:'',
        page:1,
        limit:10
    })
    const modelList = ref([])
    const total = ref(0)
    const loading = ref(false)
    const multipleSelection = ref([])

    const modelTitle = ref('新增邮件模板')
    const modelRef = ref(null)
    const show = ref(false)
    const buttonLoading = ref(false)
    const modelForm = ref({
        id:'',
        name:'',
        subject:'',
        content:''
    })
    const modelRules = ref({
        name:[{ required: true, message: '请输入名称', trigger: 'blur' }],
        subject:[{ required: true, message: '请输入主题', trigger: 'blur' }],
        content:[{ required: true, message: '请输入内容', trigger: 'blur' }]
    })

    const setRef = ref(null)
    const setShow = ref(false)
    const setButtonLoading = ref(false)
    const setForm = ref({})
    const setRules = ref({
        smtp:[{ required: true, message: '请输入邮件配置', trigger: 'blur' }],
        port:[{ required: true, message: '请输入端口号', trigger: 'blur' }],
        username:[
            { required: true, message: '请输入邮箱账号', trigger: 'blur' },
            { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱账号', trigger: 'blur' }
        ],
        password:[{ required: true, message: '请输入邮箱密码', trigger: 'blur' }]
    })

    const handleSelectionChange = (val) => {
        multipleSelection.value = val;
    }

    const handleSizeChange = (val) => {
        queryParams.value.limit = val;
        getList();
    }
    const handleCurrentChange = (val) => {
        queryParams.value.page = val;
        getList();
    }
    const getList = () => {
        loading.value = true;
        getEmailModelList(queryParams.value).then(res => {
            if(res.code!==0) return proxy.$message.error(res.msg);
            modelList.value = res.data.list;
            total.value = res.data.total;
            loading.value = false;
        }).finally(()=>{loading.value = false})
    }

    const handleAddModel = () => {
        reset();
        modelTitle.value = '新增邮件模板';
        show.value = true;
    }
    const handleEditModel = (row) => {
        modelTitle.value = '编辑邮件模板';
        getEmailModelById(row.id).then(res=>{
            if(res.code!==0) return proxy.$message.error(res.msg);
            show.value = true;
            modelForm.value = res.data;
            editor.value = Object.seal(res.data?.content)
        })
    }
    const cancel = () => {
        show.value = false;
    }
    const submitForm = () => {
        proxy.$refs.modelRef.validate((valid) => {
            if (valid) {
                if(modelForm.value.content==='<p><br></p>') return proxy.$message.error('请输入内容');
                buttonLoading.value = true;
                if(modelForm.value.id){
                    updateEmailModel(modelForm.value).then(res=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        proxy.$modal.msgSuccess("修改成功");
                        getList();
                    }).finally(()=>{buttonLoading.value = false;show.value = false;})
                }else{
                    saveEmailModel(modelForm.value).then(res=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        proxy.$modal.msgSuccess("保存成功");
                        getList();
                    }).finally(()=>{buttonLoading.value = false;show.value = false;})
                }
            }else return buttonLoading.value = false
        })
    }
    const reset = () => {
        modelForm.value = {
            id:'',
            name:'',
            subject:'',
            content:''
        }
        proxy.resetForm("modelRef");
    }
    

    const handleSetModel = () => {
        setShow.value = true;
    }
    const setCancel = () => {
        setShow.value = false;
    }
    const setSubmitForm = () => {
        setButtonLoading.value = true;
        proxy.$refs.setRef.validate((valid) => {
            if (valid) {
                saveEmailModelConfig(setForm.value).then(res=>{
                    if(res.code!==0) return proxy.$message.error(res.msg);
                    proxy.$modal.msgSuccess("保存成功");
                }).finally(()=>{setButtonLoading.value = false;setShow.value = false;})
            }else return setButtonLoading.value = false
        })
    }
    const handleDeleteMore = () => {
        if(multipleSelection.value.length === 0) return proxy.$modal.msgError("请选择要删除的数据");
        let ids = multipleSelection.value.map(item => item.id);
        proxy.$modal.confirm('确认删除选中的数据吗？').then(()=>{
            deleteEmailModel(ids).then(res=>{
                if(res.code === 0) proxy?.$modal.msgSuccess("删除成功");
                else return proxy?.$modal.msgError(res.msg);
                getList();
            });
        })
    }

    const handleSendEamil = (row) => {

    }
    const handleDeleteModel = async (row) => {
        await proxy.$modal.confirm('确认删除邮件模板【' + row.name + '】吗？');
        deleteEmailModel([row.id]).then(res=>{
            if(res.code === 0) proxy?.$modal.msgSuccess("删除成功");
            else return proxy?.$modal.msgError(res.msg);
            getList();
        });
    }

    const getEmailModelConfigFn = () => {
        getEmailModelConfig().then(res=>{
            if(res.code!==0) return proxy.$message.error(res.msg);
            setForm.value = res.data;
        })
    }

    onMounted(()=>{
        getList();
        getEmailModelConfigFn();
    })
</script>

<style scoped lang="scss">
    ::v-deep .queryInput .el-input__inner{
        border: none !important;
        height: 30px !important;
        line-height: 30px !important;
        padding: 0 !important;
        width: 200px !important;
    }

    .query{
        width: 100%;
        padding: 16px 20px;
        box-sizing: border-box;
        background: #FFFFFF;
        border-radius: 6px;
        border: 1px solid #F3F4F6;
        margin-top: 31px;
    }

    
    .page{
        padding: 28px 16px 12px;
        background: #FAFAFA;
        .title{
            font-family: PingFang-SC, PingFang-SC;
            font-weight: bold;
            font-size: 16px;
            color: #111111;
            line-height: 16px;
        }

        
        .content{
            width: 100%;
            height: calc(100vh - 170px);
            background: #FFFFFF;
            border: 1px solid #F3F4F6;
            margin-top: 5px;
        }
    }
</style>