<template>
  <a-layout class="news-detail">
    <a-layout-header class="news-detail-header">
      <a-space :size="16">
        <span class="back-btn" @click="backHome">
          <left-outlined />
          <span>返回</span>
        </span>
        <a-divider type="vertical" />
      </a-space>
    </a-layout-header>
    <a-layout-content ref="contentRef" class="news-detail-content">
      <a-spin :spinning="loading" :delay="100">
        <div class="news-content" v-if="newData">
          <div class="new-title">{{ newData?.newsTitle }}</div>
          <div class="news-detail-nav-date-user">
            <span>作者：{{ newData?.showPublishUser }}</span>
            <span v-if="newData?.showPublishTime">时间：{{ newData.showPublishTime }}</span>
            <span>点击次数：{{ newData?.clickCount }}</span>
          </div>
          <!--文章内容-->
          <div class="news-content-wrapper" v-html="newData.newsContent" @click="imageChagange($event)"></div>

          <!-- 附件 -->
          <div style="margin: 10px 0 20px 0" v-if="newData.businessFileInfoList?.length > 0">
            <div class="appendixMain" v-for="(file, index) in newData.businessFileInfoList" :key="index">
              <div class="appendixLeft">
                <div :class="'mr1 ' + handleFileSuffixClass(file.fileSuffix)"></div>
                <div class="appendixLeftContent">
                  <div class="theme-color-hover cursor-pointer" @click="previewFile(file)">{{ file.fileOriginName }}</div>
                  <div style="float: left; text-align: right">{{ file.fileSizeInfo }}</div>
                </div>
              </div>
              <div class="appendixRight">
                <a-button size="small" @click="downloadFile(file.fileId)">
                  <template #icon>
                    <download-outlined />
                  </template>
                  <span class="fs16">{{ file.downloadCount }}</span>
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </a-spin>

      <!--返回顶部-->
      <a-back-top ref="backTopRef" @click="goToTop" />
    </a-layout-content>

    <ShowImage :visible="contentImgVisible" :urlList="bigImgUrlList" @close="close" v-if="contentImgVisible"></ShowImage>
  </a-layout>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getToken } from '@/utils/token-util';
import { FileApi } from '@/views/system/backend/file/api/FileApi';
import { NewApi } from '@/views/portal/backend/config_detail/new/api/NewApi';
import { Modal } from 'ant-design-vue';
import { API_BASE_PREFIX } from '@/config/setting';

const route = useRoute();
const router = useRouter();

// 新闻id
const currentNewsId = ref('');

// 新闻详情数据
const newData = ref(null);

const loading = ref(false);

// 返回顶部dom
const backTopRef = ref(null);

const contentRef = ref(null);

// 文章内容图片展示
const contentImgVisible = ref(false);
// 图片列表
const bigImgUrlList = ref([]);

// 可预览的文件后缀
const imgFileSuffix = ref(['jpg', 'png', 'jpeg']);
// 可预览的文档文件后缀
const docFileSuffix = ref(['pdf', 'doc', 'docx']);

// 图片预览地址
const filePreviewUrl = ref(`${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`);

onMounted(() => {
  const { newsId } = route.query;
  if (!newsId) return backHome();
  currentNewsId.value = newsId;
  getNewDetail();
});

const backHome = () => {
  let url = '/home';
  router.push(url);
};

// 获取新闻详情
const getNewDetail = () => {
  loading.value = true;
  NewApi.newsDetail({ newsId: currentNewsId.value })
    .then(res => {
      newData.value = res.data;
    })
    .finally(() => (loading.value = false));
};

/**
 * 返回顶部
 */
const goToTop = () => {
  nextTick(() => {
    if (contentRef.value) {
      contentRef.value.$el.scroll({ top: 0, behavior: 'smooth' });
    }
  });
};

/**
 * 富文本渲染图片点击
 * @param e
 */
const imageChagange = e => {
  if (e.target.nodeName === 'IMG' || e.target.nodeName == 'img') {
    //判断是否图片标签
    const img = e.target.currentSrc; //获取点击图片地址
    bigImgUrlList.value = [img];
    contentImgVisible.value = true;
  }
};

const close = () => {
  bigImgUrlList.value = [];
  contentImgVisible.value = false;
};

/**
 * 根据文件后缀显示文件图标class
 */
const handleFileSuffixClass = fileSuffix => {
  // 默认文件显示图标
  let className = 'append_icon_pdf';
  if (fileSuffix === 'ppt' || fileSuffix === 'pptx') {
    className = 'append_icon_ppt';
  }

  if (fileSuffix === 'doc' || fileSuffix === 'docx') {
    className = 'append_icon_word';
  }

  if (fileSuffix === 'xls' || fileSuffix === 'xlsx') {
    className = 'append_icon_excel';
  }

  if (imgFileSuffix.value.includes(fileSuffix)) {
    className = 'append_icon_png';
  }
  return className;
};

/**
 * 文件下载
 * @param item
 */
const downloadFile = fileId => {
  FileApi.download({
    fileId,
    token: getToken()
  });
};

/**
 * 预览文件
 * @param file
 */
const previewFile = file => {
  if (file === null) {
    return;
  }

  let fileId = file.fileId;

  let fileSuffix = file.fileSuffix;

  // 判断文件是否可以预览
  let previewFileSuffix = [].concat(imgFileSuffix.value).concat(docFileSuffix.value);
  let isPreview = previewFileSuffix.includes(fileSuffix);
  if (isPreview) {
    // 如果是pdf doc
    if (docFileSuffix.value.includes(fileSuffix)) {
      let url = `${API_BASE_PREFIX}/documentPreview?fileId=${fileId}&token=${getToken()}`;
      window.open(url, '_blank');
    } else if (imgFileSuffix.value.includes(fileSuffix)) {
      // 图片预览
      let url = filePreviewUrl.value + fileId + '&token=' + getToken();
      bigImgUrlList.value = [url];
      contentImgVisible.value = true;
    }
  } else {
    Modal.error({
      content: '该文件暂不支持预览！',
      okText: '确定',
      keyboard: false
    });
  }
};
</script>

<style scoped lang="less">
.news-detail {
  position: relative;
  width: 100%;

  .news-detail-header {
    position: fixed;
    z-index: 2;
    top: var(--header-height);
    left: var(--sidebar-collapse-width);
    height: 56px;
    line-height: 56px;
    padding: 0 16px;
    width: 100%;
    background-color: #fff;

    .back-btn {
      cursor: pointer;
      font-size: 16px;
      color: #60666b;
      font-weight: 400;

      .anticon {
        font-size: 14px;
        margin-right: 4px;
        color: #60666b;
      }
    }
    .ant-divider {
      border-left: 1.5px solid #c5cfd1;
    }
  }
  .news-detail-content {
    height: 100%;
    margin-top: 56px;
    overflow-y: auto;
    padding: 10px 0;
    position: relative;

    .news-content {
      min-height: 410px;
      max-width: 912px;
      margin: 0 auto;
      border-radius: 4px;
      padding: 24px;
      background-color: #fff;

      .new-title {
        font-size: 24px;
        font-weight: bold;
        text-align: center;
        padding: 0px 0 16px 0;
        border-bottom: 1px solid #ebeced;
      }
      .news-detail-nav-date-user {
        display: flex;
        align-items: center;
        justify-content: center;
        padding-top: 16px;
        margin-bottom: 16px;
        color: #7c829a;
        font-size: 20px;

        span {
          margin-right: 30px;
        }
      }
      :deep(.news-content-wrapper) {
        line-height: 1.8;
        font-size: 16px;
        color: #333333;
        min-height: 50px;

        img {
          max-width: 100%;
          height: auto;
        }
      }

      .appendixMain {
        display: flex;
        align-items: center;
        clear: both;
        justify-content: space-between;
        height: auto;
        padding-bottom: 16px;
        border-bottom: 1px solid #f1f1f1;
      }

      .appendixLeft {
        display: flex;
        align-items: center;
        vertical-align: middle;

        .appendixLeftContent {
          font-size: 20px;
        }
      }

      .appendixMain .appendixLeft div {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: center;
      }

      .appendixRight {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.append_icon_pdf {
  width: 28px;
  height: 32px;
  background: url('@/assets/images/home/pdf.svg') no-repeat;
}

.append_icon_excel {
  width: 28px;
  height: 32px;
  background: url('@/assets/images/home/excel.svg') no-repeat;
}

.append_icon_ppt {
  width: 28px;
  height: 32px;
  background: url('@/assets/images/home/ppt.svg') no-repeat;
}

.append_icon_word {
  width: 28px;
  height: 32px;
  background: url('@/assets/images/home/word.svg') no-repeat;
}

.append_icon_png {
  width: 30px;
  height: 35px;
  background: url('@/assets/images/home/image.svg') no-repeat;
  background-size: cover;
}
</style>
