<script setup lang="ts">
import { useRoute } from 'vue-router'
import { getDick, getNewsById, type NewsData, type NewsResponseData } from '@/api/home'
import { onMounted, ref } from 'vue'
import { formatTime } from '@/utils/formatTime'
import { downloadFile } from '@/utils/request'
const route = useRoute();
const getData = async ()=>{
  const res = await getNewsById(Number(route.query.id));
  let imgTemplateArr:string[] = [];
  if(res.code == 200){
    if(res.data.files.length != 0) {
      res.data.files.forEach(item => {
        item.fileUrl;
        imgTemplateArr.push(`<div style="width: 90%;margin: 0 auto"><img src="${BASE_URL}${item.fileUrl}" alt="" style="width: 100%;margin: 0 auto;"></div>`)
      })
    }
    console.log(imgTemplateArr)
    const position = res.data.content.indexOf('&zwnj;');
    if(position != -1){
      res.data.content = replacePlaceholders(res.data.content, imgTemplateArr)
    }
    res.data.files = res.data.files.filter(item=>!(item.fileOriginalName.endsWith('.jpg') || item.fileOriginalName.endsWith('.png')))
    newsData.value = res.data;
  }
}
function replacePlaceholders(template:string, replacements:string[]) {
  return template.split('&zwnj;').map((part, index) => {
    return index < replacements.length ? part + replacements[index] : part;
  }).join('');
}

const BASE_URL = import.meta.env.VITE_APP_BASE_URL;
const newsData = ref<NewsData>();

  window.scroll({
    top: 0,
    // left: 0,
    // behavior: 'smooth' // 这个选项可以使滚动平滑进行
  })
getData()
</script>

<template>
  <div class="w-912px ml-auto mr-auto pt-20px mb-20px text-14px">
    你所在的位置：<span class="cursor-pointer" @click="$router.push('/')">首页</span> > <span class="color-#006eff">新闻详情</span>
  </div>
  <div class="min-h-500px">
    <div class="w-912px ml-a mr-a text-24px color-black bold text-center mb-30px">
      {{newsData?.title}}
    </div>
    <div class="w-912px ml-a mr-a h-1px bg-gray"></div>
    <div class="w-912px ml-a mr-a text-14px mt-10px flex justify-between">
      <div>发布时间：{{formatTime(newsData?.date)}}</div>
      <div class="mr-20px">数据来源：{{newsData?.dataSource}}</div>
    </div>
    <div class="custom-font w-912px ml-a mr-a text-18px mt-10px mb-50px line-height-34px " v-html="newsData?.content"></div>
    <div class="w-912px ml-a mr-a text-14px mt-10px" v-if="newsData?.files.length">
      <div v-if="newsData?.files.length>0">附件下载</div>
      <div v-for="(item,index) in newsData?.files" :key="index" class="line-height-40px">
        <!--      <a :href="`${BASE_URL}${item.fileUrl}`" :download="item.fileOriginalName">{{ item.fileOriginalName }}</a>-->
        <div >
          <span class="text-blue underline hover:text-red cursor-pointer" @click="downloadFile(`${BASE_URL}${item.fileUrl}`,item.fileOriginalName)">{{item.fileOriginalName}}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.custom-font{
  font-family: 等线;
}
</style>