<template>
  <div class="bg-info">
    <ul>
      <li
        v-for="(item, index) in data"
        :key="'li_' + index"
        :style="{
          width: item.full ? `100%` : `calc(100% / ${col})`,
        }"
      >
        <span :style="{ width: item.nameWidth ? item.nameWidth + 'px' : '50%'}">
          {{ item.name }}
        </span>
        <span :style="{ width: item.nameWidth ? `calc( 100% - ${item.nameWidth + 'px'})` : '50%'}">
          <span 
            style="display: inline-block;width: 100%;white-space: normal;word-break: break-all" 
            :style="{
              width: item.copy ? 'calc(100% - 36px)' : item.download || item.password ? 'calc(100% - 22px)': '100%',
              color: item.download ? '#3759be' : '#404a62'
            }"
          >{{ item.value }}</span>
          <a
            class="copy-btn"
            @click="copyText(item.value, $event)"
            v-if="item.copy"
          >
            复制
          </a>
          <bg-icon 
            class="copy-btn"
            style="font-size: 14px; color: #a9b1c7;cursor: pointer;" 
            icon="#bg-ic-download" 
            v-if="item.download"
            @click="download(item.url)"
          ></bg-icon>
          <bg-icon 
            class="copy-btn"
            style="font-size: 14px; color: #a9b1c7;cursor: pointer;" 
            :icon="show ? '#bg-ic-eye-close' : '#bg-ic-eye'" 
            v-if="item.password"
            @click="changeView(item)"
          ></bg-icon>
        </span>
      </li>
    </ul>
  </div>
</template>

<script>
import Clipboard from "clipboard";

export default {
  name: "BgInfo",
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    col: {
      type: Number,
      default: 2,
    },
  },
  data() {
    return {
      show: false
    }
  },
  methods: {
    clipboardSuccess() {
      this.$message({
        type: "success",
        message: "复制成功",
        duration: 1500,
      });
    },
    clipboardError() {
      this.$message({
        message: "浏览器不支持自动复制",
        type: "warning",
      });
    },
    copyText(text, e) {
      const clipboard = new Clipboard(e.target, {
        text: () => text,
      });

      clipboard.on("success", () => {
        this.clipboardSuccess();
        // 释放内存
        clipboard.destroy();
      });

      clipboard.on("error", () => {
        // 不支持复制
        this.clipboardError();
        // 释放内存
        clipboard.destroy();
      });
      
      // 解决第一次点击不生效的问题，如果没有，第一次点击会不生效
      clipboard.onClick(e);
    },
    download(url) {
      const a = document.createElement("a"); // 创建a标签
      a.setAttribute("download", ""); // download属性
      a.setAttribute("href", url); // href链接
      a.click(); // 自执行点击事件  
    },
    changeView(item) {
      if (!this.show) {
        item.value = item.realValue
      }else {
        item.value = "***************"
      }
      this.show = !this.show
    }
  },
};
</script>
