<template>
    <el-dialog v-model="visible" width="960px" :close-on-click-modal="false" :destroy-on-close="false"
        :show-close="false" @close="onClose">
        <template #header>
            <div class="flex items-center justify-between w-full">
                <div class="text-lg font-semibold">打招呼内容</div>
                <!-- <div class="text-xs text-gray-500">可输入多句文本 → 选择语种 → 一键翻译 → 可编辑&持久化 → 确定返回某语种结果</div> -->
            </div>
        </template>

        <div class="space-y-5">
            <!-- 源文本区 -->
            <el-card shadow="never" class="!border rounded-xl">
                <template #header>
                    <div class="flex items-center justify-between">
                        <span class="font-medium">源文本</span>
                        <div class="space-x-2">
                            <el-button size="small" @click="addSentence">新增一行</el-button>
                            <el-button size="small" @click="importFromTextarea">从多行文本导入</el-button>
                            <el-button size="small" type="warning" plain @click="clearAll">清空</el-button>
                            <el-button type="success" @click="exportPrologue()">
                                导入私信
                            </el-button>
                            <el-tooltip class="box-item" effect="dark" content="关闭后，招呼内容将不再翻译" placement="bottom">
                                <el-switch v-model="isTranslation" class="fancy-switch" :width="70" inline-prompt
                                    active-text="翻译" inactive-text="翻译" style="margin-left:16px" />
                            </el-tooltip>

                            <el-text style="margin-left: 10px;" type="primary"> </el-text>
                        </div>
                    </div>
                </template>
                <div class="grid grid-cols-12 gap-3">
                    <div class="col-span-12 lg:col-span-6">
                        <el-input v-model="bulkText" :rows="8" type="textarea"
                            placeholder="每行一条句子，可粘贴多行，然后点击『从多行文本导入』" />
                    </div>
                    <div class="col-span-12 lg:col-span-6 space-y-2">
                        <div v-for="(s, i) in sentences" :key="`src-${i}`" class="flex items-start gap-2"
                            style="display: flex;">
                            <el-input v-model="sentences[i]" :placeholder="'第 ' + (i + 1) + ' 句'" />
                            <el-button circle @click="removeSentence(i)" style="color: red;">
                                X
                            </el-button>
                        </div>
                        <div v-if="sentences.length === 0" class="text-xs text-gray-500">尚未添加句子</div>
                    </div>
                </div>
            </el-card>

            <!-- 语种与翻译控制区 -->
            <el-card v-show="isTranslation" shadow="never" class="!border rounded-xl">
                <template #header>
                    <div class="flex items-center justify-between">
                        <span class="font-medium">语种与翻译</span>
                        <div class="flex items-center gap-3">
                            <el-switch v-model="autoSave" active-text="自动保存" />
                            <el-button size="small" @click="saveToLocal">保存</el-button>
                            <el-button size="small" @click="loadFromLocal">载入</el-button>
                        </div>
                    </div>
                </template>

                <div class="grid grid-cols-12 gap-3">
                    <div class="col-span-12 lg:col-span-6 space-y-3">
                        <div class="flex items-center gap-2">
                            <div class="w-24 text-right text-sm text-gray-500">选择语种</div>
                            <el-select v-model="selectedLangs" multiple filterable placeholder="选择需要翻译到的语种"
                                class="w-full">
                                <el-option v-for="opt in languageOptions" :key="opt.value" :label="opt.label"
                                    :value="opt.value" />
                            </el-select>
                        </div>

                        <!-- <div class="flex items-center gap-2">
                            <div class="w-24 text-right text-sm text-gray-500">引擎</div>
                            <el-select v-model="engine" class="w-full">
                                <el-option label="自定义回调 (推荐在父组件里接入)" value="custom" />
                                <el-option label="本地占位引擎 (演示)" value="local" />
                            </el-select>
                        </div> -->

                        <div class="flex items-center gap-2">
                            <div class="w-24"></div>
                            <el-button type="primary" :disabled="!canTranslate || isAnyLoading" @click="onTranslate">
                                <el-icon v-if="isAnyLoading" class="mr-1 is-loading">
                                    <Loading />
                                </el-icon>
                                {{ isAnyLoading ? '翻译中...' : '翻译' }}
                            </el-button>

                            <!-- <el-button :disabled="!Object.keys(translations).length"
                                @click="syncLengths">对齐长度</el-button> -->
                        </div>
                    </div>

                    <div class="col-span-12 lg:col-span-6">
                        <el-alert title="说明" type="info" :closable="false" show-icon class="mb-3"
                            description="选择语种后点击『翻译』。翻译结果可在下方标签页逐条手动调整，选择对应地区国家所有语言语种。" />
                    </div>
                </div>

                <el-tabs v-if="selectedLangs.length" v-model="activeTab" class="mt-4">
                    <el-tab-pane v-for="lang in selectedLangs" :key="lang" :name="lang">
                        <template #label>
                            <span>{{ getLangLabel(lang) }}</span>
                            <el-icon v-if="loadingLangs[lang]" class="ml-1 is-loading" style="vertical-align: -2px;">
                                <Loading />
                            </el-icon>
                        </template>
                        <div class="space-y-2">
                            <!-- ✅ 加载中提示 -->
                            <div v-if="loadingLangs[lang]" class="text-sm text-gray-500 flex items-center gap-2">
                                <el-icon class="is-loading">
                                    <Loading />
                                </el-icon>
                                正在翻译 {{ getLangLabel(lang) }} ...
                            </div>

                            <!-- ✅ 加载完成但无结果 -->
                            <div v-else-if="!translations[lang] || translations[lang].length === 0"
                                class="text-xs text-gray-500">
                                无数据，点击『翻译』获取。
                            </div>

                            <!-- ✅ 加载完成且有结果 -->
                            <div v-else v-for="(t, i) in translations[lang]" :key="`${lang}-${i}`"
                                class="flex items-start gap-2">
                                <el-input v-model="translations[lang][i]" :placeholder="'第 ' + (i + 1) + ' 句'" />
                                <el-popover placement="top" trigger="hover">
                                    <template #reference>
                                        <el-tag type="info" effect="plain">源</el-tag>
                                    </template>
                                    <div class="max-w-72 text-xs">{{ sentences[i] }}</div>
                                </el-popover>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-card>
        </div>

        <template #footer>
            <div class="flex items-center justify-between w-full">
                <div class="text-xs text-gray-500" v-show="isTranslation">
                    共 {{ sentences.length }} 句 · 选择 {{ selectedLangs.length }} 种语言
                    <!-- <template v-if="activeTab"> · 当前返回：{{ getLangLabel(activeTab) }}</template> -->
                </div>
                <div class="space-x-2">
                    自动回复

                    <el-tooltip class="box-item" effect="dark"
                        :content="userdata.aiReplay ? '开启后，检测到新私信将自动回复' : '未开通，请联系管理员开通'" placement="bottom">

                        <el-switch :disabled="!userdata.aiReplay" style="margin-right: 20px;" v-model="auto" />
                    </el-tooltip>
                    <el-button @click="onClose">取消</el-button>
                    <el-button type="primary" @click="onConfirm">确定</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, watch, computed, onMounted } from 'vue'
import { prologue } from '@/api/account';
import { Loading } from '@element-plus/icons-vue'   // ✅ 旋转图标
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUser } from '@/stores/storage'
let userdata = ref(getUser());

const suppressCancelNext = ref(false) // ✅ 下次关闭是否屏蔽 cancel 事件
/**
 * Props & Emits（JS 版）
 */
const props = defineProps({
    // 控制弹窗显示
    modelValue: { type: Boolean, required: true },
    /**
     * 自定义翻译回调：由父组件注入，实现真正的翻译
     * 入参：sentences 原文数组、targetLang 目标语种值
     * 返回：与 sentences 等长的目标语言数组
     */
    translateFn: { type: Function, default: null },
    type: '',
    // 本地持久化 key 前缀（同一项目可自定义隔离）
    storageKeyPrefix: { type: String, default: 'translationDialog' },
})

const emit = defineEmits(['update:modelValue', 'confirm'])

let auto = ref(false);

const visible = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v),
})

/**
 * 状态
 */
let bulkText = ref('')
const sentences = reactive([])
const selectedLangs = ref([])
const translations = reactive({})   // 所有翻译后的内容
const loadingLangs = reactive({})   // ✅ { [lang]: boolean } 每个语种的加载中状态
const autoSave = ref(true)
const activeTab = ref('')
const engine = ref('custom') // 'custom' | 'local'

const MAX_SENTENCES = 30

function clampSentences(list) {
    const trimmed = list.slice(0, MAX_SENTENCES)
    if (list.length > MAX_SENTENCES) {
        ElMessage({
            type: 'warning',
            message: `最多支持 ${MAX_SENTENCES} 条，已保留前 ${MAX_SENTENCES} 条。`,
            duration: 2500,
        })
    }
    return trimmed
}

const isTranslation = ref(false)
watch(selectedLangs, (langs) => {
    const keep = new Set(langs)

    // 删掉已取消选择的语言对应的数据
    Object.keys(translations).forEach((k) => {
        if (!keep.has(k)) delete translations[k]
    })
    Object.keys(loadingLangs).forEach((k) => {
        if (!keep.has(k)) delete loadingLangs[k]
    })

    // 如果当前激活标签不在选择里，重置到第一个
    if (activeTab.value && !keep.has(activeTab.value)) {
        activeTab.value = langs[0] || ''
    }

    // 需要的话，立刻持久化
    if (autoSave.value) saveToLocal()
}, { deep: false })
/** 默认语言选项 */
const defaultLanguages = [
    { label: '英语', value: 'en' },
    { label: '简体中文', value: 'zh' },
    { label: '繁体中文', value: 'zh_tw' },
    { label: '俄语', value: 'ru' },
    { label: '日语', value: 'ja' },
    { label: '韩语', value: 'ko' },
    { label: '西班牙语', value: 'es' },
    { label: '法语', value: 'fr' },
    { label: '葡萄牙语', value: 'pt' },
    { label: '德语', value: 'de' },
    { label: '意大利语', value: 'it' },
    { label: '泰语', value: 'th' },
    { label: '越南语', value: 'vi' },
    { label: '印度尼西亚语', value: 'id' },
    { label: '马来语', value: 'ms' },
    { label: '阿拉伯语', value: 'ar' },
    { label: '印地语', value: 'hi' },
    { label: '希伯来语', value: 'he' },
    { label: '缅甸语', value: 'my' },
    { label: '泰米尔语', value: 'ta' },
    { label: '乌尔都语', value: 'ur' },
    { label: '孟加拉语', value: 'bn' },
    { label: '波兰语', value: 'pl' },
    { label: '荷兰语', value: 'nl' },
    { label: '罗马尼亚语', value: 'ro' },
    { label: '土耳其语', value: 'tr' },
    { label: '高棉语', value: 'km' },
    { label: '老挝语', value: 'lo' },
    { label: '粤语', value: 'yue' },
    { label: '捷克语', value: 'cs' },
    { label: '希腊语', value: 'el' },
    { label: '瑞典语', value: 'sv' },
    { label: '匈牙利语', value: 'hu' },
    { label: '丹麦语', value: 'da' },
    { label: '芬兰语', value: 'fi' },
    { label: '乌克兰语', value: 'uk' },
    { label: '保加利亚语', value: 'bg' },
    { label: '塞尔维亚语', value: 'sr' },
    { label: '泰卢固语', value: 'te' },
    { label: '南非荷兰语', value: 'af' },
    { label: '亚美尼亚语', value: 'hy' },
    { label: '阿萨姆语', value: 'as' },
    { label: '阿斯图里亚斯语', value: 'ast' },
    { label: '巴斯克语', value: 'eu' },
    { label: '白俄罗斯语', value: 'be' },
    { label: '波斯尼亚语', value: 'bs' },
    { label: '加泰罗尼亚语', value: 'ca' },
    { label: '宿务语', value: 'ceb' },
    { label: '克罗地亚语', value: 'hr' },
    { label: '埃及阿拉伯语', value: 'arz' },
    { label: '爱沙尼亚语', value: 'et' },
    { label: '加利西亚语', value: 'gl' },
    { label: '格鲁吉亚语', value: 'ka' },
    { label: '古吉拉特语', value: 'gu' },
    { label: '冰岛语', value: 'is' },
    { label: '爪哇语', value: 'jv' },
    { label: '卡纳达语', value: 'kn' },
    { label: '哈萨克语', value: 'kk' },
    { label: '拉脱维亚语', value: 'lv' },
    { label: '立陶宛语', value: 'lt' },
    { label: '卢森堡语', value: 'lb' },
    { label: '马其顿语', value: 'mk' },
    { label: '马加希语', value: 'mai' },
    { label: '马耳他语', value: 'mt' },
    { label: '马拉地语', value: 'mr' },
    { label: '美索不达米亚阿拉伯语', value: 'acm' },
    { label: '摩洛哥阿拉伯语', value: 'ary' },
    { label: '内志阿拉伯语', value: 'ars' },
    { label: '尼泊尔语', value: 'ne' },
    { label: '北阿塞拜疆语', value: 'az' },
    { label: '北黎凡特阿拉伯语', value: 'apc' },
    { label: '北乌兹别克语', value: 'uz' },
    { label: '书面语挪威语', value: 'nb' },
    { label: '新挪威语', value: 'nn' },
    { label: '奥克语', value: 'oc' },
    { label: '奥里亚语', value: 'or' },
    { label: '邦阿西楠语', value: 'pag' },
    { label: '西西里语', value: 'scn' },
    { label: '信德语', value: 'sd' },
    { label: '僧伽罗语', value: 'si' },
    { label: '斯洛伐克语', value: 'sk' },
    { label: '斯洛文尼亚语', value: 'sl' },
    { label: '南黎凡特阿拉伯语', value: 'ajp' },
    { label: '斯瓦希里语', value: 'sw' },
    { label: '他加禄语', value: 'tl' },
    { label: '塔伊兹-亚丁阿拉伯语', value: 'acq' },
    { label: '托斯克阿尔巴尼亚语', value: 'sq' },
    { label: '突尼斯阿拉伯语', value: 'aeb' },
    { label: '威尼斯语', value: 'vec' },
    { label: '瓦莱语', value: 'war' },
    { label: '威尔士语', value: 'cy' },
    { label: '西波斯语', value: 'fa' },
];

const languageOptions = computed(() => (defaultLanguages))
const getLangLabel = (v) => (languageOptions.value.find((x) => x.value === v)?.label || v)

/** 计算属性 */
const canTranslate = computed(() => sentences.length > 0 && selectedLangs.value.length > 0)
const isAnyLoading = computed(() => Object.values(loadingLangs).some(Boolean))
// const canConfirm = computed(() => !!activeTab.value && !!(translations[activeTab.value] || []).length)

/**
 * 方法 - 源文本
 */
function importFromTextarea() {
    const lines = bulkText.value
        .split(/\r?\n/)
        .map((s) => s.trim())
        .filter(Boolean)

    const limited = clampSentences(lines)
    sentences.splice(0, sentences.length, ...limited)
    syncLengths()
    if (autoSave.value) saveToLocal()
}

//新增一行时限制
function addSentence() {
    if (sentences.length >= MAX_SENTENCES) {
        ElMessage({
            type: 'warning',
            message: `最多只可添加 ${MAX_SENTENCES} 条。`,
        })
        return
    }
    sentences.push('')
    syncLengths()
    if (autoSave.value) saveToLocal()
}


function removeSentence(i) {
    sentences.splice(i, 1)
    syncLengths()
    if (autoSave.value) saveToLocal()
}

function clearAll() {
    bulkText.value = ''
    sentences.splice(0)
    Object.keys(translations).forEach((k) => delete translations[k])
    if (autoSave.value) saveToLocal()
}

/**
 * 方法 - 翻译
 */
/**
 * 执行翻译功能的主函数
 * 该函数会遍历所选语言，对输入文本进行批量翻译，并处理翻译结果的存储与显示
 */
async function onTranslate() {
    // 检查是否满足翻译条件，如果不满足则直接返回
    if (!canTranslate.value) return
    // 遍历所有选中的目标语言，依次进行翻译
    // ✅ 给所有选中语种先置为 loading
    const langs = selectedLangs.value.slice()
    langs.forEach(l => loadingLangs[l] = true)

    // ✅ 并行翻译；想要串行也可以改成 for...of + await
    await Promise.all(langs.map(async (lang) => {
        try {
            const arr = await translate(sentences.slice(), lang)
            translations[lang] = ensureLength(arr, sentences.length)

        } finally {
            loadingLangs[lang] = false // ✅ 不管成功/失败都清理 loading
        }
    }))
    // 如果未设置返回语言且存在选中的语言，则将第一个选中的语言设为返回语言
    if (!activeTab.value && selectedLangs.value.length) {
        activeTab.value = selectedLangs.value[0]
    }
    // 如果启用了自动保存功能，则将翻译结果保存到本地存储
    if (autoSave.value) saveToLocal()
}

async function translate(src, lang) {
    if (engine.value === 'custom' && typeof props.translateFn === 'function') {
        return await props.translateFn(src, lang)
    }
    // 本地占位：仅作演示，将文本附加 [lang] 标记
    return src.map((s) => (s ? `${s} [${lang}]` : ''))
}

/**
 * 对齐各语言数组长度到 sentences.length
 */
function ensureLength(arr, targetLen) {
    const out = (arr || []).slice(0, targetLen)
    while (out.length < targetLen) out.push('')
    return out
}

function syncLengths() {
    const n = sentences.length
    Object.keys(translations).forEach((k) => {
        translations[k] = ensureLength(translations[k] || [], n)
    })
}

/**
 * 持久化（localStorage）
 */
const storagePrefix = computed(() => props.storageKeyPrefix || 'translationDialog')

const saveToLocal = debounce(() => {
    const key = (k) => `${storagePrefix.value}:${k}`
    localStorage.setItem(key('sentences'), JSON.stringify(sentences))
    localStorage.setItem(key('selectedLangs'), JSON.stringify(selectedLangs.value))
    localStorage.setItem(key('activeTab'), JSON.stringify(activeTab.value))
    localStorage.setItem(key('translations'), JSON.stringify(translations))
}, 200) // 200ms 防抖
function debounce(fn, wait = 200) {
    let t
    return (...args) => {
        clearTimeout(t)
        t = setTimeout(() => fn(...args), wait)
    }
}
function loadFromLocal() {
    const key = (k) => `${storagePrefix.value}:${k}`
    try {
        const s = JSON.parse(localStorage.getItem(key('sentences')) || '[]')
        const limited = clampSentences(Array.isArray(s) ? s : [])
        const langs = JSON.parse(localStorage.getItem(key('selectedLangs')) || '[]')
        const a = JSON.parse(localStorage.getItem(key('activeTab')) || '""')
        const t = JSON.parse(localStorage.getItem(key('translations')) || '{}')

        sentences.splice(0, sentences.length, ...limited)
        selectedLangs.value = Array.isArray(langs) ? langs : []
        activeTab.value = typeof a === 'string' ? a : ''

        Object.keys(translations).forEach((k) => delete translations[k])
        if (t && typeof t === 'object') {
            for (const k of Object.keys(t)) {
                translations[k] = Array.isArray(t[k]) ? t[k] : []
            }
        }
        // 如果本地的 activeTab 不在当前选中语言里，退回到第一个
        if (activeTab.value && !selectedLangs.value.includes(activeTab.value)) {
            activeTab.value = selectedLangs.value[0] || ''
        }
        syncLengths()
    } catch (e) {
        console.warn('loadFromLocal error', e)
    }
}

watch([sentences, selectedLangs, translations, activeTab], () => {
    if (autoSave.value) saveToLocal()
}, { deep: true })

async function onConfirm() {
    // if (!activeTab.value) return

    // 如果关闭了翻译功能，则先提示
    if (!isTranslation.value) {
        try {
            await ElMessageBox.confirm(
                '当前「翻译」开关已关闭，打招呼内容将不会被翻译，只会使用原文发送。是否继续？',
                '提示',
                {
                    confirmButtonText: '继续',
                    cancelButtonText: '取消',
                    type: 'warning',
                    customClass: 'confirm-box-sm',
                }
            )
            // 用户点击“继续” -> 继续执行提交逻辑
        } catch {
            // 用户点击“取消” -> 直接退出
            ElMessage({
                type: 'info',
                message: '已取消发送',
            })
            return
        }
    }

    // === 以下是原逻辑 ===
    suppressCancelNext.value = true
    const out = JSON.parse(JSON.stringify(translations))

    // 追加原始内容
    out.yolo = sentences.slice()

    emit('confirm', {
        type: props.type,
        strings: out,
        autoBlo: auto.value,
        needTranslate: isTranslation.value,
    })
}

function onClose() {
    if (suppressCancelNext.value) {
        suppressCancelNext.value = false   // ✅ 仅关闭，不触发 cancel
        emit('update:modelValue', false)
        return
    }
    emit('cancel')                       // ✅ 正常关闭时才触发 cancel（如点击“取消”/Esc/右上角关闭）
    emit('update:modelValue', false)
}

function exportPrologue() {

    prologue().then(res => {
        bulkText.value = res.map(item => item).join('\n\n');
    });


}
onMounted(() => {
    loadFromLocal()
})
</script>

<style scoped>
/* 轻量美化，依赖页面存在 Tailwind 时会更佳 */
.space-y-2>*+* {
    margin-top: 0.5rem;
}

.space-y-3>*+* {
    margin-top: 0.75rem;
}

.space-y-5>*+* {
    margin-top: 1.25rem;
}

.grid {
    display: grid;
}

.grid-cols-12 {
    grid-template-columns: repeat(12, minmax(0, 1fr));
}

.gap-3 {
    gap: 0.75rem;
}

.col-span-12 {
    grid-column: span 12 / span 12;
}

.lg\:col-span-6 {
    grid-column: span 12 / span 12;
}

@media (min-width: 1024px) {
    .lg\:col-span-6 {
        grid-column: span 6 / span 6;
    }
}

.rounded-xl {
    border-radius: 0.75rem;
}

/* === 紧凑版 fancy-switch，不依赖外部库 === */
:deep(.fancy-switch) {
    vertical-align: middle;
}

/* 轨道部分（略大于默认） */
:deep(.fancy-switch .el-switch__core) {
    height: 28px;
    /* 比默认略高 */
    border-radius: 9999px;
    border: 1px solid rgba(255, 255, 255, 0.14);
    transition: all 0.25s ease;
    font-weight: 600;
}

/* 滑块部分（略缩小） */
:deep(.fancy-switch .el-switch__action) {
    width: 22px;
    height: 22px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
    transition: all 0.25s ease;
}

/* 关闭态：暗色背景，灰色文字 */
:deep(.fancy-switch:not(.is-checked) .el-switch__core) {
    background: linear-gradient(180deg, #1f2937, #111827) !important;
    color: #9CA3AF;
}

/* 开启态：蓝绿渐变高亮 */
:deep(.fancy-switch.is-checked .el-switch__core) {
    background: linear-gradient(90deg, #60a5fa, #34d399) !important;
    color: #0b1220;
    box-shadow:
        0 0 0 2px rgba(96, 165, 250, .18),
        0 4px 18px rgba(52, 211, 153, .25);
}

/* 滑块开启态：更亮一点 */
:deep(.fancy-switch.is-checked .el-switch__action) {
    background: #fff;
    box-shadow: 0 4px 16px rgba(52, 211, 153, .3);
}

/* 呼吸动画（更柔和版本） */
@keyframes glowPulseSmall {
    0% {
        box-shadow: 0 0 0 2px rgba(96, 165, 250, .16), 0 4px 18px rgba(52, 211, 153, .25);
    }

    50% {
        box-shadow: 0 0 0 5px rgba(96, 165, 250, .08), 0 4px 22px rgba(52, 211, 153, .30);
    }

    100% {
        box-shadow: 0 0 0 2px rgba(96, 165, 250, .16), 0 4px 18px rgba(52, 211, 153, .25);
    }
}

:deep(.fancy-switch.is-checked .el-switch__core) {
    animation: glowPulseSmall 2.5s ease-in-out infinite;
}

/* 键盘焦点高亮 */
:deep(.fancy-switch .el-switch__input:focus-visible + .el-switch__core) {
    outline: 2px solid rgba(96, 165, 250, .55);
    outline-offset: 2px;
}
</style>