<template>
  <view class="index-wrap">
    <!-- 顶部栏 -->
    <view class="homeTopContainer">
      <!-- 搜索框 -->
      <view class="sreach">
        <image src="@/static/logo_mini.png" class="sreach_icon" @click="messageShow = true"></image>
        <u-input v-model="keyWord" prefixIcon="search" style="flex: 1" placeholder="搜索资讯" placeholderClass="search_placeholder" class="sreach_input" :border="false" @confirm="goSreach" />
      </view>

      <!-- 渐变的背景 -->
      <view class="vipContentBg"></view>

      <!-- banner -->
      <view class="headerBanner"> </view>
      <!-- 搜索框 -->
      <!-- <view class="sreach">
        <image src="@/static/logo_mini.png" class="sreach_icon" @click="messageShow = true"></image>
        <u-input v-model="keyWord" prefixIcon="search" style="flex: 1" placeholder="搜索资讯" placeholderClass="search_placeholder" class="sreach_input" :border="false" @confirm="goSreach" />
      </view> -->

      <!-- 导航栏 -->
      <!-- <view class="homeNav"> -->
      <!-- <view class="r_tab">
          <view v-for="(item, index) in colList" :key="item.id" class="tab_item" @click="handleTabsClick(item)">
            <text :style="{ fontWeight: index == columnIndex ? 'bold' : '' }"> {{ item.name }}</text>
            <image src="@/static/bk_tab.png" class="bk_tab" v-if="index == columnIndex"></image>
            <view class="badge" v-if="isBadeg && index !== 1">
              <u-badge value="new"></u-badge>
            </view>
          </view>
        </view> -->

      <!-- <view class="tabsListContainer" v-if="!overlayShow && columnIndex === 1">
          <view class="tabsList">
            <view v-for="(item, index) in tagsList" :key="item.id" :class="['tabsItem', { active: item.id == columnState.subColumn }]" @click="handleClickSubColumn(item.id)">{{ item.name }}</view>
          </view>
          <view class="downContainer" @click="showTabsPopup" v-if="tagsList.length > 0">
            <image :src="down" class="downPng" />
          </view>
        </view> -->

      <!-- <view class="tabsPopup" v-if="overlayShow">
          <view class="popupContainer" @touchmove="handleScroll">
            <view class="tabsPopupItem" v-for="item in sortTagsList" :key="item">
              <view class="title">{{ item.name }}</view>
              <view class="itemList">
                <view v-for="(childItem, index) in item.children" :key="childItem.id" :class="['tabsItem', { active: childItem.id == columnState.subColumn }]" @click="handleClickSubColumn(childItem.id)">{{ childItem.name }}</view>
              </view>
            </view>
          </view>
        </view> -->
      <!-- </view> -->
    </view>

    <!-- tabs -->
    <u-sticky offset-top="0">
      <view class="headerTabs">
        <view class="tabsList">
          <view class="tab_item active"> 早知道 </view>
          <view class="tab_item"> 天下事 </view>
        </view>
        <view class="headerTabContent">
          <view class="newsBg">
            <view class="newsFontBg"></view>
          </view>

          <view class="content">
            <KnowEarlier @handleUpdateData="handleUpdateData" :isNewFlash="isNewFlash" :data="newsFastList" v-if="columnIndex === 0" />
          </view>
        </view>
      </view>
    </u-sticky>

    <u-overlay :show="overlayShow" zIndex="101" @click="overlayShow = false"></u-overlay>
    <!-- <KnowEarlier @handleUpdateData="handleUpdateData" :isNewFlash="isNewFlash" :data="newsFastList" v-if="columnIndex === 0" /> -->
    <WorldlyAffairs @changelockType="changelockType" @handleSub="handleSub" :finish="finish" v-if="columnIndex === 1" :column="tagsList[columnIndex]" :bannerList="bannerList" :titleCardList="titleCardList" :worldNewsList="worldNewsList" @onload="onload" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted } from "vue";
import { onShow, onPullDownRefresh } from "@dcloudio/uni-app";
import KnowEarlier from "@/pages/knowEarlier/index.vue";
import WorldlyAffairs from "@/pages/worldlyAffairs/index.vue";
import { getNewsFast, checkNews, getNewsColumn, getNewsTag, getNewsList, unlockColumn } from "@/api";
import { Session } from "@/utils/storage";
import down from "@/assets/images/down.png";
import VipHeader from "./vipHeader";
import { scrollToTop, formatTime } from "@/utils/util.ts";
import { useShareStore } from "@/stores/shareStore";
import { useTimerStore } from "@/stores/timerStore";

const emit = defineEmits(["onChange"]);
const props = defineProps({
  colList: {
    type: Array,
    default: () => [],
  },
  columnState: {
    type: Object,
    default: () => {},
  },
});

console.log("colList ===>", props.colList);

const finish = ref(false);
// 栏目索引
const columnIndex = computed(() => {
  const index = props.colList.findIndex((item: any) => item.id == props.columnState.column);
  return index === -1 ? 0 : index;
});
// 子栏目索引
const subColumnIndex = computed(() => {
  const index = tagsList.value.findIndex((item: any) => item.id == props.columnState.subColumn);
  return index === -1 ? 0 : index;
});

const stores = useShareStore(); //分享
const timerStore = useTimerStore(); //定时器
const curPages = getCurrentPages(); // 当前页面栈
const isBadeg = ref(false);
const isNewFlash = ref(false);
// newsFastList 的数据
const newsFastList = ref([]);
// 导航栏的数据
const overlayShow = ref(false);
const keyWord = ref("");
const messageShow = ref(false);
// 当前选择的子标签
// const subColumn = ref(0);
// 标签列表 --- 分类
const sortTagsList = ref([]);
// 标签
const tagsList = ref([]);
// 天下事请求参数
const worldlyAffairsParams = ref({
  page: 1,
  tagId: null,
  unlockType: null,
});
// banner 数据
const bannerList = ref([]);
// 标题卡片数据
const titleCardList = ref([]);
// 天下事新闻列表
const worldNewsList = ref([]);

const handleScroll = (e) => {
  e.stopPropagation();
};

// 获取标签
const getTags = async (type) => {
  const tagRes = await getNewsTag({
    type,
  });
  if (tagRes.code === 200) {
    return tagRes.data;
  }
};

// 点击更新数据
const handleUpdateData = () => {
  isNewFlash.value = false;
  getNewsFastList();
};

// 点击显示标签栏的弹框
const showTabsPopup = () => {
  overlayShow.value = true;
};

const handleClickSubColumn = (index: number) => {
  if (props.columnState.subColumn === index) {
    emit("onChange", 0, "subColumn");
  } else {
    emit("onChange", index, "subColumn");
  }
  worldlyAffairsParams.value.tagId = index || null;
  worldlyAffairsParams.value.page = 1;
  worldNewsList.value = [];
  finish.value = false;
  getWorldlyAffairs();
};

// 获取实时快讯
const getNewsFastList = async () => {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  const { code, data } = await getNewsFast({});
  uni.hideLoading();
  if (code === 200) {
    // 这里进行赋值
    if (data.length > 0) {
      let fastList = data.map((item) => {
        item.lastTime = item.time;
        item.time = formatTime(item.time);
        return item;
      });
      newsFastList.value = fastList;
      // const publishTimestamp = data[0].lastTime; // 取出第一条的时间戳
      // Session.set("publishTimestamp", publishTimestamp); // 将时间戳保存到缓存中
      timerStore.stopTimer();
      const lastTime = new Date().getTime();
      getCheckNews(lastTime);
    }
  }
};
// 检查快讯是否有更新
const getCheckNews = (lastTime: number) => {
  const period = 30000; // 30秒一次
  if (!timerStore.isTimerRunning) {
    timerStore.startTimer(async () => {
      // const lastTime = Session.get("publishTimestamp") || 0;
      const res = await checkNews({
        time: lastTime,
      });
      if (res.code === 200) {
        if (res.data) {
          isNewFlash.value = true;
          isBadeg.value = true;
        }
      }
    }, period);
  }
};

function goSreach() {
  uni.navigateTo({
    url: "/pages/sreachReq/index?keyWord=" + keyWord.value,
  });
}

// 订阅功能
const handleSub = async (itemType) => {
  const res = await unlockColumn({
    columnId: itemType,
  });
  if (res.code === 200) {
    let swiperResult = [];
    let blockResult = [];
    let articleResult = [];
    // === 轮播图 ===
    swiperResult = bannerList.value.map((item) => {
      if (item.type === itemType) {
        item.needpay = false;
      }
      return item;
    });
    // === 板块 ===
    blockResult = titleCardList.value.map((item) => {
      if (item.type === itemType) {
        item.needpay = false;
      }
      return item;
    });
    // === 文章列表 ===
    articleResult = worldNewsList.value.map((item) => {
      if (item.type === itemType) {
        item.needpay = false;
      }
      return item;
    });
    bannerList.value = swiperResult;
    titleCardList.value = blockResult;
    worldNewsList.value = articleResult;
  }
};

// 获取栏目子标签
const getColumnSubTags = async () => {
  const sourceTags = await getTags(0); // 来源标签
  const channelTags = await getTags(1); // 频道标签
  sortTagsList.value = [
    {
      name: "频道",
      children: channelTags,
    },
    {
      name: "来源",
      children: sourceTags,
    },
  ];
  tagsList.value = [{ name: "全部", id: 0 }, ...channelTags, ...sourceTags];
};

onPullDownRefresh(async () => {
  if (columnIndex.value === 1) {
    worldlyAffairsParams.value.page = 1;
    worldNewsList.value = [];
    worldlyAffairsParams.value.tagId = null;
    finish.value = false;
    await getWorldlyAffairs();
  } else {
    await getNewsFastList();
  }
  uni.stopPullDownRefresh();
});

// 点击导航切换页面
const handleTabsClick = async (item: any) => {
  emit("onChange", item.id, "column");
  overlayShow.value = false;
  scrollToTop();
  isBadeg.value = false;
  finish.value = false;
  // 早知道栏目id: 13是快讯
  if (item.id === 13) {
    getNewsFastList();
  } else {
    worldlyAffairsParams.value.page = 1;
    worldNewsList.value = [];
    worldlyAffairsParams.value.tagId = null;
    getWorldlyAffairs();
  }
  wxShare();
};

// 筛选新闻列表
const changelockType = (type) => {
  worldlyAffairsParams.value.page = 1;
  worldNewsList.value = [];
  finish.value = false;
  if (type === "subscribed") {
    worldlyAffairsParams.value.unlockType = 1;
  } else {
    worldlyAffairsParams.value.unlockType = null;
  }
  getWorldlyAffairs();
};

// 获取天下事的数据
const getWorldlyAffairs = async () => {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  // banner 列表
  await getBannerList();
  // 标题卡片列表
  await getTitleCardList();
  // 新闻列表
  await getWorldNewsList();
  uni.hideLoading();
};
// 获取 banner 列表
const getBannerList = async () => {
  const bannerParams = {
    type: 0,
    page: 1,
    size: 9999,
    tagId: props.columnState.subColumn || null,
    columnId: props.columnState.column,
  };
  const res = await getNewsList(bannerParams);
  if (res.code === 200) {
    bannerList.value = res.data;
  }
};

// 获取标题卡片数据
const getTitleCardList = async () => {
  const params = {
    type: 1,
    page: 1,
    size: 9999,
    tagId: props.columnState.subColumn || null,
    columnId: props.columnState.column,
  };
  const res = await getNewsList(params);
  if (res.code === 200) {
    titleCardList.value = res.data;
  }
};

// 获取新闻列表
const getWorldNewsList = async () => {
  const params = {
    type: null,
    page: worldlyAffairsParams.value.page,
    size: 20,
    tagId: props.columnState.subColumn || null,
    columnId: props.columnState.column,
    unlockType: worldlyAffairsParams.value.unlockType,
  };
  const res = await getNewsList(params);
  if (res.code === 200) {
    if (worldNewsList.value.length > 0) {
      worldNewsList.value = [...worldNewsList.value, ...res.data];
    } else {
      worldNewsList.value = res.data;
    }
    if (res.data.length === 0) {
      finish.value = true;
    }
  }
};

// 点击加载更多新闻
const onload = async () => {
  worldlyAffairsParams.value.page++;
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  await getWorldNewsList();
  uni.hideLoading();
};

const wxShare = () => {
  let link = stores.redirectUrl;
  let path = curPages[curPages.length - 1].route;
  let query = encodeURIComponent(
    JSON.stringify({
      tabIndex: 0,
      columnIndex: props.columnState.column,
    })
  );
  link += `?path=${path}&query=${query}`;
  // console.log("🚀 ~ WXconfig ~ link:", link);
  const shareData = {
    title: `中证参考-vip-${props.colList[columnIndex.value]?.name}`,
    desc: "",
    link: link,
    imgUrl: "https://cankao.cs.com.cn/static/share-vip.jpg",
  };
  // console.log("output >>>>> shareData", shareData);

  stores.initWxConfig(shareData);
};

onShow(async () => {
  await getNewsFastList();
  await getColumnSubTags();
  // await getCheckNews();
  await wxShare();
  // banner 列表
  await getBannerList();
  // 标题卡片列表
  await getTitleCardList();
  if (worldNewsList.value.length === 0) {
    await getWorldNewsList();
  }
  // console.log('===')
  // 返回时情况搜索框的数据
  keyWord.value = "";
});

onUnmounted(() => {
  timerStore.stopTimer();
});
</script>

<style lang="scss" scoped>
.index-wrap {
  height: calc(100vh - 131rpx);
  // height: 100vh;
  background-color: #f6f6f6;
  box-sizing: border-box;
  overflow-y: auto;
  .homeTopContainer {
    position: relative;
    .sreach {
      width: 100%;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 20rpx 30rpx;
      gap: 30rpx;
      background-image: url(@/assets/images/vip_header_search_bg.png);
      background-size: cover;
      position: fixed;
      left: 0;
      top: 0;
      z-index: 2;
      .sreach_icon {
        width: 78rpx;
        height: 60rpx;
        margin-top: 3rpx;
      }
      .sreach_input {
        background-color: #fff;
        border-radius: 36rpx;
        box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.1);
      }

      .search_placeholder {
        font-size: 12px;
        color: #717171 !important;
      }
    }

    .vipContentBg {
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 366rpx;
      background-image: url(@/assets/images/vip_header_content_bg.png);
      background-size: cover;
      margin-top: 100rpx;
    }

    .headerBanner {
      margin: 0rpx 26rpx;
      background-color: aquamarine;
      height: 260rpx;
      border-radius: 32rpx;
      position: relative;
      top: 0;
      margin-top: 116rpx;
      z-index: 1;
    }
  }

  .headerTabs {
    box-sizing: border-box;
    padding-top: 20rpx;
    width: 100%;
    .tabsList {
      display: flex;
      // background-color: aqua;
      background: linear-gradient(90deg, #ffc795 0%, #ffad9a 100%);
      border-top-left-radius: 32rpx;
      border-top-right-radius: 32rpx;
      .tab_item {
        width: 52%;
        height: 126rpx;
        display: flex;
        justify-content: center;
        box-sizing: border-box;
        padding-top: 24rpx;
        color: #fff;
        &.active {
          border-top-left-radius: 32rpx;
          border-top-right-radius: 32rpx;
          background: linear-gradient(90deg, #ff5e6a 0%, #e7303f 100%);
          box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.3), 1px 1px 2px 0px rgba(143, 15, 25, 0.3);
        }
      }
    }

    .headerTabContent {
      width: 100%;
      // height: calc(100vh - 229rpx);
      // overflow-y: auto;
      // background-color: red;
      // background: linear-gradient(180deg, rgba(240, 240, 240, 0.4) 0%, rgba(246, 246, 246, 0) 100%);
      position: absolute;
      top: 0;
      margin-top: 106rpx;
      backdrop-filter: blur(60rpx);
      // z-index: ;
      .newsBg {
        height: 79.52rpx;
        width: 100%;
        display: flex;
        justify-content: flex-end;
        position: absolute;
        left: 0;
        top: 0;
        .newsFontBg {
          width: 255.78rpx;
          height: 79.52rpx;
          background-image: url(@/assets/images/newFontBg.png);
          background-size: cover;
        }
      }
      .content{
        max-height: calc(100vh - 300rpx);
        // overflow-y: auto
        // height: 100vh;
        // height: 3000px;
        // overflow-y: auto;
      }
    }
  }
}
// .index-wrap {
// min-height: calc(100vh - 130rpx);
// background-color: #f6f6f6;
// box-sizing: border-box;
// overflow-y: scroll;
// }

// .badge {
//   position: absolute;
//   right: 0;
//   top: 0;
//   margin-right: 60rpx;
//   margin-top: -9rpx;
//   // z-index: 99;
//   background-color: #f56c6c;
//   border-radius: 99rpx;
// }

// .homeTopContainer {
//   position: fixed;
//   top: 0;
//   left: 0;
//   width: 100%;
//   z-index: 120;

//   .sreach {
//     display: flex;
//     align-items: center;
//     height: 60rpx;
//     gap: 30rpx;

//     .sreach_input {
//       background-color: #fff;
//     }

//     .search_placeholder {
//       font-size: 12px;
//     }
//   }

//   .homeNav {
//     box-sizing: border-box;
//     padding: 22rpx 0 20rpx 0;

//     ::v-deep {
//       .u-tabs__wrapper__nav__item__text {
//         font-size: 27rpx;
//       }
//     }

//     .navSlot {
//       display: flex;
//       align-items: center;
//       font-size: 32rpx;
//       color: #333;
//     }

//     // 标签栏
    // .tabsListContainer {
    //   box-sizing: border-box;
    //   padding-right: 60rpx;
    //   padding-bottom: 12rpx;
    //   display: flex;
    //   overflow-x: auto;
    //   position: relative;
    //   // background-color: red;
    //   margin-top: 30rpx;

    //   .tabsList {
    //     display: flex;
    //     overflow-x: auto;

    //     .tabsItem {
    //       font-size: 12px;
    //       color: #595959;
    //       box-sizing: border-box;
    //       padding: 6rpx 20rpx;
    //       border: 1px solid #dbdbdb;
    //       margin-right: 21rpx;
    //       border-radius: 99rpx;
    //       flex-shrink: 0;

    //       &.active {
    //         background-color: rgba(255, 208, 212, 0.4);
    //         border-color: rgba(255, 208, 212, 0.4);
    //         color: #e7303f;
    //       }
    //     }
    //   }

    //   .downContainer {
    //     position: absolute;
    //     right: 0;
    //     top: 50%;
    //     height: 40rpx;
    //     transform: translateY(-50%);
    //     background-color: #f6f6f6;
    //     padding: 3rpx 15rpx 15rpx 15rpx;
    //     display: flex;
    //     align-items: center;
    //     justify-content: center;
    //     background-image: url(@/assets/images/overlay_world.png);

    //     .downPng {
    //       width: 30rpx;
    //       height: 30rpx;
    //     }
    //   }
    // }

//     .tabsPopup {
//       width: 100%;
//       background-color: #f6f6f6;
//       box-sizing: border-box;
//       padding: 20rpx 30rpx;
//       position: absolute;
//       left: 0;
//       border-bottom-left-radius: 30rpx;
//       border-bottom-right-radius: 30rpx;
//       .popupContainer {
//         height: 600rpx;
//         overflow-y: auto;
//         .tabsPopupItem {
//           .title {
//             font-size: 32rpx;
//             color: #000;
//             margin-bottom: 21rpx;
//           }

//           .itemList {
//             display: flex;
//             flex-wrap: wrap;

//             .tabsItem {
//               font-size: 12px;
//               color: #595959;
//               box-sizing: border-box;
//               padding: 6rpx 20rpx;
//               border: 1px solid #dbdbdb;
//               margin-right: 21rpx;
//               border-radius: 99rpx;
//               flex-shrink: 0;
//               margin-bottom: 21rpx;

//               &.active {
//                 background-color: rgba(255, 208, 212, 0.4);
//                 border-color: rgba(255, 208, 212, 0.4);
//                 color: #e7303f;
//               }
//             }
//           }
//         }
//       }
//     }
//   }
// }

// // 趋势
// .trendArrowListContainer {
//   position: relative;
//   box-sizing: border-box;
//   padding: 0 30rpx;

//   &::before {
//     content: "";
//     width: 160rpx;
//     height: 100%;
//     position: absolute;
//     right: 0;
//     top: 0;
//     background-image: url(../assets/images/overlay.png);
//     background-size: cover;
//   }

//   .trendArrowList {
//     display: flex;
//     background-color: #fff;
//     box-sizing: border-box;
//     padding: 12rpx 21rpx;
//     overflow-x: auto;

//     .trendArrowContainer:last-child {
//       margin-right: 0;
//     }
//   }
// }

// // 精选推荐
// .recommendContainer {
//   box-sizing: border-box;
//   padding: 20rpx 30rpx;
//   margin-top: 15rpx;

//   .recommendTitle {
//     font-size: 32rpx;
//     color: #333;
//     font-weight: bold;
//   }
// }

// // 栏目
// .columnContainer {
//   box-sizing: border-box;
//   padding: 20rpx 30rpx;
// }

// // 新闻
// .articleListModule {
//   box-sizing: border-box;
//   padding: 20rpx 30rpx 0 30rpx;

//   .articleListHeader {
//     display: flex;
//     align-items: center;
//     justify-content: space-between;
//     box-sizing: border-box;

//     // padding-bottom: 21rpx;
//     .headerLeft {
//       display: flex;
//       align-items: center;

//       .articleListTitle {
//         font-size: 32rpx;
//         color: #333;
//         font-weight: bold;
//       }

//       .articleListTabs {
//         margin-left: 12rpx;

//         .articleListTabsItem {
//           ::v-deep {
//             .u-tabs__wrapper__nav__item {
//               padding: 0 15rpx;
//             }

//             .u-tabs__wrapper__nav__item__text {
//               font-size: 24rpx;
//             }
//           }

//           // font-size: 60rpx !important;
//           // background-color: red;
//         }
//       }
//     }
//   }
// }

// .sreach_icon {
//   width: 80rpx;
//   height: 60rpx;
//   margin-top: 3rpx;
// }

// .sreach_input {
//   background: rgba(118, 118, 128, 0.12);
//   height: 70%;
//   border-radius: 20rpx;
//   padding: 0 20rpx;
// }

// .banner {
//   margin-top: 30rpx;
//   // height: 254rpx !important;
//   // padding-bottom: 12rpx;
// }

// .big_title {
//   display: flex;
//   align-items: center;
//   margin-top: 30rpx;

//   .title_icon {
//     width: 22rpx;
//     height: 22rpx;
//   }

//   text {
//     font-size: 32rpx;
//     font-weight: bold;
//     margin-left: 10rpx;
//     color: #333;
//   }
// }

// .r_tab {
//   display: flex;
//   position: relative;

//   .tab_item {
//     width: 50vw;
//     display: flex;
//     text-align: center;
//     justify-content: center;
//     align-items: center;
//     position: relative;

//     text {
//       z-index: 999;
//     }
//   }
// }

// .bk_tab {
//   position: absolute;
//   width: 180rpx;
//   height: 48rpx;
// }
</style>
