<template>
    <div class="associated">
      <div style="display: flex;justify-content: flex-end;margin-bottom: 36rpx">
        <span style="font-size: 32rpx;color: #0A98D5" @tap="confirm">确认并返回</span>
      </div>
      <input v-model="searchName" class="ipt" placeholder="可输入搜索" @input="changeSearch">
      <van-checkbox-group :value="result" @change="onChange">
        <van-checkbox :name="item.truename" v-for="item in list" :key="item.id">{{item.truename}}</van-checkbox>
      </van-checkbox-group>
    </div>
</template>

<script>
import { findUserList } from "@/js_sdk/http";
export default {
  name: "associated",
  data(){
    return{
      result:[],
      list:[],
      page: 1, // 当前页数
      pageSize: 20, // 每页数据量
      hasMore: true,
      searchName:'',
      timeout:null,
      selectedItems:[]
    }
  },
  onReachBottom(){
    if (this.hasMore) {
      this.loadMore();
    }
  },
  mounted(){
    this.loadMore()
  },
  methods:{
    confirm(){
      uni.$emit('selectUserInfo',JSON.stringify(this.selectedItems))
      uni.navigateBack()
    },
    changeSearch(e){
      if (this.timeout){
        this.timeout = null
      }
      console.log(e.detail.value)
      this.list = []
      this.page = 1
      this.pageSize = 20
      this.searchName = e.detail.value
      this.timeout = setTimeout(() => {
        this.loadMore()
      }, 500)
    },
    async loadMore() {
      try {
        const res = await this.fetchListData(this.page, this.pageSize);
        console.log('res',res)
        if (res.rows && res.rows.length) {
          this.list = this.list.concat(res.rows);
          this.page += 1;
        } else {
          this.hasMore = false;
        }
      } catch (error) {
        // 处理错误
      }
    },
    async fetchListData(page, pageSize) {
      return findUserList({pageNum:page,pageSize,truename:this.searchName})
    },
    getCompanyList(){

    },
    onChange(e){
      this.result = e.detail
      this.selectedItems = this.list.filter(item => e.detail.includes(item.truename));
      // 现在你有了一个包含完整 item 对象的数组
      console.log(this.selectedItems);
    }
  }
}
</script>

<style lang="scss">
    .associated{
      min-height: 100vh;
      padding: 36rpx;
      background: white;
      .van-checkbox{
        margin: 24rpx 0;
      }
      .ipt{
        background: rgba(96,96,96,0.1);
        margin-bottom: 24rpx;
        padding: 12rpx 24rpx;
        border-radius: 12rpx;
      }
    }
</style>
