<template>
  <div v-if="fileList.length" class="file-preview">
    <el-button
      :size="size"
      type="text"
      @click="visible = true"
      style="font-size: 12px; padding: 0"
    >
      附 件
    </el-button>
    <i class="el-icon-link el-icon--right"></i>
    <el-dialog :visible.sync="visible" title="查看" append-to-body>
      <div class="file-preview_content">
        <div
          v-for="item in fileList"
          :key="item.url"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 10px;
            border: 1px dashed rgba(88, 140, 233, 0.3);
          "
        >
          <span> {{ item.name }}</span>
          <span>
            <el-button
              :size="size"
              type="text"
              icon="el-icon-view"
              @click="useView(item)"
            ></el-button>
            <el-button
              :size="size"
              type="text"
              icon="el-icon-download"
              @click="useDownload(item)"
            ></el-button>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
  <span v-else>--</span>
</template>

<script>
export default {
  name: "FilePreview",
  props: {
    // 值
    value: [String, Object, Array],
    // 组件大小
    size: {
      type: String,
      dafault: () => {
        return "mini";
      },
    },
  },
  data() {
    return {
      separator: ";",
      visible: false,
      fileList: [],
    };
  },
  computed: {},
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val)
            ? val
            : this.value.split(this.separator);
          this.fileList = list.map((item) => {
            item = JSON.parse(item);
            return {
              ...item,
              uid: item.uid || new Date().getTime() + temp++,
            };
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    //
    useDownload(prop) {
      const { url, name } = prop;
      this.download("/pu/contract/download/resource", { resource: url }, name);
    },
    //
    useView(prop) {
      this.$notify.info({ title: "暂不支持查看" });
    },
  },
  created() {},
  mounted() {},
  destroyed() {},
};
</script>
<style scoped>
.file-preview_content > div {
  margin-bottom: 10px;
}
.file-preview_content > div:last-of-type {
  margin-bottom: 0;
}
</style>
