<template>
  <div class="cell_group_box">
    <van-cell v-for="(item, index) in arrayList" :key="index+props.showSfzh">
      <template #title>
        <span>{{ item[title] }} <span v-if="showSfzh == 'sfzh'">({{item[showSfzh]}})</span></span>
      </template>
      <template #value>
        <div class="ch-box">
          <van-checkbox
            @click="choose(item)"
            v-model="item.checked"
          ></van-checkbox>
        </div>
      </template>
    </van-cell>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch, onMounted } from "vue";
const props = defineProps({
  list: {
    type: Array,
    default: [],
  },
  title: {
    type: String,
    default: "name",
  },
  showSfzh: {
    type: String,
    default: "sfzh",
  },
});
const emits = defineEmits(["update:choose"]);
const checked = ref(false);
const arrayList = ref([]);
onMounted(() => {
  arrayList.value = props.list.map((item) => {
    return {
      ...item,
      checked: false,
    };
  });
});
watch(
  () => props.list,
  (val) => {
    arrayList.value = props.list.map((item) => {
      return {
        ...item,
        checked: false,
      };
    });
    array.value.forEach((item) => {
      arrayList.value.forEach((el) => {
        if (item.id == el.id) {
          el.checked = true;
        }
      });
    });
  },
  {
    deep: true,
  }
);
const array = ref([]);
function choose(item) {
  if (item.checked == true) {
    array.value.push(item);
  } else {
    array.value.forEach((ele, index) => {
      if (ele.id == item.id) {
        array.value.splice(index, 1);
      }
    });
  }
  emits("update:choose", {
    list: array.value,
  });
}
</script>

<style scoped>
.cell_group_box {
  height: 35vh;
  overflow: hidden;
  overflow-y: auto;
}
.ch-box {
  display: flex;
  justify-content: flex-end;
}
</style>