<template>
    <el-dialog draggable :title="title" v-model="visibleLocal" width="600px" @closed="onClosed">
        <el-input type="textarea" v-model="rawText" :rows="10" :placeholder="placeholder" />
        <template #footer>
            <span v-if="title === '私信'">
                自动回复
                <el-switch style="margin-right: 20px;" v-model="value1" />
            </span>
            <el-button v-if="title !== '主播ID'" type="success" @click="exportPrologue(title)">
                导入{{ title }}
            </el-button>
            <el-button @click="onClickCancel">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { prologue, comment } from '@/api/account';

let value1 = ref(false);

const props = defineProps({
    visible: { type: Boolean, required: true },
    title: { type: String, default: '' },
    initialText: { type: String, default: '' },
    type: { type: Number, default: 10 },
    index: { type: Number, default: 999 },
    placeholder: { type: String, default: '每行一条，支持粘贴多行后自动拆分' },
    dedupe: { type: Boolean, default: true },
});

const emit = defineEmits(['update:visible', 'confirm', 'cancel']);

const rawText = ref(props.initialText);

// 区分关闭来源：true=通过“确定”关闭；false=取消/遮罩/ESC/右上角关闭
const closingByConfirm = ref(false);

watch(() => props.initialText, (v) => { rawText.value = v; });

const visibleLocal = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val),
});

function parseLines() {
    const lines = rawText.value
        .split(/\r?\n/)
        .map(s => s.trim())
        .filter(Boolean);
    return props.dedupe ? Array.from(new Set(lines)) : lines;
}

function handleConfirm() {
    const items = parseLines();
    emit('confirm', items, props.title, props.index, value1.value);
    closingByConfirm.value = true;          // 标记：这次关闭来自“确定”
    emit('update:visible', false);          // 关弹窗
}

function onClickCancel() {
    closingByConfirm.value = false;         // 非确认关闭
    emit('update:visible', false);          // 关弹窗
}

// 所有关闭后的统一收尾
function onClosed() {
    const byConfirm = closingByConfirm.value;

    // 重置表单状态
    rawText.value = '';
    value1.value = false;

    // 只有非“确定”关闭才对外发 cancel
    if (!byConfirm) emit('cancel');

    // 重置标记
    closingByConfirm.value = false;
}

function exportPrologue(title) {
    if (title === '评论') {
        comment().then(res => {
            rawText.value = res.map(item => item).join('\n\n');
        });
    } else {
        prologue().then(res => {
            rawText.value = res.map(item => item).join('\n\n');
        });
    }
}
</script>

<style scoped>
/* 根据需要自定义样式 */
</style>