<template>
  <view>
    <view class="header">
      <view class="searchBox" :style="{ height: localHeight + 'px', paddingTop: top + 'px' }">
        <view class="searchBox_left" @click="back">
          <u-icon name="arrow-left" size="20px" color="#000"></u-icon>
        </view>
      </view>
    </view>
    <view class="swiper">
      <view class="tag2 tag-img" v-if="
        currentGG.is_same_day
      ">当日达</view>
      <swiper :indicator-dots="false" :autoplay="true" :interval="3000" :duration="1000" @change="changeIndex">
        <swiper-item v-for="(item, index) in currentGG.goods_carousel" :key="index">
          <image :src="picUrl + item"></image>
        </swiper-item>
      </swiper>

      <view class="NumDot" v-if="currentGG.goods_carousel && currentGG.goods_carousel.length > 0">
        {{ currentIndex }} /{{ currentGG.goods_carousel.length }}
      </view>
    </view>

    <view class="box_15">
      <view class="section_2">
        <view class="text-wrapper_4">
          <text lines="1" class="text_31">￥</text>
          <text lines="1" class="text_30">{{ currentGG.group_buy_price }}</text>
          <text lines="1" class="text_33">/{{ currentGG.goods_unit }}</text>
        </view>
        <text lines="1" decode="true" class="text_32">单买价&nbsp;￥{{ currentGG.sales_price }}/{{
          currentGG.goods_unit }}</text>
      </view>
      <view class="section_3">
        <text lines="1" class="text_34">距结束还剩</text>
        <view class="box_16">
          <view class="timeBox">
            <view class="dayTimeBox">{{ endTheCountdownDay }}天</view>
            <view class="timeBox">
              <view class="time">{{ endTheCountdownHour }}</view>
              <view>：</view>
            </view>
            <view class="timeBox">
              <view class="time">{{ endTheCountdownMinute }}</view>
              <view>：</view>
            </view>
            <view class="timeBox">
              <view class="time">{{ endTheCountdownSecond }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="Money">
      <!-- <view class="MoneyMark">￥</view>
      {{ currentGG.group_buy_price }}
      <view class="MoneyUnit">/{{ currentGG.goods_unit }}</view> -->
      <view class="Tit">
        <view class="tag tag-text" v-if="
          currentGG.is_same_day
        ">当日达</view>
        {{ currentGG.goods_name }}
      </view>
      <view class="Msg">{{ currentGG.commodity_brief }}</view>
      <view class="num">已售{{ soldOutNum }}</view>
       <!-- | 剩余{{ currentGG.total_stock }} -->
    </view>

    <!-- 规格 -->
    <!-- @click="changeGG2(item, index)" :class="index == currentGGIndex ? 'active' : ''"> -->
    <view class="GGBox">
      <view class="GG_left">
        <view class="GG_Item" v-for="(item, index) in info.commodity_goods_info_list" :key="item.id"
          @click="changeGG(item, index)" :class="index == currentGGIndex ? 'active' : ''">
          {{ item.goods_spec }} / {{ item.goods_unit }}
        </view>
      </view>
      <view class="GG_rigth" v-if="info.commodity_goods_info_list && info.commodity_goods_info_list.length > 0">
        共{{ info.commodity_goods_info_list.length }}款
      </view>
    </view>

    <view class="fenge"></view>
    <view class="specification">
      <view class="spe_Item">
        <view class="spe_ItemCon" @click="copys(currentGG.goods_no)">
          {{ currentGG.goods_no }}
          <image src="https://static.hshuishang.com/property-img-file/shop_copy.png"></image>
        </view>
        <view class="spe_ItemTit">货号</view>
      </view>
      <view class="shu"></view>
      <view class="spe_Item">
        <view class="spe_ItemCon">{{ currentGG.goods_spec }}</view>
        <view class="spe_ItemTit">规格说明</view>
      </view>
      <view class="shu"></view>
      <view class="spe_Item">
        <view class="spe_ItemCon">{{ currentGG.goods_unit }}</view>
        <view class="spe_ItemTit">售卖单位</view>
      </view>
    </view>
    <view class="fenge"></view>

    <!-- 已购买区域 -->
    <!-- <view>
      <view class="purchase-area">
        <view class="purchase-count">{{ totalCount }}人已购买</view>
        <view class="view-more" @click="showPurchaseRecords">查看更多 &gt;</view>
      </view>
      <view class="record-list">
        <view class="record-item" v-for="(record, index) in purchaseRecords" :key="index">
          <view class="record-user">
            <image :src="record.avatar" class="user-avatar"></image>
            <view class="user-name">{{ record.nick_name }}</view>
          </view>
          <view class="record-amount">
            {{ formatDate(record.buy_time) }}买了{{ record.count }}件
          </view>
          <view class="record-time">
            <button class="buy-btn" @click="goSubmit">去下单</button>
          </view>
        </view>
      </view>
    </view> -->

    <view class="fenge"></view>

    <h3 class="GoodsMsg" v-if="currentGG.goods_detail_pic && currentGG.goods_detail_pic.length > 0">商品详情</h3>

    <!-- <view class="Msg_Item">
      <view class="Msg_ItemTit">货号</view>
      <view class="Msg_ItemCon" @click="copys(currentGG.goods_no)">
        {{ currentGG.goods_no }}
        <image src="https://static.hshuishang.com/property-img-file/shop_copy.png"></image>
      </view>
    </view>
    <view class="Msg_Item">
      <view class="Msg_ItemTit">规格说明</view>
      <view class="Msg_ItemCon">{{ currentGG.goods_spec }}</view>
    </view>
    <view class="Msg_Item">
      <view class="Msg_ItemTit">售卖单位</view>
      <view class="Msg_ItemCon">{{ currentGG.goods_unit }}</view>
    </view> -->

    <view class="GoosMsg">
      <image v-for="item in currentGG.goods_detail_pic" :src="picUrl + item" :key="item" mode="widthFix"></image>
    </view>

    <view class="priceInfo">
      <h3 class="priceInfo-title">价格说明</h3>
      <view class="priceInfo-content">
        <view>
          <text class="priceInfo-content-title">划线价格：</text>
          指商品的厂商指导价、正品零售价、市面常见价或该商品曾经展示过的销售价等，并非原价。仅供参考。
        </view>
        <view>
          <text class="priceInfo-content-title">未划线价格：</text>
          指商品的实时价格，不因表述的差异改变性质，具体成交价格根据商品参加活动，或使用优惠券等发生变化最终以订单结算价格为准。
        </view>
      </view>
    </view>

    <!-- 底部购物车 -->
    <view class="Car">
      <view class="car_left">
        <view class="share" @click="share">
          <image src="https://static.hshuishang.com/property-img-file/shop_share.png"
            mode="widthFix"></image>
          分享
        </view>
        <view class="cars" @click="car">
          <u-badge numberType="limit" :type="type" max="99" :value="carNum"></u-badge>
          <image src="https://static.hshuishang.com/property-img-file/shop_car.png"
            mode="widthFix"></image>
          购物车
        </view>
      </view>

      <view class="car_right2" v-if="info.commodity_goods_info_list[currentGGIndex].total_stock < 1">
        已售罄
      </view>

      <view class="car_right_box">
        <view class="car_right" v-if="
          info.commodity_goods_info_list[currentGGIndex].total_stock > 0 &&
          (!info.commodity_goods_info_list[currentGGIndex].cart_count ||
            info.commodity_goods_info_list[currentGGIndex].cart_count.count == 0)
        " @click="addCar">
          加入购物车
        </view>

        <view class="car_right" @click="changeCar" v-if="
          info.commodity_goods_info_list[currentGGIndex].cart_count.count > 0
          && info.commodity_goods_info_list[currentGGIndex].total_stock > 0
        ">
          加入购物车
        </view>

        <view class="seckill" v-if="info.commodity_goods_info_list[currentGGIndex].total_stock != 0"
          @click="showSeckillPopup">
          立即秒杀
        </view>
      </view>
    </view>

    <!-- 分享 -->
    <view class="shadow" @click.stop="changeShadow" v-if="boxshadow1">
      <view class="shadowBox1">
        <view class="shadowBox1Item" @click="shareFriend">
          <button class="shadowBox1Item_btn" open-type="share" bindtap="onShareButtonClick">
            <image src="https://static.hshuishang.com/property-img-file/shop_WX.png"
              mode="aspectFill"></image>
            微信好友
          </button>
        </view>
        <view class="shadowBox1Item" @click="openSave">
          <button class="shadowBox1Item_btn">
            <image src="https://static.hshuishang.com/property-img-file/shop_saveImg.png"
              mode="aspectFill"></image>
            生成海报
          </button>
        </view>
      </view>
    </view>
    <!-- 海报 -->
    <view class="shadow" @click="changeShadow2" v-if="boxshadow2">
      <view class="shadowBox2">
        <view class="shadowBox_img">
          <view class="boxshadow_tit">今日商品推荐</view>
          <view class="boxshadow_img">
            <image src="https://static.hshuishang.com/property-img-file/shop_share_img.png">
            </image>
          </view>
          <view class="line"></view>
          <view class="shadowBoxInfo">
            <view class="shadowboxInfo_left">二维码</view>
            <view class="shadowboxInfo_right">
              <view class="shadowboxInfo_right_1">正鲜生</view>
              <view class="shadowboxInfo_right_2">
                长按识别小程序 <br />
                数量有限马上抢购
              </view>
            </view>
          </view>
        </view>
        <view class="shadowBox_btn" @click.stop="saveImg">保存海报</view>
      </view>
    </view>

    <!-- 评价 查看详情 -->
    <!-- <u-popup :show="show" round="20rpx" mode="bottom" @close="close" @open="open" :z-index="10070">
      <view class="reviews-section">
        <view class="popup-header">
          <h3 class="popup-header-h3">评价</h3>
          <view class="popup-header-view" @click="close">取消</view>
        </view>
        <view class="temp">
          <view class="temp1">
            <img class="temp_img" src="https://static.hshuishang.com/pingjia.png" />
            为你展示真实评价
          </view>
          <view class="temp1" @click="showSizePopup">
            款式
            <img class="temp_img1" src="https://static.hshuishang.com/kuanshi.png" />
          </view>
        </view>
        <view class="reviews-list" v-if="comments.length > 0">
          <view class="review-item" v-for="(comment, index) in comments" :key="index">
            <view class="review-user">
              <image :src="comment.avatar" class="user-avatar"></image>
              <view class="user-info">
                <view class="user-name">{{ comment.username }}</view>
              </view>
              <view class="review-time">{{ comment.time }}</view>
            </view>
            <view class="user-purchase">已购 {{ comment.product }}</view>
            <view class="review-content">{{ comment.content }}</view>
            <view class="review-images" v-if="comment.images.length > 0">
              <image :src="img" class="review-img" v-for="(img, idx) in comment.images" :key="idx"></image>
            </view>
          </view>
        </view>
      </view>
    </u-popup> -->

    <!-- 团购记录弹窗 -->
    <u-popup :show="showPurchase" round="20rpx" mode="bottom" @close="closePurchase">
      <view class="purchase-popup">
        <view class="popup-header">
          <h3 class="popup-header-h3">团购记录</h3>
          <view class="popup-header-view" @click="closePurchase">取消</view>
        </view>
        <view class="purchase-records">
          <view class="record-header">
            <view class="record-header-item">买家</view>
            <view class="record-header-item">数量</view>
            <view class="record-header-item">购买时间</view>
          </view>
          <view class="record-list">
            <view class="record-item" v-for="(record, index) in purchaseRecords" :key="index">
              <view class="record-user">
                <image :src="record.avatar" class="user-avatar"></image>
                <view class="user-name">{{ record.nick_name }}</view>
              </view>
              <view class="record-amount">+{{ record.count }}</view>
              <view class="record-time">{{ record.buy_time }}</view>
            </view>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 选择款式 -->
    <u-popup :show="showSize" round="20rpx" mode="bottom" @close="closeSize">
      <view class="popup-header">
        <h3 class="popup-header-h3">选择款式</h3>
        <view class="popup-header-view" @click="closeSize">取消</view>
      </view>
      <view class="itemSize_top">
        <image :src="changeImg" class="itemSize-img"></image>
        <view class="itemSize_info">
          <view class="itemSize_name">{{ changeName }}</view>
          <view class="itemSize_price">￥{{ changePrice }}/{{ goodsUnit }}</view>
        </view>
      </view>
      <view class="itemSize" v-for="(item, index) in info.commodity_goods_info_list" :key="item.id"
        @click="changeGG(item, index)" :class="index == currentGGIndex ? 'itemSize_active' : ''">
        {{ item.goods_name }} {{ item.goods_spec }} / {{ item.goods_unit }}
      </view>
    </u-popup>

    <!-- 立即秒杀 -->
    <u-popup :show="showSeckill" round="20rpx" mode="bottom" @close="closeSeckill">
      <view class="popup-header">
        <h3 class="popup-header-h3">立即秒杀</h3>
        <view class="popup-header-view" @click="closeSeckill">取消</view>
      </view>
      <view class="address-section">
        <view @click="editAddress()">
          <view v-if="defZTAddress.length > 0">
            <view v-for="(adItem, adIndex) in defZTAddress" :key="adIndex">
              <view class="address-info" v-if="adItem.id == supplierId">
                <view class="address-main">
                  <view class="address-name-phone">
                    <text class="name">{{ adItem.name }}</text>
                    <text class="phone">{{ adItem.phone }}</text>
                  </view>
                  <view class="address-detail">
                    {{ adItem.address }}
                    <view class="copy-icon" @click.stop="copyZTAddress" />
                  </view>
                </view>
                <view class="address-arrow"><u-icon name="arrow-right" size="25"></u-icon>
                </view>
              </view>
            </view>
            <view class="address-info" v-if="!defZTAddress.some(adItem => adItem.id == supplierId)">
              <view class="address-main">
                <view class="address-name-phone">
                  <text class="name">请选择自提点</text>
                </view>
              </view>
              <view class="address-arrow"><u-icon name="arrow-right" size="25"></u-icon>
              </view>
            </view>
          </view>
          <view class="address-info" v-else>
            <view class="address-main">
              <view class="address-name-phone">
                <text class="name">请选择自提点</text>
              </view>
            </view>
            <view class="address-arrow"><u-icon name="arrow-right" size="25"></u-icon></view>
          </view>
        </view>
      </view>
      <view class="itemSize_top">
        <image :src="changeImg" class="itemSize-img"></image>
        <view class="itemSize_info">
          <view class="itemSize_name">{{ changeName }}</view>
          <view class="itemSize_price">￥{{ changePrice }}/{{ goodsUnit }}</view>
        </view>
        <view class="quantity-control">
          <view class="decrease-btn" @tap.stop="decreaseQuantity()">-</view>
          <view class="quantity">{{ changeCount }}</view>
          <view class="increase-btn" @tap.stop="increaseQuantity()">+</view>
        </view>
      </view>
      <view class="itemSize" v-for="(item, index) in info.commodity_goods_info_list" :key="item.id"
        @click="changeGG(item, index)" :class="index == currentGGIndex ? 'itemSize_active' : ''">
        {{ item.goods_name }} {{ item.goods_spec }} / {{ item.goods_unit }}
      </view>
      <view class="fenge"></view>
      <!-- 支付方式 -->
      <view class="payment-section">
        <view class="payment-item" @click="selectPayment('wechat')">
          <view class="payment-icon">
            <image src="https://static.hshuishang.com/property-img-file/com_wechat.png"
              mode="aspectFit"></image>
          </view>
          <view class="payment-content">
            <view class="payment-name">微信支付</view>
          </view>
          <view class="payment-select" v-if="selectedPayment === 'wechat'">
            <image src="https://static.hshuishang.com/property-img-file/com_check2.png"
              mode="aspectFit" style="width: 30rpx; height: 30rpx;"></image>
          </view>
          <view class="payment-select" v-else>
            <image src="https://static.hshuishang.com/property-img-file/com_check1.png"
              mode="aspectFit" style="width: 30rpx; height: 30rpx;"></image>
          </view>
        </view>
      </view>
      <view class="pay-button" @click="submitPayment">立即支付</view>
    </u-popup>

    <!-- 弹窗 - 支付成功 -->
    <view class="pay-success-shadow" @click="changeShadow2" v-if="boxshadow5">
      <view class="pay-success-container">
        <view class="pay-success-content">
          <view class="pay-success-title">
            <image src="https://static.hshuishang.com/af_√.png" class="success-icon">
            </image>
            已支付成功
          </view>
          <view class="verify-code-section">
            <view v-if="verifyCode">核销码：{{ verifyCode }}</view>
          </view>
          <view class="welfare-container">
            <view class="welfare-header">
              <view class="welfare-title">
                <image
                  src="https://static.hshuishang.com/property-img-file/groupPurchase/welfare.png">
                </image>
                下单福利
              </view>
              <view class="welfare-action">已获得</view>
            </view>
            <view class="welfare-box">
              <view class="welfare-item welfare-item-points">
                <view class="welfare-item-top">
                  <image src="https://static.hshuishang.com/activity_fen.png" mode="aspectFit">
                  </image>
                  <view>石榴分</view>
                </view>
                <view>
                  {{ slFen }}
                </view>
                <view class="welfare-item-bottom">
                  可抵扣 ￥{{ slFen }}
                </view>
              </view>
              <view class="welfare-item welfare-item-coupon">
                <view class="welfare-item-top">
                  <image src="https://static.hshuishang.com/activity_zi.png" mode="aspectFit">
                  </image>
                  <view>石榴籽</view>
                </view>
                <view>
                  {{ slZi }}
                </view>
                <view class="welfare-item-bottom">
                  可抵扣 ￥{{ slZi }}
                </view>
              </view>
              <view class="welfare-item welfare-item-beans">
                <view class="welfare-item-top">
                  <image src="https://static.hshuishang.com/activity_jin.png" mode="aspectFit" />
                  <view>石榴金</view>
                </view>
                <view>
                  {{ slJin }}
                </view>
                <view class="welfare-item-bottom">
                  可抵扣 ￥{{ slJin }}
                </view>
              </view>
            </view>
            <view class="bottom2">
              <view class="invite-section">
                <view class="invite-text">
                  <view class="invite-line1"></view>
                  赶快邀请好友来下单吧
                  <view class="invite-line2"></view>
                </view>
                <view @click.stop="changeShadow2">
                  <view class="share-buttons">
                    <button class="share-btn-wechat" open-type="share" bindtap="onShareButtonClick" />
                    <view class="share-item">
                      <image src="https://static.hshuishang.com/property-img-file/shop_WX.png"
                        mode="aspectFill"></image>
                      微信好友
                    </view>
                    <button class="share-btn-miniprogram" open-type="share" bindtap="onShareButtonClick" />
                    <view class="share-item" @click="shareFriend">
                      <image src="https://static.hshuishang.com/property-img-file/shop_WX.png"
                        mode="aspectFill"></image>
                      小程序链接
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { apiArr } from "../../../api/shop";
import { apiArr as apiArr2 } from "../../../api/groupPurchase";
import { picUrl, menuButtonInfo, request, NavgateTo } from "../../../utils";
export default {
  data() {
    return {
      itemObj: {},

      picUrl,
      top: "",
      localHeight: "",
      carNum: "",
      prevCarNum: "",
      currentNum: "0", //当前商品的数量
      type: "error",
      boxshadow1: false,
      boxshadow2: false,
      boxshadow5: false,
      verifyCode: '',
      slFen: 0,
      slZi: 0,
      slJin: 0,
      id: "",
      groupById: "",
      info: "",
      currentIndex: "1", //当前轮播图

      currentGG: "", //当前选中规格
      currentGGIndex: "", //当前规格index

      carOrderList: [],
      // 新增评论数据
      showReviewPopup: false,
      soldOutNum: 0,

      show: false,
      showSize: false,
      showSeckill: false,
      showPurchase: false,
      purchaseRecords: [],
      totalCount: 0,
      changeImg: "",
      changeName: "",
      changePrice: "",
      goodsUnit: "",

      endTime: "",
      endTheCountdownDay: '',
      endTheCountdownHour: '',
      endTheCountdownMinute: '',
      endTheCountdownSecond: '',
      timer: null, // 定时器ID
      defZTAddress: [],
      selectedPayment: 'wechat', // 默认选择微信支付
      changeCount: 0,
    };
  },
  methods: {
    //获取自提点
    getZTAddress() {
      setTimeout(() => {
        let changeAddress = uni.getStorageSync('changeZTAddress')
        if (changeAddress) {
          this.defZTAddress = changeAddress
        }
      }, 100)
    },
    selectPayment(payment) {
      this.selectedPayment = payment;
    },
    // 增加数量
    increaseQuantity() {
      this.changeCount++;
    },
    // 减少数量
    decreaseQuantity() {
      if (this.changeCount > 0) {
        this.changeCount--;
      }
    },
    // 提交支付
    submitPayment() {
      // 检查是否选择了自提点
      if (this.defZTAddress.length == 0) {
        uni.showToast({
          title: '请选择自提点',
          icon: 'none'
        })
        return
      }

      // 检查商品数量
      if (this.changeCount <= 0) {
        uni.showToast({
          title: '请选择购买数量',
          icon: 'none'
        })
        return
      }

      // 获取当前时间和活动时间，检查是否在团购活动时间内
      const currentTime = new Date().getTime();
      const activityInfo = this.currentGG.group_buy_activity_info;
      let isGroupBuyValid = false;

      if (activityInfo) {
        const startTime = new Date(activityInfo.start_time).getTime();
        const endTime = new Date(activityInfo.end_time).getTime();
        isGroupBuyValid = currentTime >= startTime && currentTime <= endTime;
      }

      // 根据平台设置不同的trans_type值
      // 小程序: 71, App: 51
      const systemInfo = uni.getSystemInfoSync();
      let trans_type = 51; // 默认App环境

      // 运行时判断是否为小程序环境
      if (systemInfo.platform === 'devtools' || systemInfo.platform === 'unknown') {
        trans_type = 71; // 开发工具或未知环境默认为小程序
      }

      // 条件编译：针对不同平台设置不同值
      // #ifdef MP
      trans_type = 71; // 所有小程序平台
      // #endif

      // #ifdef APP-PLUS
      trans_type = 51; // App平台
      // #endif

      // 创建订单参数
      const params = {
        user_id: uni.getStorageSync('userId'),
        order_cate: isGroupBuyValid ? 2 : 1, // 2表示团购订单
        goods_list: [{
          supplier_id: this.info.supplier_id,
          supplier_name: this.info.merchant_info.merchant_name || '',
          is_same_day: this.currentGG.is_same_day || false,
          receiving_name: this.defZTAddress[0].name || '',
          receiving_phone: this.defZTAddress[0].phone || '',
          receiving_address: this.defZTAddress[0].address || '',
          merchant_id: this.defZTAddress[0].address_id,
          group_buy_activity_id: this.currentGG.group_buy_activity_id,
          goods_and_count: [{
            goods_id: this.currentGG.id,
            count: this.changeCount,
            price: isGroupBuyValid ? this.currentGG.group_buy_price : this.currentGG.sales_price
          }]
        }]
      }

      // 调用创建订单接口
      request(apiArr.createOrder, "POST", params).then(resVal => {
        // 调用预下单接口
        const preOrderParam = {
          order_id: resVal.order_id,
          user_id: uni.getStorageSync('userId'),
          trans_type: trans_type
        }

        request(apiArr.mergePreorder, "POST", preOrderParam).then(res => {
          // 处理预下单响应
          this.handleMergePreorderResponse(res, resVal.order_id);
        })
      }).catch(err => {
        console.error('创建订单失败:', err);
        uni.showToast({
          title: '创建订单失败，请重试',
          icon: 'none'
        })
      })
    },

    // 处理mergePreorder接口的响应
    handleMergePreorderResponse(res, orderId) {
      if (res && res.timeStamp && res.nonceStr && res.package && res.signType && res.paySign) {
        // 调用微信支付
        uni.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign,
          success: (payRes) => {
            // 支付成功后查询订单
            const params = {
              order_id: orderId,
              from: 2, // 2表示团购订单
              group_buy_activity_id: this.currentGG.group_buy_activity_id,
              adver_id: ''
            }
            request(apiArr.queryOrder, "POST", params).then(res => {
              // 设置核销码和福利数据
              this.verifyCode = res.verification_code;
              this.slFen = res.shiliu_fen || 0;
              this.slZi = res.shiliu_zi || 0;
              this.slJin = res.shiliu_money || 0;

              // 显示支付成功弹窗
              this.boxshadow5 = true;

              // 关闭支付弹窗
              this.closeSeckill();
            })
          },
          fail: (payErr) => {
            uni.showToast({
              title: payErr.errMsg == 'requestPayment:fail cancel' ? '已取消支付' : '支付失败',
              icon: 'none'
            })
            const params = {
              order_ids: orderId,
            }
            request(apiArr.cancelPay, "POST", params).then(res => {
              // 取消支付后的处理
            })
          },
          complete: () => {
            // 支付完成后的回调，无论成功失败都会执行
          }
        })
      } else {
        console.error("获取支付参数失败，缺少必要参数")
        uni.showToast({
          title: '获取支付信息失败',
          icon: 'none'
        })
      }
    },
    // 显示团购记录
    showPurchaseRecords() {
      if (this.purchaseRecords.length > 0) {
        this.showPurchase = true;
      } else {
        uni.showToast({
          title: '没有更多数据',
          icon: 'none'
        })

      }
    },

    // 关闭团购记录
    closePurchase() {
      this.showPurchase = false;
    },

    // 关闭支付成功弹窗
    changeShadow2() {
      this.boxshadow5 = false;
    },

    // 分享给微信好友
    shareFriend() {
      this.boxshadow5 = false; // 关闭分享弹窗

      // 调用分享API
      if (typeof uni.share !== 'undefined') {
        uni.share({
          provider: 'weixin',
          scene: 'WXSceneSession',
          type: 0,
          title: this.currentGG.goods_name || '商品分享',
          summary: this.currentGG.commodity_brief || '快来看看这款商品吧',
          href: `${window.location.origin}/pages/goodsDetail/index?id=${this.id}`,
          imageUrl: this.picUrl + (this.currentGG.goods_carousel && this.currentGG.goods_carousel[0] || ''),
          success: () => {
            uni.showToast({
              title: '分享成功',
              icon: 'success',
              duration: 2000
            });
          },
          fail: (err) => {
            console.error('分享失败', err);
          }
        });
      }
    },

    //去下单
    goSubmit() {
      NavgateTo('/packages/shop/groupPurchaseSubmit/index')
    },

    changeIndex(e) {
      this.currentIndex = e.detail.current + 1;
    },

    back() {
      uni.navigateBack({
        delta: 1,
      });
    },
    // 分享给微信好友方法 - 触发分享给好友的聊天框
    shareFriend() {
      this.boxshadow1 = false; // 关闭分享弹窗

      // 获取当前商品的分享信息
      const shareInfo = {
        title: this.currentGG.goods_name || '商品分享', // 分享标题
        desc: this.currentGG.commodity_brief || '快来看看这款商品吧', // 分享描述
        link: `${window.location.origin}/pages/goodsDetail/index?id=${this.id}`, // 商品详情页链接
        imageUrl: this.picUrl + (this.currentGG.goods_carousel && this.currentGG.goods_carousel[0] || '') // 分享图片
      };

      // 判断环境是否支持微信分享
      if (typeof WeixinJSBridge === 'undefined') {
        // 尝试使用uni的分享API作为备选方案
        if (typeof uni.share !== 'undefined') {
          uni.share({
            provider: 'weixin',
            scene: 'WXSceneSession',
            type: 0,
            title: shareInfo.title,
            summary: shareInfo.desc,
            href: shareInfo.link,
            imageUrl: shareInfo.imageUrl,
            success: () => {
              uni.showToast({
                title: '分享成功',
                icon: 'success',
                duration: 2000
              });
            },
            fail: (err) => {
              console.error('分享失败', err);
              uni.showToast({
                title: '分享失败，请重试',
                icon: 'none',
                duration: 2000
              });
            }
          });
        } else {
          uni.showToast({
            title: '请在微信客户端打开',
            icon: 'none'
          });
        }
        return;
      }

      try {
        // 主动触发微信分享给好友聊天框
        WeixinJSBridge.invoke('sendAppMessage', {
          title: shareInfo.title,
          desc: shareInfo.desc,
          link: shareInfo.link,
          img_url: shareInfo.imageUrl,
          img_width: '120',
          img_height: '120',
          type: 'link',
          data_url: ''
        }, (res) => {
          if (res.err_msg === 'sendAppMessage:ok') {
            uni.showToast({
              title: '分享成功',
              icon: 'success',
              duration: 2000
            });
          } else if (res.err_msg === 'sendAppMessage:cancel') {
            uni.showToast({
              title: '已取消分享',
              icon: 'none',
              duration: 2000
            });
          } else {
            console.error('分享失败', res);
            uni.showToast({
              title: '分享失败，请重试',
              icon: 'none',
              duration: 2000
            });
          }
        });
      } catch (error) {
        console.error('调用微信分享接口失败', error);
        // 降级处理：使用wx.ready方式作为备选
        if (typeof wx !== 'undefined') {
          wx.ready(() => {
            // 设置分享给微信好友的回调
            wx.onMenuShareAppMessage({
              title: shareInfo.title,
              desc: shareInfo.desc,
              link: shareInfo.link,
              imgUrl: shareInfo.imageUrl,
              type: 'link',
              success: () => {
                uni.showToast({
                  title: '分享成功',
                  icon: 'success',
                  duration: 2000
                });
              },
              cancel: () => {
                uni.showToast({
                  title: '已取消分享',
                  icon: 'none',
                  duration: 2000
                });
              },
              fail: (err) => {
                console.error('分享失败', err);
                uni.showToast({
                  title: '分享失败，请重试',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
            // 提示用户点击右上角分享
            uni.showToast({
              title: '请点击右上角分享按钮',
              icon: 'none'
            });
          });

          wx.error((err) => {
            console.error('微信JS-SDK初始化失败', err);
            uni.showToast({
              title: '分享功能加载失败',
              icon: 'none'
            });
          });
        }
      }
    },
    changeShadow() {
      this.boxshadow1 = false;
    },
    openSave() {
      this.boxshadow1 = false;
      this.boxshadow2 = true;
    },
    // 保存海报
    saveImg() {
      this.boxshadow2 = false;
      // 微信小程序保存图片
      uni.downloadFile({
        url: "https://static.hshuishang.com/property-img-file/shop_share_img.png",
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: (res) => {
                uni.showToast({
                  title: "保存成功",
                  icon: "success",
                  duration: 2000,
                });
              },
              fail: (err) => {
                console.log("保存失败", err);
              },
            });
          }
        },
        fail: (err) => {
          console.log("下载失败", err);
        },
      });
    },
    changeShadow2() {
      this.boxshadow2 = false;
    },

    // 点分享按钮
    share() {
      this.boxshadow1 = true;
    },
    //商品详情
    getGoodsInfo() {
      const params = {
        id: this.id,
        group_buy_activity_id: this.groupById
      }
      request(apiArr.getGoodsInfo, "POST", params).then((res) => {
        // 分割图片
        res.commodity_goods_info_list.forEach((item) => {
          item.goods_detail_pic = item.goods_detail_pic ? item.goods_detail_pic.split(",") : [];
          item.goods_carousel = item.goods_carousel ? item.goods_carousel.split(",") : [];
          item.commodity_pic = item.commodity_pic ? item.commodity_pic.split(",") : [];
        });

        //根据购物车列表 和 当前商品列表 来更新当前商品列表在购物车中的数量
        if (this.carOrderList) {
          this.carOrderList.forEach((items) => {
            res.commodity_goods_info_list.forEach((item) => {
              if (items.goods_id == item.id) {
                item.cart_count = { count: 0 };
                item.cart_count.count = items.count;
              }
            });
          });
        }

        const currentTime = new Date().getTime();

        // 过滤掉group_buy_activity_info为空的数据
        if (res.commodity_goods_info_list && Array.isArray(res.commodity_goods_info_list)) {
          res.commodity_goods_info_list = res.commodity_goods_info_list.filter(item => {
            const startTime = new Date(item.group_buy_activity_info?.start_time).getTime();
            const endTime = new Date(item.group_buy_activity_info?.end_time).getTime();
            return item.group_buy_activity_info !== null && currentTime >= startTime && currentTime <= endTime
          });
        }

        this.info = res;

        // 确保商品列表不为空
        if (this.itemObj) {
          // 对 itemObj 进行图片分割处理
          this.itemObj.goods_detail_pic = this.itemObj.goods_detail_pic ? this.itemObj.goods_detail_pic.split(",") : [];
          this.itemObj.goods_carousel = this.itemObj.goods_carousel ? this.itemObj.goods_carousel.split(",") : [];
          this.itemObj.commodity_pic = this.itemObj.commodity_pic ? this.itemObj.commodity_pic.split(",") : [];

          this.currentGG = this.itemObj;
          // 根据itemObj在商品列表中找到对应的索引
          this.currentGGIndex = this.info && this.info.commodity_goods_info_list
            ? this.info.commodity_goods_info_list.findIndex(item => item.id === this.itemObj.id)
            : 0;

          // 如果没找到匹配项，默认为0
          if (this.currentGGIndex === -1) {
            this.currentGGIndex = 0;
          }

          this.changeImg = this.currentGG.commodity_pic[0];
          this.changeName = this.currentGG.goods_alias;
          this.changePrice = this.currentGG.sales_price;
          this.goodsUnit = this.currentGG.goods_unit;
        } else {
          // 商品列表为空时的处理
          this.currentGG = null;
          this.currentGGIndex = 0;
          this.changeImg = '';
          this.changeName = '';
          this.changePrice = '';
          this.goodsUnit = '';
        }
      });
    },

    copys(e) {
      uni.setClipboardData({
        data: e,
        success: (res) => {
          uni.showToast({
            title: "复制成功",
            icon: "success",
            duration: 2000,
          });
        },
      });
    },

    // 切换规格
    changeGG(item, index) {
      this.currentGG = item;
      this.currentGGIndex = index;
      if (this.currentGG.cart_count) {
        this.currentNum = this.currentGG.cart_count.count;
      } else {
        this.currentGG.cart_count = { count: 0 };
      }
      this.changeImg = item.commodity_pic[0]
      this.changeName = item.goods_alias
      this.changePrice = item.sales_price
      this.goodsUnit = item.goods_unit;
    },
    car() {
      const item = {
        is_group_buy: 1,
      }
      NavgateTo("../shopCar/index?item=" + JSON.stringify(item));
    },

    //获取购物车数量
    // getShopCar() {
    //   request(apiArr.getCarCount, "POST", {}).then((res) => {
    //     this.carNum = res.total;
    //     this.prevCarNum = res.total;
    //   });
    // },

    getShopCarList() {
      const params = {
        is_group_buy: 1,
      }
      return request(apiArr.getCar, "POST", params).then((res) => {
        // 合并当日达和普通商品数据
        this.carOrderList = [].concat(res.same_day_cart_list, res.normal_cart_list)
          .flatMap(supplier => supplier.commodity_cart_and_goods_model);
        this.carNum = res.total;
        return res;
      });
    },

    addCar() {
      let that = this;
      this.info.commodity_goods_info_list[this.currentGGIndex].cart_count = {
        count: this.info.commodity_goods_info_list[this.currentGGIndex].min_order_quantity,
      };
      // this.info.commodity_goods_info_list.forEach((item) => {
      //   console.log(item.cart_count);
      //   goods_id_and_count.push({
      //     goods_id: item.id,
      //     count: item.cart_count ? item.cart_count.count : 0,
      //   });
      // });

      let countVal = this.info.commodity_goods_info_list[this.currentGGIndex].min_order_quantity

      const params = {
        goods_id_and_count: [
          {
            goods_id:
              this.info.commodity_goods_info_list[this.currentGGIndex].id,
            count: countVal,
          },
        ],
        group_buy_id: this.info.commodity_goods_info_list[this.currentGGIndex].group_buy_activity_id,
      }
      request(apiArr.updateCar, "POST", params).then((res) => {
        // that.getShopCar();
        that.getShopCarList();
      });
    },

    // 购物车更改
    changeCar() {
      // 获取当前商品的购物车数量，如果不存在则设为0
      const currentCount = this.info.commodity_goods_info_list[this.currentGGIndex].cart_count?.count;
      // 新的数量为当前数量加一
      const newCount = currentCount + 1;

      const params = {
        user_id: uni.getStorageSync("userId"),
        goods_id_and_count: [
          {
            goods_id: this.info.commodity_goods_info_list[this.currentGGIndex].id,
            count: newCount,
          },
        ],
        group_buy_id: this.info.commodity_goods_info_list[this.currentGGIndex].group_buy_activity_id,
      };

      request(apiArr.updateCar, "POST", params).then((res) => {
        this.getShopCarList();
        uni.showToast({
          title: "操作成功！",
          success() { },
        });
        // this.getShopCar();
        this.getGoodsInfo();
      });
    },

    showPopup() {
      this.show = true;
    },

    showSizePopup() {
      this.showSize = true;
    },

    close() {
      this.show = false;
    },

    closeSize() {
      this.showSize = false;
    },

    // 立即秒杀
    showSeckillPopup() {
      this.showSeckill = true;
    },

    closeSeckill() {
      this.showSeckill = false;
      uni.removeStorageSync('changeZTAddress')
      this.defZTAddress = {}
      this.changeCount = 0
    },

    editAddress() {
      const item = {
        goods_id: this.info.commodity_goods_info_list[this.currentGGIndex].id,
        supplier_id: this.itemObj.supplier_id,
      }
      NavgateTo('../ztLocation/index?item=' + JSON.stringify(item));
    },

    // 购买记录
    getBuyRecord() {
      const params = {
        activity_id: this.groupById,
        goods_id: this.itemObj.id,
        adver_id: this.itemObj.adver_id,
      }
      request(apiArr2.groupBuyRecord, 'POST', params).then(res => {
        const record = res.group_buy_record.map(item => {
          return {
            ...item,
            avatar: picUrl + item.avatar
          }
        })
        this.purchaseRecords = record
        this.totalCount = res.total_count
        // 计算所有item.count的总和并赋值给soldOutNum
        this.soldOutNum = record.reduce((total, item) => total + (item.count || 0), 0)
      })
    },
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${month}月${day}日`;
    },

    // 计算距离结束日期的剩余时间
    getEndTheCountdown(endTime) {
      // 获取当前时间和结束时间的时间戳
      const now = new Date().getTime();
      const end = new Date(endTime).getTime();

      // 计算时间差（毫秒）
      let diff = end - now;

      // 如果已经结束，返回提示
      if (diff <= 0) {
        return '团购已结束';
      }

      // 计算距离结束时间
      this.endTheCountdownDay = Math.floor(diff / (1000 * 60 * 60 * 24));
      diff -= this.endTheCountdownDay * (1000 * 60 * 60 * 24);
      this.endTheCountdownHour = Math.floor(diff / (1000 * 60 * 60));
      diff -= this.endTheCountdownHour * (1000 * 60 * 60);
      this.endTheCountdownMinute = Math.floor(diff / (1000 * 60));
      diff -= this.endTheCountdownMinute * (1000 * 60);
      this.endTheCountdownSecond = Math.floor(diff / (1000));
    }
  },
  onLoad(options) {
    this.itemObj = JSON.parse(decodeURIComponent(options.item));
    const meun = menuButtonInfo();
    this.top = meun.top;
    this.localHeight = meun.height;
    this.id = this.itemObj.commodity_id ? this.itemObj.commodity_id : this.itemObj.id;
    this.groupById = this.itemObj.groupById
    if (this.itemObj.commodity_id) {
      this.endTime = this.itemObj.group_buy_activity_info.end_time
    } else {
      this.endTime = this.itemObj.group_buy_goods_list[0].group_buy_activity_info.end_time
    }
    this.getBuyRecord()
    this.getEndTheCountdown(this.endTime)

    // 启动定时器，每秒更新一次倒计时
    this.timer = setInterval(() => {
      this.getEndTheCountdown(this.endTime)
    }, 1000)
  },
  onReachBottom() { },
  onShow() {
    // 确保getShopCarList完成后再执行getGoodsInfo
    this.getShopCarList().then(() => {
      this.getGoodsInfo();
    });
    // this.getShopCar();
    this.getZTAddress()
  },

  //离开页面的时候直接更新购物车数量(目前接口是 传入商品id 数量。如果有当前商品就更新数量。如果没有就增加商品。如果删除某个商品 count 为0 就删除)
  onHide() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }

    let goods_id_and_count = [];
    this.info.commodity_goods_info_list.forEach((item) => {
      goods_id_and_count.push({
        goods_id: item.id,
        count: item.cart_count ? item.cart_count.count : 0,
      });
    });

    // request(apiArr.updateCar, "POST", {
    //   goods_id_and_count,
    // }).then((res) => {
    //   console.log("Cart updated on hide");
    // });
    return;
  },
};
</script>

<style>
@import url("./index.css");
</style>