<template>
  <div class="step-container">
    <el-button v-if = "isShowAddStep()" type="primary" @click="addStep" icon="el-icon-plus">添加步骤</el-button>
    <div class="step-list">
      <div 
        v-for="(step, index) in steps" 
        :key="step.id" 
        class="step-item"
      >
        
        
        <div class="step-content">
            <span class="step-title">{{ index + 1 }}</span>
              <HandleFormItem 
                type = "select"
                placeholder="请选择"
                class="step-type-select"
                :item = "stepSelectConfig"
                v-model="step.type" 
                @change="onTypeChange(index)"
              />
          
        <!-- 根据步骤类型显示对应的表单 -->
        <component :is="getStepComponent(step.type)" 
                    :step-data="step.formData"
                    @update="onFormUpdate(index, $event)">
        </component>
        <div class="step-header-item">
          <el-button 
            type="text" 
            @click="removeStep(index)" 
            icon="el-icon-delete"
            class="delete-btn"
          ></el-button>
        </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ContainerStep from './StepComponents/ContainerStep.vue'
import CentrifugeStep from './StepComponents/CentrifugeStep.vue'
import AutoWeighStep from './StepComponents/AutoWeighStep.vue'
import ManualWeighStep from './StepComponents/ManualWeighStep.vue'
import AddSolutionStep from './StepComponents/AddSolutionStep.vue'
import MixStep from './StepComponents/MixStep.vue'
import UltrasoundStep from './StepComponents/UltrasoundStep.vue'
import FiltrationStep from './StepComponents/FiltrationStep.vue'
import PackageStep from './StepComponents/PackageStep.vue'
import Seal2Step from './StepComponents/Seal2Step.vue'
import Seal3Step from './StepComponents/Seal3Step.vue'
import VortexStep from './StepComponents/VortexStep.vue'
import CoatStep from './StepComponents/CoatStep.vue'
import StaticStartStep from './StepComponents/StaticStartStep.vue'
import StaticEndStep from './StepComponents/StaticEndStep.vue'
import TakePlateStep from './StepComponents/TakePlateStep.vue'
import HandleFormItem from './HandleFormItem.vue'

const stepTypes =  [
        { label: '容器选择', value: 'container' },
        // { label: '离心', value: 'centrifuge' },
        // { label: '自动称量', value: 'autoWeigh' },
        // { label: '手动称量', value: 'manualWeigh' },
        // { label: '加入溶液', value: 'addSolution' },
        // { label: '混合', value: 'mix' },
        // { label: '超声', value: 'ultrasound' },
        // { label: '抽滤', value: 'filtration' },
        // { label: '分装', value: 'package' },
        // { label: '封装2管', value: 'seal2' },
        // { label: '封装3管', value: 'seal3' },
        // { label: '漩涡混匀', value: 'vortex' },
        // { label: '包被', value: 'coat' },
        // { label: '静置开始', value: 'staticStart' },
        // { label: '静置结束', value: 'staticEnd' },
        // { label: '取板', value: 'takePlate' }
      ];

export default {
  inject: ['templateFillType'],
  name: 'Step',
  props: {
    formData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      stepSelectConfig:{
        options: stepTypes,
        fillType:"preFill",
        placeholder:"请选择步骤类型"
      },
      steps: [],
      stepId: 1,
      componentMap: null
    }
  },
  computed: {
    stepComponentMap() {
      if (!this.componentMap) {
        this.componentMap = {
          'container': 'ContainerStep',
          'centrifuge': 'CentrifugeStep',
          'autoWeigh': 'AutoWeighStep',
          'manualWeigh': 'ManualWeighStep',
          'addSolution': 'AddSolutionStep',
          'mix': 'MixStep',
          'ultrasound': 'UltrasoundStep',
          'filtration': 'FiltrationStep',
          'package': 'PackageStep',
          'seal2': 'Seal2Step',
          'seal3': 'Seal3Step',
          'vortex': 'VortexStep',
          'coat': 'CoatStep',
          'staticStart': 'StaticStartStep',
          'staticEnd': 'StaticEndStep',
          'takePlate': 'TakePlateStep'
        }
      }
      return this.componentMap
    }
  },
  components: {
    HandleFormItem,
    ContainerStep,
    CentrifugeStep,
    AutoWeighStep,
    ManualWeighStep,
    AddSolutionStep,
    MixStep,
    UltrasoundStep,
    FiltrationStep,
    PackageStep,
    Seal2Step,
    Seal3Step,
    VortexStep,
    CoatStep,
    StaticStartStep,
    StaticEndStep,
    TakePlateStep
  },
  created() {
    // // 初始化步骤数据
    // if (this.value && this.value.length > 0) {
    //   this.steps = this.value.map((step) => ({
    //     id: this.stepId++,
    //     type: step.type || '',
    //     formData: step.formData || {}
    //   }))
    // } else {
    //   // 默认添加一个步骤
    //   this.addStep()
    // }
  },
  watch: {
    steps: {
      handler(newVal) {
        this.$emit('input', newVal.map(step => ({
          type: step.type,
          formData: step.formData
        })))
      },
      deep: true
    },
    'formData': {
      handler(newVal) {
        console.log('stepValue', newVal)
        if(!newVal || newVal.length === 0) return
        this.steps = newVal.map((step) => ({
          id: this.stepId++,
          type: step.type || '',
          formData: step
        }))
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    isShowAddStep() {
      return this.templateFillType === 'preFill';
    },
    addStep() {
      try {
        this.steps.push({
          id: this.stepId++,
          type: '',
          formData: {}
        })
        this.$emit('step-added', this.steps.length)
      } catch (error) {
        console.error('添加步骤失败:', error)
        this.$message.error('添加步骤失败，请重试')
      }
    },
    
    removeStep(index) {
      if (this.steps.length > 1) {
        const removedStep = this.steps.splice(index, 1)[0]
        this.$emit('step-removed', { index, step: removedStep, remaining: this.steps.length })
      } else {
        this.$message.warning('至少需要保留一个步骤')
      }
    },
    
    onTypeChange(index) {
      // 切换步骤类型时重置表单数据，并确保数据更新
      const oldType = this.steps[index].type
      this.$set(this.steps[index], 'formData', {})
      // 可选：添加类型变化的回调
      this.$emit('step-type-changed', {
        index,
        newType: this.steps[index].type,
        oldType
      })
    },
    
    onFormUpdate(stepIndex, formData) {
      console.log('stepIndex', stepIndex)
      console.log('formData', formData)
      this.steps[stepIndex].formData = formData
    },
    
    getStepComponent(type) {
      // 使用计算属性中的映射，提高性能
      return this.stepComponentMap[type] 
    },
    
    // 公共方法：获取所有步骤数据
    getFormData() {
      return new Promise((resolve, reject) => {
        // 校验所有步骤是否填写完整
        const validation = this.validateSteps()
        if (!validation.isValid) {
          // this.$message.error(validation.errors[0])
          reject(validation.errors[0])
          return
        }
        
        // 检查是否有步骤数据
        if (this.steps.length === 0) {
          // this.$message.error(this.$t('template.common.addStepError'))
          reject({errorType:"step"});
          return
        }
        
        const stepData = this.steps.map(step => ({
          type: step.type,
          ...step.formData
        }))
        resolve({stepData})
      })
    },

    // 直接获取表单数据，不做校验
    getFilledFormData() {
      const stepData =  this.steps.map(step => ({
        type: step.type,
        ...step.formData
      }))
      return {stepData}
    },
    
    // 公共方法：设置步骤数据
    setStepData(data) {
      if (Array.isArray(data)) {
        this.steps = data.map(step => ({
          id: this.stepId++,
          type: step.type || '',
          formData: step.formData || {}
        }))
      }
    },
    
    // 公共方法：重置所有步骤
    resetSteps() {
      this.steps = [{
        id: this.stepId++,
        type: '',
        formData: {}
      }]
      this.$emit('steps-reset')
    },
    
    // 公共方法：获取指定步骤的数据
    getStepDataByIndex(index) {
      if (index >= 0 && index < this.steps.length) {
        return {
          type: this.steps[index].type,
          formData: this.steps[index].formData
        }
      }
      return null
    },
    
    // 公共方法：验证所有步骤
    validateSteps() {
      const errors = []
      this.steps.forEach((step, index) => {
        if (!step.type) {
          errors.push(`步骤 ${index + 1}: 请选择步骤类型`)
        }
        // 可以在这里添加更具体的表单验证逻辑
      })
      return {
        isValid: errors.length === 0,
        errors
      }
    },
    
    // 公共方法：批量导入步骤数据
    importSteps(stepDataArray) {
      if (Array.isArray(stepDataArray)) {
        this.steps = stepDataArray.map((step, index) => ({
          id: this.stepId++,
          type: step.type || '',
          formData: step.formData || {}
        }))
        this.$emit('steps-imported', this.steps.length)
      }
    },
    
    // 公共方法：获取步骤统计信息
    getStepStatistics() {
      const stats = {
        total: this.steps.length,
        byType: {},
        filled: 0
      }
      
      this.steps.forEach(step => {
        // 统计各类型数量
        if (step.type) {
          stats.byType[step.type] = (stats.byType[step.type] || 0) + 1
        }
        
        // 统计已填写的步骤
        if (step.type && Object.keys(step.formData).length > 0) {
          stats.filled++
        }
      })
      
      return stats
    }
  },
 
}
</script>

<style lang="scss" scoped>
.step-container {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 24px;
    padding: 24px;
    border-radius: 5px 5px;
  .step-header {
    margin-bottom: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 6px;
  }
  
  .step-list {
    .step-item {
      margin-top: 20px;
      border-radius: 6px;
      overflow: hidden;

        .step-title {
          margin-right: 10px;
        }
        .step-type-select{
            width: 200px;
            margin-right: 10px;
            max-width: 200px;
        }
        .delete-btn {
          color: #f56c6c;
          
          &:hover {
            color: #f78989;
          }
          
          &:disabled {
            color: #c0c4cc;
          }
      }
      
      .step-content {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>