<template>
  <BasePage>
    <div class="goodsdetails">
      <div class="t">
        <img :src="$file(data.img)" alt="">
      </div>

      <div class="container">
        <div class="goodsshow">
          <div class="t">
            <div class="tit">
              {{ data.name }}
            </div>
            <div class="desc" v-if="data.description">
              {{ data.description }}
            </div>
          </div>

          <div class="price_box">
            <div class="price">
              ¥{{ data.saleprice?.toFixed(2) }}
            </div>
            <div class="oprice">
              ¥{{ data.originalprice?.toFixed(2) }}
            </div>
            <div class="sales r">
              已售{{ data.salenums }}
            </div>
          </div>

          <div class="deduct_box">
            <div class="point">
              <img src="/img/de-i1.png" alt="">
              积分抵￥{{ data.deductjifen?.toFixed(2) || '0.00' }}
            </div>

            <div class="vip">
              <img src="/img/de-i2.png" alt="">
              会员卡额度抵￥{{ data.deducthuiyuanka?.toFixed(2) || '0.00' }}
            </div>
          </div>

          <hr>

          <div class="gt">
            <div>
              <img src="/img/gt-i1.png" alt="">
              正品保障
            </div>
            <div>
              <img src="/img/gt-i1.png" alt="">
              快速发货
            </div>
            <div>
              <img src="/img/gt-i1.png" alt="">
              售后无忧
            </div>
          </div>
        </div>

        <div class="spec_box" @click="showSpecs = true">
          <img src="/img/spec.png" alt="">
          <span>{{ selectedSku }}</span>
          <van-icon class="r" name="arrow"></van-icon>
        </div>

        <div class="prodetail">
          <div class="tit">
            <img src="/img/pro.png" alt="">
            <span>产品详情</span>
          </div>
          <div class="vhtml" v-html="data.contents"></div>
        </div>
      </div>

      <van-action-bar safe-area-inset-bottom placeholder>
        <van-action-bar-icon icon="/img/vb-home.png" text="首页" @click="$navigate('Home')" />
        <van-action-bar-icon icon="/img/vb-service.png" text="客服" @click="$goService()" />
        <van-action-bar-icon icon="/img/vb-share.png" text="分享" @click="beforeShare" />
        <van-action-bar-button color="#ca2904" type="danger" text="立即购买" @click="showSpecs = true" />
      </van-action-bar>

      <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="options" @select="onSelect" />

      <van-popup v-model:show="showSpecs" position="bottom" closeable round>
        <div class="showspec">
          <div class="goods">
            <img :src="$file(tempSku.img || data.img)" alt="">
            <div>
              <div class="s_price">¥{{ (tempSku.saleprice * tempSku.Qty).toFixed(2) }}</div>
              <div class="s_stock">剩余：{{ tempSku.saleleft }}</div>
              <div class="s_spec">已选：{{ tempSku.skuname }}</div>
            </div>
          </div>

          <div class="spec_box" v-for="spec in specSelect">
            <span class="title">
              {{ spec.name }}
            </span>

            <div class="speccc">
              <div v-for="child in spec.children" class="spec_de"
                :class="selectedSpecs[spec.name] === child.name ? 'active' : 'inactive'"
                @click="selectSpec(spec.name, child.name)">
                {{ child.name }}
              </div>
            </div>
          </div>

          <div class="buynums box">
            <span class="title">
              购买数量
            </span>

            <van-stepper class="r" integer v-model="tempSku.Qty" min="1" max="99" theme="round" button-size="22"
              disable-input />

          </div>

          <van-action-bar safe-area-inset-bottom placeholder>
            <van-action-bar-button color="#ca2904" type="danger" text="立即购买" @click="submit" />
          </van-action-bar>
        </div>
      </van-popup>

      <van-popup v-model:show="show" class="shareimgbox" style="max-width: 80vw;">
        <div class="share_box" id="bsCard">
          <img class="logo" src="/img/logo-lr.png" alt="">

          <div class="share_userinfo">
            <img :src="$file($userInfo.userimg)" alt="">
            <div class="name"><span>{{ $userInfo.nickname }}友情推荐</span></div>
          </div>

          <div class="goods_info">
            <img class="goods_img" :src="$file(data.img)" alt="">
            <div class="goods_name">{{ data.name }}</div>
            <div class="goods_price">¥{{ data.saleprice?.toFixed(2) || '0.00' }}</div>
          </div>

          <div class="qrcode">
            <vue-qr :margin="0" :text="shareLink" backgroundColor="rgb(255,255,255)"
              colorLight="rgb(255,255,255)"></vue-qr>
            长按扫码购买
          </div>
        </div>
        <div class="share_result" v-if="ShareImg">
          <img :src="ShareImg" alt="分享海报">
          <!-- <div class="tips">长按保存图片</div> -->
        </div>
      </van-popup>


    </div>

  </BasePage>

</template>

<script>
import { html2canvas, canvasToDataURL } from '@/utils/html2image';

export default {
  name: 'GoodsDetail',
  emits: ['updateShare'],
  mounted() {
    this.init();
  },
  data() {
    return {
      data: {},
      specSelect: [],
      show: false,
      specCombinations: [],
      tempSku: {},
      showSpecs: false,
      selectedSku: '请选择规格分类',
      selectedSpecs: {},
      showShare: false,
      options: [
        { name: '分享海报', icon: '/img/share.png' },
      ],
      shareLink: '',
      ShareImg: '',
      loading: false
    }
  },
  methods: {
    init() {
      this.$get(`/v1/client/EProsClient/${this.$route.query.id}`).then(res => {
        this.data = res.data;
        this.specSelect = this.data.specSelect || [];
        this.specCombinations = this.data.specCombinations || [];
        const recommend = localStorage.getItem('member_username') || '';
        this.shareLink = `${location.origin}/#/GoodsDetail?id=${this.data.id}${recommend ? '&RecommendCode=' + recommend : ''}`;
        this.$emit('updateShare', { title: this.data.name, imageUrl: this.data.img, link: this.shareLink });
        this.initDefaultSku();
      });
    },
    initDefaultSku() {
      const mainSku = this.specCombinations.find(s => s.ismain) || this.specCombinations[0];
      if (mainSku) {
        this.tempSku = { ...mainSku, Qty: 1 };
        this.selectedSku = "已选:" + mainSku.skuname;
        // 根据skuname设置默认选中规格
        this.specSelect.forEach(spec => {
          const child = spec.children?.find(c => mainSku.skuname.includes(c.name));
          if (child) {
            this.selectedSpecs[spec.name] = child.name;
          }
        });
      }
    },
    selectSpec(specName, specValue) {
      this.selectedSpecs[specName] = specValue;
      this.refreshSku();
    },
    refreshSku() {
      const specKeys = Object.keys(this.selectedSpecs);
      if (specKeys.length === 0) return;

      let matchedSku = this.specCombinations.find(combo => {
        return specKeys.every(key => {
          const spec = this.specSelect.find(s => s.name === key);
          if (!spec) return false;
          const specValue = this.selectedSpecs[key];
          return combo.skuname === specValue;
        });
      });

      if (matchedSku) {
        this.tempSku = { ...matchedSku, Qty: this.tempSku.Qty || 1 };
        this.selectedSku = "已选:" + matchedSku.skuname;
      }
    },
    onSelect(option) {
      this.showShare = false;
      if (option.name === "分享海报") {
        this.show = true;
        this.loading = true;
        this.ShareImg = '';
        // 等待 DOM 渲染后再生成
        setTimeout(() => {
          this.generateShareImg();
        }, 200);
      } else if (option.name == "复制链接") {
        this.$copyText(location.href);
        this.$showToast({ type: "success", message: "复制成功" });
      } else if (option.name == "分享好友") {
        this.showTip = true;
      }
    },
    submit() {
      if (this.tempSku.saleleft < 1) {
        this.$showFailToast("该规格库存不足，无法购买");
        return;
      }
      this.$navigate(`/TradeConfirm?id=${this.data.id}&buynums=${this.tempSku.Qty}`);
    },
    beforeShare() {
      this.showShare = true;
    },
    async generateShareImg() {
      var shareContent = document.querySelector('#bsCard');
      if (!shareContent) return;
      var width = shareContent.offsetWidth;
      var height = shareContent.offsetHeight;
      try {
        var canvas = await html2canvas(shareContent, {
          scale: 2,
          width: width,
          height: height,
          useCORS: true,
          allowTaint: true,
        });
        this.ShareImg = canvasToDataURL(canvas, "image/png", 1.0);
        this.loading = false;
        document.querySelector('.share_box').style.display = 'none';
      } catch (e) {
        console.error(e);
        this.loading = false;
      }
    }
  }
}
</script>