<script setup lang="ts">
import type { CaseStep } from '../types'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import AppEditor from '@/components/base/AppEditor.vue'
import { dmlMenus } from '@/utils/dmlMenus'

// 步骤类型枚举
enum StepType {
  ORIGIN = 1, // 案例原文
  TASK = 2, // 任务
  SUMMARY = 3, // 案例总结
}

interface Props {
  modelValue: CaseStep[]
}

interface Emits {
  (e: 'update:modelValue', value: CaseStep[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 编辑相关状态
const editOriginDialogVisible = ref(false)
const editTaskDialogVisible = ref(false)
const editingStep = ref<CaseStep | null>(null)

// 操作步骤相关状态
const selectedStep = ref<number>(1)
const hasOperationSteps = ref<boolean>(false)
const operationSteps = ref<
  Array<{ id: number; content: string; relatedFunction?: { id: number; name: string; path: string } }>
>([])

// 计算属性：确保始终有固定的首尾节点
const steps = computed({
  get: () => {
    const currentSteps = [...props.modelValue]

    // 确保有案例原文节点
    if (!currentSteps.find((s) => s.type === StepType.ORIGIN)) {
      currentSteps.unshift({
        id: 'origin',
        type: StepType.ORIGIN,
        name: '案例原文',
        content: '',
      })
    }

    // 确保有案例总结节点
    if (!currentSteps.find((s) => s.type === StepType.SUMMARY)) {
      currentSteps.push({
        id: 'summary',
        type: StepType.SUMMARY,
        name: '案例总结',
      })
    }

    return currentSteps
  },
  set: (value) => {
    emit('update:modelValue', value)
  },
})

// 计算属性：当前选中步骤的内容
const currentStepContent = computed({
  get: () => {
    const step = operationSteps.value.find((s) => s.id === selectedStep.value)
    return step?.content || ''
  },
  set: (value: string) => {
    const stepIndex = operationSteps.value.findIndex((s) => s.id === selectedStep.value)
    if (stepIndex !== -1) {
      operationSteps.value[stepIndex].content = value
    }
  },
})

// 计算属性：当前选中步骤的关联功能ID
const currentStepRelatedFunctionId = computed({
  get: () => {
    const step = operationSteps.value.find((s) => s.id === selectedStep.value)
    return step?.relatedFunction?.id || null
  },
  set: (value: number | null) => {
    const stepIndex = operationSteps.value.findIndex((s) => s.id === selectedStep.value)
    if (stepIndex !== -1) {
      if (value) {
        // 根据ID查找对应的功能信息
        const findFunction = (menus: any[]): any => {
          for (const menu of menus) {
            if (menu.id === value) {
              return { id: menu.id, name: menu.name, path: menu.path }
            }
            if (menu.children) {
              const found = findFunction(menu.children)
              if (found) return found
            }
          }
          return null
        }

        const functionInfo = findFunction(dmlMenus)
        if (functionInfo) {
          operationSteps.value[stepIndex].relatedFunction = functionInfo
        }
      } else {
        delete operationSteps.value[stepIndex].relatedFunction
      }
    }
  },
})

// 编辑步骤
function editStep(step: CaseStep) {
  editingStep.value = { ...step }

  if (step.type === StepType.ORIGIN) {
    editOriginDialogVisible.value = true
  } else if (step.type === StepType.TASK) {
    // 恢复任务的操作步骤数据
    if (step.config?.operationSteps) {
      operationSteps.value = [...step.config.operationSteps]
      hasOperationSteps.value = operationSteps.value.length > 0
      selectedStep.value = operationSteps.value.length > 0 ? 1 : 1
    } else {
      // 重置操作步骤状态
      operationSteps.value = []
      hasOperationSteps.value = false
      selectedStep.value = 1
    }
    editTaskDialogVisible.value = true
  }
}

// 保存编辑
function saveEdit() {
  if (editingStep.value) {
    const index = steps.value.findIndex((s) => s.id === editingStep.value!.id)
    if (index !== -1) {
      const newSteps = [...steps.value]
      const updatedStep = { ...editingStep.value }

      // 如果是任务，保存操作步骤内容
      if (editingStep.value.type === StepType.TASK && hasOperationSteps.value) {
        updatedStep.config = {
          operationSteps: operationSteps.value,
        }
      }

      newSteps[index] = updatedStep
      steps.value = newSteps
    }
  }
  editOriginDialogVisible.value = false
  editTaskDialogVisible.value = false
  editingStep.value = null
}

// 添加任务
function addTask(afterIndex: number) {
  const newTask: CaseStep = {
    id: `task_${Date.now()}`,
    type: StepType.TASK,
    name: `任务${steps.value.filter((s) => s.type === StepType.TASK).length + 1}`,
  }
  const newSteps = [...steps.value]
  newSteps.splice(afterIndex + 1, 0, newTask)
  steps.value = newSteps
}

// 删除任务
function deleteTask(stepId: string) {
  const index = steps.value.findIndex((s) => s.id === stepId)
  if (index !== -1 && steps.value[index].type === StepType.TASK) {
    const newSteps = [...steps.value]
    newSteps.splice(index, 1)
    steps.value = newSteps
  }
}

// 添加操作步骤
function addOperationStep() {
  if (!hasOperationSteps.value) {
    hasOperationSteps.value = true
  }
  const newStepId = operationSteps.value.length + 1
  operationSteps.value.push({
    id: newStepId,
    content: '',
    relatedFunction: undefined,
  })
  selectedStep.value = newStepId
}

// 删除操作步骤
function deleteStep(stepId: number) {
  // 删除指定步骤
  const stepIndex = operationSteps.value.findIndex((s) => s.id === stepId)
  if (stepIndex !== -1) {
    operationSteps.value.splice(stepIndex, 1)

    // 重新整理步骤编号
    operationSteps.value.forEach((step, index) => {
      step.id = index + 1
    })

    // 调整选中状态
    if (operationSteps.value.length === 0) {
      // 如果没有步骤了，重置状态
      hasOperationSteps.value = false
      selectedStep.value = 1
    } else if (selectedStep.value >= stepId) {
      selectedStep.value = Math.max(1, selectedStep.value - 1)
    }
  }
}
</script>

<template>
  <div class="case-steps">
    <div class="steps-container">
      <template v-for="(step, index) in steps" :key="step.id">
        <!-- 步骤节点 -->
        <div
          class="step-node"
          :class="{
            origin: step.type === StepType.ORIGIN,
            task: step.type === StepType.TASK,
            summary: step.type === StepType.SUMMARY,
          }">
          <span class="step-name">{{ step.name }}</span>

          <!-- 遮罩层 -->
          <div class="node-overlay">
            <!-- 编辑按钮 -->
            <el-button
              v-if="step.type === StepType.ORIGIN || step.type === StepType.TASK"
              size="small"
              class="action-btn edit-btn"
              type="primary"
              circle
              :icon="Edit"
              @click="editStep(step)">
            </el-button>

            <!-- 删除按钮（仅任务节点） -->
            <el-button
              v-if="step.type === StepType.TASK"
              size="small"
              class="action-btn delete-btn"
              @click="deleteTask(step.id)"
              type="danger"
              :icon="Delete"
              circle>
            </el-button>
          </div>
        </div>

        <!-- 连接线和添加按钮 -->
        <div v-if="index < steps.length - 1" class="step-line-container">
          <div class="step-line"></div>
          <el-button
            v-if="step.type === StepType.TASK || step.type === StepType.ORIGIN"
            class="add-task-btn"
            size="small"
            :icon="Plus"
            @click="addTask(index)"></el-button>
        </div>
      </template>
    </div>
  </div>

  <!-- 编辑案例原文弹窗 -->
  <el-dialog v-model="editOriginDialogVisible" title="编辑案例原文" width="800px">
    <el-form v-if="editingStep && editingStep.type === StepType.ORIGIN" :model="editingStep" label-position="top">
      <el-form-item label="名称">
        <el-input v-model="editingStep.name" />
      </el-form-item>
      <el-form-item label="内容">
        <AppEditor v-model="editingStep.content" placeholder="请输入案例原文内容" hasAI />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editOriginDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveEdit">保存</el-button>
    </template>
  </el-dialog>

  <!-- 编辑任务弹窗 -->
  <el-dialog v-model="editTaskDialogVisible" title="编辑任务" width="800px">
    <el-form v-if="editingStep && editingStep.type === StepType.TASK" :model="editingStep" label-position="top">
      <el-form-item label="任务名称">
        <el-input v-model="editingStep.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="任务描述">
        <AppEditor v-model="editingStep.content" placeholder="请输入任务描述" hasAI />
      </el-form-item>

      <!-- 操作步骤 -->
      <el-form-item label="操作步骤">
        <div class="steps-selector">
          <div class="steps-row">
            <div
              v-for="step in operationSteps"
              :key="step.id"
              class="step-circle"
              :class="{ active: selectedStep === step.id }"
              @click="selectedStep = step.id">
              {{ step.id }}
              <el-button size="small" type="danger" class="delete-step-btn" circle @click.stop="deleteStep(step.id)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button type="primary" @click="addOperationStep" class="add-step-btn"> 添加操作步骤 </el-button>
          </div>
        </div>
      </el-form-item>

      <!-- 步骤内容编辑器 -->
      <el-form-item v-if="hasOperationSteps && selectedStep" :label="`步骤${selectedStep}:`">
        <el-tree-select
          v-model="currentStepRelatedFunctionId"
          placeholder="请选择关联功能"
          :render-after-expand="false"
          :data="dmlMenus"
          node-key="id"
          :props="{ label: 'name' }"
          clearable
          style="width: 100%; margin-bottom: 10px" />
        <AppEditor v-model="currentStepContent" placeholder="在这里开始编辑您的富媒体内容..." hasAI />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editTaskDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveEdit">保存</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.case-steps {
  margin: 20px 0;
  width: 100%;
  min-width: 0; /* 确保flex子元素可以收缩 */

  .steps-container {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 10px;
    overflow-x: auto;
    overflow-y: hidden;
    padding: 20px 0;

    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;

      &:hover {
        background: #a8a8a8;
      }
    }
  }

  .step-node {
    position: relative;
    width: 120px;
    height: 120px;
    border: 2px solid #dcdfe6;
    border-radius: 50%;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    cursor: pointer;
    transition: all 0.3s;
    flex-shrink: 0; /* 防止圆形被压缩 */

    &.origin {
      border-color: #409eff;
      background: #f0f6ff;

      &:hover {
        box-shadow: 0 0 10px rgba(64, 158, 255, 0.3);

        .node-overlay {
          opacity: 1;
          visibility: visible;
        }
      }
    }

    &.task {
      border-color: #e6a23c;
      background: #fdf6ec;

      &:hover {
        box-shadow: 0 0 10px rgba(230, 162, 60, 0.3);

        .node-overlay {
          opacity: 1;
          visibility: visible;
        }
      }
    }

    &.summary {
      border-color: #67c23a;
      background: #f6ffed;

      &:hover {
        box-shadow: 0 0 10px rgba(103, 194, 58, 0.3);

        .node-overlay {
          opacity: 1;
          visibility: visible;
        }
      }
    }

    .step-name {
      font-size: 14px;
      font-weight: 500;
      text-align: center;
      line-height: 1.2;
      z-index: 2;
      position: relative;
    }

    .node-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
      z-index: 3;
    }

    .action-btn {
      width: 32px;
      height: 32px;
      padding: 0;
      font-size: 14px;
      border: 2px solid #fff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

      &:hover {
        transform: scale(1.1);
      }
    }
  }

  .step-line-container {
    position: relative;
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 10px 0;
    flex-shrink: 0; /* 防止连接线被压缩 */

    .step-line {
      width: 80px;
      height: 2px;
      background: var(--main-color);
      position: relative;
      transition: all 0.3s;

      &::after {
        content: '';
        position: absolute;
        right: -5px;
        top: -3px;
        width: 0;
        height: 0;
        border-left: 8px solid var(--main-color);
        border-top: 4px solid transparent;
        border-bottom: 4px solid transparent;
      }
    }

    &:hover .step-line {
      background: #ff7875;
      box-shadow: 0 0 8px rgba(245, 108, 108, 0.4);
    }

    .add-task-btn {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 10;
      opacity: 0;
      visibility: hidden;
    }

    &:hover .add-task-btn {
      opacity: 1;
      visibility: visible;
    }
  }
}

/* 操作步骤样式 */
.no-steps {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.steps-selector {
  .steps-row {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
  }

  .step-circle {
    position: relative;
    width: 32px;
    height: 32px;
    border: 2px solid var(--main-color);
    border-radius: 50%;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background: #fef0f0;

      .delete-step-btn {
        opacity: 1;
        visibility: visible;
      }
    }

    &.active {
      background: var(--main-color);
      color: #fff;
      border-color: var(--main-color);
      box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
    }

    .delete-step-btn {
      position: absolute;
      top: -8px;
      right: -8px;
      width: 16px;
      height: 16px;
      padding: 0;
      font-size: 8px;
      opacity: 0;
      visibility: hidden;
      transition: all 0.2s;
      z-index: 10;
    }
  }
}

/* 步骤编辑器样式 */
.step-editor-header {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}
</style>
