<template>
    <div class="expandable_text">
      <div ref="textContainer" class="text_container" :class="{ 'expanded': isExpanded }">
        <slot></slot>
      </div>
      <button v-if="shouldShowButton" @click="toggleExpand" class="toggle_button" :class="isExpanded?'show_expanded':'hide_expanded'">
            {{ isExpanded ? '收起' : '展开' }}
     </button>
    </div>
  </template>
  
  <script>
  export default {
    name: 'ExpandableText',
    data() {
      return {
        isExpanded: false,//是否展开或者收缩
        shouldShowButton: true,
      };
    },
    mounted() {
      this.checkLines();
    },
    methods: {

      // 检查行数并设置是否显示按钮
      checkLines() {
        const container = this.$refs.textContainer;
        if (container) {
            const range = document.createRange();// 创建一个 Range 对象
            range.selectNodeContents(container);// 选择要测量的文本内容
            const rect = range.getBoundingClientRect();// 获取文本内容的边界矩形
            const lineHeight = parseInt(window.getComputedStyle(container).lineHeight, 10);// 获取行高
            const lines = Math.ceil(rect.height / lineHeight);// 计算行数
            console.log("打印行数lines", lines);
            this.shouldShowButton = lines > 3;
        }
      },
      toggleExpand() {
        this.isExpanded = !this.isExpanded;
      },
    },
  };
  </script>
  
  <style scoped>
  .expandable_text {
    position: relative;
  }
  

  .text_container {
    position: relative;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    transition: max-height 0.3s ease-out;
    max-height: 72px; 
  }
  
  .text_container.expanded 
  {
    -webkit-line-clamp: unset;
    max-height: none;
  }
  
  .toggle_button 
  {
    /* position: absolute;
    bottom: 0;
    right: 0; */
    margin-top: 8px;
    cursor: pointer;
    background: none;
    border: none;
    color: #2E64FA;                     
    font-size: 14px;
    line-height: 1;
    width: 100%;
    height: 24px;
    /* background-color: #ffffff; */
    text-align: right;
    padding-right: 20px;
  }

  .show_expanded
  {
    background-image: url('/src/assets/report/up_expanded.webp');
    background-size: 16px 16px;
    background-position: 100% 50%;
    background-repeat: no-repeat;
  }

  .hide_expanded
  {
    background-image: url('/src/assets/report/down_expanded.webp');
    background-size: 16px 16px;
    background-position: 100% 50%;
    background-repeat: no-repeat;
  }


  </style>