<template>
  <view class="container w-[100vw] h-[100vh] fixed top-[0] left-[0] z-88 flex items-center justify-center flex-col"
    @click="close">

    <view
      class="popup-content w-[570rpx] bg-[#fff]  translate-x-[-50%] translate-y-[-50%] rounded-[24rpx] overflow-hidden"
      @click.stop>
      <!-- 商品信息 -->
      <view class="goods-info flex py-[30rpx] px-[20rpx] border-b border-[#F5F5F5] pb-[0]">
        <!-- <image :src="img(pintuanInfo.goods.cover_thumb_big)" mode="aspectFill" class="w-[160rpx] h-[160rpx] rounded-[12rpx]"></image> -->
        <u--image width="150rpx" height="150rpx" :radius="'var(--goods-rounded-big)'"
          :src="img(pintuanInfo.goods.cover_thumb_big)" mode="aspectFill">
          <template #error>
            <image class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
              :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill" />
          </template>
        </u--image>
        <view class="ml-[20rpx] flex-1 flex flex-col justify-between">
          <view class="text-[28rpx] text-[#333] font-medium line-clamp-2  multi-hidden leading-[normal]">{{ pintuanInfo.goods.title }}</view>
          <view class="flex items-baseline">
            <text class="text-[20rpx] text-[#FF000B] relative top-[-2rpx]">拼团价</text>
            <text class="text-[#FF000D] text-[24rpx] price-font">￥</text>
            <text class="text-[48rpx] text-[#FF000D] price-font ">{{
              parseFloat(pintuanInfo.goods.pintuan_price).toFixed(2).split(".")[0]
              }}.</text>
            <text class="text-[24rpx] text-[#FF000D] price-font ">{{
              parseFloat(pintuanInfo.goods.pintuan_price)
                .toFixed(2)
                .split(".")[1]
              }}</text>
            <!-- <text class="text-[#FF000D] text-[36rpx] font-bold price-font">{{ pintuanInfo.goods.pintuan_price }}</text> -->
            <text class="text-[20rpx] text-[#999] text-[24rpx] ml-[10rpx] relative top-[-2rpx]">原价</text>
            <text class="text-[#999] text-[24rpx] "> ￥{{
              parseFloat(pintuanInfo.goods.original_price)
                .toFixed(2)
              .split(".")[0] }}</text>
            <text class="text-[#999] text-[24rpx] ml-[2rpx]">.{{
              parseFloat(pintuanInfo.goods.original_price)
                .toFixed(2)
              .split(".")[1] }}</text>
          </view>
        </view>
      </view>

      <!-- 拼团信息 -->
      <view class="pintuan-info px-[30rpx] pt-[0]">
        <view class="text-[22rpx] text-[#333333] mt-[75rpx] flex items-center justify-center">
          仅剩 <text class="text-[#EF000D]">{{ grouPinfo.target_num - grouPinfo.current_num }}</text> 个名额，距结束还有
          <view class="min-w-[42rpx] h-[38rpx] bg-[#FF212B] rounded-[8rpx] flex items-center justify-center text-[26rpx] 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-[26rpx] 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-[26rpx] 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-[26rpx] text-[#fff]">
            {{ seconds < 10 ? '0' + seconds : seconds }}
          </view>
        </view>
        <!-- 拼团成员 -->
        <view class="mt-[30rpx] flex justify-center">
            <view class="carousel-wrapper max-w-[335rpx]"  :style="'width:' + (88 * visibleImages.length + (visibleImages.length >= 3 ? 70 : visibleImages.length == 2 ? 40 : 10)) + 'rpx'">
               <view
              class="carousel-item border border-[#DDDDDD] border-solid border-width-[2rpx]"
              :style="'background:url('+img('addon/pintuan/bk.png')+');background-size: 100% 100%;'"
  
              v-for="(item, index) in visibleImages" 	:key="item.id"
              :class="[item.status == 1 ? 'leader-border' : item.status == 2 ? '!border-[#ddd] !border-solid' : '',item.imgstatus]" 
              >
              <view v-if="item.member" 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>
  
              <view :class="item.imgstatus" 
                class="w-[70rpx] h-[28rpx] rounded-[16rpx] carousel-border text-[#fff] text-[20rpx] text-center leading-[28rpx] absolute bottom-[-10rpx] left-[9rpx] primary-btn-bg"
                v-if="item.role == 'leader'">团长</view>
              <view :class="item.imgstatus"
                class="w-[70rpx] h-[28rpx] rounded-[16rpx] carousel-border text-[#fff] text-[20rpx] text-center leading-[28rpx] absolute bottom-[-10rpx] left-[9rpx] bg-[#23CD01]"
                v-if="item.status == 2">我</view>
            </view>
          </view>
            <view class="ml-[30rpx] w-[88rpx] h-[88rpx] bg-[#F6F6F6] rounded-[50%] border border-[#DDDDDD] border-width-[1px] flex items-center justify-center text-[#999999] text-[40rpx]"  @click="joinGroup">
                 <text class="iconfont iconjiahaoV6xx1 text-[#999999] text-[40rpx]"   
              ></text>
            </view>
          </view>
          
        </view>
      <!-- 底部按钮 -->
      <view class="footer p-[30rpx] flex justify-center mt-[20rpx]">
         <button
          class="share-btn w-[500rpx] h-[80rpx] text-[28rpx] rounded-[10rpx] flex items-center justify-center bg-[#FF000D] text-[#fff]"
          :class="isCountdownExpired ? 'bg-[#ccc] text-[#999]' : ''"
          @click="joinGroup"
          :disabled="isCountdownExpired">
          <text class="iconfont iconweixinV6xx mr-[10rpx] text-[32rpx]"></text>
          <text>{{ isCountdownExpired ? '拼团已结束' : '加入拼团' }}</text>
        </button>
      </view>
    </view>
    <view class="mt-[30rpx] text-[#fff] " @click="close">
      <text class="iconfont  iconguanbi1 text-[40rpx]"></text>
    </view>
  </view>
</template>

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

// 声明自定义事件
const emit = defineEmits(['close', 'confirm']);

// 定义props
const props = defineProps({
  grouPinfo: {
    type: Object,
    default: () => ({})
  },
  pintuanInfo: {
    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({
  goodsImage: img('addon/pintuan/goods/default.png'),
  goodsTitle: '云南牛干巴(散称)约5份五香味各种味道欢迎品尝',
  goodsPrice: '48.26',
  originalPrice: '89.99',
  targetNum: 3,
  remainTime: '23:59:52',
  defaultAvatar: img('addon/pintuan/avatar1.png'),
  memberList: [
    {
      avatar: img('addon/pintuan/avatar1.png'),
      nickname: '用户昵称',
      isLeader: true,
      isSelf: false
    },
    {
      avatar: img('addon/pintuan/avatar2.png'),
      nickname: '我',
      isLeader: false,
      isSelf: true
    },
    {
      avatar: '',
      nickname: '',
      isLeader: false,
      isSelf: false
    }
  ],
  list: [],

  days: initialTime.days,
  hours: initialTime.hours,
  minutes: initialTime.minutes,
  seconds: initialTime.seconds,
});

const { goodsImage, goodsTitle, goodsPrice, originalPrice, targetNum, remainTime, defaultAvatar, memberList, list, days, hours, minutes, seconds } = toRefs(state);

// 计算倒计时是否结束
const isCountdownExpired = computed(() => {
  return days.value === 0 && hours.value === 0 && minutes.value === 0 && seconds.value === 0;
});

// 关闭弹窗
const close = () => {
  // 标记组件正在关闭
  isClosing = true;
  // 立即清理定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  emit('close');
};

// 分享拼团
// const shareGroup = () => {
//   emit('confirm');
// };

const joinGroup = (item: any) => {
    if(isCountdownExpired.value){
    return;
  }
   emit('confirm', {...props.grouPinfo,check_ladder:props.pintuanInfo.check_ladder});
};


const visibleImages = ref([]);
  let isAnimating = ref(false);
  
  // 获取下一张要显示的图片
  const getNextImage = () => {
  const lastId = visibleImages.value.length > 0 ? visibleImages.value[visibleImages.value.length - 1].id : 0;
  if (lastId === 0) return state.list[0];

  const lastImageIndexInAll = state.list.findIndex(img => img.id === lastId);
  const nextImageIndex = (lastImageIndexInAll + 1) % state.list.length;
  return state.list[nextImageIndex];
};

  let intervalId: NodeJS.Timeout | null = null;
  

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;

  
    // 初始化队列，填充前5张图片，并设置初始状态
    visibleImages.value = state.list.slice(0, 3).map(img => ({ ...img, imgstatus: 'visible' }));
      if (state.list.length <= 3) {
          return;
      }
  intervalId = setInterval(async () => {
      if (isAnimating.value) return;
      isAnimating.value = true;
  
      // 1. 标记最右侧（数组末尾）的图片为“离开中”
      if (visibleImages.value.length > 0) {
          visibleImages.value[visibleImages.value.length - 1].imgstatus = 'leaving';
      }
  
      // 2. 在最左侧（数组开头）添加一个新图片，状态为“进入中”
      const newImage = getNextImage();
      visibleImages.value.unshift({ ...newImage, imgstatus: 'entering' });
      
      // 3. 等待DOM更新后，通过一个微小延迟来触发进入动画
      await nextTick();
      // ==== 关键修复 ====
      // 我们使用一个短暂的 setTimeout 来确保浏览器有时间渲染初始的 'entering' 状态。
      // 如果没有这个延迟，状态变化太快，浏览器可能会跳过动画直接渲染最终的 'visible' 状态。
      setTimeout(() => {
          if (visibleImages.value.length > 0 && visibleImages.value[0].imgstatus === 'entering') {
              visibleImages.value[0].imgstatus = 'visible';
          }
      }, 300); // 50毫秒的延迟对于人眼是无感的，但足以让渲染引擎准备好动画。
  
  
      // 4. 等待动画结束后（1秒），从数组中移除已“离开”的图片
      setTimeout(() => {
          visibleImages.value = visibleImages.value.filter(img => img.imgstatus !== 'leaving');
          isAnimating.value = false;
      }, 500); // 动画时长
  
  }, 2000);

  // 计算倒计时
  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;
        // 倒计时结束，自动关闭弹窗
        setTimeout(() => {
          close();
        }, 1000);
      } 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;
  }
  if (intervalId) {
      clearInterval(intervalId);
    }
});
</script>

<style lang="scss" scoped>
    .container {
      background: rgba(0, 0, 0, 0.8);
    }
  
    .popup-content {
      max-height: 80vh;
      overflow-y: auto;
    }
  
  //   .price-font {
  //     font-family: 'DIN';
  //   }
  
    
    .carousel-wrapper {
      display: flex;
      overflow: hidden;
      justify-content: flex-end; 
      position: relative;
      // width: calc(88rpx * 3 + 70rpx ); /* 5张图片宽度 + 4个间距 */
      height: 100rpx;
    }
   
  .carousel-item {
      width: 88rpx;
      height: 88rpx;   
      flex-shrink: 0;
      border-radius: 50%;
      // overflow: hidden;
      margin-left: 30rpx;
      // 延长过渡时间至1.2秒，让滑动更从容
      transition: all 1s cubic-bezier(0.2, 1, 0.2, 1); // 缓动曲线增强顺滑感
      transform-style: preserve-3d; // 增强动画稳定性
      
      // 进入动画：从左侧小尺寸渐入
      &.entering {
          transform: scale(0.5); // 轻微左移增强"滑入"感
          opacity: 0;
          transform-origin: left center;
      }
  
      // 可见状态：稳定显示
      &.visible {
          transform: scale(0.99);
          opacity: 1;
      }
  
      // 离开动画：核心优化
      &.leaving {
          // 宽度从88rpx收缩至0（保持顺滑过渡） 
          width: 0;
          // 保留高度避免垂直跳动
          height: 88rpx;
          // 间距同步收缩
          margin-left: -3rpx;
          // 不隐藏透明度，而是通过位移和宽度实现"滑出"
          opacity: 0;
          // 向右轻微位移，增强"滑出"视觉
          transform: scale(0) translateX(20rpx);
          transform-origin: right center;
      }
  }
  
  
    .carousel-border {
        transition: all 0.3s ease-in-out;
            // 进入动画的起始状态
        &.entering {
            opacity: 0;
        }
    
        // 可见状态（进入动画的结束状态）
        &.visible {
            opacity: 1;
        }
        &.leaving {   
            opacity: 0;
            display: none;
        }
        
    }
    .carousel-item.leader-border {
        border: 2rpx solid #FF0000 !important;
    }
    .carousel-item:first-child {
        margin-left: 0;
    }
    
    .carousel-image {
        width: 100%;
        height: 100%;
        display: block;
    }
</style>
