<template>
    <div class="template-manage">
        <common-table
            ref="pageRef"
            :pageConfig="pageConfig"
            :columns="columns"
            :bodyStyle="{ padding: 0 }"
        >
            <template #toolbar>
                <div style="display: flex; align-items: center; gap: 10px">
                    <el-button
                        type="primary"
                        plain
                        :icon="PlusOutlined"
                        v-permission="'marketing:messagePush:add'"
                        @click="handleUpdate()"
                    >
                        新增模板
                    </el-button>
                    <el-button
                        type="danger"
                        plain
                        :icon="DeleteOutlined"
                        v-permission="'marketing:messagePush:batchDelete'"
                        @click="handleDelete()"
                    >
                        批量删除
                    </el-button>

                    <div style="display: flex; align-items: center; gap: 10px">
                        <el-input
                            v-model="search"
                            placeholder="搜索模板名称"
                            style="width: 300px"
                        />
                        <el-button type="primary" @click="reload()"
                            >查询</el-button
                        >
                        <el-button type="primary" plain @click="reset"
                            >重置</el-button
                        >
                    </div>
                </div>
            </template>

            <template #miniappNotice="{ row }">
                <el-switch
                    :model-value="row.pushWay.indexOf('1') !== -1"
                    style="--el-switch-on-color: #13ce66"
                    @change="statusSwitchChange($event, row, '1')"
                />
                <el-text style="margin-left: 5px">{{
                    row.pushWay.indexOf('1') !== -1 ? '已开启' : '已关闭'
                }}</el-text>
            </template>

            <template #officialNotice="{ row }">
                <el-switch
                    :model-value="row.pushWay.indexOf('2') !== -1"
                    style="--el-switch-on-color: #13ce66"
                    @change="statusSwitchChange($event, row, '2')"
                />
                <el-text style="margin-left: 5px">{{
                    row.pushWay.indexOf('2') !== -1 ? '已开启' : '已关闭'
                }}</el-text>
            </template>

            <template #smsNotice="{ row }">
                <el-switch
                    :model-value="row.pushWay.indexOf('3') !== -1"
                    style="--el-switch-on-color: #13ce66"
                    @change="statusSwitchChange($event, row, '3')"
                />
                <el-text style="margin-left: 5px">{{
                    row.pushWay.indexOf('3') !== -1 ? '已开启' : '已关闭'
                }}</el-text>
            </template>

            <template #action="{ row }">
                <div>
                    <el-button
                        type="primary"
                        link
                        v-permission="'marketing:messagePush:edit'"
                        @click="handleUpdate(row)"
                    >
                        [编辑]
                    </el-button>
                    <el-button
                        type="danger"
                        link
                        v-permission="'marketing:messagePush:delete'"
                        @click="handleDelete(row)"
                    >
                        [删除]
                    </el-button>
                </div>
            </template>
        </common-table>

        <template-edit ref="editRef" @success="reload()" />
    </div>
</template>

<script setup>
    import { ref, reactive } from 'vue';
    import { ElMessageBox } from 'element-plus/es';
    import { EleMessage } from 'ele-admin-plus/es';
    import { PlusOutlined, DeleteOutlined } from '@/components/icons';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import TemplateEdit from './template-edit.vue';
    import request from '@/utils/request';

    const search = ref('');
    const reset = () => {
        search.value = '';
        reload();
    };
    defineOptions({ name: 'TemplateManage' });

    /** 表格列配置 */
    const columns = ref([
        {
            type: 'selection',
            columnKey: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
        },
        {
            label: '模板名称',
            prop: 'name',
            align: 'center',
            minWidth: 140
        },
        {
            label: '模板签名',
            prop: 'sign',
            align: 'center',
            minWidth: 120
        },
        {
            label: '内容',
            prop: 'content',
            align: 'center',
            minWidth: 240
        },
        {
            label: '小程序消息通知',
            prop: 'miniappNotice',
            align: 'center',
            minWidth: 120,
            slot: 'miniappNotice'
        },
        {
            label: '公众号消息通知',
            prop: 'officialNotice',
            align: 'center',
            minWidth: 120,
            slot: 'officialNotice'
        },
        {
            label: '短信消息通知',
            prop: 'smsNotice',
            align: 'center',
            minWidth: 120,
            slot: 'smsNotice'
        },
        {
            label: '添加时间',
            prop: 'createTime',
            align: 'center',
            minWidth: 160
        },
        {
            label: '三方模板KEY',
            prop: 'thirdKey',
            align: 'center',
            minWidth: 120
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 160,
            align: 'center',
            slot: 'action'
        }
    ]);

    /** 页面组件实例 */
    const pageRef = ref(null);
    const editRef = ref(null);

    const pageConfig = reactive({
        pageUrl: '/message/templetemsg/pagelist',
        fileName: '消息模板',
        cacheKey: 'messageTemplateTable'
    });

    //刷新表格
    function reload(where) {
        pageRef.value?.reload({ ...where, name: search.value });
    }

    //修改状态
    const statusSwitchChange = (value, row, key) => {
        let data = JSON.parse(JSON.stringify(row));
        let message = value == 0 ? '确认关闭？' : '确认开启？';
        ElMessageBox.confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '关闭',
            type: 'warning'
        })
            .then(() => {
                let pushWay = data.pushWay ? data.pushWay.split(',') : [];
                if (!value) {
                    pushWay = pushWay.filter((item) => item !== key);
                } else {
                    pushWay.push(key);
                }
                let params = {
                    id: data.id,
                    pushWay: pushWay.join(',')
                };

                request
                    .post(
                        '/message/templetemsg/setSendWay?id=' +
                            params.id +
                            '&pushWay=' +
                            params.pushWay
                    )
                    .then((res) => {
                        if (res.data.code === 200) {
                            EleMessage.success('操作成功');
                            reload();
                        } else {
                            EleMessage.error(res.data.msg);
                        }
                    });
            })
            .catch(() => {
                row[key] = value == 1 ? 0 : 1;
            });
    };

    //删除
    function handleDelete(row) {
        let ids = [];
        let message = '确认删除该模板？';

        if (row?.id) {
            // 单个删除
            ids = [row.id];
        } else {
            // 批量删除
            const selections = pageRef.value?.getSelections();
            if (!selections || selections.length === 0) {
                EleMessage.warning('请选择要删除的数据');
                return;
            }
            ids = selections.map((item) => item.id);
            message = `确认删除选中的 ${ids.length} 条数据？`;
        }

        ElMessageBox.confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            request
                .post('/message/templetemsg/removeTmp', { idList: ids })
                .then((res) => {
                    if (res.data.code === 200) {
                        EleMessage.success('删除成功');
                        reload();
                    } else {
                        EleMessage.error(res.data.msg);
                    }
                });
        });
    }

    //编辑页面
    function handleUpdate(row) {
        editRef.value?.handleOpen(row);
    }
</script>
