<!-- 最近浏览 -->
<script setup lang="ts">
import type {CmsArticle} from "~/api/cms/cmsArticle/model";

const props = withDefaults(
    defineProps<{
      data?: CmsArticle;
      type?: string;
    }>(),
    {}
);

const i18n = useI18n();
const list = ref<CmsArticle[]>([])
const key = 'ArticleRecently' + i18n.locale.value
// 加入最近浏览
onMounted(() => {
  const ArticleRecently = localStorage.getItem(key)
  if(props.data?.articleId){
    if(ArticleRecently){
      const json = JSON.parse(ArticleRecently);
      if(json){
        const find = json.find((item: CmsArticle) => item.articleId === props.data?.articleId);
        if(!find){
          // 保留6条记录
          if(json.length > 8){
            json.splice(-1, 1)
          }
          json.unshift({
            articleId: props.data?.articleId,
            title: props.data?.title,
            image: props.data?.image,
            detail: props.data.detail || 'item',
          })
          localStorage.setItem(key,JSON.stringify(json))
        }
      }
      reload();
    }else {
      localStorage.setItem(key, JSON.stringify([]))
    }
  }
})

const reload = () => {
  const ArticleRecently = localStorage.getItem(key);
  if(ArticleRecently){
    list.value = JSON.parse(ArticleRecently)
  }
}

</script>

<template>
  <div class="relateproduct relate">
    <h4>{{ $t('recentlyViewed') }}：</h4>
    <div class="p-1" v-if="type == 'article'">
      <ul id="relate_n" class="news_list clearfix">
        <li v-for="(item,index) in list" :key="index"><a :href="detail(item)" :title="item.title">{{ item.title }}</a></li>
      </ul>
    </div>
    <div class="py-3 px-1" v-if="type == 'product'">
      <el-row :gutter="16">
        <el-col :span="6" v-for="(item,index) in list" :key="index" class="my-1">
          <a class="flex flex-col items-center text-center block" :href="detail(item)">
            <el-image :src="item.image" fit="fill" :alt="item.title" style="height: 150px;"/>
            <span class="py-1">{{ item.title }}</span>
          </a>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>
