<template>
  <div class="steps-display-container">
    <div v-if="parsedContent" class="steps-content">
    <button>删除</button>

      <h2 class="steps-title">{{ parsedContent.title }}</h2>
      <!-- <p class="steps-id">计划ID: {{ parsedContent.planId }}</p> -->
      <el-steps 
        :active="activeStep" 
        finish-status="success"
        class="custom-steps"
        :space="60"
        direction="vertical"
      >
        <el-step 
          v-for="(step, index) in parsedContent.steps" 
          :key="index"
          :title="'步骤 ' + (index + 1)"
        >
          <template #icon>
            <div class="step-icon-container">
              <div v-if="index < activeStep" class="step-icon completed">
                <el-icon><Check /></el-icon>
              </div>
              <div v-else-if="index === activeStep" class="step-icon current">
                <el-icon><Loading /></el-icon>
              </div>
              <div v-else style="border-radius: 50%;">
                {{ index + 1 }}
              </div>
            </div>
          </template>
          <template #title>
            <div class="step-title-container" @click.stop="toggleCollapse(index)">
              <span>步骤 {{ index + 1 }}</span>
              <el-button 
                type="text" 
                class="collapse-button" 
                
              >
                <el-icon>
                  <component :is="collapsedSteps[index] ? 'ArrowDown' : 'ArrowUp'"></component>
                </el-icon>
              </el-button>
            </div>
          </template>
          <template #description>
            <div :class="['step-description', { 'collapsed': collapsedSteps[index] }]">
              <div class="step-content">
                {{ step.stepRequirement }}
               <div>22312312</div>
               <div>22312312</div>
               <div>22312312</div>
               <div>22312312</div>

              </div>
            </div>
          </template>
        </el-step>
      </el-steps>
<!--       
      <div class="steps-controls">
        <el-button 
          type="primary" 
          size="small" 
          @click="prevStep" 
          :disabled="activeStep <= 0"
        >
          上一步
        </el-button>
        <el-button 
          type="primary" 
          size="small" 
          @click="nextStep" 
          :disabled="activeStep >= parsedContent.steps.length"
        >
          下一步
        </el-button>
        <el-button 
          type="success" 
          size="small" 
          @click="completeAll" 
          :disabled="activeStep >= parsedContent.steps.length"
        >
          完成所有
        </el-button>
      </div> -->



    </div>
    <div v-else class="error-message">
      <el-alert
        title="内容格式错误"
        type="error"
        description="无法解析传入的内容，请检查格式是否正确"
        show-icon
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue'
import { ChatDotRound, Check, Loading, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { deleteExecutor, executePlanByTemplateId, executorDetail } from '@/api/advance'

// 定义props
const props = defineProps({
  content: {
    type: [String, Object],
    required: true
  },
  initialStep: {
    type: Number,
    default: 0
  }
})

// 定义事件
const emit = defineEmits(['step-change', 'complete'])

// 当前激活的步骤
const activeStep = ref(props.initialStep)

// 步骤折叠状态
const collapsedSteps = ref([])
const planTemplateId = ref('')
const planId = ref('')
const currentStepIndex = ref()
const response = ref()
const handleExecute = async () => {
    const res = await executorDetail(planId)
    response.value = res
    if (!res.completed) handleExecute()
   else deleteExecutor(planId)
}
// 解析内容
const parsedContent = computed(() => {
  try {
    if (typeof props.content === 'string') {
      const obj = JSON.parse(props.content)
      console.log(obj);
        obj.steps = obj.steps.map(_ => ({ ..._, stepRequirement: _.stepRequirement.split(' ')[1] }))
        planTemplateId.value = obj.planTemplateId
        currentStepIndex.value = 0
        setTimeout(() => {
            executePlanByTemplateId({ planTemplateId: planTemplateId.value }).then(res => {
                planId.value = res.planId
            })
        }, 1000);
      return obj
    } else {
      return props.content
    }
  } catch (error) {
    console.error('解析内容失败:', error)
    return null
  }
})

// 初始化折叠状态
watch(() => parsedContent.value, (newContent) => {
  if (newContent && newContent.steps) {
    // 默认所有步骤都展开，当前步骤之外的都折叠
    collapsedSteps.value = newContent.steps.map((_, index) => index !== activeStep.value)
  }
}, { immediate: true })

// 切换步骤折叠状态
const toggleCollapse = (index) => {
  collapsedSteps.value[index] = !collapsedSteps.value[index]
}

// 获取步骤类型
const getStepType = (requirement) => {
  if (requirement.includes('[BROWSER_AGENT]')) {
    return 'BROWSER_AGENT'
  } else if (requirement.includes('[DEFAULT_AGENT]')) {
    return 'DEFAULT_AGENT'
  } else {
    return 'UNKNOWN'
  }
}

// 开始进度条动画
const startProgressAnimation = () => {
  // 重置进度
  stepProgress.value = 0
  
  // 清除之前的定时器
  if (progressTimer) {
    clearInterval(progressTimer)
  }
  
  // 创建新的定时器，模拟进度增长
  progressTimer = setInterval(() => {
    if (stepProgress.value < 100) {
      // 使用非线性增长，开始快，接近100%时变慢
      const increment = Math.max(1, 5 * Math.pow(1 - stepProgress.value / 100, 1.5))
      stepProgress.value = Math.min(100, stepProgress.value + increment)
    } else {
      clearInterval(progressTimer)
    }
  }, 200) // 每200毫秒更新一次进度，更加流畅
}

// 上一步
const prevStep = () => {
  if (activeStep.value > 0) {
    // 折叠当前步骤，展开上一步骤
    if (collapsedSteps.value[activeStep.value - 1]) {
      collapsedSteps.value[activeStep.value - 1] = false
    }
    if (!collapsedSteps.value[activeStep.value]) {
      collapsedSteps.value[activeStep.value] = true
    }
    
    activeStep.value--
    emit('step-change', activeStep.value)
    startProgressAnimation()
  }
}

// 下一步
const nextStep = () => {
  if (parsedContent.value && activeStep.value < parsedContent.value.steps.length) {
    // 折叠当前步骤，展开下一步骤
    if (!collapsedSteps.value[activeStep.value]) {
      collapsedSteps.value[activeStep.value] = true
    }
    if (activeStep.value + 1 < parsedContent.value.steps.length && collapsedSteps.value[activeStep.value + 1]) {
      collapsedSteps.value[activeStep.value + 1] = false
    }
    
    activeStep.value++
    emit('step-change', activeStep.value)
    if (activeStep.value < parsedContent.value.steps.length) {
      startProgressAnimation()
    }
  }
}

// 完成所有步骤
const completeAll = () => {
  if (parsedContent.value) {
    activeStep.value = parsedContent.value.steps.length
    emit('complete')
    // 清除进度条定时器
    if (progressTimer) {
      clearInterval(progressTimer)
    }
  }
}

// 监听content变化，重置步骤
watch(() => props.content, () => {
  activeStep.value = props.initialStep
  // 重置进度条
  stepProgress.value = 0
  if (progressTimer) {
    clearInterval(progressTimer)
  }
  // 如果有初始步骤，开始进度动画
  if (activeStep.value > 0 && activeStep.value < parsedContent.value?.steps.length) {
    startProgressAnimation()
  }
}, { deep: true })

// 组件挂载时初始化
onMounted(() => {
  if (activeStep.value > 0 && parsedContent.value) {
    emit('step-change', activeStep.value)
    startProgressAnimation()
  }
})

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  if (progressTimer) {
    clearInterval(progressTimer)
  }
})
</script>

<style scoped>
.steps-display-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.steps-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.steps-id {
  font-size: 14px;
  color: #909399;
  margin-bottom: 20px;
}

.custom-steps {
  margin: 20px 0;
}

.steps-controls {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  justify-content: flex-end;
}

.error-message {
  margin: 20px 0;
}

:deep(.el-step__title) {
  font-weight: bold;
}

:deep(.el-step__description) {
  font-size: 14px;
  white-space: pre-wrap;
  word-break: break-word;
}

:deep(.el-step__icon) {
  background-color: #f5f7fa;
}

:deep(.el-step.is-success .el-step__icon) {
  background-color: #67c23a;
  color: white;
}

:deep(.el-step.is-process .el-step__icon) {
  background-color: #409eff;
  color: white;
}

/* 步骤标题容器 */
.step-title-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  cursor: pointer;
}

/* 折叠按钮 */
.collapse-button {
  margin-left: 8px;
  padding: 2px;
  font-size: 12px;
}

/* 步骤描述 */
.step-description {
  transition: all 0.3s ease;
  overflow: hidden;
  max-height: 500px;
}

.step-description.collapsed {
  max-height: 30px;
  overflow: hidden;
}

/* 步骤内容 */
.step-content {
  padding: 8px 0;
}

/* 步骤进度条样式 */
.step-progress {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.progress-text {
  margin-left: 8px;
  font-size: 12px;
  color: #409eff;
  font-weight: bold;
  transition: all 0.3s;
}

/* 自定义步骤图标 */
.step-icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.step-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #f5f7fa;
  color: #909399;
}

.step-icon.current {
  background-color: #409eff;
  color: white;
  animation: rotate 2s linear infinite, pulse 1.5s infinite;
}

.step-icon.completed {
  background-color: #67c23a;
  color: white;
}

/* 自定义进度条 */
.progress-bar-container {
  position: relative;
  width: 100%;
  height: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 10px;
  flex-grow: 1;
}

.progress-bar-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, #f5f7fa 0%, #e4e7ed 100%);
  opacity: 0.5;
}

.progress-bar-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: linear-gradient(90deg, #409eff 0%, #95d0ff 100%);
  border-radius: 4px;
  transition: width 0.2s ease-out;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

.progress-bar-glow {
  position: absolute;
  top: 0;
  width: 20px;
  height: 100%;
  background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.8) 50%, rgba(255, 255, 255, 0) 100%);
  transform: translateX(-50%);
  animation: shimmer 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

@keyframes rotate {
  0% {
   transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes shimmer {
  0% {
    opacity: 0.3;
  }
  50% {
    opacity: 0.7;
  }
  100% {
    opacity: 0.3;
  }
}

:deep(.el-step__icon) {
  border-radius: 50%;
}
</style>
