<template>
  <div class="main">
    <!-- 中间：工作台主体 -->
    <div class="content">
      <div class="dashboard">
        <!-- 顶部标题栏 -->
        <div class="dashboard-header">
          <div class="title-block">
            <h2>自动私信工作台</h2>
            <p class="subtitle">
              配置账号 · 设置 AI 回复策略 · 一键运行任务
            </p>
          </div>
          <div class="header-right">
            <el-tag v-if="aiConfigured" type="success" effect=" ·">
              AI 人设：已配置
            </el-tag>
            <el-tag v-else type="warning" effect="dark">
              AI 人设：未配置
            </el-tag>
            <span class="time">
              {{ printCurrentTime() }}
            </span>
          </div>
        </div>

        <!-- 小提示条 -->
        <div class="banner-tip">
          <span class="dot"></span>
          建议：最多配置 3 个账号轮询发送，开启 AI 自动回复可提升转化率。
        </div>

        <el-row :gutter="18" class="dashboard-body">
          <!-- 左：运行配置表单 -->
          <el-col :span="16">
            <el-card shadow="hover" class="panel-card panel-form">
              <template #header>
                <div class="card-header">
                  <div class="card-title">
                    <span class="bar"></span>
                    <span>运行配置</span>
                  </div>

                  <button v-if="!running" class="run-btn" type="primary" size="small" @click="startRun">
                    <span class="run-dot"></span>
                    开始运行
                  </button>
                  <button v-else class="run-btn" type="error" size="small" @click="stop">
                    <span class="run-dot"></span>
                    停止运行
                  </button>

                </div>
              </template>

              <el-form :model="runForm" label-width="120px" class="run-form">
                <!-- 账号组列表 -->
                <el-form-item label="账号组（最多3组）">
                  <div class="group-wrap">
                    <div v-for="(group, gIndex) in visibleGroups" :key="gIndex" class="group-block">
                      <div class="group-head">
                        <span class="group-title">
                          {{ group.name }}
                          <el-tag v-if="running && currentGroupIndex === gIndex" type="success" effect="dark"
                            style="margin-left:8px">
                            运行中
                          </el-tag>
                        </span>

                        <el-button type="primary" link @click="addAccount(gIndex)"
                          :disabled="group.accounts.length >= 3">
                          新增账号
                        </el-button>
                      </div>

                      <div v-for="(acc, aIndex) in group.accounts" :key="aIndex" class="account-row">
                        <el-input v-model="acc.email" placeholder="邮箱（email）" class="mr-8" />
                        <el-input v-model="acc.pwd" placeholder="密码（pwd）" show-password class="mr-8" />

                        <el-button type="danger" link @click="removeAccount(gIndex, aIndex)"
                          :disabled="group.accounts.length === 1">
                          删除
                        </el-button>
                      </div>

                      <p class="tip">每组最多 3 个账号，将按组轮换运行。</p>
                    </div>
                  </div>
                </el-form-item>
                <!-- 是否轮换 / 组数量 -->
                <el-form-item label="轮换账号组">
                  <div class="inline-field">
                    <el-switch v-model="runForm.rotateEnabled" active-text="开启轮换" inactive-text="不轮换" />
                    <span class="field-desc">关闭时只跑当前组（第1组）不切换。</span>
                  </div>
                </el-form-item>

                <el-form-item v-if="runForm.rotateEnabled" label="账号组数量">
                  <div class="inline-field">
                    <el-radio-group v-model="runForm.groupCount">
                      <el-radio :value="2">2组</el-radio>
                      <el-radio :value="3">3组</el-radio>
                    </el-radio-group>
                  </div>
                </el-form-item>
                <!-- 轮换时间（小时） -->
                <el-form-item v-if="runForm.rotateEnabled" label="轮换间隔(分钟)">
                  <div class="inline-field">
                    <el-input-number v-model="runForm.switchHours" :min="1" :step="1" controls-position="right" />
                    <span class="field-desc">每隔 N 分钟自动停止当前组并切换到下一组循环运行。</span>
                  </div>
                </el-form-item>

                <!-- AI 回复开关 -->
                <el-form-item label="AI 自动回复">
                  <div class="inline-field">
                    <el-switch v-model="runForm.aiReply" active-text="开启" inactive-text="关闭" />
                    <span class="field-desc">
                      开启后由 AI 自动根据对话内容生成回复。
                    </span>
                  </div>
                </el-form-item>

                <!-- 第一条是否发送邀请链接 -->
                <el-form-item label="第一条消息">
                  <el-radio-group v-model="runForm.sendInviteFirst">
                    <el-radio :value="false">打招呼</el-radio>
                    <el-radio :value="true">发送邀请链接</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- 添加睡眠时间输入框 -->
                <el-form-item label="睡眠时间(秒)">
                  <el-input-number v-model="runForm.sleepTime" :min="0" :step="1" controls-position="right" />
                </el-form-item>

                <!-- 打招呼后回复几句发送邀请链接 -->
                <el-form-item v-if="!runForm.sendInviteFirst" label="链接发送时机">
                  <div class="inline-field">
                    <el-input-number v-model="runForm.inviteThreshold" :min="1" :step="1" controls-position="right" />
                    <span class="field-desc">打招呼后回复 N 句再发送邀请链接</span>
                  </div>
                </el-form-item>

              </el-form>
            </el-card>
          </el-col>

          <!-- 右：快捷操作 -->
          <el-col :span="8">
            <el-card shadow="hover" class="panel-card mt-16 panel-actions">
              <template #header>
                <div class="card-header">
                  <div class="card-title">
                    <span class="bar"></span>
                    <span>快捷操作</span>
                  </div>
                </div>
              </template>
              <div class="quick-actions">
                <el-button style="margin-left: 12px;" type="primary" text @click="showHostDlg = true">
                  执行主播库
                </el-button>

                <el-button type="primary" text @click="showMyInfo = true">
                  配置 / 修改 AI 人设
                </el-button>
                <el-button type="danger" text @click="doLogout">
                  退出登录
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- AI 人设配置弹窗 -->
    <AgentGuildDialog v-model="showMyInfo" :model="{
      agentName: borkerConfig.agentName,
      guildName: borkerConfig.guildName,
      contactTool: borkerConfig.contactTool,
      contact: borkerConfig.contact
    }" @save="onSave" />

    <HostListManagerDialog v-model:visible="showHostDlg" />
    <TranslationDialog v-model="showtransDlg" :translateFn="doTranslate" storage-key-prefix="demo-translation"
      @confirm="onConfirm" @cancel="" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'

import { getUser } from '@/stores/storage'
import { logout, health } from '@/api/account'
import { aiConfig, run, shutdown } from '@/api/ios'
import { customTranslation } from '@/api/chat'

import AgentGuildDialog from '@/components/AgentGuildDialog.vue'
import HostListManagerDialog from '@/components/HostListManagerDialog.vue'
import TranslationDialog from '@/components/translationDialog.vue'

/** =========================
 * 基础状态 / 常量
 * ========================= */

// 路由实例：用于退出登录后跳转
const router = useRouter()

// 当前登录用户信息（本地缓存）
const userdata = getUser()

// localStorage 存储 key：保存运行配置（账号组/开关/间隔等）
const RUN_CONFIG_CACHE_KEY = 'autoDm_runConfig'

// 弹窗控制：AI人设 / 主播库 / 翻译弹窗
const showMyInfo = ref(false)
const showHostDlg = ref(false)
const showtransDlg = ref(false)

// AI 人设是否已配置（用于顶部 tag 显示）
const aiConfigured = ref(false)

// 心跳定时器（health 检测）
const getListTimer = ref(null)

// AI 人设配置表单（给 AgentGuildDialog 用）
const borkerConfig = reactive({
  agentName: '',
  guildName: '',
  contactTool: '',
  contact: ''
})


/** =========================
 * 运行配置
 * - rotateEnabled：是否启用账号组轮换
 * - groupCount：轮换时启用的组数量（1~3）
 * - accountGroups：账号组列表，每组最多3个账号
 * - switchHours：轮换间隔（小时）
 * ========================= */
const runForm = reactive({
  rotateEnabled: false, // 关闭时：只跑第1组，不切换
  groupCount: 1,        // 开启轮换时：2 或 3（你 UI 里限制了）

  accountGroups: [
    { name: '第1组', accounts: [{ email: '', pwd: '' }] },
  ],

  aiReply: true,
  sendInviteFirst: false,
  sleepTime: 0,
  inviteThreshold: 3,
  switchHours: 1,
})


const visibleGroups = computed(() => {
  // 不轮换：只显示第1组
  if (!runForm.rotateEnabled) return runForm.accountGroups.slice(0, 1)
  // 轮换：显示前 groupCount 组
  return runForm.accountGroups.slice(0, runForm.groupCount || 1)
})


/** =========================
 * 运行状态（轮换引擎使用）
 * ========================= */
//“加载中”标记
const isHydrating = ref(true)
// 是否处于运行中（用于控制开始/停止按钮、轮换检测）
const running = ref(false)

// 当前正在运行的组下标（0/1/2）
const currentGroupIndex = ref(0)

// 上一次切组的时间戳（ms）
const lastSwitchAt = ref(0)

// 轮换检测 timer：每分钟检查一次是否到达切换时间
const switchCheckTimer = ref(null)

// 可选：记录 run 接口返回/错误（目前未展示）
const runResult = ref('')

// 切换锁：防止切换过程中重复触发切换
let switchingLock = false

// 停止时 loading 实例
let stopLoading = null


/** =========================
 *  配置持久化：读取/保存
 *  ========================= */
function loadRunConfig() {
  try {
    const raw = localStorage.getItem(RUN_CONFIG_CACHE_KEY)
    if (!raw) return
    const cfg = JSON.parse(raw)

    // 兼容旧版：cfg.account -> 第1组
    if (Array.isArray(cfg.account) && !cfg.accountGroups) {
      const normalized = cfg.account
        .filter(item => item && typeof item.email === 'string' && typeof item.pwd === 'string')
        .slice(0, 3)

      if (normalized.length) {
        runForm.accountGroups[0].accounts.splice(
          0,
          runForm.accountGroups[0].accounts.length,
          ...normalized
        )
      }
    }

    // 新版：accountGroups
    if (Array.isArray(cfg.accountGroups)) {
      const groups = cfg.accountGroups.slice(0, 3).map((g, idx) => ({
        name: g?.name || `第${idx + 1}组`,
        accounts: Array.isArray(g?.accounts) && g.accounts.length
          ? g.accounts
            .filter(a => a && typeof a.email === 'string' && typeof a.pwd === 'string')
            .slice(0, 3)
          : [{ email: '', pwd: '' }],
      }))

      while (groups.length < 3) {
        groups.push({ name: `第${groups.length + 1}组`, accounts: [{ email: '', pwd: '' }] })
      }

      runForm.accountGroups.splice(0, runForm.accountGroups.length, ...groups)
    }

    if (typeof cfg.aiReply === 'boolean') runForm.aiReply = cfg.aiReply
    if (typeof cfg.sendInviteFirst === 'boolean') runForm.sendInviteFirst = cfg.sendInviteFirst
    if (typeof cfg.sleepTime === 'number') runForm.sleepTime = cfg.sleepTime
    if (typeof cfg.inviteThreshold === 'number') runForm.inviteThreshold = cfg.inviteThreshold
    if (typeof cfg.switchHours === 'number' && cfg.switchHours >= 1) runForm.switchHours = cfg.switchHours
    if (typeof cfg.rotateEnabled === 'boolean') runForm.rotateEnabled = cfg.rotateEnabled
    if (typeof cfg.groupCount === 'number') runForm.groupCount = Math.min(3, Math.max(1, cfg.groupCount))
    ensureGroups(runForm.groupCount)
  } catch (e) {
    console.error('加载运行配置失败', e)
  }
}

function saveRunConfig() {
  try {
    const payload = {
      accountGroups: runForm.accountGroups.map(g => ({
        name: g.name || '',
        accounts: (g.accounts || []).slice(0, 3).map(a => ({
          email: a.email || '',
          pwd: a.pwd || '',
        }))
      })).slice(0, 3),
      aiReply: runForm.aiReply,
      sendInviteFirst: runForm.sendInviteFirst,
      sleepTime: runForm.sleepTime,
      inviteThreshold: runForm.inviteThreshold,
      switchHours: runForm.switchHours,
      rotateEnabled: runForm.rotateEnabled,
      groupCount: runForm.groupCount,
    }
    localStorage.setItem(RUN_CONFIG_CACHE_KEY, JSON.stringify(payload))
  } catch (e) {
    console.error('保存运行配置失败', e)
  }
}
/**
 * 根据 groupCount 自动维护账号组数量（1~3）
 * - 不足则补组（默认每组1个空账号输入框）
 * - 多余则裁剪
 * - 当前运行组越界时重置为 0
 */
function ensureGroups(count) {
  const c = Math.min(3, Math.max(1, Number(count) || 1))

  // 补足
  while (runForm.accountGroups.length < c) {
    const idx = runForm.accountGroups.length
    runForm.accountGroups.push({
      name: `第${idx + 1}组`,
      accounts: [{ email: '', pwd: '' }],
    })
  }

  // 裁剪
  if (runForm.accountGroups.length > c) {
    runForm.accountGroups.splice(c)
  }

  // 防止当前组越界
  if (currentGroupIndex.value >= c) currentGroupIndex.value = 0
}

// groupCount 变化：调整组数量并保存
watch(
  () => runForm.groupCount,
  (val) => {
    ensureGroups(val)
    if (isHydrating.value) return
    saveRunConfig()
  },
  { immediate: true }
)

// 任一配置变化：自动保存到 localStorage（✅补上 rotateEnabled/groupCount）
watch(
  () => ({
    accountGroups: runForm.accountGroups,
    aiReply: runForm.aiReply,
    sendInviteFirst: runForm.sendInviteFirst,
    sleepTime: runForm.sleepTime,
    inviteThreshold: runForm.inviteThreshold,
    switchHours: runForm.switchHours,
    rotateEnabled: runForm.rotateEnabled,
    groupCount: runForm.groupCount,
  }),
  () => {
    if (isHydrating.value) return
    saveRunConfig()
  },
  { deep: true }
)
watch(
  () => runForm.rotateEnabled,
  (enabled) => {
    if (!enabled) {
      runForm.groupCount = 1
      ensureGroups(1)       // 只保留第1组
      stopSwitchTimer()     // 双保险：确保不会有轮换timer
    } else {
      // 开启轮换时，至少2组（你UI只有2/3）
      if (runForm.groupCount < 2) runForm.groupCount = 2
      ensureGroups(runForm.groupCount)
    }
    if (isHydrating.value) return
    saveRunConfig()
  },
  { immediate: true }
)

/** =========================
 *  生命周期
 *  ========================= */
onMounted(async () => {
  loadRunConfig()
  isHydrating.value = false
  // MQ 链接
  window.electronAPI.startMq(userdata.tenantId, userdata.id)

  // 心跳
  getListTimer.value = setInterval(() => {
    health().catch(() => stop())
  }, 3000)

  // 检查 AI 人设
  if (!(await isAiConfig())) {
    showMyInfo.value = true
    aiConfigured.value = false
  } else {
    aiConfigured.value = true
  }
})

onUnmounted(() => {
  if (getListTimer.value) clearInterval(getListTimer.value)
  getListTimer.value = null
  stopSwitchTimer()
})

/** =========================
 *  业务：AI配置/退出
 *  ========================= */
function onSave(payload) {
  aiConfig(payload).then(() => {
    aiConfigured.value = true
    ElMessage.success('AI 人设配置已保存')
  })
}

async function isAiConfig() {
  const res = await window.electronAPI.fileExists()
  return res.exists
}

async function doLogout() {
  try {
    if (getListTimer.value) clearInterval(getListTimer.value)
    getListTimer.value = null
    await logout({ userId: userdata.id, tenantId: userdata.tenantId })
  } finally {
    router.push('/')
  }
}

/** =========================
 *  账号组增删
 *  ========================= */
function addAccount(groupIndex) {
  const group = runForm.accountGroups[groupIndex]
  if (!group) return
  if (group.accounts.length >= 3) return
  group.accounts.push({ email: '', pwd: '' })
  saveRunConfig()
}

function removeAccount(groupIndex, accountIndex) {
  const group = runForm.accountGroups[groupIndex]
  if (!group) return
  if (group.accounts.length === 1) return
  group.accounts.splice(accountIndex, 1)
  saveRunConfig()
}

/** =========================
 *  核心：按组运行
 *  ========================= */
async function runGroup(groupIndex, strings, needTranslate) {
  const group = runForm.accountGroups[groupIndex]
  if (!group) return false

  const validAccounts = (group.accounts || []).filter(a => a.email && a.pwd)
  if (!validAccounts.length) {
    ElMessage.error(`第${groupIndex + 1}组没有可用账号（邮箱和密码不能为空）`)
    return false
  }

  const list = runForm.sendInviteFirst ? [] : (strings || [])
  const payload = {
    account: validAccounts,
    aiReply: runForm.aiReply,
    sendInviteFirst: runForm.sendInviteFirst,
    prologueList: list,
    needTranslate,
    sleepTime: runForm.sleepTime,
    inviteThreshold: runForm.inviteThreshold,
  }

  await run(payload)
  return true
}

/**
 * 启动轮换检测定时器：每分钟检查一次是否到达切换点
 * 注意：不用 setTimeout(1小时) 是为了减少计时漂移影响
 */
function startSwitchTimer(strings, needTranslate) {
  stopSwitchTimer()
  lastSwitchAt.value = Date.now()

  switchCheckTimer.value = setInterval(async () => {
    if (!running.value) return

    const intervalMs = (runForm.switchHours || 1) * 60 * 1000
    const now = Date.now()

    // 到达切换点 -> 切到下一组
    if (now - lastSwitchAt.value >= intervalMs) {
      await switchToNextGroup(strings, needTranslate)
    }
  }, 60 * 1000)
}

/** 停止轮换检测定时器 */
function stopSwitchTimer() {
  if (switchCheckTimer.value) {
    clearInterval(switchCheckTimer.value)
    switchCheckTimer.value = null
  }
}

/**
 * 切换到下一组：
 * 1) shutdown 当前任务
 * 2) 按 groupCount 范围内寻找下一组有有效账号的组并 run
 * 3) 若都无效 -> stop
 */
async function switchToNextGroup(strings, needTranslate) {
  if (switchingLock) return
  switchingLock = true

  try {
    const groupCount = runForm.rotateEnabled ? (runForm.groupCount || 1) : 1
    const nextIndex = (currentGroupIndex.value + 1) % groupCount

    // 先停
    try {
      await shutdown()
    } catch (e) {
      console.warn('切换时 shutdown 失败（继续尝试 run 下一组）', e)
    }

    // 再跑：最多尝试 groupCount 次
    for (let i = 0; i < groupCount; i++) {
      const idx = (nextIndex + i) % groupCount
      const ok = await runGroup(idx, strings, needTranslate)
      if (ok) {
        currentGroupIndex.value = idx
        lastSwitchAt.value = Date.now()
        ElMessage.success(`已切换到第 ${idx + 1} 组`)
        return
      }
    }

    ElMessage.error('所有账号组都没有可用账号，已停止轮换')
    await stop()
  } finally {
    switchingLock = false
  }
}


/**
 * 启动运行：
 * - 默认从第1组开始
 * - 如果开启轮换：启动轮换检测 timer
 * - 如果不轮换：确保轮换 timer 关闭
 */
async function startRotation(strings, needTranslate) {
  runResult.value = ''
  currentGroupIndex.value = 0

  try {
    const ok = await runGroup(currentGroupIndex.value, strings, needTranslate)
    if (!ok) return

    running.value = true
    showtransDlg.value = false

    if (runForm.rotateEnabled) {
      startSwitchTimer(strings, needTranslate)
      ElMessage.success(`启动成功：轮换开启（第 ${currentGroupIndex.value + 1} 组运行中）`)
    } else {
      stopSwitchTimer()
      ElMessage.success(`启动成功：不轮换（第1组持续运行）`)
    }
  } catch (err) {
    console.error(err)
    runResult.value = String(err)
    ElMessage.error('启动失败')
    running.value = false
    stopSwitchTimer()
  }
}

function startRun() {
  if (runForm.sendInviteFirst) {
    startRotation(undefined, false)
  } else {
    showtransDlg.value = true
  }
}

async function stop() {
  stopSwitchTimer()
  switchingLock = false

  stopLoading = ElLoading.service({
    lock: true,
    text: '停止中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    await shutdown()
    running.value = false
    ElMessage.success('停止成功')
  } catch (e) {
    console.error(e)
    running.value = false
    ElMessage.error('停止失败')
  } finally {
    stopLoading?.close?.()
  }
}

/** =========================
 *  翻译弹窗相关
 *  ========================= */
function onConfirm(data) {
  startRotation(data.strings, data.needTranslate)
}

async function doTranslate(sentences, targetLang) {
  const str = arrayToString(sentences)
  try {
    const response = await customTranslation({ msg: str, language: targetLang })

    const raw = response.replace(/^{|}$/g, '')
    const arr = raw.split('\n').map(s => s.trim()).filter(Boolean)
    return arr
  } catch (error) {
    console.error('Translation error:', error)
    return []
  }
}

function arrayToString(arr) {
  return arr.filter(Boolean).join('  \n')
}

/** =========================
 *  UI小工具
 *  ========================= */
function printCurrentTime() {
  return new Date().toLocaleString()
}
</script>


<style scoped lang="less">
@import '../static/css/video.less';
</style>
