<template>
  <view class='content'>
    <view class='swiper-container'>
      <swiper class='swiper' :interval='1500' :duration='1000' @change='swiperChange'>
        <swiper-item v-for='(item,index) in bannerList' :key='index'>
          <image :src='item' />
        </swiper-item>
      </swiper>
      <view class='indicator'>
        <text>{{ swiperIndex + 1 }}</text>
        <text>/{{ bannerList.length }}</text>
      </view>
    </view>
    <view class='countdown c-flex-row'>
      <view class='super-second-kill'>
        超级\n秒杀
      </view>
      <view class='price c-flex-column' style='flex: 1'>
        <text>{{ groupBuyBean?.payPrice || 0 }}</text>
        <text>￥{{ groupBuyBean?.price || 0 }}</text>
      </view>
      <view class='countdown-time c-flex-column'>
        <view class='c-flex-row'>{{ countdownTime?.days || 0 }}天
          <text class='time'>{{ countdownTime?.hours || '00' }}</text>
          :
          <text class='time'>{{ countdownTime?.minutes || '00' }}</text>
          :
          <text class='time'>{{ countdownTime?.seconds || '00' }}</text>
        </view>
        <text>距离活动结束仅剩</text>
      </view>
    </view>

    <view class='goods-info-view c-flex-column'>
      <view class='c-flex-row'>
        <text class='goods-price accent-text-color'>{{ groupBuyBean?.payPrice || 0 }}</text>
        <text>销量{{ groupBuyBean?.totalNum || 0 }}</text>
      </view>

      <view class='c-flex-row'>
        <text style='flex: 1'>{{ groupBuyBean?.name }}</text>
        <view class='share-button c-flex-column'>
          <image :src='assetsUrl("ic_share.png")'></image>
          <button class='btn' plain open-type='share'>分享</button>
        </view>
      </view>
    </view>

    <view class='goods-sku-view c-flex-column'>
      <view class='c-flex-row' @click.stop='showSkuDialog'>
        <text>选择</text>
        <text>规格 颜色/尺码</text>
        <image :src='assetsUrl("ic_arrow_right_gray.png")' />
        <text>共{{ getStockColorCount }}种颜色可选</text>
      </view>
    </view>

    <view class='recommend-view c-flex-column'>
      <text>浏览此商品的客户还浏览了</text>
      <scroll-view scroll-x>
        <view style='display: inline-block' v-for='(item, index) in recommendList'
              :key='index'>
          <view class='recommend-item c-flex-column'>
            <image :src='item.images' />
            <text>{{ item.goodsName }}</text>
            <text class='goods-price'>{{ item.price }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!--  商品详情图片  -->
    <view class='card-view image-container' v-if='groupBuyBean?.content'>
      <text class='card-view-title'>商品详情</text>
      <image
        v-for='(item,index) in JSON.parse(groupBuyBean?.content).filter((a: any) => a.type === 2).map((b: any) => b.images)'
        :src='item' mode='aspectFill' :key='index' />
    </view>

    <!--  商品详情  -->
    <view class='card-view goods-container'>
      <view class='c-flex-row'>
        <image :src='groupBuyBean?.goods?.images' />
        <view class='c-flex-column'>
          <text class='goods-name'>{{ groupBuyBean?.goods?.name }}</text>
          <text style='color: #a6a6a6'>精选</text>
          <view class='tag-view c-flex-row'>
            <text>团长推荐</text>
            <text>今日必买</text>
          </view>
          <text style='color: #a6a6a6'>不参与会员折扣</text>
          <text style='color: #F32B2B'>¥{{ groupBuyBean?.goods?.payPrice }}</text>
          <text class='bought_count'>已团{{ groupBuyBean?.sendNum }}</text>
        </view>
      </view>
    </view>

    <!--  商品详情优惠券  -->
    <view class='card-view coupon-container'>
      <text class='card-view-title'>赠送优惠券</text>
      <view class='c-flex-column'>
        <coupon-item v-for='(item,index) in groupBuyBean?.couponsList' :key='index' :item='item' />
      </view>
    </view>

    <!--  商品详情跟团记录  -->
    <view class='card-view record-container'>
      <text class='card-view-title'>跟团记录</text>
      <u-list :list='recordList' :border='false' @scrolltolower='loadMore'>
        <u-list-item v-for='(item,index) in recordList' :key='index'>
          <view class='item-view c-flex-row'>
            <image :src='item.memberImage' />
            <view class='c-flex-column' style='flex: 1'>
              <text>{{ item.goodsCode }}</text>
              <text>{{ item.createTime }}</text>
            </view>
            <text>+{{ item.goodsNum }}</text>
          </view>
        </u-list-item>
        <u-loadmore status='loading' />
      </u-list>
    </view>

    <view class='bottom-view c-flex-row'>
      <view class='place-order-button' @click.stop='placeOrder'>跟团购买</view>
    </view>
  </view>
  <sku-dialog ref='skuDialogRef' :flash-price='groupBuyBean?.payPrice || 0' />
</template>

<script lang='ts' setup>
import { assetsUrl } from '@/utils/assets';
import dayjs from 'dayjs';
import { formatTimeWithZeroPad, goPath } from '@/utils';
import SkuDialog from '@/components/sku-dialog.vue';
import CouponItem from './components/coupon-item.vue';

import { getGroupBuyDetail, getGroupBuyRecordList, preOrder } from '@/api/groupbuy';
import { getGoodsList } from '@/api/goods';
import { GoodsBean } from '@/api/goods/types';
import { useUserStore } from '@/store';
import { GroupBuyBean, RecordBean } from '@/api/groupbuy/types';

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

const skuDialogRef = ref();
const groupBuyBean = ref<GroupBuyBean>();
const recommendList = ref<GoodsBean[]>();

const bannerList = ref([]);
const swiperIndex = ref(0);

let interval: number;
const countdownTime = ref<{
  days: string,
  hours: string,
  minutes: string,
  seconds: string
}>();

const recordList = ref<RecordBean[]>([]);
const currentPageNum = ref(1);

onLoad(async (e: any) => {
  groupBuyBean.value = await getGroupBuyDetail(e.id);
  groupBuyBean.value.goods.price = groupBuyBean.value.price;
  bannerList.value = JSON.parse(groupBuyBean.value.content).filter((item: any) => item.type === 2).map((item: any) => item.images);
  countdown();
  await fetchRecommendList();
  await fetchBuyRecordList();
});

onUnload(() => {
  if(interval) {
    clearInterval(interval);
  }
});

const getStockColorCount = computed(() => {
  const list = Array.from(new Set(groupBuyBean.value?.goods?.stocks?.map(item => item.colorName)))
    .map(colorName => groupBuyBean.value?.goods?.stocks?.find(item => item.colorName === colorName)!);
  return list.length;
});

const fetchRecommendList = async () => {
  const { rows } = await getGoodsList({
    page: {
      page: 1,
      pageSize: 20,
      bean: {
        keyword: '',
        typeIds: ['1724629185362591745']
      }
    }
  });
  recommendList.value = rows;
};

const fetchBuyRecordList = async (refresh: boolean = true) => {
  if(!refresh) {
    currentPageNum.value += 1;
  }
  const { list } = await getGroupBuyRecordList(groupBuyBean?.value?.id || '', currentPageNum.value, 20);
  recordList.value = recordList.value.concat(list);
};

const loadMore = () => {
  fetchBuyRecordList(false);
};

const swiperChange = (e: any) => {
  swiperIndex.value = e.detail.current;
};

const countdown = () => {
  interval = setInterval(() => {
    if(groupBuyBean.value?.endDate) {
      let now = new Date();
      let end = dayjs(groupBuyBean.value?.endDate).toDate().getTime();
      let remaining = Math.floor((end - now.getTime()) / 1000);
      if(remaining > 0) {
        countdownTime.value = {
          days: formatTimeWithZeroPad(Math.floor(remaining / 60 / 60 / 24)),
          hours: formatTimeWithZeroPad(Math.floor(remaining / 60 / 60 % 24)),
          minutes: formatTimeWithZeroPad(Math.floor(remaining / 60 % 60)),
          seconds: formatTimeWithZeroPad(Math.floor(remaining % 60))
        };
      } else {
        clearInterval(interval);
      }
    }
  }, 1000);
};

const showSkuDialog = (fn: Function) => {
  skuDialogRef.value.show(groupBuyBean?.value?.goods?.goodsId, fn);
};

const placeOrder = async () => {

  async function create(bean: GoodsBean) {
    const params = {
      'colorId': bean.checkedStock.colorId,
      'sizeId': bean.checkedStock.sizeId,
      'goodsId': groupBuyBean?.value?.goods.goodsId,
      'groupId': groupBuyBean?.value?.id,
      'memberId': userInfo.value.id,
      'shareId': '123456'
    };

    const result = await preOrder(params);
    goPath(`/pages/common/groupbuy/order?orderBean=${encodeURIComponent(JSON.stringify(result))}`);
  }

  showSkuDialog((e: GoodsBean) => {
    create(e);
  });
};
</script>

<style lang='scss' scoped>
.content {
  padding-bottom: 200rpx;
}

.swiper-container {
  position: relative;

  .swiper {
    display: flex;
    width: 100%;
    height: 750rpx;

    image {
      width: 100%;
      height: 750rpx;
    }
  }

  .indicator {
    background: rgba(1, 1, 1, 0.5);
    border-radius: 45rpx;
    font-weight: 400;
    font-size: 24rpx;
    color: #FFFFFF;
    position: absolute;
    right: 20rpx;
    bottom: 20rpx;
    padding: 5rpx 25rpx;

    text:nth-of-type(1) {
      font-size: 30rpx;
    }

    text:nth-of-type(2) {
      font-size: 24rpx;
    }
  }
}

.countdown {
  display: flex;
  height: 130rpx;
  position: relative;
  padding: 15rpx 30rpx;
  background: #F32B2B;
  //background-image: url('../../../static/images/bg_groupbuy_countdown.png');
  background-size: 100% 100%;

  .super-second-kill {
    display: flex;
    width: 100rpx;
    height: 100rpx;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 20rpx;
    border: 1rpx solid #FFFFFF;
    font-weight: 400;
    font-size: 36rpx;
    text-align: center;
    color: #FFFFFF;
    margin-right: 23rpx;
  }

  .price {
    color: #FFFFFF;

    text:nth-of-type(1) {
      font-weight: bold;
      font-size: 55rpx;
    }

    text:nth-of-type(1):before {
      content: '¥  ';
      font-size: 30rpx;
    }

    text:nth-of-type(2) {
      font-weight: 400;
      font-size: 30rpx;
      text-decoration-line: line-through;
    }
  }

  .countdown-time {
    color: #FFFFFF;
    align-items: center;

    view:nth-of-type(1) {
      margin-bottom: 20rpx;
      align-self: flex-end;
    }

    .time {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40rpx;
      height: 40rpx;
      margin-left: 12rpx;
      margin-right: 12rpx;
      background: #FFFFFF;
      border-radius: 7rpx;
      color: #F32B2B;
    }

    .time:nth-of-type(1) {
      margin-left: 18rpx;
    }

    .time:nth-of-type(3) {
      margin-right: 0;
    }

    text:not(.time):nth-of-type(1) {
      align-self: flex-end;
    }
  }
}

.goods-info-view {
  background: #FFFFFF;
  padding: 20rpx 30rpx;

  view:nth-of-type(1) {
    text:nth-of-type(1) {
      display: flex;
      font-size: 40rpx;
      text-align: center;
      align-items: flex-end;
      flex: 1;
    }

    .goods-price:before {
      content: "¥";
      font-size: 30rpx;
      margin-bottom: 5rpx;
      margin-right: 5rpx;
    }

    text:nth-of-type(2) {
      font-size: 26rpx;
      font-weight: 400;
      color: #999999;
    }
  }

  view:nth-of-type(2) {
    text {
      font-weight: bold;
      font-size: 32rpx;
      color: #333333;
      margin-right: 10rpx;
    }

    .share-button {
      align-items: center;

      image {
        width: 36rpx;
        height: 32rpx;
      }

      .btn {
        background: #00000000;
        font-size: 24rpx;
        color: #636566;
        white-space: nowrap;
        padding: 0;
        border: none !important;
      }
    }
  }
}

.goods-sku-view {
  background: #FFFFFF;
  padding: 20rpx 30rpx;
  margin-top: 20rpx;

  view:nth-of-type(n+1) {
    position: relative;
    align-items: center;
    height: 80rpx;

    text:nth-of-type(1) {
      width: 100rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: #999999;
    }

    text:nth-of-type(2) {
      font-weight: 400;
      font-size: 28rpx;
      color: #333333;
      flex: 1;
    }

    image {
      width: 13rpx;
      height: 24rpx;
    }

    text:nth-of-type(3) {
      font-weight: 400;
      font-size: 24rpx;
      color: #999999;
      position: absolute;
      top: 50rpx;
      left: 100rpx;
    }
  }

  view:nth-of-type(1) {
    align-items: flex-start;
    //padding-top: 20rpx;
  }
}

.recommend-view {
  background: #FFFFFF;
  padding: 20rpx 30rpx;
  margin-top: 20rpx;

  text {
    font-weight: bold;
    font-size: 28rpx;
    color: #333333;
  }

  scroll-view {
    width: 100%;
    margin-top: 20rpx;
    white-space: nowrap;
    height: 300rpx;
  }

  .recommend-item {
    margin-right: 20rpx;

    image {
      width: 200rpx;
      height: 200rpx;
      border-radius: 10rpx;
    }

    text:nth-of-type(1) {
      font-weight: bold;
      font-size: 28rpx;
      color: #333333;
      margin-top: 20rpx;
    }

    text:nth-of-type(2) {
      font-weight: bold;
      font-size: 28rpx;
      color: #F32B2B;
    }

    .goods-price:before {
      content: "¥";
      font-size: 28rpx;
    }
  }
}

.bottom-view {
  background: #FFFFFF;
  padding: 20rpx 30rpx 78rpx 30rpx;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;

  .place-order-button {
    display: flex;
    flex: 1;
    font-weight: bold;
    width: 100%;
    font-size: 30rpx;
    height: 80rpx;
    align-items: center;
    justify-content: center;
    background: #F32B2B;
    color: #FFFFFF;
    border-radius: 40rpx;
  }
}

.card-view {
  display: flex;
  flex-direction: column;
  background: #FFFFFF;
  margin-top: 20rpx;

  .card-view-title {
    margin: 20rpx 30rpx;
    font-weight: bold;
    font-size: 30rpx;
    color: #333333;
  }
}

.image-container {
  image {
    width: 100%;
  }
}

.goods-container {
  padding: 30rpx;
  position: relative;

  image {
    width: 200rpx;
    height: 200rpx;
    margin-right: 15rpx;
    border-radius: 8rpx;
  }

  .c-flex-column {
    justify-content: space-between;
    position: relative;
    flex: 1;

    text {
      margin-top: 5rpx;
    }

    .goods-name {
      font-size: 30rpx;
      color: #333333;
    }

    .tag-view {
      text {
        background: #fff0ee;
        margin-right: 10rpx;
        padding: 5rpx 10rpx;
        color: #fc6e51;
        border-radius: 8rpx;
      }
    }

    .bought_count {
      position: absolute;
      bottom: 0;
      right: 0;
      color: #fc6e51;
      font-size: 20rpx;
    }
  }
}

.record-container {

  .item-view {
    margin: 10rpx 30rpx;

    image {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
    }

    .c-flex-column {
      margin: 0 15rpx;

      text:nth-of-type(1) {
        font-size: 20rpx;
        color: #333333;
      }

      text:nth-of-type(2) {
        font-size: 15rpx;
        color: #666666;
        margin-top: 10rpx;
      }
    }

    text:nth-of-type(1) {
      color: #F32B2B;
    }
  }
}
</style>
