<template>
  <view class="search-container">
    <!-- 搜索框 -->
    <view class="search-header">
      <view class="cancel-btn" @click="goBack">
        <uni-icons type="left" size="22" color="#1F1F1F"></uni-icons>
      </view>
      <view class="search-box">
        <!-- <uni-icons type="search" size="16" color="#999"></uni-icons> -->
        <input type="text" v-model="searchKeyword" placeholder="请输入关键词" confirm-type="search" @confirm="onSearch"
          @input="handleInput" />
        <uni-icons v-if="searchKeyword" type="clear" size="16" color="#999" @click="clearKeyword"></uni-icons>
        <view class="searchImgBox" @click="onSearch">
          <image class="image" src="@/static/home/sy_icon_sousuo.png"></image>
        </view>
      </view>
    </view>
    <view class="reserveASeat"></view>
    <!-- 搜索历史 -->
    <view class="search-history" v-if="searchStatus && historyList.length > 0">
      <view class="history-header">
        <text class="title">搜索历史</text>
        <image @click="clearHistory" style="width: 32rpx;height: 32rpx;" class="deleteAll"
          src="@/static/home/sy_icon_shanchu.png"></image>
      </view>
      <view class="history-list">
        <view class="history-item" v-for="(item, index) in displayedHistoryList" :key="index"
          @click="useHistoryKeyword(item)">
          <view>
            <uni-icons type="clock" size="14" color="#999"></uni-icons>
            <view class="history-text">
              <image src="@/static/home/sy_icon_lishijilu.png"></image> {{ item }}
            </view>
          </view>
          <image class="deleteBtn" @click.stop="deleteHistoryItem(item)" src="@/static/icon/close.png"></image>
        </view>
        <view class="expandBtn" @click="toggleHistory">
          <view v-if="!isExpanded">
            <template v-if="historyList.length > 5">
              查看全部
              <image src="@/static/home/sy_icon_chakanquanbu.png"></image>
            </template>
          </view>
          <view v-else class="fold">
            折叠历史记录
            <image src="@/static/home/sy_icon_chakanquanbu.png"></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-result" v-if="!searchStatus">
      <block v-if="searchResult.length > 0">
        <view class="items-grid">
          <CrowdFundingItem v-for="item in searchResult" :key="item.id" :item="item" @click="goToDetail(item.id)" />
        </view>
        <view v-if="isLoading" class="loading-more">加载中...</view>
        <view v-else-if="!hasMore" class="no-more">没有更多了</view>
      </block>
      <view class="no-data" v-else-if="!isLoading">
        <text>暂无数据</text>
      </view>
    </view>
    <DialogBox ref="DialogBox"></DialogBox>
  </view>
</template>

<script>
import CrowdFundingItem from './components/CrowdFundingItem/CrowdFundingItem.vue';
const HISTORY_KEY = 'search_history';
const MAX_HISTORY = 20;

export default {
  components: { CrowdFundingItem },
  data() {
    return {
      searchKeyword: '', // 搜索关键词
      historyList: [], // 搜索历史
      searchResult: [],
      page: 1,
      pageSize: 20,
      hasMore: true,
      isLoading: false,
      isExpanded: false, // 添加展开/折叠状态变量
      searchStatus: true,//显示搜索历史  false显示搜索结果
    }
  },
  onLoad() {
    // 加载历史记录
    this.loadHistory();
  },
  onPullDownRefresh() {
    this.onSearch(true);
    uni.stopPullDownRefresh();
  },
  onReachBottom() {
    this.onSearch(false);
  },
  computed: {
    // 添加计算属性以控制显示的历史记录数量
    displayedHistoryList() {
      return this.isExpanded ? this.historyList : this.historyList.slice(0, 5);
    }
  },
  methods: {
    // 加载历史记录
    loadHistory() {
      try {
        const history = uni.getStorageSync(HISTORY_KEY);
        this.historyList = history ? JSON.parse(history) : [];
      } catch (e) {
        console.error('Failed to load search history:', e);
        this.historyList = [];
      }
    },

    // 保存历史记录
    saveHistory() {
      try {
        // 将当前搜索词添加到历史记录开头
        if (this.searchKeyword && !this.historyList.includes(this.searchKeyword)) {
          console.log(this.historyList, 11111);
          this.historyList.unshift(this.searchKeyword);
          console.log(this.historyList, 11111);

          // 限制历史记录数量
          if (this.historyList.length > MAX_HISTORY) {
            this.historyList = this.historyList.slice(0, MAX_HISTORY);
          }
          uni.setStorageSync(HISTORY_KEY, JSON.stringify(this.historyList));
        }
      } catch (e) {
        console.error('Failed to save search history:', e);
      }
    },

    // 清空历史记录
    clearHistory() {

      this.$refs['DialogBox'].confirm({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        DialogType: 'inquiry',
        btn1: '否',
        btn2: '是',
        animation: 0
      }).then((res) => {
        if (res.isConfirm) {
          this.historyList = [];
          uni.setStorageSync(HISTORY_KEY, '[]');
        }
      })


    },
    // 清空单个历史记录
    deleteHistoryItem(item) {
      console.log(item, '删除历史记录');

      this.$refs['DialogBox'].confirm({
        title: '提示',
        content: '确定要删除搜索历史吗？',
        DialogType: 'inquiry',
        btn1: '否',
        btn2: '是',
        animation: 0
      }).then((res) => {
        if (res.isConfirm) {
          const index = this.historyList.indexOf(item);
          if (index !== -1) {
            this.historyList.splice(index, 1);
          }
          uni.setStorageSync(HISTORY_KEY, JSON.stringify(this.historyList));
        }
      })


    },

    // 使用历史记录中的关键词
    useHistoryKeyword(keyword) {
      this.searchKeyword = keyword;
      this.onSearch();
    },

    // 处理搜索
    async onSearch(isRefresh = true) {
      if (!this.searchKeyword.trim()) return;
      if (isRefresh) {
        this.page = 1;
        this.hasMore = true;
        this.searchResult = [];
      }
      if (!this.hasMore || this.isLoading) return;
      this.isLoading = true;
   
      try {
        const [err, res] = await uni.request({
          url: this.$apiHost + '/crowdfund/list',
          method: 'GET',
          data: {
            page: this.page,
            pageSize: this.pageSize,
            keyword: this.searchKeyword
          }
        });
        if (!err && res && res.data && res.data.data && res.data.data.list) {
          const list = res.data.data.list;
          if (isRefresh) {
            this.searchResult = list;
          } else {
            this.searchResult = [...this.searchResult, ...list];
          }
          this.hasMore = this.searchResult.length < (res.data.data.total || 0);
          this.page++;
        } else {
          this.hasMore = false;
        }
      } catch (e) {
        this.hasMore = false;
      }
      this.isLoading = false;
      // 保存历史记录
      this.saveHistory();
      this.searchStatus = false;
    },

    // 清空搜索框
    clearKeyword() {
      this.searchKeyword = '';
    },

    // 处理输入
    handleInput(e) {
      this.searchKeyword = e.detail.value;
      if (this.searchKeyword.trim() == '') {
        this.searchStatus = true;
      }
      console.log(this.historyList, e.detail.value);

    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 添加展开/折叠方法
    toggleHistory() {
      this.isExpanded = !this.isExpanded;
    },
    goToDetail(id) {
      uni.navigateTo({ url: '/pages/crowdFunding/crowdfundingDetails?id=' + id });
    },
    handleSearch() {
      if (!this.searchKeyword.trim()) return;
      // 保存到历史记录
      this.saveHistory();
      this.searchStatus = false;
      // 加载搜索结果
      this.queryList();
    },
  }
}
</script>

<style lang="scss">
.search-container {
  background-color: #f2f6f2;
  min-height: 100vh;
  width: 100%;
  overflow-x: hidden;
  position: relative;

  .search-header {
    background-color: #ffffff;
    padding: 16rpx 30rpx;
    display: flex;
    align-items: center;
    padding-top: calc(16rpx + var(--status-bar-height));
    padding-left: 40rpx;
    padding-right: 28rpx;
    padding-bottom: 16rpx;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 9;
    width: 100%;
    box-sizing: border-box;

    .search-box {
      flex: 1;
      height: 72rpx;
      background-color: #f1f1f1;
      border-radius: 36rpx;
      display: flex;
      align-items: center;
      padding: 0 24rpx;
      padding-left: 14rpx;
      width: 622rpx;
      height: 72rpx;
      background: #FFFFFF;
      border-radius: 36rpx;
      border: 6rpx solid #000000;
      position: relative;
      left: 0;
      top: 0;
      box-sizing: border-box;
      max-width: calc(100% - 60rpx);

      input {
        flex: 1;
        height: 100%;
        margin: 0 16rpx;
        font-size: 24rpx;
        font-family: 'PingFang SC-Medium';
        width: auto;
        min-width: 0;
      }

      .searchImgBox {
        width: 88rpx;
        height: 56rpx;
        background: #1F1F1F;
        border-radius: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        top: 50%;
        right: 6rpx;
        transform: translateY(-50%);
        flex-shrink: 0;

        .image {
          width: 36rpx;
          height: 36rpx;
        }
      }
    }

    .cancel-btn {
      color: #1f1f1f;
      width: 36rpx;
      height: 100%;
      margin-right: 24rpx;
      font-weight: 700;
      flex-shrink: 0;
    }
  }

  .reserveASeat {
    width: 100%;
    height: calc(108rpx + var(--status-bar-height));
  }

  .search-history {
    background-color: #ffffff;
    padding: 30rpx;
    padding-top: 15rpx;
    width: 100%;
    box-sizing: border-box;

    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15rpx;
      width: 100%;
      box-sizing: border-box;

      .title {
        font-size: 30rpx;
        color: #333;
        font-weight: bold;
      }
    }

    .history-list {
      transition: all 1s;
      overflow: hidden;
      width: 100%;
      box-sizing: border-box;

      .history-item {
        display: flex;
        align-items: center;
        padding: 18rpx 0;
        justify-content: space-between;
        width: 100%;
        box-sizing: border-box;

        .history-text {
          font-size: 28rpx;
          color: #666;
          display: flex;
          align-items: center;
          justify-content: flex-start;
          font-weight: 400;
          color: #1F1F1F;
          margin-left: 6rpx;
          font-family: 'PingFang SC-Bold';
          flex: 1;
          overflow: hidden;
          min-width: 0;

          image {
            width: 32rpx;
            height: 32rpx;
            margin-right: 16rpx;
            flex-shrink: 0;
          }
        }

        .deleteBtn {
          width: 30rpx;
          height: 30rpx;
          flex-shrink: 0;
        }
      }
    }
  }

  .search-result {
    // background-color: #ffffff;
    margin-top: 20rpx;
    min-height: 200rpx;
    width: 100%;
    box-sizing: border-box;
  }

  .no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60rpx 0;
    // background-color: #fff;
    width: 100%;
    box-sizing: border-box;

    text {
      color: #808080;
      font-size: 28rpx;
    }
  }
}

.expandBtn {
  view {
    font-family: 'PingFang SC-Bold';
    color: #999999;
    display: flex;
    align-items: center;
    justify-content: center;

    &.fold {
      image {
        transform: rotate(180deg) translateY(-2rpx);
      }
    }

    image {
      width: 28rpx;
      height: 28rpx;
    }
  }
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx 12rpx;
  padding: 16rpx 12rpx 0 12rpx;
  background: #f2f6f2;
}
.loading-more { text-align: center; color: #999; font-size: 26rpx; padding: 24rpx 0; }
.no-more { text-align: center; color: #ccc; font-size: 24rpx; padding: 20rpx 0; }
</style>