<template>
    <el-dialog
        title="消息推送"
        v-model="visible"
        width="800px"
        destroy-on-close
    >
        <el-form
            ref="sendFormRef"
            :model="sendForm"
            :rules="rules"
            label-width="100px"
            class="send-form"
        >
            <el-form-item label="用户类型：" prop="userType">
                <el-radio-group v-model="sendForm.userType">
                    <el-radio :label="1">全部用户</el-radio>
                    <el-radio :label="2">部分用户</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item
                v-if="sendForm.userType === 2"
                label="用户标签："
                prop="userSearch"
            >
                <el-select
                    v-model="sendForm.userSearch"
                    multiple
                    placeholder="请选择用户标签"
                    clearable
                    class="w-full"
                >
                    <el-option
                        v-for="item in tagList"
                        :key="item.id"
                        :label="item.tagName"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>

            <div class="content-section">
                <div class="section-title">设置消息内容</div>

                <el-form-item label="消息模板：" prop="templeteId" required>
                    <el-select
                        v-model="sendForm.templeteId"
                        placeholder="请选择消息模板"
                        clearable
                        @change="handleTemplateChange"
                    >
                        <el-option
                            v-for="item in templateList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="签名名称：" v-if="templateDetail.sign">
                    <el-input v-model="templateDetail.sign" readonly disabled />
                </el-form-item>

                <el-form-item label="短信内容：" v-if="templateDetail.content">
                    <el-input
                        v-model="templateDetail.content"
                        type="textarea"
                        :rows="3"
                        readonly
                        disabled
                    />
                </el-form-item>

                <el-form-item label="备注：" prop="remark">
                    <el-input
                        v-model="sendForm.remark"
                        placeholder="请输入备注"
                        clearable
                    />
                </el-form-item>
            </div>

            <el-form-item label="发送方式：" prop="sendType">
                <el-radio-group v-model="sendForm.sendType">
                    <el-radio :label="1">立即发送</el-radio>
                    <el-radio :label="2">定时发送</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item
                v-if="sendForm.sendType === 2"
                label="发送时间："
                prop="sendTime"
            >
                <el-date-picker
                    v-model="sendForm.sendTime"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="选择时间"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                type="primary"
                :loading="loading"
                @click="handleSubmitSend"
            >
                确 定
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
    import { ref, reactive, onMounted } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import request from '@/utils/request';

    defineOptions({ name: 'MessagePushDialog' });

    const emit = defineEmits(['success']);
    const visible = defineModel({ type: Boolean });
    const loading = ref(false);
    const sendFormRef = ref(null);
    const templateList = ref([]);
    const tagList = ref([]);
    const templateDetail = reactive({
        content: '',
        sign: ''
    });

    const sendForm = reactive({
        id: undefined,
        userType: 1,
        userSearch: [],
        templeteId: '',
        remark: '',
        sendType: 1,
        sendTime: ''
    });

    const rules = {
        templeteId: [
            { required: true, message: '请选择消息模板', trigger: 'change' }
        ],
        userSearch: [
            { required: true, message: '请输入搜索条件', trigger: 'blur' }
        ],
        sendTime: [
            { required: true, message: '请选择发送时间', trigger: 'change' }
        ]
    };

    // 获取模板列表
    const getTemplateList = async () => {
        try {
            const { data } = await request.get(
                '/message/templetemsg/listNormal'
            );
            if (data.code === 200) {
                templateList.value = data.data;
            }
        } catch (e) {
            console.error('获取模板列表失败:', e);
        }
    };

    // 获取用户标签列表
    const getTagList = async () => {
        try {
            const { data } = await request.get(
                '/user/tag/pagelist?pageNum=1&pageSize=1000'
            );
            console.log(data);
            if (data.code === 200) {
                tagList.value = data.rows || [];
            }
        } catch (e) {
            console.error('获取用户标签列表失败:', e);
        }
    };

    // 获取模板详情
    const getTemplateDetail = async (id) => {
        try {
            const { data } = await request.get(
                `/message/templetemsg/getInfo/${id}`
            );
            if (data.code === 200) {
                templateDetail.content = data.data.content;
                templateDetail.sign = data.data.sign;
            }
        } catch (e) {
            console.error('获取模板详情失败:', e);
        }
    };

    // 模板选择变更
    const handleTemplateChange = async (templeteId) => {
        if (!templeteId) {
            sendForm.templeteId = '';
            templateDetail.content = '';
            templateDetail.sign = '';
            return;
        }
        sendForm.templeteId = templeteId;
        await getTemplateDetail(templeteId);
    };

    function handleReset() {
        Object.assign(sendForm, {
            id: undefined,
            userType: 1,
            userSearch: [],
            templeteId: '',
            remark: '',
            sendType: 1,
            sendTime: ''
        });
        Object.assign(templateDetail, {
            content: '',
            sign: ''
        });
    }

    async function handleSubmitSend() {
        if (loading.value) return;
        try {
            const valid = await sendFormRef.value?.validate();
            if (!valid) return;
            loading.value = true;

            // 构建请求参数
            const params = {
                ...sendForm,
                userSearch: sendForm.userSearch.join(','),
                sendTime: sendForm.sendTime
            };

            const url = sendForm.id
                ? '/message/messagepush/update'
                : '/message/messagepush/add';

            const { data } = await request.post(url, params);
            if (data.code === 200) {
                EleMessage.success(sendForm.id ? '修改成功' : '发送成功');
                visible.value = false;
                handleReset();
                emit('success');
            } else {
                EleMessage.error(data.msg);
            }
        } catch (e) {
            EleMessage.error(e.message);
        } finally {
            loading.value = false;
        }
    }

    // 打开弹窗时获取模板列表
    const handleOpen = (row) => {
        visible.value = true;
        getTemplateList();
        getTagList();
        if (row) {
            const formData = { ...row };
            if (formData.userSearch) {
                formData.userSearch = formData.userSearch.split(',');
            }
            Object.assign(sendForm, formData);
        } else {
            handleReset();
        }
    };

    defineExpose({ handleOpen });
</script>

<style lang="scss" scoped>
    .send-form {
        padding: 0 20px;
    }

    .content-section {
        margin: 20px 0;

        .section-title {
            font-weight: bold;
            margin-bottom: 20px;
        }
    }

    :deep(.el-form-item__label) {
        color: #333;
    }

    :deep(.el-input),
    :deep(.el-textarea) {
        width: 100%;
    }
</style>
