<template>
  <div class="personList">
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
    />
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell title="全选">
        <template #right-icon>
          <input type="checkbox" v-model="isAll" @change="selectAll" />
        </template>
      </van-cell>
      <van-cell v-for="(item, index) in list" :key="item" :title="item">
        <template #right-icon>
          <input
            type="checkbox"
            :ref="getList"
            @change="selectPerson(item, index)"
          />
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import { ref, toRef } from "vue";

export default {
  name: "personList",
  emits: ["selected"],
  setup(props, { emit }) {
    const list = [];
    const loading = ref(false);
    const finished = ref(false);

    const onLoad = () => {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          list.push(list.length + 1);
        }

        // 加载状态结束
        loading.value = false;

        // 数据全部加载完成
        if (list.length >= 10) {
          finished.value = true;
        }
      }, 1000);
    };
    // 搜索
    const value = ref("");
    const onSearch = (val) => showToast(val);
    const onCancel = () => showToast("取消");
    // 选择人员
    let selects = [];
    // 全选
    let isAll = ref(false);
    let checks = [];
    const getList = (el) => {
      checks.push(el);
    };
    const selectAll = () => {
      checks.forEach((item) => {
        item.checked = isAll.value;
      });
      if (isAll) {
        selects = list;
      } else {
        selects = [];
      }
      emit("selected", selects.join(","));
    };
    const selectPerson = (value, index) => {
      if (checks[index].checked) {
        selects.push(value);
      } else {
        selects.splice(selects.indexOf(value), 1);
      }

      if (selects.length == getList.length) {
        isAll.value = true;
      } else {
        isAll.value = false;
      }
      emit("selected", selects.join(","));
    };
    return {
      list,
      onLoad,
      loading,
      finished,
      selectPerson,
      value,
      onSearch,
      onCancel,
      selectAll,
      getList,
      isAll,
    };
  },
};
</script>

<style scoped>
.personList {
  height: 65vh;
  overflow: auto;
  margin: 10px;
}
.van-button {
  top: -5px;
}
.search {
  height: 40px;
  line-height: 40px;
}
.van-list {
  height: 80%;
  margin-top: 5px;
}
.keyword {
  width: 70%;
  height: 25px;
  border-radius: 25px;
  border: 1px solid;
  padding-left: 15px;
}
</style>