<template>
  <div class="x-buttons">
    <a-button-group>
      <template v-for="(button) in renderConfig">
        <!-- 带 Tooltip 的按钮 -->
        <a-tooltip
          v-if="button.tooltip"
          :key="'tooltip-' + button.key"
          placement="top"
        >
          <template slot="title">
            <span>{{ button.tooltip }}</span>
          </template>
          <a-button
            :style="buttonStyle"
            :type="button.type || 'default'"
            :disabled="button.disabled"
            :class="{
              'selected-button': enableSelect && selectedButtonKey === button.key,
              'icon-only-button': buttonsMode === 'icon'
            }"
            @click="handleButtonClick(button)"
          >
            <!-- 水印图标 -->
            <div class="watermark-icon" v-if="watermarkMode && button.icon">
              <a-icon :type="button.icon" />
            </div>
            <!-- 普通模式 -->
            <template v-if="buttonsMode === 'default'">
              <a-icon v-if="!watermarkMode && button.icon" :type="button.icon" />
              {{ button.label }}
            </template>
            <!-- 图标模式 -->
            <template v-if="buttonsMode === 'icon' && button.icon">
              <a-icon :type="button.icon" />
              <span class="sr-only">{{ button.label }}</span>
            </template>
            <!-- 卡片模式 -->
            <template v-if="buttonsMode === 'card'">
              <div class="card-content">
                <div class="card-label">{{ button.label }}</div>
                <div class="card-value">
                  <span class="number">{{ button.value || 0 }}</span>
                  <span class="unit">{{ button.unit || '' }}</span>
                </div>
              </div>
            </template>
          </a-button>
        </a-tooltip>
        <!-- 不带 Tooltip 的按钮 -->
        <a-button
          v-else
          :key="button.key"
          :style="buttonStyle"
          :type="button.type || 'default'"
          :disabled="button.disabled"
          :class="{
            'selected-button': enableSelect && selectedButtonKey === button.key,
            'icon-only-button': buttonsMode === 'icon'
          }"
          @click="handleButtonClick(button)"
        >
          <!-- 水印图标 -->
          <div class="watermark-icon" v-if="watermarkMode && button.icon">
            <a-icon :type="button.icon" />
          </div>
          <!-- 普通模式 -->
          <template v-if="buttonsMode === 'default'">
            <a-icon v-if="!watermarkMode && button.icon" :type="button.icon" />
            {{ button.label }}
          </template>
          <!-- 图标模式 -->
          <template v-if="buttonsMode === 'icon' && button.icon">
            <a-icon :type="button.icon" />
            <span class="sr-only">{{ button.label }}</span>
          </template>
          <!-- 卡片模式 -->
          <template v-if="buttonsMode === 'card'">
            <div class="card-content">
              <div class="card-label">{{ button.label }}</div>
              <div class="card-value">
                <span class="number">{{ button.value || 0 }}</span>
                <span class="unit">{{ button.unit || '' }}</span>
              </div>
            </div>
          </template>
        </a-button>
      </template>
    </a-button-group>
  </div>
</template>

<script>
import { getConfigByName, runLogic } from '@vue2-client/services/api/common'

export default {
  name: 'XButtons',
  components: {},
  props: {
    // 查询参数名
    queryParamsName: {
      type: String,
      default: null
    },
    // 服务名
    serviceName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    }
  },
  data () {
    return {
      // 配置内容
      renderConfig: undefined,
      // 按钮格式
      buttonsMode: 'default',
      // 按钮事件禁用开启状态
      eventDisabled: false,
      // 按钮样式
      buttonStyle: '',
      // 选中效果
      enableSelect: false,
      // 选中key
      selectedButtonKey: undefined,
      // 按钮图标样式
      watermarkMode: false
    }
  },
  methods: {
    /**
     * 初始化按钮组参数
     */
    initData (parameter) {
      this._configEndEmitted = false
      this._configEndPromise = new Promise(resolve => { this._configEndResolve = resolve })
      if (!parameter) {
        this._emitConfigEnd()
        return
      }
      // 按钮组需要主动调用初始化方法
      getConfigByName(parameter, this.serviceName, (res) => {
        if (!res) {
          this._emitConfigEnd()
          return
        }
        this.buttonsMode = ['default', 'card', 'icon'].includes(res.buttonsMode) ? res.buttonsMode : 'default'
        this.enableSelect = res.enableSelect ?? false
        this.buttonStyle = res.style ?? ''
        this.eventDisabled = res.eventDisabled ?? false
        this.watermarkMode = res.watermarkMode ?? false
        if (res.logicName) {
          runLogic(res.logicName, {}, this.serviceName).then((result) => {
            res.value = result
            this.init({
              ...res,
              serviceName: this.serviceName,
            })
            this._emitConfigEnd()
          })
        } else {
          this.init({
            ...res,
            serviceName: this.serviceName,
          })
          this._emitConfigEnd()
        }
      }, this.env === 'dev')
    },
    /** 配置加载结束后发出，供 XReport 判断「所有 slot 配置结束」；仅发出一次 */
    _emitConfigEnd () {
      if (this._configEndEmitted) return
      this._configEndEmitted = true
      if (this._configEndResolve) {
        this._configEndResolve()
        this._configEndResolve = null
      }
      this.$emit('configEnd')
    },
    /**
     * 等待配置结束的异步方法。配置已结束则立即 resolve，否则在 configEnd 时 resolve。
     * @returns {Promise<void>}
     */
    waitConfigEnd () {
      if (this._configEndEmitted) return Promise.resolve()
      return this._configEndPromise || Promise.resolve()
    },
    init (params) {
      const {
        // 配置内容
        value
      } = params
      this.renderConfig = value
    },
    getKey () {
      return this.selectedButtonKey
    },
    /**
     * 触发前端 Logic（FrontLogicPlugin / LogicRunner）
     * 约定：按钮配置中提供 frontLogicName / frontLogicMode
     * @returns {Promise<boolean>} 是否已处理（命中 frontLogicName 即视为已处理）
     */
    async _triggerFrontLogic (item) {
      const logicName = item?.frontLogicName
      if (!logicName) return false

      const mode = item?.frontLogicMode
      const runner = this?.$runFrontLogic
      if (typeof runner !== 'function') {
        this.$message?.error?.('未注册 $runFrontLogic，请确认已安装 FrontLogicPlugin')
        return true
      }

      try {
        await runner(logicName, {proxy:this}, mode)
      } catch (e) {
        // cancel 模式下 abort 导致的取消错误，静默处理不提示用户
        // ExpressionException 会把原始错误存在 e.cause 中
        const cause = e?.cause || e
        const isCanceled = cause?.name === 'CanceledError' || cause?.name === 'AbortError' ||
          cause?.code === 'ERR_CANCELED'
        if (isCanceled) {
          console.log(`[XButtons] ${logicName} 被取消（cancel 模式），静默忽略`)
          return true
        }
        console.error('[XButtons] $runFrontLogic error:', e)
        this.$message?.error?.(`前端逻辑执行失败：${logicName}`)
      }
      return true
    },
    handleButtonClick (item) {
      this.selectedButtonKey = this.selectedButtonKey === item.key ? null : item.key
      if (!this.eventDisabled) {
        // 优先执行前端逻辑（如果按钮配置提供了 frontLogicName）
        this._triggerFrontLogic(item).then((handled) => {
          if (handled) return

          if (item.clickEventName && this.$listeners[item.clickEventName]) {
            // 交由父级处理
            this.$emit(item.clickEventName, item)
          } else {
            this.defaultAction(item.clickEventName, item)
          }
        })
      }
    },
    defaultAction (clickEventName, item, callback) {
      setTimeout(() => {
        this.$message.warn(`已触发按钮 [${item.key}]，注册事件名 [${clickEventName}]，未实现事件函数`)
        callback()
      }, 200)
    }
  },
  watch: {
    queryParamsName: {
      immediate: true,
      handler (newVal) {
        this.initData(newVal)
      },
      deep: true
    }
  }
}
</script>
<style scoped>
.ant-btn-group {
  flex-wrap: wrap;
}
/* 选中按钮的样式 */
.selected-button {
  background-color: #1890ff !important;  /* 蓝色背景 */
  color: white !important;              /* 白色文字 */
  border-color: #1890ff !important;     /* 蓝色边框 */
}
/* 卡片模式样式 */
.card-button {
  width: 120px;
  height: 80px;
  padding: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.card-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-label {
  font-size: 24px;
  text-align: left;
  align-self: flex-start;
  margin-top: 20px;
  font-weight: normal;
  font-family: Source Han Sans;
}

.card-value {
  text-align: right;
  align-self: flex-end;
  margin-top: auto;
  font-family: Source Han Sans;

}

.card-value .number {
  font-size: 32px;
  font-weight: bold;
  line-height: 39px;
  color: #1890ff;
}

.card-value .unit {
  font-size: 20px;
  font-weight: normal;
  line-height: 39px;
}
/* 水印图标样式 */
.watermark-icon {
  position: absolute;
  font-size: 164px;
  opacity: 0.15;
  z-index: 0;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none; /* 防止水印图标拦截点击事件 */
}
/* 当有水印图标时，自动应用背景色 */
.ant-btn:has(.watermark-icon) {
  background-color: #f0f0f0 !important; /* 浅灰色背景 */
  border-color: #d9d9d9 !important; /* 边框色 */
}

/* 普通模式下的图标位置调整 */
.ant-btn > .anticon + span {
  margin-left: 8px;
}

/* 水印模式下的文字层级 */
.button-label {
  position: relative;
  z-index: 1;
}

/* 纯图标模式核心样式 */
.icon-only-button {
  /* 移除所有边框和背景 */
  border: none !important;
  background: transparent !important;
  box-shadow: none !important;

  /* 控制按钮大小与图标一致 */
  width: auto !important;
  height: auto !important;
  padding: 4px !important; /* 缩小内边距 */
  min-width: unset !important; /* 移除默认最小宽度 */

  /* 确保图标居中 */
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
}

/* 图标大小控制 */
.icon-only-button .anticon {
  font-size: 24px !important; /* 图标大小 */
  color: #888888 !important; /* 默认图标颜色 */
}

/* 悬停和激活状态优化 */
.icon-only-button:hover {
  background-color: #e6f7ff !important; /* 轻微hover背景 */
  color: #1890ff !important; /* hover时图标颜色 */
}

.icon-only-button.selected-button {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
}

/* 屏幕阅读器专用样式（视觉隐藏，语义保留） */
.sr-only {
  position: absolute !important;
  width: 1px !important;
  height: 1px !important;
  padding: 0 !important;
  margin: -1px !important;
  overflow: hidden !important;
  clip: rect(0, 0, 0, 0) !important;
  border: 0 !important;
}
</style>
