// @ts-nocheck
import { debugLog } from '../common';
import { usePolicyStore } from '../../../stores/policy';
import { useModelStore } from '../../../stores/model';
import { usePersonalizationStore } from '../../../stores/personalization';
import { useTutorialStore } from '../../../stores/tutorial';
import { renderMarkdown as renderMarkdownHelper } from '../../../composables/useMarkdownRenderer';
import { scrollToBottom as scrollToBottomHelper, conditionalScrollToBottom as conditionalScrollToBottomHelper, scrollThinkingToBottom as scrollThinkingToBottomHelper } from '../../../composables/useScrollControl';
import { startResize as startPanelResize, handleResize as handlePanelResize, stopResize as stopPanelResize } from '../../../composables/usePanelResize';
import {
  SUB_AGENT_DONE_PREFIX_RE,
  BG_RUN_COMMAND_DONE_PREFIX_RE,
  userMDebug,
  UI_BOUNCE_TRACE_MAX,
  uiBounceTraceLastTsByKey,
  isUiBounceTraceEnabled,
  uiBounceTrace,
  isConnectionDiagEnabled,
  pushConnectionDiagRecord,
  connectionDiag,
  parseSubAgentDoneLabel,
  parseBackgroundRunCommandDoneLabel,
  parseSystemNoticeLabel,
} from './shared';

export const dialogMethods = {
  openPersonalPage() {
    if (this.isPolicyBlocked('block_personal_space', '个人空间已被管理员禁用')) {
      return;
    }
    this.personalizationOpenDrawer();
  },
  closeHostWorkspaceManageDialog() {
    if (this.hostWorkspaceCreateSubmitting || this.hostWorkspaceManageSubmitting) {
      return;
    }
    this.hostWorkspaceManageDialogOpen = false;
    this.hostWorkspaceCreateError = '';
  },
  closeHostWorkspaceCreateDialog() {
    if (this.hostWorkspaceCreateSubmitting) {
      return;
    }
    this.hostWorkspaceCreateDialogOpen = false;
    this.hostWorkspaceCreateError = '';
  },
  minimizeUserQuestionDialog() {
    if (!Array.isArray(this.pendingUserQuestions) || !this.pendingUserQuestions.length) {
      return;
    }
    this.userQuestionDialogVisible = false;
    this.userQuestionMinimized = true;
  },
  restoreUserQuestionDialog() {
    if (!Array.isArray(this.pendingUserQuestions) || !this.pendingUserQuestions.length) {
      return;
    }
    this.userQuestionDialogVisible = true;
    this.userQuestionMinimized = false;
  },
  approveToolApproval(approvalId) {
    return this.decideToolApproval(approvalId, 'approved');
  },
  rejectToolApproval(approvalId) {
    return this.decideToolApproval(approvalId, 'rejected');
  },
  openReviewDialog() {
    if (this.isPolicyBlocked('block_conversation_review', '对话引用已被管理员禁用')) {
      return;
    }
    if (!this.isConnected) {
      this.uiPushToast({
        title: '无法使用',
        message: '当前未连接，无法生成回顾文件',
        type: 'warning'
      });
      return;
    }
    this.reviewDialogOpen = true;
    this.reviewSelectedConversationId = null;
    this.reviewPreviewLines = [];
    this.reviewPreviewError = null;
    this.reviewGeneratedPath = null;
    this.closeQuickMenu();
    // 弹窗使用独立列表（仅含有内容的对话），加载完成后自动选中首个可用项
    this.loadReviewConversations();
  },
  autoSelectReviewConversation() {
    if (this.reviewSelectedConversationId) return;
    const fallback = this.reviewConversations.find((c) => c.id !== this.currentConversationId);
    if (fallback && fallback.id) {
      this.reviewSelectedConversationId = fallback.id;
      this.loadReviewPreview(fallback.id);
    }
  },
  closeHeaderMenu() {
    this.headerMenuOpen = false;
  },
  handleReviewSelect(id) {
    if (id === this.currentConversationId) {
      this.uiPushToast({
        title: '无法引用当前对话',
        message: '请选择其他对话生成回顾',
        type: 'warning'
      });
      return;
    }
    this.reviewSelectedConversationId = id;
    this.loadReviewPreview(id);
  },
  confirmAction(options = {}) {
    return this.uiRequestConfirm(options);
  },
  async submitUserQuestionAnswers(answers) {
    const list = Array.isArray(answers) ? answers : [];
    if (!list.length) {
      return;
    }
    const ids = list.map((item) => String(item?.question_id || '')).filter(Boolean);
    this.answeringUserQuestionIds = ids;
    try {
      for (const answer of list) {
        const questionId = String(answer?.question_id || '').trim();
        if (!questionId) {
          continue;
        }
        const response = await fetch(`/api/user-questions/${encodeURIComponent(questionId)}/answer`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            selected_option_id: answer?.selected_option_id || undefined,
            text: answer?.text || ''
          })
        });
        const payload = await response.json().catch(() => ({}));
        if (!response.ok || !payload?.success) {
          throw new Error(payload?.message || payload?.error || '提交回答失败');
        }
      }
      this.pendingUserQuestions = (this.pendingUserQuestions || []).filter(
        (item) => item && !ids.includes(String(item.question_id || ''))
      );
      if (!this.pendingUserQuestions.length) {
        this.userQuestionDialogVisible = false;
        this.userQuestionMinimized = false;
        this.userQuestionActiveIndex = 0;
        if (typeof this.restoreUserQuestionTitle === 'function') {
          this.restoreUserQuestionTitle();
        }
      } else {
        this.userQuestionActiveIndex = Math.min(this.userQuestionActiveIndex, this.pendingUserQuestions.length - 1);
      }
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error || '提交回答失败');
      this.uiPushToast({ title: '提交回答失败', message: msg, type: 'error' });
    } finally {
      this.answeringUserQuestionIds = [];
    }
  },
  async answerUserQuestionFromComposer(text) {
    const clean = String(text || '').trim();
    if (!clean || !Array.isArray(this.pendingUserQuestions) || !this.pendingUserQuestions.length) {
      return false;
    }
    const index = Math.min(
      Math.max(0, Number(this.userQuestionActiveIndex || 0)),
      Math.max(0, this.pendingUserQuestions.length - 1)
    );
    const question = this.pendingUserQuestions[index] || this.pendingUserQuestions[0];
    if (!question?.question_id) {
      return false;
    }
    await this.submitUserQuestionAnswers([{ question_id: question.question_id, text: clean }]);
    if (this.pendingUserQuestions.length > 0) {
      this.userQuestionDialogVisible = true;
      this.userQuestionMinimized = false;
    }
    return true;
  },
  async decideToolApproval(approvalId, decision) {
    const id = String(approvalId || '').trim();
    if (!id) {
      return;
    }
    if (!Array.isArray(this.decidingApprovalIds)) {
      this.decidingApprovalIds = [];
    }
    if (!this.decidingApprovalIds.includes(id)) {
      this.decidingApprovalIds.push(id);
    }
    try {
      const response = await fetch(`/api/tool-approvals/${encodeURIComponent(id)}/decision`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ decision })
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok || !payload?.success) {
        throw new Error(payload?.message || payload?.error || '提交审批失败');
      }
      this.pendingToolApprovals = (this.pendingToolApprovals || []).filter(
        (item) => item && item.approval_id !== id
      );
      if (!this.pendingToolApprovals.length) {
        this.rightCollapsed = true;
        if (this.isMobileViewport && this.activeMobileOverlay === 'approval') {
          this.closeMobileOverlay();
        }
      }
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error || '审批失败');
      this.uiPushToast({
        title: '审批失败',
        message: msg,
        type: 'error'
      });
    } finally {
      this.decidingApprovalIds = (this.decidingApprovalIds || []).filter((item) => item !== id);
    }
  }
};
