<template>
  <view class="selectBlank">
    <view class="search_input">
      <tui-input v-model="search"
                 :placeholder="inputProps.placeholder"
                 clearable
                 isFillet
                 confirm-type="search"
                 @confirm="doSearch">
        <template #left>
          <tui-icon name="search"
                    :size="20"
                    margin="0 15px 0 0"></tui-icon>
        </template>
      </tui-input>
    </view>
    <!-- 多次使用 缓存  -->
    <!-- <view class="employ"
          v-if="storageList.length>0">经常使用：</view>
    <tui-card class="card"
              v-for="(item, index) in storageList"
              :key="index"
              @click="navigateBack(item)"
              :image="item.img"
              :title="{ text: cardProps.renderText.title(item) }"
              :tag="{ text: cardProps.renderText.tag ? cardProps.renderText.tag(item) : '' }">
      <template v-if="cardProps.renderText.footer"
                v-slot:footer>
        <view class="footer"
              v-if="cardProps.renderText.footer(item)"> {{ cardProps.renderText.footer(item) }}
        </view>
      </template>
    </tui-card>
    <view class="itemAll"
          v-if="storageList.length>0">全部：</view> -->
    <!-- 无限滚动容器，实现滚动加载，12个地方复用 -->
    <infiniteScroll v-if="fetchUrl"
                    ref="infiniteScroll"
                    :fetchItems="fetchItems"
                    :hasMore="hasMore">
      <tui-card class="card"
                v-for="(item, index) in list"
                :key="index"
                @click="navigateBack(item)"
                :image="item.img"
                :title="{ text: cardProps.renderText.title(item) }"
                :tag="{ text: cardProps.renderText.tag ? cardProps.renderText.tag(item) : '' }">
        <template v-if="cardProps.renderText.footer"
                  v-slot:footer>
          <view class="footer"
                v-if="cardProps.renderText.footer(item)"> {{ cardProps.renderText.footer(item) }}
          </view>
        </template>
      </tui-card>
    </infiniteScroll>
  </view>
</template>
<script>
import infiniteScroll from "../../../components/infiniteScroll/infiniteScroll.vue";
import { kyeStorage, setStorage, getStorage } from "@/utils/storage.js";
import { getCurrentOrg } from "@/common/httpRequest";
export default {
  components: { infiniteScroll },
  data() {
    return {
      list: [],
      pageSize: 10,
      hasMore: true,
      inputProps: {},
      cardProps: {},
      fetchUrl: "",
      search: "",
      storageList: [],
      Key: "",
      org_id: "",
      loading: false,
    };
  },
  async created() {
    this.fetchItems();
  },
  methods: {
    // 请求体
    async fetchItems() {
      // await this.getKey(); //获取Key
      const { data } = await this.$request.get(this.fetchUrl, {
        params: {
          search: this.search,
          page: Math.ceil(this.list.length / this.pageSize) + 1,
          limit: this.pageSize,
        },
      });
      this.list = [...this.list, ...data.data];
      if (data.data.length < this.pageSize) {
        this.hasMore = false;
      }
    },
    async doSearch() {
      this.list = [];
      await this.fetchItems();
    },
    // 点击行为
    navigateBack(item) {
      if (!!this.Key) {
        console.log("设置保存:", item);
        this.saveStorage(item); //保存
      } else {
        console.log("暂未设置保存");
      }
      uni.navigateBack({
        success: () => {
          const eventChannel = this.getOpenerEventChannel();
          console.log("点击了供应商：", item);
          eventChannel.emit("rowClick", item);
        },
      });
    },
    saveStorage(item) {
      /**使用key值 */
      let Key = this.Key;
      let name = !!item.supplier_name //name  作为数组项的识别标识
        ? item.supplier_name
        : !!item.name
        ? item.name
        : item.labour_name;
      // console.log("点击行为,返回参数item:", item);
      let storageData = getStorage(Key);
      if (!!storageData) {
        storageData = storageData;
      } else {
        storageData = [];
      }
      console.log("storageData前:", storageData);
      let keyIndex = 0;
      for (keyIndex; keyIndex < storageData.length; keyIndex++) {
        if (storageData[keyIndex].name == name) {
          storageData[keyIndex].count++;
          break;
        }
      }
      if (keyIndex == storageData.length) {
        storageData.push({
          count: 1,
          item: item,
          name: name,
        });
      }
      //排序 只需要排序现在添加  的item
      while (true) {
        if (keyIndex == 0) break;
        if (
          storageData[keyIndex].count >= //相同大小 后来优先
          storageData[keyIndex - 1].count
        ) {
          // console.log("排序中");
          let obj = storageData[keyIndex];
          storageData[keyIndex] = storageData[keyIndex - 1];
          storageData[keyIndex - 1] = obj;
          keyIndex--;
          // console.log("排序完成:", storageData);
        } else break;
      }
      //保存 10个数据 大于10个时 删除最小
      if (storageData.length > 20) {
        delete storageData[storageData.length - 1];
      }
      // console.log("storageData结束:", storageData, Key);
      setStorage(Key, storageData);
    },
    //
    storage() {},
  },
  // uniapp触底钩子函数
  onReachBottom() {
    // this.$refs.infiniteScroll.reachBottom();
    if (!this.hasMore) return;
    this.fetchItems();
  },
  // 向起始页通过事件传递数据
  onLoad() {
    const eventChannel = this.getOpenerEventChannel();
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on("acceptDataFromOpenerPage", (data) => {
      uni.setNavigationBarTitle({
        title: data.navigationBarTitleText,
      });
      this.inputProps = data.inputProps;
      this.cardProps = data.cardProps;
      this.fetchUrl = data.fetchUrl;
      this.onRowClick = data.onRowClick ?? (() => {});
    });
  },
};
</script>
<style lang="scss" scoped>
.selectBlank {
  .search_input {
    padding: 15rpx;
    background-color: rgb(81, 121, 239);
  }
  .employ {
    margin: 30rpx;
  }
  .card {
    margin: 20rpx !important;
  }

  .footer {
    font-size: 16rpx;
    color: #999;
    padding: 22rpx;
  }
  .line {
    margin: 20rpx 50rpx;
    border-bottom: 1rpx solid #474747;
  }
  .itemAll {
    margin: 30rpx;
  }
}
</style>
