<template>
  <block>
    <view class="container search-container" v-if="isUserBindingPhoneNumber">
      <view class="sticky-content">
        <view class="searchTarget-header">
          <input
            type="text"
            :placeholder="searchPlaceholderList.TabSearch"
            placeholder-class="sea_ipt_placeholder"
            class="sea_ipt"
            v-model="searchTxt"
            focus="true"
            confirm-type="search"
            @confirm="searchHandle"
          />
          <icon type="search" size="15" class="sea_ico" />
          <view class="ipt-right">
            <icon type="clear" size="16" color="#E0E0E0" v-show="searchTxt" @click="clearIpt" />
            <text class="line">|</text>
            <text @click="searchHandle" style="color: #3385ff">搜索</text>
          </view>
        </view>
        <!-- // 综合及各种类型的的tabs -->
        <view class="search-tabs" v-if="isResult">
          <view :class="['tabs-item', tabsActive == item.id && 'active']" v-for="item in tabsList" :key="item.id" @click="tabsHandel(item)">
            {{ item.title }}
            <view class="item-act" v-if="tabsActive == item.id"></view>
          </view>
        </view>
        <!-- // 活动微路演的筛选 -->
        <block v-if="isResult">
          <view class="activity-select" style="display: flex; align-items: center; justify-content: flex-end" v-if="tabsActive == 4 || tabsActive == 5">
            <block v-for="item in activitySelect" :key="item.type">
              <view :class="['summary-select', item.type == 5 && 'select-roadshow']" v-if="tabsActive == item.type">
                <text @click="summarySelectHandler(key, item.name)" :class="['select-item', activitySelectActive == key.value && 'active-item']" v-for="key in item.list" :key="key.value">
                  {{ key.name }}
                </text>
              </view>
            </block>
          </view>
        </block>
      </view>

      <view class="search-cont" v-if="!isResult">
        <block v-for="key in keywordList" :key="key.title">
          <view class="history" v-if="key.title !== '搜索历史' || (key.title == '搜索历史' && historySearchList.length)">
            <view class="history-title title">
              <text>{{ key.title }}</text>
              <image v-if="key.imgShown" @click="clearHistory" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/empty_ico.png" class="empty_ico"></image>
            </view>
            <view class="history-item">
              <block v-for="(item, index) in relyOn(key.title)" :key="item">
                <block v-if="key.title == '搜索历史'">
                  <view v-if="index < 8" class="item" @click="chooseTarget(item)">{{ item }}</view>
                </block>
                <view v-else class="item" @click="chooseTarget(item)">{{ item }}</view>
              </block>
            </view>
          </view>
        </block>
      </view>
      <view v-else class="content">
        <block v-if="haveResult">
          <block v-if="tabsActive === 1">
            <synthetical :searchTxt="searchTxt" :isSyntheticalShow="isSyntheticalShow" :pageNumSynthetical="pageNumSynthetical" />
          </block>
          <view v-else>
            <summary-chart :resultList="tabsActive == 1 ? resultList.slice(0, 10) : resultList" :tabsActiveChild="tabsActive" v-if="resultList.length && (tabsActive == 2 || tabsActive == 1)" />
            <reportPage @updateFllow="updateFllow" :reportPageData="reportPageData" id="container-report-page" v-if="Object.keys(reportPageData).length && (tabsActive == 3 || tabsActive == 1)" />
            <activityBack :collectLists="collectList" :tabsActiveSearch="tabsActive" v-if="collectList.length && (tabsActive == 4 || tabsActive == 1)" />
            <roadshowPage :roadshowPageList="roadshowPageList" :tabsRoadshowSearch="tabsActive" v-if="roadshowPageList.length && (tabsActive == 5 || tabsActive == 1)" />
          </view>
        </block>
        <view class="nodata" v-else>
          <image src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/act_search.png" mode="" class="nodata_ico"></image>
          <text>未找到您想搜索的内容</text>
        </view>
      </view>
    </view>
    <not-have-login v-else />
    <Loading />
  </block>
</template>

<script>
import { KeywordList, TabsList, SummarySelect, ActivitySelect } from "./searchList";
import { Search, activity, Report, Home, User } from "@/config/api";
import { Debounce, Throttle } from "@/config/util.js";
import summaryChart from "../components/summaryChart.vue";
import activityBack from "../components/activityBack.vue";
import reportPage from "../components/report.vue";
import roadshowPage from "../components/roadshow.vue";
import NotHaveLogin from "../../components/notHaveLogin.vue";
import Synthetical from "../components/synthetical.vue";

export default {
  components: { summaryChart, activityBack, reportPage, roadshowPage, NotHaveLogin, Synthetical },
  data() {
    return {
      searchTxt: "",
      isResult: false,
      historySearchList: [], //历史搜索
      hotKeyWord: [], //热搜关键词
      wordList: [], //推荐关键词
      tabsActive: 1, //搜索的筛选条件
      resultList: [], //纪要与图表
      resultDataList: [], ////纪要与图表
      collectList: [], //活动的数据
      reportPageData: {}, //报告的数据
      roadshowPageList: [], //微路演的数据
      // haveResult: true, //是否有搜索数据
      haveResultSummary: true, //是否有搜索数据 纪要
      haveResultActivity: true, //是否有搜索数据 活动
      haveResultReport: true, //是否有搜索数据 报告
      haveResultRoadshow: true, //是否有搜索数据 微路演
      summarySelectActive: "Matching",
      activitySelectActive: "0",
      refresh: false, //正在下拉
      pageNum: 1,
      pageNumSynthetical: 0,
      pageSize: 10,
      totalPage: 0,
      status: "loadmore",
      loadText: {
        loadmore: "上拉加载更多",
        loading: "加载中",
        nomore: "已经到底了",
      },
      isSearchKeyWord: [],
      isSyntheticalShow: false,
    };
  },
  computed: {
    keywordList() {
      return KeywordList;
    },
    tabsList() {
      return TabsList;
    },
    summarySelect() {
      return SummarySelect;
    },
    activitySelect() {
      return ActivitySelect;
    },
    haveResult() {
      let all = this.haveResultSummary || this.haveResultActivity || this.haveResultReport || this.haveResultRoadshow;
      return this.tabsActive == 1
        ? all
        : this.tabsActive == 2
        ? this.haveResultSummary
        : this.tabsActive == 3
        ? this.haveResultReport
        : this.tabsActive == 4
        ? this.haveResultActivity
        : this.haveResultRoadshow;
    },
  },
  watch: {},
  methods: {
    //搜索事件
    searchHandle() {
      if (this.searchTxt) {
        if (!this.historySearchList.includes(this.searchTxt)) {
          this.historySearchList.unshift(this.searchTxt);
          this.$db.set("historySearchList", JSON.stringify(this.historySearchList));
        }
        this.getListInit();
        this.getDataList();
      } else {
        this.$util.toast("请输入关键字");
      }
    },
    //清除搜索关键字
    clearIpt() {
      this.searchTxt = "";
      this.tabsActive = 1;
      this.isResult = false;
      this.getListInit();
    },
    //关键词 遍历的依赖
    relyOn(val) {
      return val == "搜索历史" ? this.historySearchList : val == "热搜关键词" ? this.hotKeyWord : this.wordList;
    },
    //点击了筛选项目
    tabsHandel(item) {
      this.tabsActive = item.id;
      this.getListInit();
      this.getDataList();
    },
    //获取热搜关键词的请求
    async researchHotKeyWord() {
      const res = await Search.getKeys();
      if (res.Ret === 200) {
        this.hotKeyWord = res.Data.ListHot ? res.Data.ListHot.map((key) => key.KeyWord) : [];
        this.wordList = res.Data.Item ? res.Data.Item.ConfigValue.split(",") : [];
      }
    },
    // 选择历史搜索
    chooseTarget(item) {
      this.searchTxt = item;
      if (!this.historySearchList.includes(item)) {
        this.historySearchList.unshift(item);
        this.$db.set("historySearchList", JSON.stringify(this.historySearchList));
      }
      this.getListInit();
      this.getDataList();
    },
    //搜索
    async getDataList() {
      this.pageNumSynthetical = 0;
      this.isResult = true;
      this.isSyntheticalShow = false;
      if (!this.isSearchKeyWord.includes(this.searchTxt)) {
        this.isSearchKeyWord.push(this.searchTxt);
        await User.userSearchKeyWordLog({ KeyWord: this.searchTxt });
      }
      if (this.tabsActive == 1) {
        this.isSyntheticalShow = true;
        this.pageNumSynthetical = 1;
      } else if (this.tabsActive == 2) {
        this.synthesiz();
      } else if (this.tabsActive == 3) {
        this.getReportList();
      } else if (this.tabsActive == 4) {
        this.getActivityBackList();
      } else if (this.tabsActive == 5) {
        this.getRoadshowList();
      }
    },
    //纪要 图表的搜索
    async synthesiz() {
      const res = await Search.getArtAndChartList({
        KeyWord: this.searchTxt.replace(/^\s+|\s+$/g, ""),
        OrderColumn: this.summarySelectActive,
        PageSize: this.pageSize,
        CurrentIndex: this.pageNum,
        ListType: 1,
      });
      if (res.Ret === 200) {
        this.status = this.pageNum < res.Data.Paging.Pages ? "loadmore" : "nomore";
        this.totalPage = res.Data.Paging.Totals;
        if (this.pageNum == 1) {
          this.haveResultSummary = res.Data.List.length || res.Data.ChartList.length ? true : false;
        }
        if (res.Data.List.length && res.Data.ChartList.length) {
          if (this.pageNum == 1) {
            this.resultDataList.push(res.Data.List.shift());
            if (this.refresh) {
              uni.stopPullDownRefresh();
              this.refresh = false;
            }
          }
          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.resultDataList = this.resultDataList.concat(arr.flat(Infinity));
        } else if (!res.Data.List.length) {
          res.Data.ChartList.length && this.resultDataList.push(...res.Data.ChartList);
        } else if (!res.Data.ChartList.length) {
          res.Data.List.length && this.resultDataList.push(...res.Data.List);
        }
        this.resultList = this.resultDataList;
      }
    },
    //活动回放的接口获取列表
    async getActivityBackList() {
      const res =
        this.tabsActive === 1 || this.activitySelectActive == 0
          ? await activity.getActivityListSearch({
              PageSize: this.pageSize,
              CurrentIndex: this.pageNum,
              KeyWord: this.searchTxt,
              ActiveState: "1,2,3", //活动进行状态
              PlayBack: Number(this.activitySelectActive),
            })
          : await activity.getActivityListNew({
              PageSize: this.pageSize,
              CurrentIndex: this.pageNum,
              KeyWord: this.searchTxt,
              ActiveState: "1,2,3", //活动进行状态
              PlayBack: Number(this.activitySelectActive),
            });
      if (res.Ret !== 200) return;
      this.status = this.pageNum < res.Data.Paging.Pages ? "loadmore" : "nomore";
      this.totalPage = res.Data.Paging.Pages; //总页数
      if (this.pageNum === 1) {
        this.collectList = res.Data.List || [];
        this.haveResultActivity = this.collectList.length ? true : false;
        if (this.refresh) {
          uni.stopPullDownRefresh();
          this.refresh = false;
        }
      } else {
        this.collectList.push(...res.Data.List);
      }
    },
    //获取报告的
    async getReportList() {
      const res = await Report.getSearchReportAndResource({
        KeyWord: this.searchTxt.replace(/^\s+|\s+$/g, ""),
        PageSize: "",
      });
      if (res.Ret === 200) {
        if (this.refresh) {
          uni.stopPullDownRefresh();
          this.refresh = false;
        }
        this.reportPageData = res.Data || {};
        if (res.Data.ListHzReport.length || res.Data.ListHzResource.length || res.Data.ListYxReport.length || res.Data.ListYxResource.length) {
          this.haveResultReport = true;
        } else {
          this.haveResultReport = false;
        }
      }
    },
    //获取微路演
    async getRoadshowList() {
      const res = await Home.microRoadshowList({
        PageSize: this.pageSize,
        CurrentIndex: this.pageNum,
        KeyWord: this.searchTxt.replace(/^\s+|\s+$/g, ""),
        Filter: Number(this.activitySelectActive),
      });
      if (res.Ret === 200) {
        this.status = this.pageNum < res.Data.Paging.Pages ? "loadmore" : "nomore";
        this.totalPage = res.Data.Paging.Pages; //总页数
        if (this.pageNum == 1) {
          this.roadshowPageList = res.Data.List || [];
          this.haveResultRoadshow = this.roadshowPageList.length > 0 ? true : false;
          if (this.refresh) {
            uni.stopPullDownRefresh();
            this.refresh = false;
          }
        } else {
          this.roadshowPageList = this.roadshowPageList.concat(res.Data.List);
        }
      }
    },
    //点击了更多
    tabsActiveMore(val) {
      this.tabsActive = val;
      this.getListInit();
      this.getDataList();
    },
    //纪要、图标的筛选
    summarySelectHandler(item, type) {
      this.pageNum = 1;
      if (type == "纪要") {
        this.summarySelectActive = item.value;
        this.resultList = [];
        this.resultDataList = [];
        this.synthesiz();
      } else if (type == "活动") {
        this.activitySelectActive = item.value;
        this.collectList = [];
        this.getActivityBackList();
      } else if (type == "微路演") {
        this.activitySelectActive = item.value;
        this.roadshowPageList = [];
        this.getRoadshowList();
      }
    },
    /* 历史搜索清空 */
    clearHistory() {
      this.getRecordTracking("清空搜索历史");
      this.historySearchList = [];
      this.$db.del("historySearchList");
    },
    // 数据 初始化
    getListInit() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300,
      });
      this.pageNum = 1;
      this.pageNumSynthetical = 0;
      this.totalPage = 0;
      this.summarySelectActive = "Matching";
      this.activitySelectActive = "0";
      this.status = "loadmore";
      this.resultList = [];
      this.resultDataList = [];
      this.collectList = [];
      this.reportPageData = {};
      this.roadshowPageList = [];
    },
    // 进入页面 load的事件
    laodInit(options) {
      if (Object.keys(options).length && options.searchTxt) {
        this.searchTxt = options.searchTxt;
        this.tabsActive = options.tabsActive;
        this.summarySelectActive = options.summaryActive;
        this.activitySelectActive = options.activityActive;
        this.searchTxt && this.getDataList();
      }
    },
    // 报告、资源包的关注 改变状态
    updateFllow(id, type) {
      let typeName = type == "弘则" ? "ListHzResource" : "ListYxResource";

      this.reportPageData[typeName].forEach((key) => {
        if (key.IndustrialManagementId == id) {
          if (key.IsFollw) {
            uni.showToast({
              title: "已取消关注",
              icon: "none",
              duration: 2000,
            });
          }
          key.IsFollw = !key.IsFollw;
        }
      });
    },
  },
  onLoad(options) {
    this.getRecordTracking("搜索入口:" + options.source);
    this.researchHotKeyWord();
    this.laodInit(options);
    if (this.$db.get("historySearchList")) {
      this.historySearchList = JSON.parse(this.$db.get("historySearchList"));
    }
  },
  onShow() {
    this.$store.commit("setRouterActivity", "搜索");
    this.$store.commit("setRouterReport", "搜索");
  },
  /* 下拉刷新 */
  onPullDownRefresh: Throttle(function () {
    this.page_no = 1;
    this.refresh = true;
    this.getDataList();
  }),
  // 上拉加载this.resultList
  onReachBottom: Throttle(function () {
    if (this.tabsActive == 3) return;
    if (this.status === "nomore") return;
    this.status = "loading";
    if (this.tabsActive == 1) {
      this.pageNumSynthetical++;
      return;
    }
    this.pageNum++;
    this.getDataList();
  }),
  // 分享
  onShareAppMessage({ 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.searchTxt || "搜索",
        path:
          "/pages-search/indedxSearch/indedxSearch?searchTxt=" +
          this.searchTxt +
          "&tabsActive=" +
          this.tabsActive +
          "&summaryActive=" +
          this.summarySelectActive +
          "&activityActive=" +
          this.activitySelectActive,
      };
    }
  },
};
</script>

<style lang="scss" scoped>
.search-container {
  background-color: #f5f6fa;
  padding: 200rpx 0 0rpx;
  min-height: 100vh;
  box-sizing: border-box;
  .sticky-content {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 99;
    background-color: #fff;
  }
  .searchTarget-header {
    padding: 0 34rpx;
    width: 100%;
    position: relative;
    padding: 30rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
    .sea_ipt_placeholder {
      color: #8d8d8d;
    }
    .sea_ipt {
      width: 682rpx;
      height: 70rpx;
      line-height: 70rpx;
      box-sizing: border-box;
      background: #f9f9f9;
      font-size: 26rpx;
      color: #4a4a4a;
      padding: 0 180rpx 0 78rpx;
      border-radius: 70rpx;
    }
    .sea_ico {
      width: 31rpx;
      height: 31rpx;
      position: absolute;
      left: 68rpx;
      top: 50%;
      transform: translateY(-50%);
    }
    .ipt-right {
      display: flex;
      align-items: center;
      position: absolute;
      right: 59rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #3385ff;
      .line {
        margin: 0 21rpx;
        color: #e0e0e0;
      }
    }
  }
  .search-cont {
    padding: 32rpx;
    font-size: 24rpx;
    margin-top: -80rpx;
    color: #666666;
    background-color: #fff;
    height: calc(100vh - 135rpx);
    overflow: hidden;
    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
    }
    .history {
      height: 270rpx;
      overflow: hidden;
      .history-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .empty_ico {
          width: 36rpx;
          height: 36rpx;
        }
      }
      .history-item {
        width: 100%;
        overflow: hidden;
        display: flex;
        flex-wrap: wrap;
        .item {
          background-color: #f9f9f9;
          padding: 10rpx 20rpx;
          margin: 20rpx 20rpx 0 0;
          border-radius: 4rpx;
        }
      }
    }
  }
  .search-tabs {
    display: flex;
    align-items: center;
    width: 100%;
    font-size: 32rpx;
    color: #333333;
    padding-left: 35rpx;
    overflow: hidden;
    overflow-x: auto;
    background-color: #fff;
    margin-bottom: 10rpx;
    .tabs-item {
      margin-right: 50rpx;
      flex-shrink: 0;
      padding-bottom: 10rpx;
      position: relative;
      .item-act {
        width: 80%;
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        height: 4rpx;
        border-radius: 21px;
        background: linear-gradient(90deg, #2e85ff 0%, #7eeaf6 100%);
      }
    }
    .active {
      color: #4791ff;
      font-weight: 500;
    }
  }
  .content {
    width: 100%;
    background-color: #f5f6fa;
  }
  .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;
    }
  }
  .more-box {
    display: flex;
    height: 88rpx;
    padding: 0 30rpx;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    background-color: #f5f6fa;
    position: sticky;
    left: 0;
    z-index: 99;
    .more-text {
      font-weight: 500;
      color: #333333;
      &::before {
        content: "";
        display: inline-block;
        height: 20rpx;
        width: 4rpx;
        background-color: #3189ff;
        margin-right: 20rpx;
      }
    }
    .more-rivet {
      color: #3385ff;
      margin-left: 20rpx;
    }
  }
  .summary-select {
    display: flex;
    align-items: center;
    width: 252rpx;
    background-color: #fff;
    color: #999999;
    font-size: 24rpx;
    height: 51rpx;
    border-radius: 47rpx;
    box-shadow: 0rpx 0rpx 4rpx 0rpx rgba(0, 0, 0, 0.09);
    overflow: hidden;
    .select-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 50%;
      height: 100%;
      border-radius: 47rpx;
    }
    .active-item {
      background-color: #3385ff;
      color: #fff;
    }
  }
  .activity-select {
    padding-right: 34rpx;
    height: 88rpx;
    position: sticky;
    top: 184rpx;
    left: 0;
    z-index: 99;
    background-color: #f5f6fa;
  }
  .select-roadshow {
    width: 345rpx !important;
  }
  .more-summary {
    top: 184rpx;
  }
  .more-report {
    top: 184rpx;
    z-index: 100;
  }
  .more-activity {
    top: 184rpx;
    z-index: 101;
  }
}
</style>
<style lang="scss">
#container-report-page {
  .industry-video-module {
    .global-video-box {
      .video-content {
        top: 400rpx !important;
      }
      .close-icon {
        top: 330rpx !important;
      }
    }
  }
}
</style>
