<template>
  <view class="container Index-container">
    <view class="top-content-box">
      <search-bar @goSearch="goSearch" :searchTitle="searchPlaceholderList.SummarySearch" :width="70" />
      <view class="top-tabs">
        <block v-for="item in topTabBars" :key="item.Id">
          <view v-if="item.IsShow" :class="['item', item.val == topTabsActive && 'tabs-active']" @click="topTabsChange(item)">
            {{ item.Name }}
            <block v-if="(item.Id === 3 || item.Name == '图表') && wholeShowListData.IsShowChart">
              <image class="limit-img tabs-img" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/limit_icon.png" mode=""></image>
            </block>
            <view class="active" v-if="item.Id == topTabsActive"></view>
          </view>
        </block>
      </view>
      <view class="tabs-content">
        <view class="second-tabs" v-if="topTabsActive == '2' || topTabsActive == '3'">
          <view :class="['item', item.ChartPermissionId == secondActive && 'tabs-active']" v-for="(item, index) in secondBars" :key="item.ChartPermissionId" @click="handleClickTopSub(item)">
            {{ item.PermissionName }}
            <block v-if="wholeShowListData.IsShowResearch && index === secondBars.length - 1 && topTabsActive == '2'">
              <image class="limit-img tabs-img" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/limit_icon.png" mode=""></image>
            </block>
            <view class="active" v-if="item.ChartPermissionId == secondActive"></view>
          </view>
        </view>
        <block v-if="topTabsActive == '3'">
          <view class="children-ul">
            <view :class="['chart-children', chartChildrenActive == item.CtagId ? 'children-active' : '']" v-for="item in chartChildren" :key="item.CtagId" @click="handleChartChildren(item)">{{
              item.Name
            }}</view>
          </view>
        </block>
        <view v-if="topTabsActive == '4'" class="medium-ul">
          <view class="item-content">
            <view @click="mediumClickHandler(item)" :class="['item', mediumActive === item.value && 'item-act']" v-for="item in mediumSelect" :key="item.value">{{ item.name }}</view>
          </view>
        </view>
      </view>
    </view>
    <block v-if="haveData">
      <view class="content-ul">
        <block v-if="topTabsActive == 4">
          <view style="width: 49%" v-for="item in roadshowPageList" :key="item.Id">
            <RoadshowItem :list="item" @isCollectionHandeler="isCollectionHandeler" />
          </view>
        </block>
        <block v-else>
          <view class="report-ul" style="width: 49%">
            <block v-for="(item, index) in dataList" :key="index">
              <view v-if="index % 2 == 0">
                <ChartItem v-if="topTabsActive == 3" :list="item" :isMyChartCollection="isMyChartCollection" @myChartIsTop="myChartIsTop" @myChartCollect="myChartCollect" />
                <ReportItem v-if="topTabsActive == 2" :list="item" />
              </view>
            </block>
          </view>
          <view class="report-ul" style="width: 49%">
            <block v-for="(item, index) in dataList" :key="index">
              <view v-if="index % 2 !== 0">
                <ChartItem v-if="topTabsActive == 3" :list="item" :isMyChartCollection="isMyChartCollection" @myChartIsTop="myChartIsTop" @myChartCollect="myChartCollect" />
                <ReportItem v-if="topTabsActive == 2" :list="item" />
              </view>
            </block>
          </view>
        </block>
      </view>
      <u-loadmore :status="status" icon-type="flower" :load-text="loadText" margin-top="20" v-if="pageNum > 1" />
    </block>
    <view class="nodata" v-else-if="haveData === false" style="padding-top: 400rpx">
      <block class="nodata" v-if="!isBindingMobile && secondActive == 0">
        <text>请先绑定联系方式</text>
        <view class="bind-mobile" @click="bindingMobile">绑定联系方式</view>
      </block>
      <block v-else>
        <image src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/act_search.png" mode="" class="nodata_ico"></image>
        <text>{{ topTabsActive == 3 && secondActive == 0 ? "暂无收藏的图表" : "暂时没有数据" }}</text>
      </block>
    </view>
    <freeCharge class="free-charge" :isShowFreeBtn="isShowFree" />
  </view>
</template>

<script>
import { Home, Reports, Chart, activity } from "@/config/api.js";
import { Throttle, deepCopy } from "@/config/util.js";
import freeCharge from "@/components/freeCharge";
import SearchBar from "@/components/search-bar/searchBar.vue";

import ChartItem from "@/components/ItemComponent/chartItem.vue";
import ReportItem from "@/components/ItemComponent/reportItem.vue";
import RoadshowItem from "@/components/ItemComponent/roadshowItem.vue";
let app = getApp();
export default {
  data() {
    return {
      topTabBars: [],
      topTabsActive: 2, //一级top的tabs
      secondActive: "", //二级的tabs
      secondBars: [], //二级的tabs数组
      chartChildren: [], //二级的tabs下的标签
      chartChildrenActive: 0,
      refresh: false,
      pageSize: 10, //条数
      pageNum: 1, //页码
      haveMore: true, //是否有更多数据
      haveData: null, //是否有数据
      //数据列表
      dataList: [],
      status: "loadmore",
      loadText: {
        loadmore: "上拉加载更多",
        loading: "加载中",
        nomore: "已经到底了",
      },
      showTransition: false, //点击绝密后的隐现
      isBindingMobile: true, //图表我的收藏是否绑定手机号
      videoContext: null,
      audioShareId: "", //通过分享单个音频点进页面时使用
      videoShareId: "", //通过分享单个视频点进页面时使用
      activityShareId: "",
      roadshowPageList: [], //音频  视频 list
      mediumSelect: [
        { name: "全部", value: 0 },
        { name: "视频", value: 1 },
        { name: "音频", value: 2 },
      ],
      mediumActive: 0,
    };
  },
  components: {
    freeCharge,
    ChartItem,
    ReportItem,
    RoadshowItem,
    SearchBar,
  },
  watch: {},
  onLoad(optios) {
    this.getHeaderTab();
    if (optios.topTabsActive) {
      this.topTabsActive = optios.topTabsActive;
      this.secondActive = optios.secondActive;
      this.chartChildrenActive = optios.childrenActive;
      this.videoShareId = optios.videoShareId;
      this.audioShareId = optios.audioShareId;
      this.activityShareId = optios.activityId;
    }
    this.getTabs();
    this.getReportList();
    this.$store.dispatch("checkHandle", "noGO");
  },
  onShow() {
    this.getRecordTracking("纪要库");
    this.$store.commit("setRouterActivity", "纪要库");
    this.$store.commit("setRouterReport", "纪要库");
    //进入页面的记录
    this.$store.dispatch("statistics", { PageType: "Activit" });
    // #ifdef MP-WEIXIN
    uni.hideHomeButton();
    // #endif
    this.$store.commit("audioBg/parseIntAudio", true);
  },
  computed: {
    curVoiceId() {
      //当前正在播放的音频id
      return this.$store.state.audioBg.indexId;
    },
    curAudioPaused() {
      //当前音频是否暂停状态
      return this.$store.state.audioBg.paused;
    },
    showAudioBox() {
      return this.$store.state.audioBg.parseIntShow;
    },
    isMyChartCollection() {
      return this.topTabsActive == "3" && this.secondActive == 0;
    },
  },
  methods: {
    //点击顶部一级分类
    topTabsChange(item) {
      this.topTabsActive = item.Id;
      this.chartChildren = [];
      this.chartChildrenActive = 0;
      this.secondActive = "";
      this.pageNum = 1;
      this.dataList = [];
      this.audioShareId = "";
      this.videoShareId = "";
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
      if (this.topTabsActive == "2" || this.topTabsActive == "3") {
        this.getTabs();
      } else {
        this.initData();
      }
      this.$store.commit("setRouterReport", item.Id === 3 ? "我的收藏" : "纪要库");
    },
    //点击顶部二级分类
    handleClickTopSub(item) {
      this.$store.commit("setRouterReport", item.PermissionName === "我的收藏" ? "我的收藏" : "纪要库");
      this.secondActive = item.ChartPermissionId;
      this.chartChildren = [];
      this.chartChildrenActive = 0;
      this.childrenChartData();
      this.initData();
    },
    //点击图标的二级分类 处理数据
    childrenChartData() {
      if (this.topTabsActive == 3 && this.secondActive != 0) {
        let arr = [];
        this.secondBars &&
          this.secondBars.forEach((item) => {
            if (this.secondActive == item.ChartPermissionId) {
              deepCopy(arr, item.List);
              arr.unshift({
                CtagId: 0,
                Name: "全部",
              });
              this.chartChildren = arr;
            }
          });
        this.chartChildrenActive > 0 ? "" : (this.chartChildrenActive = 0);
      }
    },
    //点击图标的三级分类
    handleChartChildren(item) {
      this.chartChildrenActive = item.CtagId;
      this.initData();
    },
    // 点击为路演的筛选
    mediumClickHandler(item) {
      this.mediumActive = item.value;
      this.initData();
    },
    //点击
    initData() {
      this.pageNum = 1;
      this.dataList = [];
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
      this.getReportList();
    },
    /* 获取tab分类 */
    getTabs() {
      this.secondBars = [];
      this.topTabsActive == "2"
        ? Home.Tab().then((res) => {
            if (res.Ret === 200) {
              this.secondBars = res.Data.List;
              this.secondActive > 0 ? "" : (this.secondActive = this.secondBars[0].ChartPermissionId);
              this.getReportList();
            }
          })
        : this.topTabsActive == "3"
        ? Chart.getChartPatg().then((res) => {
            if (res.Ret === 200) {
              let arr = res.Data;
              arr.unshift({
                ChartPermissionId: 0,
                PermissionName: "我的收藏",
              });
              this.secondBars = arr;
              this.secondActive ? "" : (this.secondActive = 0);
              this.secondActive > 0 && this.childrenChartData();
              this.getReportList();
            }
          })
        : "";
    },
    /* 获取列表 */
    async getReportList() {
      if (this.topTabsActive == "3" && this.secondActive == 0) {
        const res = await Chart.getChartcollection({
          PageSize: this.pageSize,
          CurrentIndex: this.pageNum,
        });
        if (res.Ret === 200) {
          this.status = this.pageNum < res.Data.Paging.Pages ? "loadmore" : "nomore";
          this.isBindingMobile = res.Data.IsBindingMobile;
          if (this.pageNum === 1) {
            this.dataList = res.Data.List || [];
            this.haveData = this.dataList.length > 0 ? true : false;
          } else {
            this.dataList = this.dataList.concat(res.Data.List);
          }
        }
      } else if (this.topTabsActive == 4) {
        const res = await Home.microRoadshowList({
          PageSize: this.pageSize,
          CurrentIndex: this.pageNum,
          AudioId: this.audioShareId,
          VideoId: this.activityShareId ? "" : this.videoShareId,
          ActivityVideoId: this.activityShareId && this.videoShareId,
          Filter: this.mediumActive,
        });
        if (res.Ret === 200) {
          this.status = this.pageNum < res.Data.Paging.Pages ? "loadmore" : "nomore";
          if (this.pageNum == 1) {
            this.roadshowPageList = res.Data.List || [];
            this.haveData = this.roadshowPageList.length > 0 ? true : false;
            if (this.refresh) {
              uni.stopPullDownRefresh();
              this.refresh = false;
            }
          } else {
            this.roadshowPageList = this.roadshowPageList.concat(res.Data.List);
          }
        }
      } else {
        const res = await Home.getList({
          PageSize: this.pageSize,
          CurrentIndex: this.pageNum,
          ChartPermissionId: this.secondActive,
          CtagId: this.chartChildrenActive,
          ListType: this.topTabsActive,
        });
        if (res.Ret === 200) {
          this.processingData(res);
        }
      }
    },
    //处理数据
    processingData(res) {
      if (!res.Data.HaveResearch) {
        this.$util.modalShow("", "您暂无查看买方研选权限", "", () => {
          uni.reLaunch({
            url: "/pages/index/index",
          });
        });
      }
      this.status = this.pageNum < res.Data.Paging.Pages ? "loadmore" : "nomore";
      res.Data.List &&
        res.Data.List.forEach((item) => {
          if (item.BodyHtml) {
            item.BodyHtml = item.BodyHtml.replace(/'\'/g, "");
          }
        });
      if (this.topTabsActive == "2") {
        if (this.pageNum === 1) {
          this.dataList = res.Data.List || [];
          this.haveData = this.dataList.length ? true : false;
        } else {
          this.dataList = this.dataList.concat(res.Data.List);
        }
      } else {
        if (this.pageNum === 1) {
          this.haveData = res.Data.List ? true : res.Data.ChartList ? true : false;
        }
        if (!res.Data.List) {
          this.dataList = this.dataList.concat(res.Data.ChartList);
        } else if (!res.Data.ChartList) {
          this.dataList = this.dataList.concat(res.Data.List);
        } else {
          this.dataList.push(res.Data.List.shift());
          let newArr = [];
          let newArrTwo = [];
          for (let i = 0; i < res.Data.List.length; i += 2) {
            newArr.push(res.Data.List.slice(i, i + 2));
          }
          for (let i = 0; i < res.Data.ChartList.length; i += 2) {
            newArrTwo.push(res.Data.ChartList.slice(i, i + 2));
          }
          let arr = [];
          newArr.forEach((item, index) => {
            if (newArrTwo[index]) {
              arr.push(newArrTwo[index], item);
            } else {
              arr.push(item);
            }
          });
          this.dataList = this.dataList.concat(arr.flat(Infinity));
        }
      }

      if (this.refresh) {
        uni.stopPullDownRefresh();
        this.refresh = false;
      }
    },
    //我的收藏的删除
    myChartCollect(id) {
      uni.showModal({
        content: "确认要将该图表移除我的收藏吗？",
        confirmColor: "#3385FF",
        cancelColor: "#606266",
        success: async (res) => {
          if (res.confirm) {
            const res = await Chart.myChartCollect({
              ChartId: id,
            });
            if (res.Ret === 200) {
              this.initData();
              this.$util.toast("已取消收藏");
            }
          }
        },
      });
    },
    //我的收藏 置顶
    async myChartIsTop(id) {
      const res = await Chart.myChartTop({
        ChartId: id,
      });
      if (res.Ret === 200) {
        this.initData();
        this.$util.toast(res.Msg);
      }
    },
    /* 搜索 */
    goSearch() {
      this.$store.dispatch("checkHandle", "/pages-search/indedxSearch/indedxSearch?isType=" + this.topTabsActive + "&source=纪要库页面");
    },
    /* 绑定联系方式 */
    bindingMobile() {
      uni.navigateTo({
        url: "/pageMy/login/login",
      });
    },
    //获取顶部导航
    async getHeaderTab() {
      const res = await Home.headerTab();
      if (res.Ret === 200) {
        this.topTabBars = res.Data || [];
      }
    },
    // 微路演收藏
    async isCollectionHandeler(item) {
      const res = await Home.microRoadshowCollect({
        Id: item.Id,
        SourceType: item.Type,
        PageRouter: this.$store.state.pageRouterReport,
      });
      if (res.Ret === 200) {
        let index = this.roadshowPageList.findIndex((key) => key.Id == item.Id);
        res.Data.Status == 1 ? (this.roadshowPageList[index].IsCollect = true) : (this.roadshowPageList[index].IsCollect = false);
        uni.showToast({
          title: res.Msg,
          duration: 2000,
        });
      }
    },
  },
  onHide() {
    this.$store.commit("audioBg/parseIntAudio", false);
  },
  mounted() {
    uni.$on("updateAudioVideo", (data) => {
      this.$store.dispatch("checkHandle", "noGO");
      this.getReportList();
    });
  },
  /* 下拉刷新 */
  onPullDownRefresh: Throttle(function () {
    this.audioShareId = "";
    this.videoShareId = "";
    this.activityShareId = "";
    this.status = "loadmore";
    this.refresh = true;
    this.dataList = [];
    this.pageNum = 1;
    this.getReportList();
  }),
  // 上拉加载
  onReachBottom: Throttle(function () {
    if (this.status === "nomore") return;
    this.status = "loading";
    this.pageNum++;
    this.getReportList();
  }),
  /** 用户点击分享*/
  onShareAppMessage: function ({ from, target }) {
    if (from === "button") {
      let item = target.dataset.item;
      let audio_id = item.Type == 1 || item.AudioType == 1 ? item.Id : "";
      // type=2 -- 活动视频 type=3 -- 产业视频
      let video_id = item.Type == 2 || item.Type == 3 ? item.Id : "";
      let activity_id = item.Type == 2 && item.ActivityId > 0 ? item.ActivityId : "";
      let title_share = item.AudioTitle || item.Title;
      this.getRecordTracking("微路演转发", { ActivityId: item.ActivityId, Id: item.Id, Type: item.Type });
      return {
        title: this.isHorzMobile ? "好友向您推荐此内容，上传名片享查研观向免费月卡！" : title_share,
        path: "/pages/material/material?topTabsActive=4" + "&audioShareId=" + audio_id + "&videoShareId=" + video_id + "&activityId=" + activity_id,
        imageUrl: item.AudioShareImg || item.ShareImg,
      };
    } else {
      return {
        title: this.isHorzMobile ? "好友向您推荐此内容，上传名片享查研观向免费月卡！" : "素材库",
        path: "/pages/material/material?topTabsActive=" + this.topTabsActive + "&secondActive=" + this.secondActive + "&childrenActive=" + this.chartChildrenActive,
        success: (res) => {},
        fail: (err) => {},
      };
    }
  },
};
</script>

<style lang="scss">
.Index-container {
  background-color: #f7f7f7;
  font-size: 30rpx;
  .content-ul {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 20rpx 15rpx;
  }
  .top-content-box {
    position: sticky;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9;
    .top-tabs {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 34rpx;
      background-color: #fff;
      padding: 35rpx 0 10rpx;
      &::-webkit-scrollbar {
        width: 0;
        height: 0;
        display: none;
      }
      .item {
        position: relative;
        padding-bottom: 8rpx;
        margin-right: 60rpx;
        flex-shrink: 0;
        .limit-img {
          position: absolute;
          top: -15rpx;
          right: -50rpx;
          z-index: 99;
        }
        .active {
          position: absolute;
          left: 0;
          bottom: 0;
          height: 4rpx;
          width: 100%;
          border-radius: 1rpx;
          background: linear-gradient(90deg, #2e85ff 0%, #7eeaf6 100%);
        }
      }
      .tabs-active {
        color: #3385ff;
        font-weight: 500;
      }
    }
  }
  .nav-bar-wrap {
    padding-left: 35rpx;
  }
  .tabs-content {
    padding: 0 30rpx;
    background-color: #fff;
    .children-ul {
      display: flex;
      flex-wrap: wrap;
      .children-active {
        background-color: #3385ff;
        color: #fff;
      }
    }
    .medium-ul {
      display: flex;
      justify-content: flex-end;
      padding: 10px 0;
      .item-content {
        display: flex;
        height: 51rpx;
        background: #f8f8fa;
        width: 345rpx;
        border-radius: 64rpx;
        color: #999999;
      }
      .item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 115rpx;
        height: 51rpx;
        border-radius: 47rpx;
      }
      .item-act {
        background-color: #3385ff;
        color: #fff;
      }
    }
    .chart-children {
      padding: 10rpx 20rpx;
      margin: 0rpx 20rpx 20rpx 0;
      background-color: #f9f9f9;
      color: #666666;
      font-size: 26rpx;
      border-radius: 4rpx;
    }
  }
  .second-tabs {
    width: 100%;
    display: flex;
    overflow-x: auto;
    background-color: #fff;
    font-size: 30rpx;
    color: #999999;
    padding: 20rpx 0;
    &::-webkit-scrollbar {
      width: 0;
      height: 0;
      display: none;
    }
    .item {
      position: relative;
      padding-bottom: 16rpx;
      margin-right: 50rpx;
      flex-shrink: 0;
      .limit-img {
        position: absolute;
        top: -15rpx;
        right: -50rpx;
        z-index: 99;
      }
      .active {
        position: absolute;
        left: 0;
        bottom: 0;
        height: 4rpx;
        width: 100%;
        border-radius: 1rpx;
        background: linear-gradient(90deg, #2e85ff 0%, #7eeaf6 100%);
      }
    }
    .tabs-active {
      color: #3385ff;
      font-weight: 500;
    }
  }
  .tabs-img {
    width: 46rpx;
    height: 26rpx;
  }
  .nodata {
    font-size: 40rpx;
    .bind-mobile {
      width: 244rpx;
      height: 58rpx;
      background: #3385ff;
      border-radius: 8rpx;
      font-size: 28rpx;
      line-height: 58rpx;
      text-align: center;
      color: #fff;
      margin: 50rpx auto;
    }
  }
}
</style>
