<template>
  <view>
    <uni-popup
      ref="popup_result"
      type="center"
      mask-background-color="rgba(0,0,0,0.9)"
      :is-mask-click="false"
    >
      <view v-if="bagData" class="popup-fudai-cards">
        <view class="fudai-title">
          <text class="fudai-title-text">恭喜您抽到以下商品</text>
          <view v-if="cdTime" class="fudai-title-cd"
            >{{ cdText
            }}<text class="fudai-title-time">{{ cdTime }}</text></view
          >
        </view>
        <view class="fudai-cards">
          <view
            v-for="item in bagData.relations2"
            :key="item.id"
            :class="[
              'card-item',
              `card-item-${item.card_style}`,
              {
                'card-item-small': bagData.relations2.length > 1,
                checked: item.select && bagData.can_retrive === 1,
              },
            ]"
            @click="handleChangeSelect(item)"
          >
            <image class="sku-img" :src="item.img"></image>
            <image v-if="item.label" class="label" :src="item.label"></image>
            <view v-else class="label-text">{{ item.level_name }}</view>
            <view class="sku-num"
              >x<text class="big">{{ item.num }}</text></view
            >
            <text class="sku-name">{{ item.name }}</text>
            <text class="sku-price">回血: &yen; {{ item.retrive_price }}</text>
          </view>
        </view>
        <view
          v-if="bagData.retrive && bagData.can_retrive === 1"
          class="fudai-tips"
          >用户<image class="img" :src="bagData.retrive.avatar"></image
          ><text class="text"
            >{{ bagData.retrive.nickname }}{{ bagData.retrive.info }}</text
          ></view
        >
        <view class="fudai-btns">
          <view
            v-if="bagData.can_retrive === 1"
            class="fudai-btn"
            @click="handleRetrive"
            ><text class="btntext-1">{{
              Number(bagData.total_retrive_price) === retrivePrice
                ? "全部回血"
                : "回血"
            }}</text
            ><text class="btntext-2">&yen; {{ retrivePrice }}</text></view
          >
          <button class="fudai-btn fudai-btn-border" @click="handleBuy">
            继续购买
          </button>
        </view>
        <image
          class="popup_close"
          :src="require('@/assets/icon/icon-close.png')"
          @click="handlePopupClose('popup_result')"
        ></image>
      </view>
      <view v-else class="popup-fudai-cards">
        <view class="fudai-title">
          <text class="fudai-title-text">没有回血商品</text>
        </view>
        <image
          class="popup_close"
          :src="require('@/assets/icon/icon-close.png')"
          @click="handlePopupClose('popup_result')"
        ></image>
      </view>
    </uni-popup>
    <popup-dialog ref="popupDialog" />
  </view>
</template>

<script>
import Decimal from "decimal.js";
import api from "@/lib/api/api";
import popupDialog from "@/components/popup-dialog/popup-dialog.vue";

import cardLabelN from "@/assets/detail/card-label-N.png";
import cardLabelR from "@/assets/detail/card-label-R.png";
import cardLabelSP from "@/assets/detail/card-label-SP.png";
import cardLabelSR from "@/assets/detail/card-label-SR.png";
import cardLabelSSR from "@/assets/detail/card-label-SSR.png";

export default {
  name: "PayResult",
  components: {
    popupDialog,
  },
  props: {
    id: {
      type: String,
      default: "0",
    },
    type: {
      type: Number,
      default: 1, // 1：福袋； 2：一番赏；
    },
    cdText: {
      type: String,
      default: "",
    },
    cdTime: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      bagData: null,
    };
  },
  computed: {
    // 回血金额
    retrivePrice() {
      if (
        !this.bagData ||
        this.bagData.can_retrive !== 1 ||
        this.bagData.relations2.length === 0
      ) {
        return 0;
      }

      let price = new Decimal(0);
      this.bagData.relations2.forEach((item) => {
        if (item.select)
          price = price.plus(new Decimal(item.retrive_price).mul(item.num));
      });

      return price.toNumber();
    },
  },
  methods: {
    handlePopupShow(popup_ref) {
      this.$refs[popup_ref].open();
    },
    handlePopupClose(popup_ref) {
      this.$refs[popup_ref].close();
    },
    open(bagData) {
      const now = Date.now();
      bagData.relations2.forEach((item, i) => {
        item.select = true;
        item.id = now + i;
        if (this.type === 1) {
          switch (item.level_name) {
            case "N":
              item.label = cardLabelN;
              break;
            case "R":
              item.label = cardLabelR;
              break;
            case "SP":
              item.label = cardLabelSP;
              break;
            case "SR":
              item.label = cardLabelSR;
              break;
            case "SSR":
              item.label = cardLabelSSR;
              break;
            default:
              item.label = "";
          }
        }
      });
      this.bagData = bagData;
      this.handlePopupShow("popup_result");
    },
    handleChangeSelect(sku) {
      if (!this.bagData || this.bagData.relations2.length < 2) {
        return;
      }
      sku.select = !sku.select;
    },
    async handleRetrive() {
      if (this.retriving) return;
      this.retriving = true;

      if (this.retrivePrice === 0) {
        uni.showToast({
          icon: "none",
          title: "请选择回血商品",
          duration: 3000,
        });
        return;
      }

      const skus = this.bagData.relations2.filter((item) => item.select);

      const levels = Array.from(
        new Set(
          skus
            .filter((item) => ["SR", "SSR", "SP"].includes(item.level_name))
            .map((item) => item.level_name)
        )
      );

      if (levels.length && this.type === 1) {
        const confirm = await this.$refs.popupDialog
          .open(`你抽到${levels.join(",")}卡， 确定要全部回血吗？`)
          .then(() => true)
          .catch(() => false);
        this.retriving = false;
        if (!confirm) return;
      }

      uni.showLoading({
        title: "回血中",
        mask: true,
      });

      const skuIds = skus
        .map((item) => new Array(item.num).fill("" + item.sku_id))
        .flat();

      let userInfo = uni.getStorageSync("userinfo");
      if (userInfo) {
        userInfo = JSON.parse(userInfo);
      }

      try {
        const data = await api.orderRecovery({
          session: userInfo.session,
          order_id: "" + (this.bagData.order_id || "none"),
          sku_id: skuIds,
          retrive_user_id: this.bagData.retrive?.user_id || "-1",
        });
        uni.hideLoading();
        if (data.errno === 10000) {
          uni.showToast({
            icon: "none",
            title: `回血成功，当前余额${data.data.balance}元`,
            duration: 3e3,
          });
          this.handlePopupClose("popup_result");
        } else {
          throw new Error(data.errmsg);
        }
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          icon: "none",
          title: e.message || "请求失败，请稍后重试",
          duration: 2e3,
        });
      }
      setTimeout(() => {
        this.retriving = false;
      }, 500);
    },
    handleBuy() {
      this.handlePopupClose("popup_result");
      this.$emit("buy", this.bagData.num);
    },
  },
};
</script>

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