<template>
  <view class="my-3" v-if="data.allMembers && data.allMembers.length">
    <view class="flex justify-between">
      <view class="flex flex-wrap text-center items-center">
        <u-tag
          :type="member.checked ? 'primary' : 'info'"
          :mode="member.checked ? 'dark' : 'light'"
          v-for="(member, index) in data.topMembers"
          :key="member.memberId"
          class="mb-2 mr-3"
          style="width: 60px"
          :text="member.name"
          :closeable="false"
          @click="tagClick(index, member, 'topMembers')"
        />
        <span class="ml-2" v-if="!data.show" @click="data.show = true">...</span>
      </view>
    </view>
    <!-- 折叠起来的 -->
    <view class="flex flex-wrap text-center items-center" v-if="data.show">
      <u-tag
        :type="member.checked ? 'primary' : 'info'"
        :mode="member.checked ? 'dark' : 'light'"
        v-for="(member, index) in data.bottomMembers"
        :key="member.memberId"
        class="mb-2 mr-3"
        style="width: 60px"
        :text="member.name"
        :closeable="false"
        @click="tagClick(index, member, 'bottomMembers')"
      />
      <u-icon class="ml-2" name="arrow-up" v-if="data.show" size="26" @click="data.show = false"></u-icon>
    </view>
  </view>
</template>

<script setup>
import { reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';

const props = defineProps({
  checkerList: {
    default: () => [],
    type: Array,
  },
});

const data = reactive({
  allMembers: [],
  show: false,
  topMembers: [],
  bottomMembers: [],
});

const store = useStore();
const members = computed(() => store.state.role.members);
const emit = defineEmits(['setCheckerList']);

onMounted(() => {
  if (members.value && members.value.length) {
    data.allMembers = members.value;
    // TODO: 等后台返回默认检查人后修改
    data.allMembers.forEach(item => {
      item.checked = false;
    });
    data.topMembers = members.value.slice(0, 3);
    data.bottomMembers = members.value.slice(3);
  }
});

function tagClick(index, item, membersType) {
  // 点击选择或取消选择
  const arr = uni.$u.deepClone(data[membersType]);
  arr[index].checked = !arr[index].checked;
  data[membersType] = [...arr];
  // 将选中的id传给checkerList
  emit('setCheckerList', arr[index].checked, item);
}

// 清空所有选中的检查人
function clearChecked() {
  for (let i = 0; i < data.topMembers.length; i++) {
    data.topMembers[i].checked = false;
  }
  for (let i = 0; i < data.bottomMembers.length; i++) {
    data.bottomMembers[i].checked = false;
  }
}
</script>
