<template>
  <view
    class="card"
    :style="{
      backgroundImage:
        userInfo && userInfo.card_img ? `url(${userInfo.card_img})` : '',
    }"
  >
    <view class="card-title">VIP会员</view>
    <view class="card-desc" v-if="!isVip">开通VIP会员专享权益</view>
    <view class="card-status">
      <button
        class="card-btn"
        v-if="userInfo && userInfo.phone && !isVip"
        @click="handlePay"
      >
        立即开通
      </button>
      <button
        v-else-if="!(userInfo && userInfo.phone)"
        class="card-btn"
        open-type="getPhoneNumber"
        @getphonenumber="handlePhoneLogin"
      >
        登录开通
      </button>
    </view>
    <view class="card-number" v-if="userInfo && userInfo.show_id">
      {{ userInfo.show_id }}
    </view>
    <navigator url="/pages/vip/card" v-if="userInfo && userInfo.type === '1'">
      <image
        :src="require('@/assets/detail/icon-edit.png')"
        class="icon-edit"
      ></image>
    </navigator>
  </view>
</template>

<script>
import login from "@/lib/utils/login";
import { getUserInfo } from "@/lib/api/user";
import { vipPrePay, vipCompletePay, vipQueryPay } from "@/lib/api/pay";

export default {
  name: "VipCard",

  props: {
    userInfo: {
      type: Object,
      default: () => null,
    },
    edit: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {};
  },

  computed: {
    isVip() {
      return this.userInfo && this.userInfo.type === "1";
    },
  },

  created() {
    console.log(this.userInfo);
  },

  methods: {
    async handlePay() {
      try {
        await this.wechatPay();
        const res = await getUserInfo();
        const userInfo = { ...(this.userInfo || {}), ...res.data };
        login.setUserInfo(userInfo);
        this.$emit("login", userInfo);
      } catch (e) {
        uni.showToast({
          icon: "none",
          title: e.message,
        });
      }
    },

    async wechatPay() {
      uni.showLoading({
        title: "加载中",
        mask: true,
      });

      const { errno, errmsg, data } = await vipPrePay();

      uni.hideLoading();

      if (errno !== 10000) {
        throw new Error(errmsg);
      }
      const {
        timeStamp,
        nonceStr,
        package: pkg,
        signType,
        paySign,
        order_id,
      } = data;

      const type = await new Promise((resolve) => {
        uni.requestPayment({
          provider: "wxpay",
          timeStamp,
          nonceStr,
          package: pkg,
          signType,
          paySign,
          success: async (res) => {
            console.log(res);
            resolve(
              res.errMsg === "requestPayment:ok"
                ? 1
                : res.errMsg === "requestPayment:fail cancel"
                ? 3
                : 2
            );
          },
          fail: async (err) => {
            resolve(err.errMsg === "requestPayment:fail cancel" ? 3 : 2);
          },
        });
      });

      const res = await vipCompletePay({
        order_id: `${order_id}`,
        type,
      }).catch((e) => {
        console.log(e);
      });

      if (res.errno !== 10000) throw new Error(res.errmsg);

      if (type !== 1) throw new Error(type === 3 ? "取消支付" : "支付失败");

      return this.loopPayRes("" + order_id);
    },
    async loopPayRes(order_id) {
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      const data = await vipQueryPay({
        order_id,
      });

      if (data.errno == 90000) {
        return new Promise((r) => {
          setTimeout(() => r(), 1000);
        }).then(() => this.loopPayRes(order_id));
      }

      uni.hideLoading();

      if (data.errno == 10000) {
        return data.data;
      }

      throw new Error("订单查询失败");
    },
    async handlePhoneLogin(e) {
      if (e.detail.code) {
        login.setPhoneData({
          phone_code: e.detail.code,
          callback: async (data) => {
            const res = await getUserInfo();
            this.$emit("login", { ...data, ...res.data });
            if (res.data.type === "1") {
              return;
            }
            this.handlePay();
          },
          fail: (e) => {
            console.log(e);
          },
        });
      }
    },
  },
};
</script>

<style lang="scss">
.card {
  width: 660rpx;
  height: 392rpx;
  background: url("~@/assets/vip/card-vip.png") no-repeat center;
  background-size: contain;
  box-sizing: border-box;
  padding: 40rpx;
  margin: 0 auto;
  color: rgb(251, 222, 190);
  overflow: hidden;
  border-radius: 24rpx;
  position: relative;
  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background-image: linear-gradient(
      135deg,
      rgba(0, 0, 0, 0.4) 0%,
      transparent 100%
    );
  }
  .card-title {
    font-size: 56rpx;
    position: relative;
  }
  .card-desc {
    font-size: 28rpx;
    margin-top: 20rpx;
    position: relative;
  }
  .card-status {
    margin-top: 100rpx;
    text-align: right;
    line-height: 92rpx;
    font-size: 36rpx;
    position: relative;
  }
  .card-btn {
    color: rgb(3, 3, 3);
    background: rgb(251, 222, 190);
    display: inline-block;
    padding: 0 50rpx;
    border-radius: 100rpx;
    font-weight: bold;
    &::after {
      display: none;
    }
  }
  .icon-edit {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    width: 48rpx;
    height: 48rpx;
  }
  .card-number {
    position: absolute;
    left: 30rpx;
    bottom: 30rpx;
    font-size: 28rpx;
    color: #fff;
    text-shadow: 0 0 4px #000000;
  }
}
</style>
