<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="handleSearch"
          @input="handleInput" />
        <uni-icons v-if="searchKeyword" type="clear" size="16" color="#999" @click="clearKeyword"></uni-icons>
        <view class="searchImgBox" @click="handleSearch">
          <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="searchKeyword && !searchStatus">
      <!-- <view class="search-result"> -->
      <!-- 这里添加搜索结果的展示逻辑 -->
      <view>
        <view class="tab-nav">
          <view v-for="(tab, index) in ['作品', '作者']" :key="index"
            :class="['tab-item', currentTab === index ? 'active' : '']" @click="switchTab(index)">
            {{ tab }}
            <view class="indicator-triangle">
            </view>
          </view>
        </view>

        <!-- 关注列表 - 类似my.vue -->
        <view v-show="currentTab === 0" class="follow-list">
          <block v-if="followList.length > 0">
            <w-waterfall :data="followList">
              <template v-slot:content="{ item, width }">
                <card :item="formatItem(item)" findType="search" :width="width" :custom-style="{ background: '#fff' }" textColor="#999"  titleTextColor="#000">
                </card>
              </template>
            </w-waterfall>
          </block>
          <view class="no-data" v-else-if="!isLoadingFollow">
            <text>暂无作品数据</text>
          </view>
        </view>

        <view v-show="currentTab === 1" class="follow-list" style="padding: 0 30rpx;">
          <block v-if="recommendList.length > 0">
            <view class="follow-item" v-for="(item, index) in recommendList" :key="index" @click="goToUserHomepage(item.id)"> 
              <CircleAvatar  @click="goToUserHomepage(item.user_id)" class="avator" :src="item.avator"></CircleAvatar>
              <view class="info">
                <view class="top-box" @click="goToUserHomepage(item.user_id)"> 
                  <view class="name one-omit">{{ item.nickname }}</view>
                  <image src="../../static/icon/wd_icon_nan.png" mode="widthFix" v-if="item.sex_id == 1" />
                  <image src="../../static/icon/wd_icon_nv.png" mode="widthFix" v-else-if="item.sex_id == 2" />
                  <view class="level">Lv{{ item.level }}</view>
                </view>
                <!-- <view class="desc">{{ item.description }}</view> -->
              </view>
              <view :class="item.is_attention ? 'unfollow-btn active' : 'unfollow-btn'" @click="toggleFollow(item)">
                <image src="../../static/me/wd_icon_guanzhu.png"></image>
                {{ item.is_attention == 0 ? '取消关注' : '关注' }}
              </view>
            </view>
          </block>
          <view class="no-data" v-else-if="!isLoadingFollow">
            <text>暂无作者数据</text>
          </view>
        </view>
        <!-- avator: "http://e.yujianmate.com/images/avator/b1.jpg"
      is_attention: 0
      level: 0
      nickname: "刘畅"
      sex_id: 2 -->

      </view>
    </view>
    <DialogBox ref="DialogBox"></DialogBox>
  </view>
</template>

<script>
const HISTORY_KEY = 'search_history';
const MAX_HISTORY = 20;

export default {
  data() {
    return {
      searchKeyword: '', // 搜索关键词
      historyList: [], // 搜索历史
      searchResult: [], // 搜索结果
      primaryHistoryList: [],
      isExpanded: false, // 添加展开/折叠状态变量
      currentTab: 0, // 当前激活的标签页
      followList: [], // 关注列表数据
      followOffset: 0, // 关注列表偏移量
      hasMoreFollow: true, // 是否有更多关注列表数据
      recommendList: [], // 推荐列表数据
      recommendOffset: 0, // 推荐列表偏移量
      hasMoreRecommend: true, // 是否有更多推荐列表数据
      isLoadingFollow: false, // 是否正在加载关注列表
      isLoadingRecommend: false, // 是否正在加载推荐列表 

      searchStatus: true,//显示搜索历史  false显示搜索结果
    }
  },
  onLoad() {
    // 加载历史记录
    this.loadHistory();
  },
  onReachBottom() {
    // 触底加载更多数据
    if (!(hasMoreFollow || hasMoreRecommend)) {
      switch (this.currentTab) {
        case 0:
          this.loadFollowList();
          break;
        case 1:
          this.loadRecommendList();
          break;
      }
    } else {
      uni.hideToast();
      uni.showToast({
        title:'没有更多数据了',
        icon: 'none'
      });
      return;
    }
  },
  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 = [];
      }
      // this.primaryHistoryList = JSON.parse(JSON.stringify(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.handleSearch();
    },

    // 处理搜索
    handleSearch() {
      if (!this.searchKeyword.trim()) return;
      // 保存到历史记录
      this.saveHistory();
      this.searchStatus = false;
      // this.loadHistory()
      // TODO: 实现搜索逻辑
      console.log('Searching for:', this.searchKeyword);
      this.queryList()
    },

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

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

    },

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

    // 添加展开/折叠方法
    toggleHistory() {
      this.isExpanded = !this.isExpanded;
    },
    switchTab(index) {
      this.currentTab = index;
      this.searchRequest(index);
      this.queryList()
    },
    formatItem(item) {

      this.downloadAndProcessImage(item.images)
        .then((color) => {
          console.log(`平均颜色: R=${color.r}, G=${color.g}, B=${color.b}`);
        })
        .catch((error) => {
          console.error("获取图像失败:", error);
        });
      // 处理接口返回的数据，使其适配card组件
      return {
        id: item.id,
        allowEdit: false,
        nickname: item.nickname,
        avator: item.avator,
        num_like: item.num_like,
        num_view: item.num_view,
        image: item.images || item.img_url || item.image, // 优先使用images字段
        w: item.width,
        h: item.height,
        title: item.title || "",
        desc: item.desc || "",
        backgroundColor: "#f6f6f6",
      };
    },
    downloadAndProcessImage(imageUrl, width = 10, height = 10) {
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url: imageUrl,
          success: (downloadResult) => {
            if (downloadResult.statusCode === 200) {
              const tempFilePath = downloadResult.tempFilePath;
              const ctx = uni.createCanvasContext('myCanvas', this);
              ctx.drawImage(tempFilePath, 0, 0, width, height);
              ctx.draw(false, () => {
                uni.canvasGetImageData({
                  canvasId: 'myCanvas',
                  x: 0,
                  y: 0,
                  width: width,
                  height: height,
                  success: (res) => {
                    const data = res.data;
                    let r = 0,
                      g = 0,
                      b = 0;
                    for (let i = 0; i < data.length; i +=
                      4) {
                      r += data[i];
                      g += data[i + 1];
                      b += data[i + 2];
                    }
                    const count = width * height;
                    r = Math.floor(r / count);
                    g = Math.floor(g / count);
                    b = Math.floor(b / count);
                    resolve({
                      r,
                      g,
                      b
                    });
                  },
                  fail: (err) => {
                    reject(err);
                  }
                });
              });
            } else {
              reject(new Error('下载图像失败'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    queryList() {
      // 根据当前标签刷新数据
      switch (this.currentTab) {
        case 0:
          // 重置作品列表
          this.followList = [];
          this.followOffset = 0;
          this.hasMoreFollow = true;
          // this.loadFollowList();
          this.loadFollowList();
          break;
        case 1:
          // 重置作者列表
          this.recommendList = [];
          this.recommendOffset = 0;
          this.hasMoreRecommend = true;
          // this.loadRecommendList();
          this.loadRecommendList();
          break;
      }
    },
    loadFollowList() {
      if (this.isLoadingFollow) return;
      this.isLoadingFollow = true;

      uni.request({
        url: this.$apiHost + "/Work/getlist",
        data: {
          uuid: getApp().globalData.uuid,
          skey: getApp().globalData.skey,
          offset: this.followOffset,
          search: this.searchKeyword,
        },
        header: {
          "content-type": "application/json",
          sign: getApp().globalData.headerSign,
        },
        success: (res) => {
          console.log("作品列表数据:", res.data);
          // 确保在任何情况下都完成加载
          if (
            res.data.success == "yes" &&
            res.data.list &&
            res.data.list.length > 0
          ) {
            // 只有当列表有数据时才追加
            this.followList = [...this.followList, ...res.data.list];
            this.followOffset += res.data.list.length;
            console.log(this.followOffset, "作品列表数据");

            if (res.data.list.length < 20) {
              this.hasMoreFollow = false;
            }
          } else {
            // 如果列表为空，确保标记没有更多数据
            this.hasMoreFollow = false;
          }

          // 无论是否有数据，都需要通知z-paging组件完成刷新
          if (this.$refs.paging) {
            this.$refs.paging.complete(this.followList);
          }
        },
        complete: () => {
          this.isLoadingFollow = false;
        },
        fail: (e) => {
          console.log("请求关注列表失败:", e);
          this.isLoadingFollow = false;
          // 加载失败时也要通知组件完成
          if (this.$refs.paging) {
            this.$refs.paging.complete(false);
          }
        },
      });
    },
    loadRecommendList() {
      console.log(this.recommendOffset, 666);

      if (this.isLoadingRecommend) return;
      this.isLoadingRecommend = true;
      uni.request({
        url: this.$apiHost + "/User/getlist",
        data: {
          uuid: getApp().globalData.uuid,
          skey: getApp().globalData.skey,
          offset: this.recommendOffset,
          search: this.searchKeyword,
        },
        header: {
          "content-type": "application/json",
          sign: getApp().globalData.headerSign,
        },
        success: (res) => {
          console.log("作者列表数据:", res.data);
          if (
            res.data.success == "yes" &&
            res.data.list &&
            res.data.list.length > 0
          ) {
            this.recommendList = [...this.recommendList, ...res.data.list];
            this.recommendOffset += res.data.list.length;
            console.log(this.recommendOffset, "作者列表数据");

            if (res.data.list.length < 20) {
              this.hasMoreRecommend = false;
            }
          } else {
            this.hasMoreRecommend = false;
          }

          // 无论是否有数据，都需要通知z-paging组件完成刷新
          if (this.$refs.paging) {
            this.$refs.paging.complete(this.recommendList);
          }
        },
        complete: () => {
          this.isLoadingRecommend = false;
        },
        fail: (e) => {
          console.log("请求推荐列表失败:", e);
          this.isLoadingRecommend = false;
          // 加载失败时也要通知组件完成
          if (this.$refs.paging) {
            this.$refs.paging.complete(false);
          }
        },
      });
    },
    toggleFollow(item) {
      uni.request({
        url: this.$apiHost + '/Member/attention',
        data: {
          uuid: getApp().globalData.uuid,
          id: item.user_id,
        },
        header: {
          "content-type": "application/json",
          'sign': getApp().globalData.headerSign
        },
        success: (res) => {
          console.log("关注结果:", res.data);
          uni.showToast({
            title: res.data.str,
            icon: 'none'
          });
          if (res.data.success === "yes") {
            if (res.data.str === "关注成功") {
              item.is_attention = false
            }
            if (res.data.str === "取消关注") {
              item.is_attention = true
            }
          }
        },
        fail: (e) => {
          console.log("关注失败:", e);
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
      // 这里可以添加调用后端API的逻辑
    },
    // 搜索请求
    searchRequest() {
    },
    	goToUserHomepage(id) {
			if (!id) {
				return;
			} 
      uni.navigateTo({
        url: "/pages/my/userHomepage?id=" + id,
      });
    },
  }
}
</script>

<style lang="scss">
.search-container {
  background-color: #ffffff;
  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;

    .tab-nav {
      display: flex;
      justify-content: flex-start;
      padding: 20rpx 20rpx;
      padding-top: 0;
      box-sizing: border-box;
      background: #ffffff;
      width: 100%;
      overflow-x: hidden;

      .tab-item {
        padding: 10rpx 38rpx;
        color: #1F1F1F;
        font-size: 28rpx;
        background: #F2F6F2;
        margin-right: 20rpx;
        border-radius: 30rpx;
        position: relative;
        left: 0;
        top: 0;
        line-height: 1;
        flex-shrink: 0;
        white-space: nowrap;

        .indicator-triangle {
          position: absolute;
          bottom: -10rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 0;
          height: 0;
          border-left: 10rpx solid transparent;
          border-right: 10rpx solid transparent;
          border-top: 10rpx solid #ACF934;
          display: none;
        }

        &.active {
          background: #ACF934;
          font-family: "CustomFont" !important;

          .indicator-triangle {
            display: block;
          }
        }
      }
    }

    .follow-list {
      padding: 0;
      width: 100%;
      box-sizing: border-box;

      .follow-item {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        width: 100%;
        box-sizing: border-box;

        .avator {
          width: 120rpx;
          height: 120rpx;
          margin-right: 24rpx;
          flex-shrink: 0;
        }

        .info {
          flex: 1;
          min-width: 0;

          .top-box {
            display: flex;
            align-items: center;
            width: 100%;
            box-sizing: border-box;

            .name {
              font-size: 32rpx;
              font-weight: 500;
              margin-bottom: 8rpx;
              max-width: 200rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            >image {
              width: 36rpx;
              margin-left: 8rpx;
              margin-right: 10rpx;
              flex-shrink: 0;
            }

            .level {
              font-weight: 400;
              font-size: 20rpx;
              font-family: "PingFang SC-Bold";
              background: linear-gradient(360deg, #acf934 0%, #ffe439 100%);
              border-radius: 8rpx;
              padding: 2rpx 8rpx;
              display: inline-block;
              flex-shrink: 0;
            }
          }
        }

        .unfollow-btn {
          font-size: 24rpx;
          width: 144rpx;
          height: 52rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #1f1f1f;
          background: #fff;
          border: 2rpx solid #1f1f1f;
          border-radius: 112rpx;
          margin: 0;
          font-family: 'PingFang SC-Bold';
          flex-shrink: 0;

          image {
            display: none;
            width: 16rpx;
            height: 16rpx;
            margin-right: 5rpx;
          }

          &.active {
            color: #ACF934;
            background: #000;

            image {
              display: inline-block;
            }
          }
        }
      }
    }
  }

  .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;
        }
      }
    }
</style>