<template>
  <view class="container" v-if="show">
    <view class="mask" @click="closePopup"></view>
    <view class="popup">
      <view class="popup-content">
        <view class="popup-header">
          <view class="title">
            <view>

              <text class="title-text">我的拼团</text>
              <text class="ml-[10rpx]">仅剩 <text class="text-[#EF000D]">{{ grouPinfo.target_num -
                grouPinfo.current_num }}</text> 个名额</text>
              <text class="text-[#FB240A] ml-[10rpx]"
                @click="redirect({ url: '/addon/pintuan/pages/share?order_no=' + grouPinfo.order_no, mode: 'navigateTo' })">

                详情
                <text class="arrow">></text>
              </text>

            </view>
            <text class="detail-link" v-if="state.isJoined"
              @click="redirect({ url: '/addon/pintuan/pages/share?order_no=' + grouPinfo.order_no, mode: 'navigateTo' })">详情<text
                class="arrow">></text></text>
            <text class="more-link" v-else
              @click="redirect({ url: '/addon/pintuan/pages/my_spell', mode: 'navigateTo' })">更多<text
                class="arrow">></text></text>
          </view>
        </view>

        <view class="pintuan-info">


          <view class="mx-[55rpx] mt-[30rpx] flex justify-center">
            <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 memberList" :key="index"
              :class="item.status == 1 ? '!border-[#FF000D] !border-solid' : item.status == 2 ? '!border-[#23CD01] !border-solid' : ''">
              <view v-if="item.member">
                <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]"
                @click="!item.member && joinGroup(item)" v-else></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 class="text-[24rpx] text-[#333333] mt-[35rpx] flex items-center justify-center">
            距结束还有
            <view
              class="min-w-[50rpx] h-[38rpx] bg-[#FF212B] rounded-[8rpx] flex items-center justify-center text-[28rpx] text-[#fff] ml-[10rpx]">
              {{ days }}
            </view>
            <view class="text-[#FF212B] mx-[8rpx]">天</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>
          </view>
          </view>
          </view>
</template>

<script setup lang="ts">
import { reactive, toRefs, ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { img, redirect } from '@/utils/common';

const emit = defineEmits(['confirm', 'close']);

const show = ref(true);

const props = defineProps({
  groupId: {
    type: [Number, String],
    default: 0
  },
  isJoined: {
    type: Boolean,
    default: false
  },
  grouPinfo: {
    type: Object,
    default: () => ({})
  },
  pintuanInfo: {
    type: Object,
    default: () => ({})
  }
});
 
// 定时器引用
let countdownTimer: NodeJS.Timeout | null = null;
// 组件是否正在关闭
let isClosing = false;

const state = reactive({
  memberList: [] as any[],
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0,
});
const { memberList, days, hours, minutes, seconds } = toRefs(state)
// 关闭弹窗
const closePopup = () => {
  // 标记组件正在关闭
  isClosing = true;
  // 立即清理定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  show.value = false;
  emit('close');
};

// 加入拼团
const joinGroup = (item: any) => {
  emit('confirm', props.grouPinfo);
  // closePopup();
};

// 邀请好友
const inviteFriends = () => {
  // 实现邀请好友的逻辑，可能是调用分享API
  uni.showToast({
    title: '邀请好友功能',
    icon: 'none'
  });
};

// 获取拼团详情
const getgrouPinfo = () => {
  const { member_list, leader_id, target_num, current_num, expire_time } = props.grouPinfo;
  let processedList = [];

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

  // 添加其他成员
  member_list.forEach((member: any) => {
    if (member.member_id !== leader_id) {
      processedList.push(member);
    }
  });

  // 计算要显示的位置数量，最多显示4个
  const maxDisplaySlots = Math.min(4, 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.memberList = 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);
  }
};

onMounted(() => {
   getgrouPinfo();
});

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

onLoad(() => {
  // 可以在这里加载拼团详情数据
});
</script>

<style lang="scss" scoped>
.container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
}

.popup {
  position: relative;
  width: 90%;
  max-width: 650rpx;
  background-color: #f0f6ff;
  border-radius: 20rpx;
  overflow: hidden;
  z-index: 1000;
}

.popup-content {
  padding: 20rpx 30rpx;
}

.popup-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10rpx;
  position: relative;
}

.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #e60012;
}

.detail-link,
.more-link {
  font-size: 24rpx;
  color: #666;
}

.arrow {
  margin-left: 4rpx;
}

.pintuan-info {
  background-color: #f0f6ff;
  border-radius: 10rpx;
  padding: 10rpx 0;
}

.group-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.status-text {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.members {
  margin: 20rpx 0;
  display: flex;
  justify-content: center;
}

.member-avatars {
  display: flex;
  justify-content: center;
}

.avatar-item {
  position: relative;
  margin: 0 10rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  border: 2rpx solid #fff;
}

.leader-tag {
  position: absolute;
  bottom: -10rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: #e60012;
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 10rpx;
  border-radius: 10rpx;
  white-space: nowrap;
}

.empty-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  border: 2rpx dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 40rpx;
}

.countdown-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20rpx;
}

.countdown-label {
  font-size: 24rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.countdown-timer {
  display: flex;
  align-items: center;
  justify-content: center;
}

.time-box {
  display: inline-block;
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  background-color: #e60012;
  color: #fff;
  font-size: 28rpx;
  border-radius: 8rpx;
}

.time-separator {
  margin: 0 8rpx;
  color: #e60012;
  font-size: 28rpx;
  font-weight: bold;
}
</style>
