<template>
  <div class="outer-layer select-members-page">
    <div class="root">
      <ZPaging
        ref="zPaging"
        :show-scrollbar="false"
        :use-virtual-list="true"
        :virtual-list-col="5"
        :refresher-enabled="false"
        :loading-more-enabled="false"
        @scroll="onScroll"
      >
        <template #top>
          <tm-navbar
            :hideBack="false"
            hideHome
            title=""
            :leftWidth="220"
            id="topArea"
          >
            <div class="navBar-title flex flex-col items-center justify-center">
              <span
                class="text-[34rpx] font-medium"
                v-if="state.manageType === 'silence'"
              >
                {{ $t('chat.manage.addSilenceMember') }}
              </span>
              <span
                class="text-[34rpx] font-medium"
                v-if="state.manageType === 'admin'"
              >
                {{ $t('chat.manage.addAdmin') }}
              </span>
              <span
                class="text-[34rpx] font-medium"
                v-if="state.manageType === 'searchRecord'"
              >
                {{ $t('search.condition.member') }}
              </span>
            </div>
          </tm-navbar>
        </template>
        <div class="select-members">
          <div class="search-member">
            <customInput
              :searchText="state.searchText"
              @inputSearchText="inputSearchText"
            ></customInput>
          </div>
          <div
            class="member-list"
            :style="{
              padding: state.manageType === 'searchRecord' ? '20rpx 0 0' : '',
            }"
          >
            <div class="member-list-alphabet-anchor-point">
              <div
                class="member-list-alphabet-anchor-point-each"
                v-for="(alphabetItem, alphabetIndex) in state?.alphabet"
                :key="alphabetIndex"
                :style="{
                  margin: state?.alphabet?.length > 17 ? '0' : '',
                }"
                @click.stop="scrollToView(alphabetItem)"
              >
                <span
                  class="text-[32rpx] font-regular"
                  :style="{
                    color:
                      state.currentAlphabet === alphabetItem ? '#7A58DE' : '',
                  }"
                >
                  {{ alphabetItem }}
                </span>
              </div>
            </div>
            <div
              class="member-list-alphabet"
              v-for="(alphabetItem, alphabetIndex) in state.resultMemberList"
              :key="alphabetIndex"
            >
              <div
                class="member-list-alphabet-key"
                :style="{
                  padding:
                    state.manageType === 'searchRecord' ? '10rpx 30rpx' : '',
                }"
                v-if="alphabetItem?.memberList?.length > 0"
                :id="alphabetItem.key"
                :ref="
                  (el) => {
                    if (el) alphabetElementRefs[alphabetIndex] = el
                  }
                "
              >
                <span class="text-[32rpx] font-regular">
                  {{ alphabetItem.key }}
                </span>
              </div>
              <div v-if="alphabetItem?.memberList?.length > 0">
                <div
                  class="member-list-each"
                  v-for="(item, index) in alphabetItem?.memberList"
                  :key="index"
                >
                  <tm-checkbox-group v-model="item.checkArr">
                    <selectMemberItem
                      :memberItem="item"
                      @clickItem="handleClickItem(item)"
                      :manageType="state.manageType"
                      :itemStyle="
                        state.manageType === 'searchRecord' ? 'list' : 'card'
                      "
                    >
                      <template
                        #left
                        v-if="state.manageType !== 'searchRecord'"
                      >
                        <tm-checkbox
                          :round="10"
                          color="#46299d"
                          :value="item.id"
                          :disabled="item.is_mute === 1"
                        ></tm-checkbox>
                      </template>
                    </selectMemberItem>
                  </tm-checkbox-group>
                </div>
              </div>
            </div>
          </div>
        </div>
        <template #bottom v-if="state.manageType !== 'searchRecord'">
          <customBtn
            :isBottom="true"
            :btnText="$t('ok')"
            @clickBtn="confirmSilenceMember"
          ></customBtn>
        </template>
      </ZPaging>
    </div>
  </div>
</template>
<script setup>
import customInput from '@/components/custom-input/custom-input.vue'
import selectMemberItem from '../components/select-member-item.vue'
import customBtn from '@/components/custom-btn/custom-btn.vue'
import ZPaging from '@/uni_modules/z-paging/components/z-paging/z-paging.vue'
import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js'
import { computed, onMounted, reactive, ref, watch, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

import { useDialogueStore } from '@/store'

const zPaging = ref()
useZPaging(zPaging)

const dialogueStore = useDialogueStore()
const state = reactive({
  searchText: '', //搜索内容
  manageType: '', //管理类型
  alphabet: [], //A-Z列表
  resultMemberList: [], //按A-Z整理后的人员列表
  currentAlphabet: 'A', //当前A-Z位置
  scrollDirection: '', //当前列表滚动方向
  isAssign: false, //是否指定view
})
const dialogueParams = reactive({
  memberList: computed(() => {
    const lowerCaseSearchText = state?.searchText.toLowerCase()
    return dialogueStore.members.filter((item) =>
      state?.searchText
        ? item.nickname.toLowerCase().includes(lowerCaseSearchText)
        : true,
    )
  }),
  receiverId: computed(() => dialogueStore.talk.receiver_id),
})

watch(
  () => dialogueParams?.memberList,
  (newMemberList) => {
    assembleAlphabetMmeberList(newMemberList)
  },
  { deep: true },
)

//获取A-Z tag元素
const alphabetElementRefs = ref([])
//观察者
let observer

onLoad((options) => {
  console.log(options)
  if (options.manageType) {
    state.manageType = options.manageType
    assembleAlphabetMmeberList(dialogueParams?.memberList)
  }
})

onMounted(() => {
  dialogueParams.memberList.forEach((ele) => {
    ele.checkArr = []
  })
  const options = {
    root: null, // 使用浏览器窗口作为根容器
    threshold: 1.0, // 当元素100%离开视口时触发
  }
  observer = new IntersectionObserver(handleIntersection, options)
  nextTick(() => {
    watch(
      alphabetElementRefs,
      (newAlphabetElementRefs) => {
        if (Array.isArray(newAlphabetElementRefs)) {
          newAlphabetElementRefs.forEach((el, index) => {
            observeElement(el, index)
          })
        }
      },
      { immediate: true, deep: true },
    )
    if (alphabetElementRefs.value.length > 0) {
      alphabetElementRefs.value.forEach((el, index) =>
        observeElement(el, index),
      )
    }
  })
})

// 观察者函数
const handleIntersection = (entries) => {
  if (state.isAssign) {
    state.isAssign = false
    return
  }
  entries.forEach((entry) => {
    if (!entry.isIntersecting && state.scrollDirection === 'down') {
      state.currentAlphabet = entry.target.id
    } else if (entry.isIntersecting && state.scrollDirection === 'up') {
      if (state?.alphabet?.length > 1) {
        state?.alphabet.forEach((item, index) => {
          if (item === entry.target.id && index > 0) {
            state.currentAlphabet = state?.alphabet[index - 1]
          }
        })
      } else {
        state.currentAlphabet = entry.target.id
      }
    }
  })
}

//观察元素
const observeElement = (el, index) => {
  if (el && observer) {
    observer.observe(el)
  }
}

//输入搜索文本
const inputSearchText = (e) => {
  // console.log(e)
  state.searchText = e
}

//点击item
const handleClickItem = (item) => {
  dialogueParams.memberList.forEach((ele) => {
    if (ele.id == item.id) {
      ele.checkArr = ele.checkArr?.length > 0 ? [] : [item.id]
    }
  })
}

//点击确认要禁言的成员
const confirmSilenceMember = () => {
  let selectedUserIds = ''
  dialogueParams.memberList.forEach((ele) => {
    if (ele.checkArr?.length > 0) {
      if (!selectedUserIds) {
        selectedUserIds = ele.checkArr[0]
      } else {
        selectedUserIds += ',' + ele.checkArr[0]
      }
    }
  })
  console.log(selectedUserIds)
  if (selectedUserIds) {
    let params = {
      mode: 1, //1禁言2解禁
      group_id: dialogueParams.receiverId, //群id
      user_ids: selectedUserIds, //用户ids
    }
    console.log(params)
  }
}

//组装A-Z排序的人员列表
const assembleAlphabetMmeberList = (newMemberList) => {
  if (state.manageType === 'searchRecord') {
    const resultMemberList = ref([])
    const alphabet = Array.from({ length: 26 }, (_, i) =>
      String.fromCharCode(i + 65),
    )
    let tempAlphabet = []
    alphabet.forEach((letter) => {
      const matchedItems = newMemberList.filter((item) => item.key === letter)
      if (matchedItems.length > 0) {
        tempAlphabet.push(letter)
      }
      resultMemberList.value.push({
        key: letter,
        memberList: matchedItems.length ? matchedItems : [],
      })
    })
    state.alphabet = tempAlphabet
    state.resultMemberList = resultMemberList
  } else {
    state.resultMemberList = [
      {
        key: '',
        memberList: newMemberList,
      },
    ]
  }
}

//滚动到指定的view
const scrollToView = (alphabet) => {
  state.currentAlphabet = alphabet
  state.isAssign = true
  console.log()
  zPaging.value?.scrollIntoViewById(
    alphabet,
    document.getElementById('topArea').clientHeight
      ? document.getElementById('topArea').clientHeight - 1
      : 80,
  )
}

//监听列表滚动
const onScroll = (e) => {
  if (e.detail.deltaY < 0) {
    state.scrollDirection = 'down'
  } else if (e.detail.deltaY > 0) {
    state.scrollDirection = 'up'
  } else {
    state.scrollDirection = ''
  }
}
</script>
<style scoped lang="scss">
.outer-layer {
  flex: 1;
  background-image: url('@/static/image/clockIn/z3280@3x.png');
  background-size: cover;
  background-repeat: no-repeat;
}

.select-members {
  padding: 20rpx 32rpx;
  .search-member {
    padding: 22rpx 16rpx;
    background-color: #fff;
  }
  .member-list {
    .member-list-alphabet-anchor-point {
      position: fixed;
      right: 32rpx;
      top: 0;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .member-list-alphabet-anchor-point-each {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin: 0 0 14rpx;
        span {
          width: 52rpx;
          text-align: center;
          line-height: 44rpx;
          color: $theme-text;
        }
      }
    }
    .member-list-alphabet {
      .member-list-alphabet-key {
        background-color: #f3f3f3;
        span {
          line-height: 44rpx;
          color: $theme-text;
        }
      }
    }
  }
}
</style>
