<!--新闻组件-->
<template>
  <card-widget
    :is-show-tab="showTab"
    :active-key="activeName"
    :tab-list="categoryList"
    :is-tab-slot="true"
    @tab-change="tabChange"
    :style="style"
  >
    <template #tab="{ scope }">
      <span>{{ scope.name }}</span>
    </template>

    <template #header v-if="showHeaderFlag">
      <div class="news-header">
        <div class="news-header-left">
          <span class="text_box">{{ title }}</span>
        </div>
        <div class="news-header-right" @click="gotoList">
          <div class="news-header-right-content">
            <span class="text_more" v-if="dataList.length > 0">更多</span>
          </div>
        </div>
      </div>
    </template>

    <template #body>
      <!--加载状态-->
      <a-spin :spinning="loading" style="position: absolute; left: 50%; top: 50%"></a-spin>

      <div class="news-list" v-if="dataList.length > 0">
        <a-row class="news-list-item" v-for="(item, index) in dataList" :key="index" @click="handleClick(item)">
          <a-col :span="19" class="news-list-title">
            <span class="drop"></span>
            <span :class="item.clickStatusFlag == 'N' ? 'text-bold' : ''">
              <a-tooltip>
                <template #title>{{ item.newsTitle }}</template>
                {{ item.newsTitle }}
              </a-tooltip>
            </span>
            &nbsp;&nbsp;
          </a-col>
          <a-col :span="5" style="display: flex; justify-content: center; color: #898e91">
            {{ item.showPublishTime }}
          </a-col>
        </a-row>
      </div>

      <div class="news-list-empty" v-else>
        <a-empty description="暂无数据" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
      </div>
    </template>
  </card-widget>
</template>

<script setup name="NewsWidget">
import { onMounted, ref, computed } from 'vue';
import { Empty } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { NewApi } from '@/views/portal/backend/config_detail/new/api/NewApi';
import CardWidget from '@/views/home/components/card_widget.vue';
import { constant } from '@/views/portal/constant/constant';
import { redirectUrl } from '@/utils/common/util';

const props = defineProps({
  widget: Object,
  /**
   * 组件名称
   */
  widgetName: {
    type: String,
    default: constant.NEWS
  },
  /**
   * 组件id
   */
  widgetId: {
    type: String,
    default: '',
    required: true
  },
  /**
   * 是否是预览模式 表示不可点击
   */
  preview: {
    type: Boolean,
    default: false
  },
  designId: {
    type: String,
    default: ''
  }
});

// router
const router = useRouter();

// tabs 选中的tab
const activeName = ref('');

// 分类列表
const categoryList = ref([]);

// 数据列表
const dataList = ref([]);

// 加载状态
const loading = ref(false);

// 更多url
const moreUrl = ref('');

// 标题
const title = ref(constant.NEWS);

const style = ref({});

const showHeaderFlag = ref(false);

const showTab = computed(() => {
  return categoryList.value?.length > 1 ? true : false;
});

/**
 * tabChange
 * @param key
 */
const tabChange = key => {
  if (props.preview) {
    return;
  }
  activeName.value = key;
  getPortalNewsIndexNews(key);
};

/**
 * 根据新闻分类ID获取新闻列表
 * @param newsCategoryId
 */
const getPortalNewsIndexNews = newsCategoryId => {
  loading.value = true;
  NewApi.pageList({ categoryId: newsCategoryId, designId: props.designId, pageNo: 1, pageSize: 10 })
    .then(res => {
      let _dataList = res.data.rows?.map(item => {
        return {
          ...item,
          showPublishTime: item?.showPublishTime.substr(0, 10)
        };
      });

      // 构建更多url
      const { href } = router.resolve({
        path: '/home/newsList',
        query: {
          newsCategoryId: newsCategoryId,
          designId: props.designId,
          elementId: props.widgetId
        }
      });
      moreUrl.value = href;
      dataList.value = _dataList && _dataList.length > 0 ? _dataList : [];
    })
    .finally(() => {
      loading.value = false;
    });
};

/**
 * 跳转到更多列表
 */
const gotoList = () => {
  if (props.preview) {
    return;
  }
  if (moreUrl.value) {
    window.open(moreUrl.value, '_blank');
  }
};

/**
 * 新闻单条点击事件
 * @param item
 */
const handleClick = async item => {
  if (props.preview) {
    return;
  }
  // 判断是否是外链新闻
  let _linkFlag = item.linkFlag;
  if (_linkFlag && _linkFlag === 'Y') {
    let _linkUrl = item.linkUrl;
    if (_linkUrl) {
      // 判断是否是以指定字符串结尾 需要拼接gunsToken
      const result = _linkUrl.endsWith('&grantType=token&gunsToken=');
      if (result) {
        let token = await HomeApi.jwtAaToken();
        redirectUrl(_linkUrl + token, 2);
      } else {
        redirectUrl(_linkUrl, 2);
      }
    }
  } else {
    const { href } = router.resolve({
      path: '/home/newsDetail',
      query: {
        newsId: item.newsId
      }
    });
    window.open(href, '_blank');
  }
  item.clickStatusFlag = 'Y';
};

/**
 * 获取数据列表
 */
const getDataList = () => {
  if (props.widget?.param) {
    title.value = props.widget?.param?.elementName;
    if (props.widget?.param?.config) {
      const { showHeader, borderLeft, borderRight, borderTop, borderBottom } = props.widget?.param?.config;
      showHeaderFlag.value = showHeader;
      style.value = {
        'border-left': borderLeft,
        'border-right': borderRight,
        'border-top': borderTop,
        'border-bottom': borderBottom
      };
    }
  }
  if (props.widget?.param?.selectCateList?.length) {
    loading.value = true;
    NewApi.summary({ designId: props.designId, categoryIdList: props.widget?.param?.selectCateList.map(item => item.id) })
      .then(res => {
        if (res.data && res.data.length > 0) {
          // 构建分类列表
          let _tabs = [];
          res.data.forEach(item => {
            _tabs.push({
              key: item.categoryId,
              name: item.categoryName
            });
          });
          categoryList.value = _tabs;

          if (!activeName.value) {
            if (_tabs.length > 0) {
              activeName.value = _tabs[0].key;
              getPortalNewsIndexNews(activeName.value);
            }
          }
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

/**
 * 更新组件
 */
const updateWidget = () => {
  if (props.widgetName) {
    title.value = props.widgetName;
  }
  getDataList();
};

onMounted(() => {
  updateWidget();
});

defineExpose({
  updateWidget
});
</script>

<style scoped lang="less">
.news-header {
  display: flex;
  position: relative;
}

.news-header-left {
  flex: 1;
  display: flex;
  align-items: center;
}

.news-header-right {
  position: absolute;
  right: 0px;
  top: 5px;
  font-size: 14px;
  color: #808080;
  cursor: pointer;
}

.news-header-right-content {
  display: flex;
  align-items: center;
}

.news-list {
  overflow-x: hidden;
  overflow-y: auto;
  height: v-bind('showTab ? "calc(100% - 60px)" : "100%"');
}

.news-list-item {
  padding: 5px 0;
  cursor: pointer;
}

.drop {
  width: 8px;
  height: 8px;
  margin-right: 4px;
  display: inline-block;
  background-color: #d9d9d9;
  border-radius: 50%;
}

.news-list-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.news-list-title:hover {
  color: #006cb9;
}

.news-list-empty {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
