<template>
  <section class='dialog-page'>
    <el-dialog v-model="dialogTableVisible" title=" " @close="emit('close')">
      <div>
        <div class="content-container-title">{{ props.item.name || props.item.title }}</div>
        <div style="height: calc(90vh - 200px);overflow-y: auto;">
          <p v-html="props.item.content"></p>
          <div style="text-align: center;" v-if="imgObj.url">
            <video controls v-if="imgObj.isMp4" style="width: 80%;" :src="imgObj.url"></video>
            <img v-else style="width: 80%;" :src="imgObj.url" alt="无图">
          </div>
          <div class="btn-container">
            <el-button class="btn-download" type="primary" v-for="(item, index) in fileList"
              @click="doPreviewqd(item)">{{
                item.name }}-预览</el-button>
          </div>
        </div>
        <div class="writer-container">
          <div class="btn-container">
            <!-- <el-button v-if="fileList.length > 0" :disabled="!fileList.length" type="primary"
                            @click="downLoad(props.item)">下载附件({{
                                fileList.length }}个文件)</el-button> -->
            <!-- <el-button class="btn-download" type="primary" v-for="(item, index) in fileList" @click="doPreviewqd(item)">{{
                            item.name && item.name.slice(0,10) }}</el-button> -->
          </div>
          <div>
            <article class="writer">
              撰稿人：<span>{{ props.item.writer }}</span>
            </article>
            <article class="writer">
              发布时间：<span>{{ props.item.issuedTime }}</span>
            </article>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="flyldialog" :show-close="false" top="10px" bottom="10px" width="1120px">
      <div style="height: 84vh; text-align: center">
        <Kkfile :files="fileid" @changedialog="changedialog" />
      </div>
    </el-dialog>
  </section>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import Kkfile from "@/components/MyComponents/kkfile/index.vue";
import { IS_MP4 } from "@/utils/tools.js";

const dialogTableVisible = ref(true)
const props = defineProps({
  item: {
    type: Object,
    default: () => { }
  },
})
const emit = defineEmits(['close'])
const fileList = ref([])
const imgObj = ref({})
const flyldialog = ref(false)

const fileid = ref('')
const changedialog = () => {
  flyldialog.value = false
}
/** 文件 */
const filesData = ref()
const doPreviewqd = (row) => {
  fileid.value = row.files || row.id;
  flyldialog.value = true
}
const createAndClickLink = (downloadUrl, fileName) => {
  return new Promise((resolve, reject) => {
    const xhr = new window.XMLHttpRequest();
    xhr.open("GET", downloadUrl, true);
    xhr.responseType = "blob";
    xhr.onload = () => {
      const url = window.URL.createObjectURL(xhr.response);
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName;
      // 使用 setTimeout 延迟点击操作
      setTimeout(() => {
        a.click();
        window.URL.revokeObjectURL(url); // 释放资源
        resolve(); // 解决 Promise
      }, 0);
    };
    xhr.onerror = () => {
      reject(new Error("文件下载失败"));
    };
    xhr.send();
  });
};
const getImage = (id) => {
  getApi({}, `/mosty-base/minio/file/download/${id}`).then((res) => {
    res = res || {}
    imgObj.value = {
      name: res.originalName,
      id: res.id,
      url: res.url,
      suffix: res.suffix,
      isMp4: IS_MP4(res.suffix ? res.suffix.replace('.', '') : '')
    }
  });
}
const getFile = (item) => {
  item.file = item.file || item.otherFile
  const ids = item.file ? item.file.split(',') : []
  filesData.value = item.file
  ids.forEach((item) => {
    if (item == "" || item == null) return;
    getApi({}, `/mosty-base/minio/file/download/${item}`).then((res) => {
      fileList.value.push({
        name: res.originalName,
        id: res.id,
        url: res.url,
        suffix: res.suffix
      });
      //去重
      let map = new Map();
      for (let item of fileList.value) {
        map.set(item.id, item);
      }
      fileList.value = [...map.values()];
      //   fileList.value[0].start = true;
      //   fileNamelist.value = fileList.value;
      //   emits("filehandleChange", fileList.value);
    });
  });
}
const downLoad = (item) => {
  fileList.value.forEach((file) => {
    handleDownload(file);
  });
}

const handleDownload = (file) => {
  if (file.response) {
    window.open(`/mosty-api/mosty-base/minio/image/download/${file.response.data}`, "_blank");
  } else {
    // window.open(file.url, "_blank");
    createAndClickLink(file.url, file.name);
  }
};
onMounted(() => {
  getFile(props.item)
  if (props.item?.titleFile) getImage(props.item?.titleFile)
});
</script>
<style scoped lang="scss">
.content-container-title {
  font-size: 23px;
  font-weight: bolder;
  padding: 0px 0 9px;
  text-align: center;
}

.writer-container {
  padding-top: 5px;
  display: flex;
  justify-content: space-between;
}

::v-deep .el-dialog__header {
  height: 50px;
}

.btn-container {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.btn-download {
  margin: 0 5px;
}
</style>
