<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-else-if="addDataList.length"
        v-model:loading="loading"
        error-text="获取失败"
        finished-text="-- 没有更多了 --"
        :finished="finished"
        :immediate-check="false"
      >
        <!--    @load="getLoadList"  -->
        <div style="height: calc(100vh - 170px)">
          <van-checkbox-group v-model="checked">
            <!-- <van-index-bar highlight-color="#FD9A00" index-list :sticky="false"> -->
            <template v-for="(item, index) in addDataList" :key="item?.attentionIdDictMap?.userId">
              <!-- <van-index-anchor index="A" /> -->
              <van-cell center clickable @click="toggle(item)">
                <template #icon>
                  <div class="flex justify-start">
                    <van-checkbox
                      checked-color="#FD9A00"
                      :name="item?.attentionIdDictMap?.userId"
                      :ref="(el) => (checkboxRefs[item?.attentionIdDictMap?.userId] = el)"
                      @click.stop="toggle(item)"
                    />

                    <div class="w-40 h-40 ml-13 mr-12 rounded-full overflow-hidden">
                      <img
                        v-if="item?.attentionIdDictMap?.headImageUrl"
                        class="w-full h-full shrink-0 object-cover"
                        :src="item?.attentionIdDictMap?.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?.attentionIdDictMap?.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>
            <!-- </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?.attentionIdDictMap?.headImageUrl"
              class="w-full h-full object-cover"
              :src="item?.attentionIdDictMap?.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
        :loading="isLoading"
        :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()
const router = useRouter()

definePageMeta({
  layout: false
})

onMounted(() => {
  getList()
})
// 对方的那个id
const toUserId = computed(() => route.query?.toUserId ?? '')
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)

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

// 字母的数组
const letterList = ref([])

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

const addDataList = ref([])
const filterDataList = ref([])

const searchText = computed(() => (showName.value ? '暂无互关好友' : '暂无搜索结果'))

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

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

  checkboxRefs.value[item?.attentionIdDictMap?.userId].toggle()
}

const search = () => {
  finished.value = true
  if (showName.value) {
    addDataList.value = filterDataList.value.filter((item) =>
      item.attentionIdDictMap.name.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/tourism/fans/getFriends`

    loading.value = true
    let {
      data: { dataList, totalCount }
    } = await request(url, {
      query: {
        ...queryParams
      }
    })

    if (Array.isArray(dataList) && dataList?.length) {
      addDataList.value = dataList

      nextTick(() => {
        checkboxRefs.value[toUserId.value].toggle()
        let item = dataList.find((el) => el?.attentionIdDictMap?.userId == toUserId.value)
        if (item) {
          checkedList.value.push(item)
        } else {
          router.back()
        }
      })
    } 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
  }
}

// 节流
const isLoading = ref(false)

function handleKeyDown(event) {
  // 启动节流
  // 1000ms 后解除节流
  // setTimeout(() => {
  //   isThrottled.value = false
  // }, 3000)
}

// 创建多人聊天
async function handleCreateGroup() {
  if (!isLoading.value) {
    isLoading.value = true
    try {
      showLoadingToast({
        message: '准备开始群聊...',
        duration: 100000
      })

      let { data } = await request('/website/tourGroup/createGroup', {
        method: 'post',
        body: {
          createType: 2,
          ids: [...checked.value]
        }
      })

      if (data) {
        navigateTo({
          path: '/chat/group-chat',
          query: {
            groupId: data
          },
          replace: true
        })
        isLoading.value = false
      }
    } catch (error) {
    } finally {
      closeToast()
    }
  }
}

useSeoMeta({
  title: '我的消息'
})
</script>
<style lang="scss" scoped></style>
