<template>
  <div class="container w-[100vw] h-[100vh] fixed top-[0] left-[0] z-88" @click="close">
    <view class="w-[620rpx] min-h-[287rpx] bg-[#fff] absolute right-[30rpx] bottom-[120rpx] rounded-[12rpx]" @click.stop>
      <view class="flex items-center justify-center">
        
        <view class="text-[24rpx] text-[#333333] mt-[43rpx] flex items-center">
          <image :src="img(grouPinfo.leader?.headimg)" @error="grouPinfo.leader.headimg = 'static/resource/images/default_headimg.png'" mode="scaleToFill" class="w-[40rpx] h-[40rpx] rounded-[50%] mr-[20rpx]" />

          <text class="text-[#EF000D]">{{grouPinfo.leader?.nickname}}</text>
          邀请你加入TA的团</view>
      </view>
      <view class="text-[24rpx] text-[#333333] mt-[35rpx] flex items-center justify-center">
        仅剩 <text class="text-[#EF000D]">{{grouPinfo.target_num - grouPinfo.current_num}}</text> 个名额，距结束还有
        <view class="min-w-[50rpx] h-[38rpx] bg-[#FF212B] rounded-[8rpx] flex items-center justify-center text-[28rpx] text-[#fff] ml-[10rpx]" v-if="days > 0">
          {{ days }}
        </view>
        <view class="text-[#FF212B] mx-[8rpx]" v-if="days > 0">天</view>
        <view class="min-w-[38rpx] h-[38rpx] bg-[#FF212B] rounded-[8rpx] flex items-center justify-center text-[28rpx] text-[#fff]">
          {{ hours < 10 ? '0' + hours : hours }}
        </view>
        <view class="text-[#FF212B] mx-[8rpx]">:</view>
        <view class="w-[38rpx] h-[38rpx] bg-[#FF212B] rounded-[8rpx] flex items-center justify-center text-[28rpx] text-[#fff]">
          {{ minutes < 10 ? '0' + minutes : minutes }}
        </view>
        <view class="text-[#FF212B] mx-[8rpx]">:</view>
        <view class="w-[38rpx] h-[38rpx] bg-[#FF212B] rounded-[8rpx] flex items-center justify-center text-[28rpx] text-[#fff]">
          {{ seconds < 10 ? '0' + seconds : seconds }}
        </view>
      </view>
      <view class="mx-[55rpx] mt-[30rpx] flex justify-center mb-[30rpx]">
        <view
          class="mr-[30rpx] relative w-[88rpx] h-[88rpx] bg-[#F6F6F6] rounded-[50%] border border-[#DDDDDD] border-width-[1px] border-dashed flex items-center justify-center text-[#999999] text-[40rpx]]"
          v-for="(item, index) in list"
          :key="index"
          :class="item.status == 1 ? '!border-[#FF000D] !border-solid' : item.status == 2 ? '!border-[#23CD01] !border-solid' : ''">
          <view v-if="item.member && index<2" class="w-[100%] h-[100%] overflow-hidden">
            <image :src="item.member ? img(item.member.headimg) : ''" mode="scaleToFill" class="w-[88rpx] h-[88rpx] rounded-[50%]" v-if="item.member"  @error="item.member.headimg='static/resource/images/default_headimg.png'" />
            <!-- <image v-else :src="img('static/resource/images/default_headimg.png')" mode="scaleToFill"  class="w-[88rpx] h-[88rpx] rounded-[50%]" /> -->
          </view>

          <text class="iconfont iconVector-3 text-[#ccc] text-[40rpx]" v-else @click="joinGroup(item)"></text>

          <view
            class="w-[70rpx] h-[28rpx] rounded-[16rpx]  text-[#fff] text-[20rpx] text-center leading-[28rpx] absolute bottom-[-10rpx] lef-[9rpx] primary-btn-bg"
            v-if="item.status == 1">团长</view>
          <view
            class="w-[70rpx] h-[28rpx] rounded-[16rpx]  text-[#fff] text-[20rpx] text-center leading-[28rpx] absolute bottom-[-10rpx] lef-[9rpx] bg-[#23CD01]"
            v-if="item.status == 2">我</view>
        </view>

      </view>
    </view>
  </div>
</template>

<script setup lang="ts">
import { reactive, toRefs, ref, onMounted, onUnmounted, defineEmits, computed} from "vue";
import { img, } from '@/utils/common';

// 声明自定义事件
const emit = defineEmits(['close', 'join']);
const props = defineProps({
    grouPinfo: {
        type: Object,
        default: () => ({})
    }
});

// 定时器引用
let countdownTimer: NodeJS.Timeout | null = null;
// 组件是否正在关闭
let isClosing = false;

// 计算初始倒计时值
const calculateInitialTime = () => {
  const { expire_time } = props.grouPinfo;
  if (!expire_time) return { days: 0, hours: 0, minutes: 0, seconds: 0 };
  
  const now = new Date().getTime();
  const end = new Date(expire_time.replace(/-/g, '/')).getTime();
  const diff = end - now;
  
  if (diff <= 0) {
    return { days: 0, hours: 0, minutes: 0, seconds: 0 };
  }
  
  return {
    days: Math.floor(diff / (1000 * 60 * 60 * 24)),
    hours: Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
    minutes: Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)),
    seconds: Math.floor((diff % (1000 * 60)) / 1000)
  };
};

const initialTime = calculateInitialTime();

const state = reactive({
  list: [
 
  ],
  days: initialTime.days,
  hours: initialTime.hours,
  minutes: initialTime.minutes,
  seconds: initialTime.seconds,
})
const {list, days, hours, minutes, seconds } = toRefs(state)

// 计算倒计时是否结束
const isCountdownExpired = computed(() => {
  return days.value === 0 && hours.value === 0 && minutes.value === 0 && seconds.value === 0;
});
onMounted(() => {
  const { member_list, leader_id, target_num, current_num, expire_time } = props.grouPinfo;
   let processedList = [];

  // 找到团长并将其放在列表首位，并添加 status = 1
  const leader = member_list.find(member => member.role == "leader");
  if (leader) {
    processedList.push({ ...leader, status: 1 });
  }

  // 添加其他成员
  member_list.forEach(member => {
    if (member.role !== "leader") {
      processedList.push(member);
    }
  });

  // 计算要显示的位置数量，最多显示4个
  const maxDisplaySlots = Math.min(3, target_num);

  // 如果当前成员数量少于最大显示数量，填充空位
  if (processedList.length < maxDisplaySlots) {
    const remainingSlots = maxDisplaySlots - processedList.length;
    for (let i = 0; i < remainingSlots; i++) {
      processedList.push({});
    }
  } else if (processedList.length > maxDisplaySlots) {
    // 如果成员数量超过最大显示数量，只显示前面的成员
    processedList = processedList.slice(0, maxDisplaySlots);
  }

  state.list = processedList;

  // 启动倒计时定时器
  const now = new Date().getTime();
  const end = new Date(expire_time.replace(/-/g, '/')).getTime();
  let diff = end - now;

  if (diff > 0) {
    countdownTimer = setInterval(() => {
      // 如果组件正在关闭，不再更新状态
      if (isClosing) {
        if (countdownTimer) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
        return;
      }

      diff -= 1000;
      if (diff <= 0) {
        if (countdownTimer) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
        state.days = 0;
        state.hours = 0;
        state.minutes = 0;
        state.seconds = 0;
      } else {
        state.days = Math.floor(diff / (1000 * 60 * 60 * 24));
        state.hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        state.minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        state.seconds = Math.floor((diff % (1000 * 60)) / 1000);
      }
    }, 1000);
  }
});

// 组件销毁时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});

const close = () => {
  // 标记组件正在关闭
  isClosing = true;
  // 立即清理定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  emit('close')
}
const joinGroup = (item: any) => {
   if(isCountdownExpired.value){
    return;
  }
   emit('join',props.grouPinfo);
}

</script>

<style scoped lang='scss'>
.container {
  background: rgba(0, 0, 0, 0.8);
}
</style>