<template>
  <div class="w-full h-[100vh]">
    <ChatHeaderBar title="添加成员" />

    <ChatSearch v-model:searchString="showName" @search="search" placeholder="请输入关键词" />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <ChatEmpty
        image="search"
        v-if="!addDataList?.length && !loading"
        title="暂无数据"
        top="100"
      />

      <van-list
        v-model:loading="loading"
        error-text="获取失败"
        finished-text="-- 没有更多了 --"
        :finished="finished"
        :immediate-check="false"
      >
        <div style="height: calc(100vh - 170px)">
          <van-checkbox-group v-model="checked">
            <!-- <van-index-bar
              highlight-color="#FD9A00"
              :index-list="sortStringToAZ.sortIndex"
              :sticky="false"
            > -->
            <!-- <template v-for="(el, index) in addDataList" :key="index"> -->
            <!-- <van-index-anchor v-if="el[1].length" :index="el[0]" /> -->
            <!-- <template v-for="(el, index) in addDataList" :key="index"> -->
            <!-- <van-index-anchor  :index="el[0]" /> -->

            <template v-for="item in addDataList" :key="item.userId">
              <van-cell center clickable @click.stop="toggle(item)">
                <template #icon>
                  <div class="flex justify-start">
                    <van-checkbox
                      checked-color="#FD9A00"
                      :name="item?.userId"
                      :ref="(el) => (checkboxRefs[item?.userId] = el)"
                      @click.stop="toggle(item)"
                    />

                    <div class="w-40 h-40 ml-13 mr-12 rounded-full overflow-hidden">
                      <img
                        v-if="item?.headImageUrl"
                        class="w-full h-full shrink-0 object-cover"
                        :src="item?.headImageUrl"
                        alt=""
                      />

                      <img
                        class="w-full h-full shrink-0 object-cover"
                        src="~/assets/img/default_avatar.png"
                        alt=""
                      />
                    </div>
                  </div>
                </template>
                <template #title>
                  <div class="flex items-center">
                    <h1 class="text-xl text-black-3">
                      {{ item?.showName }}
                    </h1>
                    <van-tag
                      v-if="item.fansStatus == 2"
                      style="margin-left: 5px; padding: 3px 6px"
                      color="#F7F8FA"
                      text-color="#666666"
                    >
                      相互关注
                    </van-tag>
                  </div>
                </template>
              </van-cell>
            </template>
            <!-- </template> -->
            <!-- </template> -->
            <!-- </van-index-bar> -->
          </van-checkbox-group>
        </div>
      </van-list>
    </van-pull-refresh>

    <div
      class="w-full box-border p-16 pb-40 bg-white fixed bottom-0 left-0 flex justify-between items-center shadow-[0px_-4px_4px_0px_rgba(0,0,0,0.1)]"
    >
      <div class="shrink-0 flex justify-start items-center">
        <div class="w-118 shrink-0 flex justify-start items-center overflow-hidden">
          <div
            v-for="(item, index) in checkedList.slice(0, 5)"
            :key="index + 'avatar'"
            :class="`w-36 h-36  ${index == 0 ? '' : '-ml-16'} shrink-0 rounded-full overflow-hidden`"
          >
            <img
              v-if="item?.headImageUrl"
              class="w-full h-full object-cover"
              :src="item?.headImageUrl"
              alt=""
            />
            <img
              v-else
              class="w-full h-full shrink-0 object-cover"
              src="~/assets/img/default_avatar.png"
              alt=""
            />
          </div>
        </div>

        <div v-if="checkedList.length > 5" class="shrink-0 w-24 h-24 ml-8">
          <img class="w-full h-full object-cover" src="~/assets/img/chat/ellipsis.svg" alt="" />
        </div>
      </div>
      <van-button
        :disabled="checkedList.length > 0 ? false : true"
        @click="handleCreateGroup"
        style="width: 160px"
        class="shrink-0"
        block
        size="large"
        color="#FD9A00"
        round
      >
        完成
        <span v-if="checkedList.length">({{ checkedList.length }})</span>
      </van-button>
    </div>
  </div>
</template>
<script setup>
const route = useRoute()

definePageMeta({
  layout: false
})

onMounted(() => {
  getList()
})

const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)

const checked = ref([])
const showName = ref('')
const checkboxRefs = ref([])
const checkedList = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  flagPage: 1
})

// const _addDataList = ref(new Map([]))
const addDataList = ref([])
const filterDataList = ref([])

useSeoMeta({
  title: '群聊'
})

// 选中要邀请的人
const toggle = (item) => {
  let index = checkedList.value.findIndex((el) => el?.userId == item?.userId)

  if (index != -1) {
    checkedList.value.splice(index, 1)
  } else {
    checkedList.value.push(item)
  }

  checkboxRefs.value[item.userId].toggle()
}
// 搜索
const search = () => {
  finished.value = true
  if (showName.value) {
    addDataList.value = filterDataList.value.filter((item) =>
      item.showName.includes(showName.value)
    )
  } else {
    addDataList.value = filterDataList.value
  }
}

// 刷新
const onRefresh = () => {
  queryParams.pageNum = 1
  addDataList.value = []
  filterDataList.value = []
  getList()
}

// 获取数据
const getList = async () => {
  try {
    let url = `/website/tourMember/memberLit`

    loading.value = true
    let { data } = await request(url, {
      query: {
        groupId: route.query.groupId
      }
    })

    if (Array.isArray(data) && data?.length) {
      // const { sortListMap } = sortStringToAZ.sort(data, 'showName')

      addDataList.value = data
      filterDataList.value = data
    } else {
      addDataList.value = []
    }

    loading.value = false
    refreshing.value = false
    if (addDataList.value.length >= totalCount) {
      finished.value = true
    } else {
      finished.value = false
    }
  } catch (err) {
  } finally {
    refreshing.value = false
    loading.value = false
  }
}

// 创建多人聊天
async function handleCreateGroup() {
  try {
    showLoadingToast({
      message: '准备开始群聊...',
      duration: 100000
    })
    let { data } = request('/website/tourMember/invite', {
      method: 'post',
      body: {
        groupId: route.query.groupId,
        ids: checked.value
      }
    })
    if (data) {
      navigateTo({
        path: '/chat/group',
        query: data,
        replace: true
      })
    }
  } catch (error) {
  } finally {
    closeToast()
  }
}
</script>
<style lang="scss" scoped></style>
