<template>
  <div>
    <div v-if="render" class="XCard">
      <template v-for="(card, itemIndex) in data">
        <a-card
          :key="'card' + itemIndex"
          class="data-card"
          :class="{ 'card-clicked': card.isClicked }"
          :headStyle="{ backgroundColor: '#f9f9f9' }"
        >
          <div
            v-if="config && card[config.ribbon]"
            class="ribbon"
            :style="{ backgroundColor: getRibbonColor(card[config.ribbonColor]) }">
            {{ card[config.ribbon] }}
          </div>
          <!-- 自定义标题 -->
          <template #title>
            <div class="custom-title" @click="cardClick(card, 'cardclick', itemIndex)">
              <a-tooltip placement="top">
                <template #title>{{ card[config.id] }}</template>
                <div class="title-id" v-if="card[config.id]">{{ card[config.id] }}</div>
              </a-tooltip>
              <div class="title-basic">
                <div class="title-main">
                  <span class="title-name">{{ card[config.title] }}</span>
                  <span class="title-info">{{ card[config.title2] }}</span>
                  <span class="title-title3">{{ card[config.title3] }}</span>
                </div>
                <div class="additional-info" v-if="card[config.subtitle2] || card[config.subtitle3] || card[config.subtitle4]">
                  <a-tooltip placement="top" v-if="card[config.subtitle2]">
                    <template #title>{{ card[config.subtitle2] }}</template>
                    <span class="subtitle2">{{ card[config.subtitle2] }}</span>
                  </a-tooltip>
                  <a-tooltip placement="top" v-if="card[config.subtitle3]">
                    <template #title>{{ card[config.subtitle3] }}</template>
                    <span class="subtitle3">{{ card[config.subtitle3] }}</span>
                  </a-tooltip>
                  <span class="subtitle4" v-if="card[config.subtitle4]">{{ card[config.subtitle4] }}</span>
                </div>
              </div>
            </div>
          </template>
          <!-- 主体 -->
          <div class="body" v-if="card[config.text] || (config.content && config.content.length > 0)">
            <div class="body-text" v-if="card[config.text]">
              <a-tooltip :title="card[config.text]">
                <span class="text-ellipsis">{{ card[config.text] }}</span>
              </a-tooltip>
            </div>
            <template v-for="(item, bodyIndex) in config.content" v-if="bodyIndex < 6">
              <div :key="'body' + bodyIndex" class="body-item">
                <span class="body-item-label">{{ item.label }}：</span>
                <template v-if="item.type === 'progress'">
                  <div class="progress">
                    <div class="progress-bar">
                      <div class="progress-done" :style="'width:' + card[item.key] * 100 + '%;backgroundColor: ' + determineRatioColor(card[item.key] * 100)"></div>
                    </div>
                  </div>
                  <a-progress :percent="card[item.key]" :stroke-color="{ '0%': '#108ee9', '100%': '#87d068' }" strokeWidth="10" :style="{ width: '95%' }" />
                </template>
                <template v-else-if="item.type === 'custom' && tableColumns">
                  <!-- 根据 tableColumns 显示自定义内容 -->
                  <span v-for="column in tableColumns" v-if="column.dataIndex === item.key" :key="column.dataIndex">
                    <template v-if="column.slotType === 'badge'">
                      <x-badge
                        :service-name="serviceName"
                        :env="env"
                        :dataCard="true"
                        :badge-key="column.slotKeyMap"
                        :value="card[item.key]" />
                    </template>
                    <template v-else>
                      <slot :name="column.slots.customRender">{{ card[item.key] }}</slot>
                    </template>
                  </span>
                </template>
                <template v-else>
                  <span class="body-item-value" style="float: right;">{{ card[item.key] }}</span>
                </template>
              </div>
              <a-divider
                v-if="bodyIndex !== config.content.length - 1"
                dashed
                :key="'body' + bodyIndex + 'after'"
                class="body-split" />
            </template>
          </div>
          <!-- 下方按钮 -->
          <template #actions>
            <div class="custom-actions" v-if="config && config.footer && config.footer.length > 0">
              <template v-for="(item, footerIndex) in config.footer">
                <div :key="'footer_' + footerIndex" class="footer-item" @click="clickFooter(card, item.emit, itemIndex)">
                  <a-icon :type="item.icon" class="footer-icon" />
                  <span>{{ item.label }}</span>
                </div>
                <a-divider
                  v-if="footerIndex !== config.footer.length - 1"
                  :key="'footer_' + footerIndex + 'after'"
                  type="vertical"
                  class="footer-item-split" />
              </template>
            </div>
          </template>
        </a-card>
      </template>
    </div>
    <div v-else>
      <a-skeleton />
    </div>
    <div v-if="this.showPagination">
      <a-divider />
      <a-pagination
        v-model="pageNum"
        style="float: right"
        :total="total"
        show-less-items
        :page-size="pageSize"
        :page-size-options="pageSizeOptions"
        show-size-changer
        @change="pageNumChange"
        :showTotal="paginationShowTotal"
        @showSizeChange="pageSizeChange">
      </a-pagination>
    </div>
  </div>
</template>

<script>
import XBadge from '@vue2-client/base-client/components/common/XBadge'

export default {
  name: 'XDataCard',
  components: {
    XBadge,
  },
  props: {
    // 卡片数据更新方法
    cardData: {
      type: Function,
      default: undefined
    },
    // 卡片的配置
    cardConfig: {
      type: Object,
      default: undefined
    },
    showPagination: {
      type: Boolean,
      default: false
    },
    // 临时
    testData: {
      type: Array,
      default: undefined
    },
    tableColumns: {
      type: Array,
      default: undefined
    },
    // 服务名称
    serviceName: undefined,
    // 当前环境
    env: {
      type: String,
      default: 'prod'
    },
    // pageSize参数
    prePageSize: {
      type: Number,
      default: undefined
    },
    // 初始是否加载数据
    createdQuery: {
      type: Boolean,
      default: false
    }
  },
  inject: ['getConfigByName'],
  data () {
    return {
      // 配置
      config: {},
      // 数据
      data: {},
      // 当前页码
      pageNum: 1,
      // 控制渲染
      render: true,
      // 分页大小
      pageSize: 10,
      // 分页大小选项
      pageSizeOptions: ['4', '6', '8', '10'],
      // 数据总数
      total: 0,
      activeCardIndex: null, // 新增：记录当前激活的卡片索引
      // 混入插槽组件的数据
      mixinData: {},
    }
  },
  created () {
    // 根据参数初始化数据值
    if (this.prePageSize) {
      this.pageSize = this.prePageSize
    }
  },
  mounted () {
    // 配置初始化
    if (this.cardConfig) {
      this.config = this.cardConfig
    } else {
      this.config = {
        id: '未获取到配置',
        title: '未获取到配置',
        title2: '未获取到配置',
        title3: '未获取到配置',
        subtitle2: '未获取到配置',
        subtitle3: '未获取到配置',
        subtitle4: '未获取到配置',
        text: '未获取到配置',
        ribbon: '未获取到配置',
        ribbonColor: '未获取到配置',
        content: [
          {
            label: '未获取到配置',
            key: 'one'
          },
          {
            label: '未获取到配置',
            key: 'two'
          },
          {
            label: '未获取到配置',
            key: 'three'
          },
          {
            label: '未获取到配置',
            key: 'four'
          },
          {
            label: '未获取到配置',
            key: 'five'
          },
          {
            label: '未获取到配置',
            key: 'six',
            type: 'progress'
          }
        ],
        footer: [
          {
            icon: 'edit',
            label: '未获取到配置',
            emit: 'planEdit'
          },
          {
            icon: 'user',
            label: '未获取到配置',
            emit: 'user'
          }
        ]
      }
      console.warn(this.config)
    }

    // 数据初始化
    if (this.cardData) {
      // if (this.createdQuery) {
      //   this.loadData()
      // }
    } else {
      this.data = {
          one: '未获取到配置',
          two: '未获取到配置',
          three: '未获取到配置',
          four: '未获取到配置',
          five: '未获取到配置',
          six: 70,
        }
    }
    // 测试数据初始化
    if (this.testData) {
      this.data = this.testData
    }
  },
  methods: {
    // 根据比例计算出颜色
    determineRatioColor (ratio, isNum = false) {
      let result
      // 如果是数字，并且比例大于79，则将数字显示为黑色
      if (isNum && ratio > 79) {
        return 'rgb(0,0,0)'
      }
      if (ratio >= 90) {
        result = 'rgb(   1,245, 38 )'
      } else if (ratio >= 75) {
        result = 'rgb( 139,245,  0)'
      } else if (ratio >= 40) {
        result = 'rgb(245,163,  0)'
      } else if (ratio >= 20) {
        result = 'rgb(244, 96,  0)'
      } else {
        result = 'rgb(255,  0,  0)'
      }
      return result
    },
    async cardClick (card, itemIndex) {
      try {
        // 等待 beforeSwitch 完全执行完成
        const result = await this.beforeSwitch(card, 'beforeSwitch', itemIndex)
        // 如果返回 undefined 说明没有监听器，或者返回 true 说明检查通过
        if (result === undefined || result === true) {
          await this.clickFooter(card, 'cardclick', itemIndex)
        }
      } catch (error) {
      }
    },
    // 点击按钮
    async clickFooter (data, eventName, index) {
      if (eventName === 'cardclick') {
        // 清除所有卡片的点击状态
        if (this.data && Array.isArray(this.data)) {
          this.data.forEach(item => {
            if (item.isClicked) {
              this.$set(item, 'isClicked', false)
            }
          })
        }
        // 设置当前卡片的点击状态
        this.$set(data, 'isClicked', true)
      }
      this.$emit('cardEmit', data, eventName)
    },
    async beforeSwitch (data, eventName, index) {
      return new Promise((resolve) => {
        // 检查是否有其他卡片已经被点击
        const hasClickedCard = this.data.some(item => item.isClicked)
        // 如果没有任何卡片被点击过，直接通过
        if (!hasClickedCard) {
          resolve(true)
          return
        }
        // 检查是否有监听器
        const hasListeners = this._events?.cardEmit?.length > 0

        // 如果没有监听器，返回 undefined 表示继续执行
        if (!hasListeners) {
          resolve(undefined)
          return
        }
        // 如果有监听器，执行事件检查
        try {
          this.$emit('cardEmit', data, eventName)
          resolve(true)
        } catch (error) {
          resolve(false)
        }
      })
    },
    // 获取数据
    loadData () {
      this.render = false
      const parameter = Object.assign({
          querySummary: false, // 分页查询的情况不重新获取汇总数据
          pageNo: this.pageNum,
          pageSize: this.pageSize
        }
      )
      this.cardData(parameter).then(res => {
        this.data = res.data
        this.total = res.totalCount
        this.render = true
      })
    },
    // 页码改变
    pageNumChange (page, pageSize) {
      this.pageNum = page
      this.pageSize = pageSize
      this.loadData()
    },
    // 分页大小改变
    pageSizeChange (current, pageSize) {
      this.pageSize = pageSize
      this.loadData()
    },
    // 刷新
    refresh () {
      this.loadData()
    },
    // 分页前展示当前项和总数
    paginationShowTotal () {
      return `${(this.pageNum - 1) * this.pageSize + 1 } - ${ this.pageNum * this.pageSize } | 共 ${ this.total } 项`
    },
    getRibbonColor (color) {
      switch (color) {
        case 'red':
          return '#ff4d4f'
        case 'blue':
          return '#1890ff'
        case 'yellow':
          return '#fadb14'
        default:
          return '#ff4d4f' // 默认红色
      }
    }
  }
}
</script>

<style lang="less" scoped>
.hide-page-numbers /deep/ .ant-pagination-item,
.hide-page-numbers /deep/ .ant-pagination-jump-next {
    display: none !important; /* 隐藏数字页码和多页跳转 */
}
.hide-page-numbers /deep/ .ant-pagination-prev,
.hide-page-numbers /deep/ .ant-pagination-next {
    display: inline-block !important; /* 保留左右跳转按钮 */
}

.XCard {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: 85vh;
  .data-card {
    flex: 0 0 20%;
    max-width: 20%;
    box-sizing: border-box;
    border: 2px solid rgb(244,244,244);
    border-radius: 5px;
    margin: 0;
    overflow: hidden;

    ::v-deep .ant-card-body {
      padding: 15px !important; // 使用 !important 确保样式覆盖
    }
    ::v-deep .ant-card-head {
      padding: 0 8px !important; // 收紧左右内边距，贴近边框
    }
    ::v-deep .ant-card-head-title {
      padding: 10px 0 !important; // 仅上下留白
      margin: 0 !important;
    }
    ::v-deep .ant-card-head-wrapper { padding: 0 !important; }

    .header {
      width: 100%;
      background-color: rgb(244,244,244);
      padding: 5px 15px;

      span {
        font-weight: bold;
        font-size: 1.1em;
      }
    }

    .body {
      .body-text{
        width: 500px;
        font-weight: bold;
        font-size: 1.1em;
        .text-ellipsis{
          display: inline-block;
          max-width: 260px;  /* 控制文本的最大宽度 */
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .body-item {
        padding: 3px 5px;
      }

      .body-split {
        margin: 1px 0;
      }

      .body-item-label {
        color: rgba(117, 117, 117, 0.8);
        font-size: 0.95em;
      }

      .body-item-value {
        color: black;
      }

      .progress {
        display: inline-block;
        width: 60%;
        height: 60%;
        float: right;
        padding-right: 1.5%;
        margin-top: 0.5%;

        .progress-bar {
          width: 100%;
          height: 90%;
          display: inline-block;
          border-radius: 10%;
          background-color: rgba(212,217,218, 0.6);

          .progress-done {
            float: left;
            display: inline-block;
            height: 100%;
            border-radius: 10%;
          }
        }
      }
      .progress-num {
        position: relative;
        top: -83%;
        left: -3%;
        text-align: end;
        font-size: 0.9em;
        color: black;
      }
    }

    &.card-clicked {
      :deep(.ant-card-head) {
        background-color: #e6f7ff;
        transition: background-color 0.3s ease;
      }
    }
  }

  .custom-title {
    display: flex;
    align-items: center;
    gap: 12px;
    padding-left: 0; // 取消额外左缩进，进一步贴边

    &:hover {
      cursor: pointer;
    }

    .title-id {
      flex-shrink: 0;
      width: 65px;
      color: #1890ff;
      font-size: 16px;
      font-weight: bold;
      padding: 4px 8px;
      border: 1px solid #1890ff;
      border-radius: 4px;
      line-height: 1.4;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .title-basic {
      display: flex;
      flex-direction: column;
      flex-grow: 1;

      .subtitle2, .subtitle3 {
        display: inline-block;
        max-width: 50px; /* 固定宽度 */
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .title-main {
        display: flex;
        align-items: center;
        gap: 8px;
        .title-info {
          margin-left: 6px;
          color: #808080;
        }
        .title-name {
          font-weight: bold;
        }
        .title-title3 {
          color: #808080;
        }
      }

      .additional-info {
        display: flex;
        gap: 8px;
        font-size: 13px;
        color: #808080;
        .subtitle4 {
          color: rgba(0, 0, 255, 0.8);
        }
      }
    }
  }

  .ribbon {
    position: absolute;
    top: 16px;
    right: -6px;
    background-color: #ff4d4f;
    color: white;
    padding: 5px 25px;
    font-size: 12px;
    transform: rotate(45deg) translateX(30%);
    transform-origin: top right;
    z-index: 1;
  }

  .custom-actions {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .footer-icon {
        margin-right: 5px;
      }

      .footer-item-split {
        color: rgba(220, 220, 220, 0.59);
      }

      .footer-item {
        color: rgba(117, 117, 117, 0.8);
        font-size: 1em;
        white-space: nowrap;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        flex: 1 1 0;
        min-width: 0;
      }

      .footer-item:hover {
        color: rgb( 24,144,255 );
        cursor: pointer;
      }
      :deep(.ant-divider-vertical) {
        height: 24px;
        border-left: 1px solid rgba(220, 220, 220, 0.59);
        top: 0;
        margin: 0 8px;
      }
  }
}

.ellipsis {
  display: inline-block;
  max-width: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
