<template>
  <view class="content">
    <lff-barrage ref="lffBarrage" class="danmu"></lff-barrage>
    <view class="main">
      <text class="buynumbers"
        >已抽 <text class="buynumber">{{ info.sell_count || 0 }}</text> 次</text
      >
      <swiper class="swiper" :current="currentIdx" @change="handleSwiperChange">
        <swiper-item
          v-for="(item, idx) in skuList"
          :key="idx"
          class="swiper-item"
        >
          <text class="title">{{ item.name }}</text>
          <view class="image">
            <image
              class="cover"
              :src="item.big_img"
              mode="aspectFit"
              @click="handleShowImages"
            ></image>
            <image v-if="item.label" class="label" :src="item.label"></image>
          </view>
          <view class="banner-price"
            ><text v-if="item.unit === '元' || item.unit === '￥'" class="small"
              >&yen;</text
            ><text class="price">{{ item.sale_price }}</text
            ><text
              v-if="item.unit !== '元' && item.unit !== '￥'"
              class="small"
              >{{ item.unit }}</text
            >
          </view>
        </swiper-item>
      </swiper>
      <image
        class="left"
        src="@/assets/detail/btn-left.png"
        @click="switchTo(Math.max(0, currentIdx - 1))"
      >
      </image>
      <image
        class="right"
        src="@/assets/detail/btn-right.png"
        @click="switchTo(Math.min(skuList.length - 1, currentIdx + 1))"
      ></image>
      <view class="all">
        <view v-for="(item, idx) in skuList" :key="idx" class="item">
          <image
            class="img"
            :src="item.img"
            mode="aspectFit"
            @click="switchTo(idx)"
          >
          </image>
          <!-- <image class="label" v-if="item.label" :src="item.label"></image> -->
          <view class="item-price"
            ><text v-if="item.unit === '元' || item.unit === '￥'" class="small"
              >&yen;</text
            ><text class="price">{{ item.sale_price }}</text
            ><text
              v-if="item.unit !== '元' && item.unit !== '￥'"
              class="small"
              >{{ item.unit }}</text
            >
          </view>
        </view>
      </view>
      <view class="btns">
        <view class="btn-item" @click="handlePopupShow('popup_shipping')"
          ><text>发货说明</text></view
        >
        <image
          class="btn-img"
          src="@/assets/detail/btn-show-all.png"
          @click="handlePopupShow('popup_allsku')"
        ></image>
        <view class="btn-item" @click="handlePopupShow('popup_play')"
          ><text>玩法说明</text></view
        >
      </view>
    </view>
    <view class="more-title">更多福袋</view>
    <view class="base-list">
      <list-item
        v-for="item in moreList"
        :key="item.id"
        :item="item"
        class="base-list-item"
        @click="handleDetail(item.id)"
      >
      </list-item>
    </view>
    <buy-btns
      v-if="info"
      class="buy-btns"
      :user-info="userInfo"
      :buy-btns="computedBtns"
      @login="handleUpdateUserInfo"
      @click="handleBtnsClick"
    />
    <uni-popup
      ref="popup_shipping"
      type="center"
      mask-background-color="rgba(0,0,0,0.8)"
      :is-mask-click="true"
    >
      <view class="popup-wrap">
        <view class="popup-content">
          <view class="h1"><text>发货说明</text></view>
          <view class="p" v-html="info.info || ''"></view>
        </view>
        <image
          class="popup_close"
          :src="require('@/assets/icon/icon-close.png')"
          @click="handlePopupClose('popup_shipping')"
        ></image>
      </view>
    </uni-popup>
    <uni-popup
      ref="popup_play"
      type="center"
      mask-background-color="rgba(0,0,0,0.8)"
      :is-mask-click="true"
    >
      <view class="popup-wrap">
        <view class="popup-content">
          <view class="h1"><text>玩法说明</text></view>
          <view class="p" v-html="info.play_info || ''"></view>
        </view>
        <image
          class="popup_close"
          :src="require('@/assets/icon/icon-close.png')"
          @click="handlePopupClose('popup_play')"
        ></image>
      </view>
    </uni-popup>
    <popup-img-detail ref="imgdetail" />
    <uni-popup
      ref="popup_allsku"
      type="bottom"
      mask-background-color="rgba(0,0,0,0.8)"
      :is-mask-click="true"
    >
      <view class="popup-detail">
        <view>
          <image
            class="close"
            src="@/assets/icon/icon-close-dark.png"
            @click="handlePopupClose('popup_allsku')"
          >
          </image>
          <text class="title">全部商品详情</text>
          <text class="desc">图片仅供参考，请以实物为准</text>
          <view class="levels">
            <view v-for="item in skuPercent" :key="item.name" class="level">
              <text class="name">{{ item.name }}</text>
              <text class="percent">{{ item.percent }}</text>
            </view>
          </view>
        </view>
        <view class="popup-detail-list">
          <view v-for="(item, i) in skuList" :key="i" class="list-item">
            <image class="img" :src="item.img" mode="aspectFit"></image>
            <image v-if="item.label" class="label" :src="item.label"></image>
            <view class="list-item-body">
              <text class="title">{{ item.name }}</text>
              <text class="price"
                >参考价<text class="unit">&yen;</text>
                <text class="price-text">{{ item.sale_price }}</text></text
              >
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
    <paypop
      v-if="info"
      ref="paypop"
      :title="info.name"
      :img="info.img"
      :detail-id="id"
      :type="1"
      :score-text="info.score_info"
      @paySuccess="handlePaySuccess"
    />
    <payresult v-if="info" ref="payresult" :type="1" @buy="handleBuy" />
    <popup-dialog ref="popupDialog" />
  </view>
</template>

<script>
import Decimal from "decimal.js";
import api from "@/lib/api/api";
import lffBarrage from "@/components/lff-barrage/lff-barrage.vue";
import listItem from "@/components/list-item/list-item.vue";
import popupDialog from "@/components/popup-dialog/popup-dialog.vue";
import paypop from "components/paypop/paypop.vue";
import payresult from "components/payresult/payresult.vue";
import buyBtns from "@/components/buy-btns/buy-btns.vue";
import popupImgDetail from "@/components/popup-img-detail/popup-img-detail.vue";
import { reqAcceptSubMsgs, defaultTemplateIds } from "@/lib/utils/wxSubscribe";

import labelN from "@/assets/icon/icon-medal-n.png";
import labelR from "@/assets/icon/icon-medal-r.png";
import labelSP from "@/assets/icon/icon-medal-sp.png";
import labelSR from "@/assets/icon/icon-medal-sr.png";
import labelSSR from "@/assets/icon/icon-medal-ssr.png";

export default {
  name: "PageDetail",
  components: {
    lffBarrage,
    listItem,
    popupDialog,
    popupImgDetail,
    buyBtns,
    paypop,
    payresult,
  },
  data() {
    return {
      info: null,
      userInfo: null,
      params: {},
      id: "0",
      moreList: [],
      skuList: [],
      skuPercent: [],
      currentIdx: 0,
      danmu: [],
      buyNums: [
        {
          num: 1,
          key: "price",
          title: "1发入魂",
          isPopKey: "bubble",
          popKey: "bubble_notice",
        },
        {
          num: 3,
          key: "three_price",
          title: "幸运3连",
          isPopKey: "three_bubble",
          popKey: "three_bubble_notice",
        },
        {
          num: 5,
          key: "five_price",
          title: "欧气5连",
          isPopKey: "five_bubble",
          popKey: "five_bubble_notice",
        },
        {
          num: 10,
          key: "ten_price",
          title: "豪气10连",
          isPopKey: "ten_bubble",
          popKey: "ten_bubble_notice",
        },
      ],
      buyNum: 0,
    };
  },
  computed: {
    computedBtns() {
      if (!this.info) return this.buyNums;
      return this.buyNums.map((item) => {
        const obj = {
          num: item.num,
          title: item.title,
          price: this.info[item.key],
        };
        if (
          item.isPopKey &&
          item.popKey &&
          this.info[item.popKey] &&
          this.info[item.isPopKey] === 1
        ) {
          obj.pop = this.info[item.popKey];
        }
        return obj;
      });
    },
    currentDetail() {
      return this.skuList[this.currentIdx];
    },
  },
  onLoad(data) {
    this.params = data;
    this.id = data.id;
    const uinfoStr = uni.getStorageSync("userinfo");
    if (uinfoStr) {
      this.userInfo = JSON.parse(uinfoStr);
    }
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    this.loadDetail();
    this.loadDanmu();
  },
  onShow() {
    reqAcceptSubMsgs(defaultTemplateIds);
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  onShareAppMessage() {
    // 来自页面内转发按钮
    return {
      title: this.info?.name || "来抽赏啦，抽中SP赏可好运加倍！",
      imageUrl:
        this.info?.img ||
        "https://chujianchaowan.oss-cn-beijing.aliyuncs.com/images/45bfb688e6e9dba557f64fd052e850cc.png", //图片路径
      path: "/pages/detail/detail?id=" + this.id,
    };
  },
  onShareTimeline() {
    return {
      title: this.info?.name || "来抽赏啦，抽中SP赏可好运加倍！",
      imageUrl:
        this.info?.img ||
        "https://chujianchaowan.oss-cn-beijing.aliyuncs.com/images/45bfb688e6e9dba557f64fd052e850cc.png", //图片路径
      path: "/pages/detail/detail?id=" + this.id,
    };
  },
  methods: {
    async loadDetail() {
      try {
        const data = await api.detail(this.id);
        if (data.errno) {
          this.moreList = data.data.more_kujis;
          this.skuList = data.data.sku_info.map((item) => {
            switch (item.sub_info) {
              case "N":
                item.label = labelN;
                break;
              case "R":
                item.label = labelR;
                break;
              case "SP":
                item.label = labelSP;
                break;
              case "SR":
                item.label = labelSR;
                break;
              case "SSR":
                item.label = labelSSR;
                break;
              default:
                item.label = "";
            }
            return item;
          });
          this.skuPercent = data.data.sku_percent;
          this.info = data.data.kuji_info;
          uni.hideLoading();
        } else {
          throw new Error(data.errmsg);
        }
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          icon: "none",
          title: e.message || "出错啦，请稍后重试",
          duration: 3000,
        });
      }
    },
    async loadDanmu() {
      const data = await api.detailDanmu(this.id);

      if (data.errno === 10000 && data.data.length) {
        this.danmu = data.data;
        this.runDanmu();
      }
    },
    runDanmu(down = false) {
      clearTimeout(this.timer);
      const item = this.danmu.shift();
      if (!item || !this.$refs.lffBarrage) return;
      this.$refs.lffBarrage.add({
        img: item.user_img,
        img2: item.sku_img,
        content: item.content,
        link: item.link,
        level: item.level,
        top: (down ? 80 : 4) + (Math.floor(Math.random() * (20 - 2)) + 1),
        name: `${item.user_name[0]}**${
          item.user_name[item.user_name.length - 1]
        }`,
        type: item.type,
      });
      this.timer = setTimeout(() => {
        this.runDanmu(!down);
      }, 4000);
    },
    handleSwiperChange(e) {
      this.currentIdx = e.detail.current;
    },
    switchTo(idx) {
      this.currentIdx = idx;
    },
    handleDetail(id) {
      uni.redirectTo({
        url: `../detail/detail?id=${id}`,
      });
    },
    handlePopupShow(popup_ref) {
      this.$refs[popup_ref].open();
    },
    handlePopupClose(popup_ref) {
      this.$refs[popup_ref].close();
    },
    handleBuy(num = 1, useLoading = true) {
      this.buyNum = num;
      let originPrice = 0;
      const item = this.buyNums.find((item) => item.num === this.buyNum);
      if (item && this.info[item.key]) {
        originPrice = Number(this.info[item.key]);
      }

      if (originPrice === 0) {
        originPrice = new Decimal(this.info.price).mul(this.buyNum).toNumber();
      }

      this.$refs.paypop.buy(this.buyNum, originPrice, useLoading);
    },
    handlePaySuccess(data) {
      if (this.$refs.payresult) {
        this.$refs.payresult.open(data);
      } else {
        uni.showToast({
          icon: "success",
          title: "购买成功",
          duration: 2e3,
        });
      }
    },
    handleUpdateUserInfo(data, item, useLoading = true) {
      this.userInfo = data;
      if (item) {
        this.handleBuy(item.num, useLoading);
      }
    },
    handleBtnsClick(item) {
      this.handleBuy(item.num);
    },
    handleShowImages() {
      this.$refs.imgdetail.open({
        title: this.currentDetail?.name || "",
        list: this.currentDetail?.long_img || [this.currentDetail?.big_img],
      });
    },
  },
};
</script>

<style lang="scss">
@import "./detail.scss";
</style>
