<!-- =============================================================================
// 企微IT智能服务台 — 排查步骤栏组件
// =============================================================================
// 说明：位于聊天输入框下方，始终可见（不可整体收起）
// 包含：
//   1. 默认视图：横向路径方块（①→②→③→④→⑤）
//   2. 展开视图：完整决策树（递归渲染）
// 数据：从 troubleshooting API 获取模板，默认选中第一个
// ============================================================================= -->

<template>
  <div class="troubleshoot-bar">
    <!-- ================================================================== -->
    <!-- 栏头（标题 + 模板选择 + 内联路径 + 三角切换） -->
    <!-- ================================================================== -->
    <div class="troubleshoot-bar__header">
      <span class="troubleshoot-bar__title">🔧 排查步骤</span>

      <!-- 模板选择下拉 -->
      <el-select
        v-model="selectedTemplateId"
        size="small"
        style="width: 140px;"
        @change="handleTemplateChange"
      >
        <el-option
          v-for="tpl in templates"
          :key="tpl.id"
          :label="tpl.name"
          :value="tpl.id"
        />
      </el-select>

      <!-- 内联路径步骤 -->
      <div class="troubleshoot-bar__path-inline">
        <template v-for="(step, index) in currentPathSteps" :key="index">
          <span
            class="path-step-inline"
            :class="`path-step-inline--${step.status}`"
            @click="handleStepClick(index)"
          >
            {{ index + 1 }} {{ step.label }}
          </span>
          <span v-if="index < currentPathSteps.length - 1" class="path-arrow-inline">→</span>
        </template>
      </div>

      <!-- 展开全流程图三角图标 -->
      <span
        class="troubleshoot-bar__toggle"
        @click="toggleFlowchart"
        :title="isFlowchartExpanded ? '收起全流程图' : '展开全流程图'"
      >{{ isFlowchartExpanded ? '▼' : '▶' }}</span>
    </div>

    <!-- ================================================================== -->
    <!-- 展开视图：决策树 -->
    <!-- ================================================================== -->
    <div
      class="troubleshoot-bar__flowchart"
      :class="{ 'is-expanded': isFlowchartExpanded }"
    >
      <div class="troubleshoot-bar__flowchart-inner">
        <FlowchartNode
          v-if="currentFlowchart"
          :node="currentFlowchart"
          :base-index="1"
        />
        <div v-else class="troubleshoot-bar__flowchart-empty">
          暂无流程图数据
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// ============================================================================
// 导入
// ============================================================================
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import FlowchartNode from './FlowchartNode.vue'
import {
  getTroubleshootingTemplates,
} from '@/api/troubleshooting'
import type { TroubleshootingTemplate, PathStep, FlowchartNode as FlowchartNodeType } from '@/api/troubleshooting'
import { useConversationStore } from '@/stores/conversation'

// ============================================================================
// 状态
// ============================================================================

const conversationStore = useConversationStore()

/** 是否展开全流程图 */
const isFlowchartExpanded = ref(false)

/** 模板列表 */
const templates = ref<TroubleshootingTemplate[]>([])

/** 当前选中的模板 ID */
const selectedTemplateId = ref<string>('')

/** 当前模板的路径步骤（本地状态，可由坐席推进） */
const localPathSteps = ref<PathStep[]>([])

/** 当前模板的流程图数据 */
const localFlowchart = ref<FlowchartNodeType | null>(null)

// ============================================================================
// 计算属性
// ============================================================================

/** 当前显示的路径步骤 */
const currentPathSteps = computed(() => {
  return localPathSteps.value
})

/** 当前显示的流程图 */
const currentFlowchart = computed(() => {
  return localFlowchart.value
})

// ============================================================================
// 方法
// ============================================================================

/**
 * 切换全流程图展开/收起
 */
function toggleFlowchart(): void {
  isFlowchartExpanded.value = !isFlowchartExpanded.value
}

/**
 * 模板选择变更
 */
function handleTemplateChange(templateId: string): void {
  const tpl = templates.value.find(t => t.id === templateId)
  if (tpl) {
    localPathSteps.value = [...tpl.path_steps]
    localFlowchart.value = tpl.flowchart || null
  }
}

/**
 * 点击路径方块 → 将该步骤设为 current
 *
 * @param index - 步骤索引
 */
function handleStepClick(index: number): void {
  const steps = localPathSteps.value
  if (!steps || index < 0 || index >= steps.length) return

  // 更新步骤状态：index 之前的为 done，当前为 current，之后的为 pending
  const updated = steps.map((step, i) => ({
    ...step,
    status: i < index ? 'done' as const : i === index ? 'current' as const : 'pending' as const,
  }))
  localPathSteps.value = updated

  // 同步更新流程图节点状态
  if (localFlowchart.value) {
    updateFlowchartStatus(localFlowchart.value, index)
  }

  ElMessage.success(`当前步骤：${steps[index].label}`)
}

/**
 * 递归更新流程图节点状态
 */
function updateFlowchartStatus(node: FlowchartNodeType, currentStepIndex: number): void {
  // 简单线性匹配：按遍历顺序给步骤编号
  let counter = 0
  function walk(n: FlowchartNodeType): void {
    if (n.type === 'step') {
      if (counter < currentStepIndex) {
        n.status = 'done'
      } else if (counter === currentStepIndex) {
        n.status = 'current'
      } else {
        n.status = 'pending'
      }
      counter++
      if (n.children) {
        for (const child of n.children) {
          walk(child)
        }
      }
    } else if (n.type === 'decision') {
      // 判断节点保持原状态
      n.status = 'pending'
      if (n.yes_branch) walk(n.yes_branch)
      if (n.no_branch) walk(n.no_branch)
    }
  }
  walk(node)
}

/**
 * 加载排查模板列表
 */
async function loadTemplates(): Promise<void> {
  try {
    const data = await getTroubleshootingTemplates()
    templates.value = data.items

    // 默认选中第一个模板
    if (data.items.length > 0) {
      selectedTemplateId.value = data.items[0].id
      localPathSteps.value = [...data.items[0].path_steps]
      localFlowchart.value = data.items[0].flowchart || null
    }
  } catch (error) {
    console.error('获取排查模板失败:', error)
    // 使用内置 Mock 数据
    loadFallbackMockData()
  }
}

/**
 * 内置 Mock 数据（API 不可用时的降级方案）
 */
function loadFallbackMockData(): void {
  const mockTemplates: TroubleshootingTemplate[] = [
    {
      id: 'tpl-vpn',
      name: 'VPN连接故障',
      category: 'vpn',
      is_active: true,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      path_steps: [
        { label: '确认VPN版本', status: 'done' },
        { label: '清除缓存重连', status: 'current' },
        { label: '远程排查', status: 'pending' },
        { label: '升级客户端', status: 'pending' },
        { label: '回访确认', status: 'pending' },
      ],
      flowchart: {
        id: 'fc-vpn-1',
        type: 'step',
        label: '确认VPN客户端版本',
        status: 'done',
        children: [
          {
            id: 'fc-vpn-2',
            type: 'decision',
            label: '版本是否为最新？',
            status: 'pending',
            yes_branch: {
              id: 'fc-vpn-3',
              type: 'step',
              label: '清除DNS缓存并重连',
              status: 'current',
              children: [
                {
                  id: 'fc-vpn-4',
                  type: 'decision',
                  label: '重连是否成功？',
                  status: 'pending',
                  yes_branch: {
                    id: 'fc-vpn-5',
                    type: 'step',
                    label: '回访确认',
                    status: 'pending',
                  },
                  no_branch: {
                    id: 'fc-vpn-6',
                    type: 'step',
                    label: '发起远程协助',
                    status: 'pending',
                    children: [
                      {
                        id: 'fc-vpn-7',
                        type: 'decision',
                        label: '远程能否解决？',
                        status: 'pending',
                        yes_branch: {
                          id: 'fc-vpn-8',
                          type: 'step',
                          label: '回访确认并结单',
                          status: 'pending',
                        },
                        no_branch: {
                          id: 'fc-vpn-9',
                          type: 'step',
                          label: '升级至二线团队',
                          status: 'pending',
                        },
                      },
                    ],
                  },
                },
              ],
            },
            no_branch: {
              id: 'fc-vpn-10',
              type: 'step',
              label: '升级VPN客户端到最新版',
              status: 'pending',
              children: [
                {
                  id: 'fc-vpn-11',
                  type: 'step',
                  label: '重试连接',
                  status: 'pending',
                },
              ],
            },
          },
        ],
      },
    },
    {
      id: 'tpl-email',
      name: '邮箱登录故障',
      category: 'email',
      is_active: true,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      path_steps: [
        { label: '确认邮箱状态', status: 'done' },
        { label: '重置密码', status: 'current' },
        { label: '检查配置', status: 'pending' },
        { label: '清理缓存', status: 'pending' },
        { label: '回访确认', status: 'pending' },
      ],
      flowchart: {
        id: 'fc-email-1',
        type: 'step',
        label: '确认邮箱账号状态',
        status: 'done',
        children: [
          {
            id: 'fc-email-2',
            type: 'decision',
            label: '账号是否被锁定？',
            status: 'pending',
            yes_branch: {
              id: 'fc-email-3',
              type: 'step',
              label: '解锁账号并重置密码',
              status: 'current',
            },
            no_branch: {
              id: 'fc-email-4',
              type: 'step',
              label: '检查Outlook配置',
              status: 'pending',
              children: [
                {
                  id: 'fc-email-5',
                  type: 'decision',
                  label: '配置是否正确？',
                  status: 'pending',
                  yes_branch: {
                    id: 'fc-email-6',
                    type: 'step',
                    label: '清理Outlook缓存',
                    status: 'pending',
                  },
                  no_branch: {
                    id: 'fc-email-7',
                    type: 'step',
                    label: '重新配置Outlook',
                    status: 'pending',
                  },
                },
              ],
            },
          },
        ],
      },
    },
    {
      id: 'tpl-system',
      name: '系统登录异常',
      category: 'system',
      is_active: true,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      path_steps: [
        { label: '确认系统状态', status: 'current' },
        { label: '清除浏览器缓存', status: 'pending' },
        { label: '更换浏览器', status: 'pending' },
        { label: '检查网络权限', status: 'pending' },
        { label: '回访确认', status: 'pending' },
      ],
      flowchart: {
        id: 'fc-sys-1',
        type: 'step',
        label: '确认系统服务是否正常',
        status: 'current',
        children: [
          {
            id: 'fc-sys-2',
            type: 'decision',
            label: '系统服务是否正常？',
            status: 'pending',
            yes_branch: {
              id: 'fc-sys-3',
              type: 'step',
              label: '清除浏览器缓存',
              status: 'pending',
              children: [
                {
                  id: 'fc-sys-4',
                  type: 'decision',
                  label: '清除后是否恢复？',
                  status: 'pending',
                  yes_branch: {
                    id: 'fc-sys-5',
                    type: 'step',
                    label: '回访确认并结单',
                    status: 'pending',
                  },
                  no_branch: {
                    id: 'fc-sys-6',
                    type: 'step',
                    label: '更换浏览器重试',
                    status: 'pending',
                  },
                },
              ],
            },
            no_branch: {
              id: 'fc-sys-7',
              type: 'step',
              label: '联系运维检查服务端',
              status: 'pending',
            },
          },
        ],
      },
    },
    {
      id: 'tpl-account',
      name: '账号权限问题',
      category: 'account',
      is_active: true,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      path_steps: [
        { label: '确认权限需求', status: 'current' },
        { label: '提交审批', status: 'pending' },
        { label: '配置权限', status: 'pending' },
        { label: '验证权限', status: 'pending' },
        { label: '回访确认', status: 'pending' },
      ],
      flowchart: {
        id: 'fc-acc-1',
        type: 'step',
        label: '确认权限需求与合规性',
        status: 'current',
        children: [
          {
            id: 'fc-acc-2',
            type: 'decision',
            label: '权限是否符合策略？',
            status: 'pending',
            yes_branch: {
              id: 'fc-acc-3',
              type: 'step',
              label: '提交权限审批流程',
              status: 'pending',
              children: [
                {
                  id: 'fc-acc-4',
                  type: 'step',
                  label: '审批通过后配置权限',
                  status: 'pending',
                },
              ],
            },
            no_branch: {
              id: 'fc-acc-5',
              type: 'step',
              label: '建议替代方案或申请特批',
              status: 'pending',
            },
          },
        ],
      },
    },
  ]

  templates.value = mockTemplates
  if (mockTemplates.length > 0) {
    selectedTemplateId.value = mockTemplates[0].id
    localPathSteps.value = [...mockTemplates[0].path_steps]
    localFlowchart.value = mockTemplates[0].flowchart
  }
}

// ============================================================================
// 生命周期
// ============================================================================

onMounted(() => {
  loadTemplates()
})

// 切换会话时重置步骤进度
watch(
  () => conversationStore.currentConversationId,
  () => {
    // 重新加载当前模板
    handleTemplateChange(selectedTemplateId.value)
    isFlowchartExpanded.value = false
  }
)
</script>

<style scoped>
/* 主容器 */
.troubleshoot-bar {
  background: var(--bg-secondary);
  border-top: 1px solid var(--border-color);
  flex-shrink: 0;
}

/* 栏头 — 紧凑单行：标题 + 下拉 + 内联路径 + 三角图标 */
.troubleshoot-bar__header {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  gap: 8px;
  min-height: 36px;
  background: var(--bg-tertiary);
  border-bottom: 1px solid var(--border-light);
}

.troubleshoot-bar__header:hover {
  background: var(--bg-hover);
}

.troubleshoot-bar__title {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
  white-space: nowrap;
  flex-shrink: 0;
}

/* 内联路径步骤（flex: 1 填充剩余空间） */
.troubleshoot-bar__path-inline {
  display: flex;
  align-items: center;
  gap: 0;
  flex: 1;
  overflow: hidden;
}

/* 紧凑步骤标签 */
.path-step-inline {
  padding: 2px 7px;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-light);
  border-radius: 3px;
  font-size: 11px;
  color: var(--text-secondary);
  white-space: nowrap;
  flex-shrink: 0;
  cursor: pointer;
  transition: all 0.2s;
}

.path-step-inline:hover {
  border-color: var(--accent);
  color: var(--accent);
}

/* 已完成 */
.path-step-inline--done {
  background: var(--color-success);
  border-color: var(--color-success);
  color: var(--bg-secondary);
}

/* 当前 */
.path-step-inline--current {
  background: var(--bg-accent-soft);
  border-color: var(--accent);
  color: var(--accent);
  font-weight: 600;
}

/* 待处理 */
.path-step-inline--pending {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
}

/* 内联箭头 */
.path-arrow-inline {
  display: flex;
  align-items: center;
  color: var(--text-tertiary);
  font-size: 10px;
  padding: 0 3px;
  flex-shrink: 0;
}

/* 三角切换图标 */
.troubleshoot-bar__toggle {
  font-size: 12px;
  color: var(--accent);
  cursor: pointer;
  padding: 4px 6px;
  border-radius: 3px;
  transition: all 0.2s;
  user-select: none;
  flex-shrink: 0;
  line-height: 1;
}

.troubleshoot-bar__toggle:hover {
  background: var(--bg-accent-soft);
}

/* 展开流程图区域 */
.troubleshoot-bar__flowchart {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.35s ease;
}

.troubleshoot-bar__flowchart.is-expanded {
  max-height: 800px;
  overflow-y: auto;
}

.troubleshoot-bar__flowchart-inner {
  padding: 12px 16px 16px;
  border-top: 1px solid var(--border-light);
}

.troubleshoot-bar__flowchart-empty {
  text-align: center;
  color: var(--text-tertiary);
  font-size: 12px;
  padding: 16px 0;
}
</style>
