<template>
  <div class="x-workflow-progress">
    <div class="workflow-steps-wrapper">
      <div :class="['workflow-steps', { center: isCentered }]" ref="workflowSteps">
        <div
          v-for="(step, index) in displaySteps"
          :key="index"
          class="workflow-step"
          :class="{ 'is-completed': step.status === 'executed', 'is-pending': step.status === 'not-executed' }"
        >
          <!-- 直接显示图标（去掉外层圆圈），标签在图标后面 -->
          <div class="step-circle">
            <x-icon
              :name="getIconName(step)"
              class="step-icon"
              :style="{ fontSize: '20px' }"
            />
          </div>

          <!-- 步骤名称（在图标后面） -->
          <div class="step-label">{{ step.label }}</div>

          <!-- 连接线 -->
          <div
            v-if="index < displaySteps.length - 1"
            class="step-connector"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getConfigByName } from '@vue2-client/services/api/common'
import XIcon from '@vue2-client/base-client/components/his/XIcon'

export default {
  name: 'XWorkflowProgress',
  components: {
    XIcon
  },
  props: {
    // 配置对象，用于通过 runLogic 获取步骤数据
    queryParamsName: {
      type: Object,
      default: null
    },
    // 服务名称，默认为 af-his
    serviceName: {
      type: String,
      default: 'af-his'
    },
    // 步骤数据（直接传入，优先级高于 queryParamsName）
    steps: {
      type: Array,
      required: false,
      default: () => []
    },
    // (图标名称已固定为 executed / not-executed，移除可配置 props)
  },
  data() {
    return {
      internalSteps: [],
      // 拖拽滚动状态
      isDown: false,
      startX: 0,
      startScrollLeft: 0,
      // 是否显示为居中（当内容不溢出）
      isCentered: false,
      // 当前步骤索引（从0开始）
      currentStepIndex: -1
    }
  },
  computed: {
    displaySteps() {
      // 如果直接传入了 steps，优先使用
      if (this.steps && this.steps.length > 0) {
        return this.steps
      }
      // 否则使用从配置获取的数据
      return this.internalSteps
    }
  },
  created() {
    // 如果没有直接传入 steps，且配置了 queryParamsName，则通过配置获取数据
    if ((!this.steps || this.steps.length === 0) && this.queryParamsName) {
      this.getData(this.queryParamsName)
    } else if (this.steps && this.steps.length > 0) {
      // 如果直接传入了 steps，直接使用
      this.internalSteps = this.steps
    }
  },
  mounted() {
    this.$nextTick(() => {
      const el = this.$refs.workflowSteps
      if (el) {
        this.addDragListeners(el)
        this.checkOverflow()
      }
      window.addEventListener('resize', this.checkOverflow)
    })
  },
  beforeDestroy() {
    const el = this.$refs.workflowSteps
    if (el) this.removeDragListeners(el)
    window.removeEventListener('resize', this.checkOverflow)
  },
  methods: {
    getData(config) {
      // 如果config是字符串，直接使用；如果是对象，提取配置名称
      const configName = typeof config === 'string' ? config : config?.configName || config?.name
      if (!configName) {
        console.warn('配置名称不能为空')
        this.internalSteps = []
        return
      }

      getConfigByName(configName, this.serviceName, (res) => {
        // 处理返回的数据格式
        // 支持 res.data.value, res.data, 或直接返回数组
        const rawData = res?.data || res
        let data = null

        if (rawData && Array.isArray(rawData)) {
          // 直接是数组格式
          data = rawData
        } else if (rawData && rawData.value && Array.isArray(rawData.value)) {
          // {value: [...]} 格式
          data = rawData.value
        }

        if (data && Array.isArray(data)) {
          // 返回字段固定，直接使用 label/value/status
          this.internalSteps = data.map(item => ({
            label: item.label,
            value: item.value,
            status: item.status
          }))
          // 初始化当前步骤索引
          this.updateCurrentStepIndex()
        } else {
          this.internalSteps = []
        }
      })
    },
    // 仅根据新状态判断：执行 -> executed，否则 -> not-executed
    getIconName(step) {
      return step && step.status === 'executed' ? 'executed' : 'not-executed'
    },
    /**
     * 添加拖拽滚动监听
     */
    addDragListeners(el) {
      // 鼠标
      el.addEventListener('mousedown', this.onDragStart)
      el.addEventListener('mousemove', this.onDragMove)
      el.addEventListener('mouseup', this.onDragEnd)
      el.addEventListener('mouseleave', this.onDragEnd)
      // 触摸
      el.addEventListener('touchstart', this.onDragStart, { passive: false })
      el.addEventListener('touchmove', this.onDragMove, { passive: false })
      el.addEventListener('touchend', this.onDragEnd)
    },
    removeDragListeners(el) {
      el.removeEventListener('mousedown', this.onDragStart)
      el.removeEventListener('mousemove', this.onDragMove)
      el.removeEventListener('mouseup', this.onDragEnd)
      el.removeEventListener('mouseleave', this.onDragEnd)
      el.removeEventListener('touchstart', this.onDragStart)
      el.removeEventListener('touchmove', this.onDragMove)
      el.removeEventListener('touchend', this.onDragEnd)
    },
    /**
     * 检查是否溢出；未溢出时将内容居中
     */
    checkOverflow() {
      const el = this.$refs.workflowSteps
      if (!el) {
        this.isCentered = false
        return
      }
      // 如果实际宽度 <= 可见宽度，则居中显示
      this.isCentered = el.scrollWidth <= el.clientWidth + 4
    },
    onDragStart(e) {
      const el = this.$refs.workflowSteps
      if (!el) return
      this.isDown = true
      el.classList.add('dragging')
      const pageX = e.touches ? e.touches[0].pageX : e.pageX
      this.startX = pageX - el.getBoundingClientRect().left
      this.startScrollLeft = el.scrollLeft
    },
    onDragMove(e) {
      if (!this.isDown) return
      const el = this.$refs.workflowSteps
      if (!el) return
      e.preventDefault()
      const pageX = e.touches ? e.touches[0].pageX : e.pageX
      const x = pageX - el.getBoundingClientRect().left
      const walk = x - this.startX
      el.scrollLeft = this.startScrollLeft - walk
    },
    onDragEnd() {
      const el = this.$refs.workflowSteps
      if (el) el.classList.remove('dragging')
      this.isDown = false
    },
    // scrollPrev/Next & old overflow logic removed (use drag + isCentered)
    /**
     * 更新当前步骤索引（根据已完成步骤数量）
     */
    updateCurrentStepIndex() {
      const steps = this.displaySteps
      // 以 executed 作为已完成判断
      const executedCount = steps.filter(step => step.status === 'executed').length
      this.currentStepIndex = executedCount > 0 ? executedCount - 1 : -1
    },
    /**
     * 按 value 设置指定步骤的状态（只按 value 匹配）
     * @param {String|Number} stepValue - 步骤的 value 字段
     * @param {String} status - 状态：'executed' 或 'not-executed'
     */
    setStepStatus(stepValue, status) {
      const steps = this.displaySteps
      if (!steps || steps.length === 0) {
        console.warn('步骤数据为空，无法设置状态')
        return
      }

      const asString = `${stepValue}`
      const targetIndex = steps.findIndex(step => `${step.value}` === asString)
      if (targetIndex < 0) {
        console.warn(`未找到对应 value 的步骤: ${stepValue}`)
        return
      }

      // 仅允许 executed / not-executed
      if (!['executed', 'not-executed'].includes(status)) {
        console.warn(`状态值无效: ${status}，应为 'executed' 或 'not-executed'`)
        return
      }

      // 更新步骤状态
      const step = steps[targetIndex]
      this.$set(step, 'status', status)

      // 更新当前步骤索引
      this.updateCurrentStepIndex()

      // 触发状态变更事件
      this.$emit('statusChange', {
        index: targetIndex,
        value: step.value,
        label: step.label,
        status: status,
        steps: [...steps]
      })
    },
    /**
     * 设置当前步骤（自动将之前的步骤设为已完成，当前及之后的设为待处理）
     * @param {Number|String} stepIndexOrLabel - 步骤索引（从0开始）或步骤标签
     */
    /**
     * 以 value 设置当前步骤：指定 value 及之前设为 executed，之后设为 not-executed
     * @param {String|Number} stepValue
     */
    setCurrentStep(stepValue) {
      const steps = this.displaySteps
      if (!steps || steps.length === 0) {
        console.warn('步骤数据为空，无法设置当前步骤')
        return
      }

      const asString = `${stepValue}`
      const targetIndex = steps.findIndex(step => `${step.value}` === asString)
      if (targetIndex < 0) {
        console.warn(`未找到对应 value 的步骤: ${stepValue}`)
        return
      }

      // 更新所有步骤状态
      steps.forEach((step, index) => {
        if (index <= targetIndex) {
          // 当前及之前设为 executed
          this.$set(step, 'status', 'executed')
        } else {
          // 之后的设为 not-executed
          this.$set(step, 'status', 'not-executed')
        }
      })

      // 更新当前步骤索引
      this.currentStepIndex = targetIndex

      // 触发状态变更事件（已执行）
      this.$emit('statusChange', {
        index: targetIndex,
        label: steps[targetIndex].label,
        status: 'executed',
        steps: [...steps]
      })
    },
    /**
     * 完成下一步（将下一个待处理步骤设为已完成）
     */
    completeNextStep() {
      const steps = this.displaySteps
      if (!steps || steps.length === 0) {
        console.warn('步骤数据为空，无法完成下一步')
        return
      }

      const nextIndex = steps.findIndex(step => step.status !== 'executed')
      if (nextIndex === -1) {
        console.warn('没有待执行的步骤')
        return
      }

      this.setCurrentStep(nextIndex)
    },
    /**
     * 重置所有步骤为待处理状态
     */
    resetAllSteps() {
      const steps = this.displaySteps
      if (!steps || steps.length === 0) {
        return
      }

      steps.forEach(step => {
        this.$set(step, 'status', 'not-executed')
      })

      this.currentStepIndex = -1

      // 触发状态变更事件（全部未执行）
      this.$emit('statusChange', {
        index: -1,
        label: '',
        status: 'not-executed',
        steps: [...steps]
      })
    },
    /**
     * 获取当前步骤信息
     * @returns {Object} 当前步骤信息
     */
    getCurrentStep() {
      const steps = this.displaySteps
      if (this.currentStepIndex >= 0 && this.currentStepIndex < steps.length) {
        return {
          index: this.currentStepIndex,
          label: steps[this.currentStepIndex].label,
          status: steps[this.currentStepIndex].status
        }
      }
      return null
    },
    /**
     * 获取所有步骤数据
     * @returns {Array} 步骤数组
     */
    getSteps() {
      return [...this.displaySteps]
    }
  },
  watch: {
    queryParamsName: {
      handler(newVal) {
        if (newVal) {
          this.getData(newVal)
        }
      },
      deep: true
    },
    steps: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.internalSteps = newVal
          // 更新当前步骤索引
          this.updateCurrentStepIndex()
        }
      },
      deep: true,
      immediate: true
    },
    displaySteps: {
      handler() {
        // 当显示步骤变化时，更新当前步骤索引
        this.updateCurrentStepIndex()
        this.$nextTick(() => {
          if (typeof this.checkOverflow === 'function') this.checkOverflow()
        })
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
.x-workflow-progress {
  width: 100%;
  padding: 0px 0;

  .workflow-steps-wrapper {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .workflow-steps {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    position: relative;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    white-space: nowrap;
    flex-wrap: nowrap;
    scrollbar-width: none;
    cursor: grab;
  }
  .workflow-steps::-webkit-scrollbar { display: none; }
  .workflow-steps.center {
    justify-content: center;
  }
  .workflow-steps.dragging { cursor: grabbing; user-select: none; }

  .workflow-step {
    display: flex;
    flex-direction: row;
    align-items: center;
    position: relative;
    flex: 0 0 auto;
    min-width: 0;

    /* 只保留图标（去掉外层圆圈样式） */
    .step-circle {
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      z-index: 2;
      padding: 0;
      background: transparent;
      border: none;
      transition: all 0.2s;

      .step-icon {
        font-size: 18px;
        transition: color 0.2s;
        /* 默认灰色，具体颜色由状态覆盖 */
        color: #D8D8D8;
      }
    }

    /* 完成状态：图标蓝色 */
    &.is-completed {
      .step-circle {
        .step-icon {
          color: #0057FE;
        }
      }
    }

    /* 待处理状态：图标灰色（继承默认） */
    &.is-pending {
      .step-circle {
        .step-icon {
          color: #D8D8D8;
        }
      }
    }

    .step-label {
      margin-left: 8px;
      font-size: 16px;
      color: #333;
      text-align: left;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 160px;
    }

    /* 连接线：短线，位于徽章右侧，状态完成时变蓝 */
    .step-connector {
      top: 50%;
      margin-left: 10px;
      margin-right: 10px;
      width: 30px;
      height: 1px;
      background: #d9d9d9;
      transform: translateY(-50%);
      transition: background 0.3s;

      &.is-completed {
        background: #0057FE;
      }
    }

    // 最后一个步骤不需要连接线
    &:last-child {
      margin-right: 0;
      .step-connector {
        display: none;
      }
    }
  }
  /* （移除导航按钮，支持直接拖动滑动） */
}

// 响应式设计
@media (max-width: 768px) {
  .x-workflow-progress {
    .workflow-step {
      .step-label {
        font-size: 12px;
      }

      .step-circle {
        padding: 0 2px;

        .step-icon {
          font-size: 18px;
        }
      }
    }
  }
}
</style>

