<template>
  <view class="search-container container">
    <view class="sticky-content">
      <view class="searchTarget-header">
        <input type="text" placeholder="请输入关键字" 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>
      <view class="radio-content">
        <van-radio-group :value="radioSelect" @change="onChangeRadio" direction="horizontal">
          <van-radio icon-size="16" name="1">搜全部</van-radio>
          <van-radio icon-size="16" name="2">搜纪要</van-radio>
          <van-radio icon-size="16" name="3">搜图表</van-radio>
        </van-radio-group>
      </view>
      <view class="tab-cont" v-if="radioSelect == 2 && isResult">
        <view :class="['item', item.mode == orderColumn && 'tabs-active text_twoLine']" v-for="item in tabBars" :key="item.mode" @click.stop="toggleTab(item)">
          {{ item.PermissionName }}
          <view class="active" v-if="orderColumn === item.mode"></view>
        </view>
      </view>
    </view>
    <view class="search-cont" v-if="!isResult">
      <view class="search-cont-top">
        <view class="cont-tit">
          <text>热搜关键词：</text>
        </view>
        <view class="targetList">
          <view class="target-item" v-for="(item, index) in hotKeyWord" :key="index" @click="chooseTarget(item.KeyWord)"># {{ item.KeyWord }}</view>
        </view>
      </view>
      <view class="search-cont-top">
        <view class="cont-tit">
          <text>推荐关键词：</text>
        </view>
        <view class="targetList">
          <view class="target-item" v-for="(item, index) in keywordList" :key="index" @click="chooseTarget(item)"># {{ item }}</view>
          <view class="chart-item" v-for="(item, index) in chartWordList" :key="index" @click="chooseTarget(item.KeyWord)"># {{ item.KeyWord }}</view>
        </view>
      </view>
      <view class="search-cont-top" v-if="historySearchList.length">
        <view class="cont-tit">
          <text>搜索历史：</text>
          <image src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/czbk/empty_ico.png" class="empty_ico" @click="clearHistory"></image>
        </view>
        <view class="targetList">
          <block v-for="(item, index) in historySearchList" :key="index">
            <view v-if="index < 8" class="target-item" @click="chooseTarget(item)"># {{ item }}</view>
          </block>
        </view>
      </view>
    </view>
    <!-- 内容地方 -->
    <view class="search-cont" v-else>
      <block v-if="haveResult">
        <view class="result-data">
          <view class="report-ul">
            <view class="report-item" v-for="(report, index) in resultList" :key="index" v-if="index % 2 === 0" @click="goDetail(report)">
              <view class="item-content-img" v-if="report.BodyHtml">
                <image :src="report.BodyHtml" mode=""></image>
              </view>
              <view class="item-content" v-else><u-parse :html="report.Body[0] + '...'"></u-parse></view>
              <view class="line"></view>
              <view :class="['item-title', report.Source != 1 && 'chart-title text_twoLine']"><u-parse :html="report.Title"></u-parse></view>
              <text class="item-createtime" v-if="report.Source == 1">{{ report.PublishDate }}</text>
              <view class="item-createtime chart-tag" v-else>
                <text class="tag-item" v-if="report.PtagName">{{ report.PtagName }}</text>
                <text class="tag-item" v-if="report.CtagName">{{ report.CtagName }}</text>
              </view>
            </view>
          </view>
          <view class="report-ul">
            <view class="report-item" v-for="(report, index) in resultList" :key="index" v-if="index % 2 !== 0" @click="goDetail(report)">
              <view class="item-content-img" v-if="report.BodyHtml">
                <image :src="report.BodyHtml" mode=""></image>
              </view>
              <view class="item-content" v-else><u-parse :html="report.Body[0] + '...'"></u-parse></view>
              <view class="line"></view>
              <view :class="['item-title', report.Source != 1 && 'chart-title text_twoLine']"><u-parse :html="report.Title"></u-parse></view>
              <text class="item-createtime" v-if="report.Source == 1">{{ report.PublishDate }}</text>
              <view class="item-createtime chart-tag" v-else>
                <text class="tag-item" v-if="report.PtagName">{{ report.PtagName }}</text>
                <text class="tag-item" v-if="report.CtagName">{{ report.CtagName }}</text>
              </view>
            </view>
          </view>
        </view>
        <u-loadmore :status="status" icon-type="flower" :load-text="loadText" margin-top="20" v-if="pageNum > 1" />
      </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>
</template>

<script>
import { Search } from "@/config/api.js";
import { Debounce, Throttle } from "@/config/util.js";
let app = getApp({ allowDefault: true });
export default {
  data() {
    return {
      searchTxt: "", //搜索关键字
      isResult: false, //显示搜索结果
      haveResult: true, //是否有搜索数据
      // 历史搜索列表
      historySearchList: [],
      // 关键字列表
      keywordList: [],
      chartWordList: [],
      // 搜索结果列表
      resultList: [],
      resultDataList: [],
      indList: [],
      pageNum: 1,
      pageSize: 10,
      totalPage: 0,
      hotKeyWord: [],
      radioSelect: "1",
      tabBars: [
        {
          PermissionName: "匹配度排序",
          mode: "Matching",
        },
        {
          PermissionName: "综合排序",
          mode: "Comprehensive",
        },
        {
          PermissionName: "发布时间排序",
          mode: "PublishDate",
        },
      ],
      orderColumn: "Matching",
      status: "loadmore",
      loadText: {
        loadmore: "上拉加载更多",
        loading: "加载中",
        nomore: "已经到底了",
      },
    };
  },
  watch: {
    searchTxt(newVal) {
      if (newVal.length <= 0) {
        this.isResult = false;
        this.orderColumn = "Matching";
      }
    },
  },
  methods: {
    //获取热搜关键词的请求
    async researchHotKeyWord() {
      const res = await Search.getKeys();
      if (res.Ret === 200) {
        this.hotKeyWord = res.Data.ListHot || [];
        this.chartWordList = res.Data.List || [];
        this.keywordList = res.Data.Item ? res.Data.Item.ConfigValue.split(",") : [];
      }
    },
    //点击了搜索的变化
    onChangeRadio(value) {
      this.radioSelect = value.detail;
      this.orderColumn = "Matching";
      let srt = this.searchTxt.replace(/^\s+|\s+$/g, "");
      if (!srt) return this.$util.toast("请输入关键字");
      this.dataInit();
      this.getDataList();
    },
    /* 获取关键词 */
    getKeyWord() {
      Search.getKeys().then((res) => {
        if (res.Ret === 200) {
          this.keywordList = res.Data.Item.ConfigValue ? res.Data.Item.ConfigValue.split(",") : [];
        }
      });
    },
    // 选择历史搜索
    chooseTarget(item) {
      this.searchTxt = item;
      this.SecName = item;
      this.dataInit();
      this.indList = [];
      if (!this.historySearchList.includes(this.searchTxt)) {
        this.historySearchList.unshift(this.searchTxt);
        this.$db.set("historySearchList", JSON.stringify(this.historySearchList));
      }
      this.getDataList();
    },
    // 拼接
    join(str, key) {
      return str.replace(new RegExp(`${key}`, "g"), `%%${key}%%`).split("%%");
    },
    // 搜索数据
    searchHandle: Debounce(function () {
      if (this.searchTxt) {
        //添加搜索记录
        if (!this.historySearchList.includes(this.searchTxt)) {
          this.historySearchList.unshift(this.searchTxt);
          this.$db.set("historySearchList", JSON.stringify(this.historySearchList));
        }
        this.indList = [];
        this.dataInit();
        this.getDataList();
      } else {
        this.$util.toast("请输入关键字");
      }
    }),
    // 查找数据
    async getDataList() {
      this.isResult = true;
      const res = await Search.getArtAndChartList({
        KeyWord: this.searchTxt.replace(/^\s+|\s+$/g, ""),
        OrderColumn: this.radioSelect == 2 ? this.orderColumn : "",
        ListType: this.radioSelect,
      });
      if (res.Ret === 200) {
        this.totalPage = res.Data.Paging.Totals;
        if (this.radioSelect == 1) {
          if (!res.Data.List.length) {
            this.resultDataList = res.Data.ChartList || [];
          } else if (!res.Data.ChartList.length) {
            this.resultDataList = res.Data.List || [];
          } else {
            this.resultDataList.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.resultDataList = this.resultDataList.concat(arr.flat(Infinity));
          }
          this.haveResult = this.resultDataList.length ? true : false;
        } else if (this.radioSelect == 2) {
          this.resultDataList = res.Data.List || [];
          this.haveResult = this.resultDataList.length ? true : false;
        } else {
          this.resultDataList = res.Data.ChartList || [];
          this.haveResult = this.resultDataList.length ? true : false;
        }
        this.resultList = this.haveResult ? this.resultDataList.slice((this.pageNum - 1) * this.pageSize, this.pageNum * this.pageSize) : [];
      }
    },
    /* 表单清空 */
    clearIpt() {
      this.searchTxt = "";
      this.dataInit();
      this.isTabAct = false;
    },
    /* 进入详情 校验是否有该品种权限 */
    goDetail(item) {
      if (item.Source == 2) {
        /* 无需授权且已绑定 检验是或否有权限 */
        this.$store.dispatch("checkHandle", "/pageMy/chartPage/chartPage?id=" + item.ChartId);
      } else {
        /* 无需授权且已绑定 检验是或否有权限 */
        this.$store.dispatch("checkHandle", "/pageMy/reportDetail/reportDetail?id=" + item.ArticleId);
      }
    },
    /* 历史搜索清空 */
    clearHistory() {
      this.historySearchList = [];
      this.$db.del("historySearchList");
    },
    //获取数据的初始值
    dataInit() {
      this.pageNum = 1;
      this.resultList = [];
      this.resultDataList = [];
      this.status = "loadmore";
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
    },
    //tabs切换事件
    toggleTab(item) {
      this.orderColumn = item.mode;
      this.pageNum = 1;
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
      this.resultList = [];
      this.getDataList();
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
    },
  },
  onLoad(options) {
    if (options.text) {
      this.searchTxt = options.text;
      this.getDataList();
    }
    // 获取历史搜索记录
    if (this.$db.get("historySearchList")) {
      let historyList = JSON.parse(this.$db.get("historySearchList"));
      this.historySearchList = historyList;
    }
  },
  onShow() {
    this.$store.dispatch("statistics", { PageType: "SummarySearch" });
    this.getKeyWord();
    this.researchHotKeyWord();
  },
  // 上拉加载this.resultList
  onReachBottom: Throttle(function () {
    if (!this.resultList.length) return;
    if (this.status === "nomore") return;
    this.status = "loading";
    this.pageNum++;
    this.resultList = this.resultList.concat(this.resultDataList.slice((this.pageNum - 1) * this.pageSize, this.pageNum * this.pageSize));
    this.status = this.pageNum * 10 < this.totalPage ? "loadmore" : "nomore";
  }),
};
</script>

<style lang="scss">
.search-container {
  background-color: #fff;
  padding-bottom: 30rpx;
  .sticky-content {
    position: sticky;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 99;
    padding-bottom: 10rpx;
    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;
      border: 1rpx solid #e5e5e5;
      background-color: rgba(245, 245, 245, 0.2);
      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;
      }
    }
  }
  .radio-content {
    width: 100%;
    padding-left: 58rpx;
    background-color: #fff;
    display: flex;
  }
  .search-cont {
    .search-cont-top {
      padding: 0 34rpx 0;
      margin-bottom: 10rpx;
      padding-top: 20rpx;
      &:last-child {
        margin-bottom: 0;
      }
      .cont-tit {
        font-size: 32rpx;
        margin-bottom: 20rpx;
        font-weight: 500;
        display: flex;
        justify-content: space-between;
        .empty_ico {
          width: 32rpx;
          height: 33rpx;
        }
      }
      .targetList {
        display: flex;
        flex-wrap: wrap;
        font-size: 28rpx;
        .target-item {
          width: 50%;
          margin-bottom: 20rpx;
        }
        .chart-item {
          width: 100%;
          margin-bottom: 20rpx;
        }
      }
    }
    .result-cont {
      padding: 0 34rpx 0;
      padding-left: 21rpx;
      .result-list {
        display: flex;
        align-items: center;
        color: #333;
        padding-bottom: 30rpx;
        border-bottom: 1rpx solid #ebedf0;
        margin-bottom: 30rpx;
        .result_ico {
          width: 28rpx;
          height: 28rpx;
          margin-right: 20rpx;
        }
        text {
          display: inline;
        }
        .highlight {
          color: #3385ff;
        }
      }
    }
    .result-data {
      min-height: calc(100vh - 130rpx);
      padding: 20rpx 34rpx 40rpx;
      display: flex;
      background-color: #f7f7f7;
      .report-ul {
        width: 50%;
        &:first-child {
          margin-right: 10rpx;
        }
        .report-item {
          padding: 20rpx 20rpx 24rpx 20rpx;
          margin-bottom: 20rpx;
          border-radius: 8rpx;
          box-shadow: 0 3rpx 6rpx rgba($color: #000000, $alpha: 0.16);
          background: #fff;
          .item-content {
            font-size: 24rpx;
            line-height: 40rpx;
            color: #7f7f7f;
            display: -webkit-box;
            word-break: break-all;
            text {
              display: inline;
            }
          }
          .line {
            margin: 18rpx 0;
            content: "";
            width: 100%;
            height: 1px;
            padding: 0 32rpx;
            box-sizing: border-box;
            background-color: #e5e5e5;
            -webkit-transform: scale(1, 0.5);
            transform: scale(1, 0.5);
            -webkit-transform-origin: center bottom;
            transform-origin: center bottom;
          }
          .item-title {
            font-size: 28rpx;
            color: #4a4a4a;
            margin-bottom: 10rpx;
            position: relative;
            text-indent: 0.5em;
            &::before {
              content: "";
              position: absolute;
              top: 5rpx;
              left: 0;
              width: 6rpx;
              height: 31rpx;
              background-color: #3385ff;
            }
            text {
              display: inline;
            }
          }
          .chart-title {
            height: 72rpx;
            padding-bottom: 10rpx;
            text-indent: 0em;
            &::before {
              display: none;
            }
          }
          .item-abstract {
            font-size: 26rpx;
            color: #6a6a6a;
            margin-bottom: 10rpx;
            .report_ico {
              width: 32rpx;
              height: 26rpx;
              margin-right: 20rpx;
              display: inline-block;
            }
          }
          .item-createtime {
            color: #acacac;
            font-size: 24rpx;
          }
        }
      }
      .chart-tag {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-top: 1rpx;
        height: 36rpx;
        .tag-item {
          width: 148rpx;
          border-radius: 28rpx;
          border: 2rpx solid rgba(49, 137, 255, 1);
          overflow: hidden;
          color: #3385ff;
          text-align: center;
          line-height: 32rpx;
        }
      }
      .item-content-img {
        display: flex;
        align-items: center;
        width: 330rpx;
        margin-left: -15rpx;
        margin-bottom: -20rpx;
        image {
          width: 100%;
          height: 262rpx;
          vertical-align: middle;
        }
      }
    }
  }
  .tab-cont {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx 0;
    font-size: 32rpx;
    &::-webkit-scrollbar {
      width: 0;
      height: 0;
      display: none;
    }
    .item {
      position: relative;
      padding-bottom: 16rpx;
      margin-right: 50rpx;
      flex-shrink: 0;
      .active {
        position: absolute;
        left: 0;
        bottom: 0;
        height: 4rpx;
        width: 100%;
        border-radius: 2rpx;

        font-weight: 500;
        background: linear-gradient(90deg, #2e85ff 0%, #7eeaf6 100%);
      }
    }
    .tabs-active {
      color: #3385ff;
    }
  }
}
</style>
