<template>
    <el-dialog draggable :title="title" v-model="visibleLocal" width="600px" :close-on-click-modal="false"
        @closed="onClosed">
        <!-- <el-input type="textarea" v-model="rawText" :rows="10" :placeholder="placeholder" /> -->
        <el-input type="textarea" v-model="rawText" :rows="10" :placeholder="placeholder" @input="enforceLineLimit" />
        <template #footer>
            <span v-if="title === '主播ID'" style="margin-right: 12px; color:#909399;">
                {{ lineCount }}/{{ MAX_LINES_FOR_ANCHOR }} 行
            </span>
            <span v-if="title === '私信'">
                <!-- 翻译
                <el-tooltip class="box-item" effect="dark" content="开启后，打招呼将自动翻译为主播地区使用的语言" placement="bottom">

                    <el-switch style="margin-right: 20px;" v-model="data.needTranslate" />
                </el-tooltip> -->

                自动回复

                <el-tooltip class="box-item" effect="dark" content="开启后，检测到新私信将自动回复" placement="bottom">

                    <el-switch style="margin-right: 20px;" v-model="data.auto" />
                </el-tooltip>
            </span>
            <span v-if="title === '评论' || title === '视频评论'">
                评论
                <el-tooltip class="box-item" effect="dark" content="关闭后，将不在评论" placement="bottom">

                    <el-switch style="margin-right: 20px;" v-model="data.common" />
                </el-tooltip>
            </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 { ElMessage } from 'element-plus';
import { ref, computed, watch } from 'vue';
import { prologue, comment } from '@/api/account';
import { getMultiLineInputCache, setMultiLineInputCache } from '@/stores/storage';
const MAX_LINES_FOR_ANCHOR = 100;



let data = ref({
    // needTranslate: false,
    auto: false,
    common: true,
});
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('');

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

function loadCachedText() {
    const cached = getMultiLineInputCache(props.title);
    if (cached !== null && cached !== undefined) {
        rawText.value = cached;
        return;
    }
    rawText.value = props.initialText || '';
}

watch(() => props.visible, (v) => {
    if (v) loadCachedText();
});

watch(() => props.title, () => {
    if (props.visible) loadCachedText();
});

watch(() => props.initialText, (v) => {
    const cached = getMultiLineInputCache(props.title);
    if (props.visible && cached === null) rawText.value = v;
});

watch(rawText, (v) => {
    setMultiLineInputCache(props.title, 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() {
    if (props.title === '主播ID' && lineCount.value > MAX_LINES_FOR_ANCHOR) {
        ElMessage.error(`“主播ID”最多 ${MAX_LINES_FOR_ANCHOR} 行，请精简后再提交。`);
        enforceLineLimit();   // 再次截断以保证安全
        return;
    }
    const items = parseLines();
    emit('confirm', items, props.title, props.index, data.value);
    closingByConfirm.value = true;
    emit('update:visible', false);
}

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

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

    // 重置表单状态
    // data.value = {
    //     needTranslate: false,
    //     auto: false,
    //     common: true,
    // }

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

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

function exportPrologue(title) {
    if (title === '私信') {
        prologue().then(res => {
            rawText.value = res.map(item => item).join('\n\n');
        });

    } else {
        comment().then(res => {
            rawText.value = res.map(item => item).join('\n\n');
        });
    }
}

function enforceLineLimit() {
    if (props.title !== '主播ID') return;
    const lines = (rawText.value || '').split(/\r?\n/);
    if (lines.length > MAX_LINES_FOR_ANCHOR) {
        rawText.value = lines.slice(0, MAX_LINES_FOR_ANCHOR).join('\n');
        ElMessage.warning(`“主播ID”最多 ${MAX_LINES_FOR_ANCHOR} 行，已自动截断。`);
    }
}

const lineCount = computed(() =>
    (rawText.value || '')
        .split(/\r?\n/)
        .filter(s => s.trim().length > 0).length
);
</script>

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