<template>
  <layout
    :bgImgName="currentLoading ? 'purchase-img' : ''"
    bgColor="#FDF2E3"
    bgHeight="219"
    @goBack="goBack"
  >
    <div class="purchase" v-if="currentLoading">
      <div class="purchase-privilege">
        <div>
          <img src="@/assets/image/claimCloudPhone/privilege-1.png" alt="" />
          应用预装已完成
        </div>
        <div style="animation-delay: 0.2s">
          <img src="@/assets/image/claimCloudPhone/privilege-2.png" alt="" />
          任意下单
        </div>
        <div style="animation-delay: 0.4s">
          <img src="@/assets/image/claimCloudPhone/privilege-3.png" alt="" />
          立即使用云机
        </div>
      </div>
      <template v-for="item in packageList">
        <setMealItem
          :key="item.serialNumber"
          :data="item"
          v-if="item.mealList && item.mealList.length"
          :type="0"
          @buy="buy"
        />
      </template>
      <van-popup
        v-model="visible"
        position="bottom"
        :style="{ background: 'transparent' }"
      >
        <div class="payment-container">
          <div class="payment-container-title">新增云手机</div>
          <div class="payment-container-info">
            <div>
              <div class="payment-container-info_value">
                <span>￥</span>{{ currentData.actualPrice }}
              </div>
              <div class="payment-container-info_name">
                {{ packageType[currentData.phoneType]
                }}{{ currentData.day }}天卡
              </div>
            </div>
          </div>
          <div class="payment-container-num">
            数量：<van-stepper button-size="18" v-model="stepper" />
          </div>
          <div class="payment-container-method">
            <div class="payment-container-method_title">选择支付方式</div>
            <div class="payment-container-method_select">
              <template v-for="item in paymentList">
                <div
                  :key="item.key"
                  v-if="
                    currentData.paySupportTypeList &&
                    currentData.paySupportTypeList.includes(item.key)
                  "
                  :class="{ active: active === item.key }"
                  @click="active = item.key"
                >
                  <img
                    :src="active === item.key ? item.activeImg : item.img"
                    alt=""
                  />
                  {{ item.name }}
                  <div v-if="active === item.key" class="active-icon">
                    <van-icon name="success" />
                  </div>
                </div>
              </template>
            </div>
          </div>
          <div class="payment-container-amount">
            <div>
              需支付金额:<span
                ><span>¥</span>{{ currentData.actualPrice * stepper }}
              </span>
            </div>
            <div @click="payment" :class="{ disabled: btnLoading }">
              <template v-if="btnLoading"> 正在支付中... </template>
              <template v-else> 确认协议并付款</template>
            </div>
          </div>
          <div class="payment-container-agreement">
            购买前阅读<span @click="toAgreement">
              《双子星云手机服务协议》
            </span>
          </div>
        </div>
      </van-popup>

      <van-dialog
        v-model="activityPurchaseVisible"
        @cancel="confirm(false)"
        @confirm="confirm(true)"
        show-cancel-button
        confirmButtonText="已完成支付"
        confirmButtonColor="#3367d1"
      >
        <div class="payment-tips">如果您已支付成功</div>
        <div class="payment-tips">请点击"已完成支付"按钮</div>
      </van-dialog>
    </div>
  </layout>
</template>

<script>
import layout from './components/layout';
import setMealItem from './components/setMealItem.vue';
import common from './mixins/common.js';
const RSA = require('@/plugins/wx_rsa.js');
export default {
  auth: false,
  name: 'purchase',
  head: {
    title: '0元购机，尽情享受',
  },
  mixins: [common],
  data() {
    return {
      visible: false,
      currentData: {},
      packageType: {
        VIP: '星动',
        SVIP: '星曜',
        STARRYSKY: '星空',
        STAR: '唔即',
        STARPRO: '唔即Pro',
      },
      stepper: 1,
      active: '',
      paymentList: [
        {
          name: '微信',
          img: require('@/assets/image/claimCloudPhone/weChat.png'),
          activeImg: require('@/assets/image/claimCloudPhone/weChatActvie.png'),
          key: 'wxPay',
        },
        {
          name: '支付宝',
          img: require('@/assets/image/claimCloudPhone/alipay.png'),
          activeImg: require('@/assets/image/claimCloudPhone/alipayActive.png'),
          key: 'aliPay',
        },
      ],
      btnLoading: false,
      activityPurchaseVisible: false,
    };
  },
  mounted() {
    if (sessionStorage.getItem('isAgreementBool')) {
      this.currentData = JSON.parse(sessionStorage.getItem('currentData'));
      this.stepper = sessionStorage.getItem('stepper');
      this.active = sessionStorage.getItem('active');
      this.visible = true;
      sessionStorage.removeItem('isAgreementBool');
      sessionStorage.removeItem('currentData');
      sessionStorage.removeItem('active');
      sessionStorage.removeItem('stepper');
    }
    if (localStorage.getItem('activityPurchaseVisible')) {
      this.activityPurchaseVisible = true;
      localStorage.removeItem('activityPurchaseVisible');
    }

    this.getActivitySortRuleAndActivityMealList({
      personnelMealType: 2,
    });
  },
  components: { layout, setMealItem },
  methods: {
    buy(data) {
      console.log(data);
      this.stepper = 1;
      this.visible = true;
      this.currentData = JSON.parse(JSON.stringify(data));
      this.currentData.paySupportTypeList =
        this.currentData.paySupportTypeList.split(',');
      this.active = this.currentData.paySupportTypeList[0];
    },
    // 确认支付
    payment() {
      let params = {
        buyType: 1,
        quantity: this.stepper,
        id: this.currentData.id,
        phoneType: this.currentData.phoneType,
        activityId: 690009,
        returnUrl: location.origin + '/h5/claimCloudPhone/confirmation',
      };
      params = this.sort_ASCII(params);
      console.log(params);
      const sign = this.jiaqian(JSON.stringify(params));
      this.btnLoading = true;
      this.$axios
        .$post('pay/v1/order/create', params, { headers: { sign } })
        .then((res) => {
          console.log(res);
          const obj = {
            aliPay: 'pay/v1/alipay/h5/spend',
            wxPay: 'pay/v1/wxPay/h5/spend',
          };

          if (res.success) {
            localStorage.setItem(
              'activityPurchaseMyOrderNum',
              res.data.myOrderNum,
            );
            const data = {
              myOrderNum: res.data.myOrderNum,
            };

            const headers = {
              sign: this.jiaqian(JSON.stringify(data)),
            };
            this.$axios
              .$get(obj[this.active], { headers, params: data })
              .then((res) => {
                if (this.active === 'aliPay') {
                  const div = document.createElement('div');
                  div.innerHTML = res.data;
                  document.body.appendChild(div);
                  document.forms[0].submit();
                  // 这个是为了兼容安卓支付宝没有跳转页面
                  localStorage.setItem('activityPurchaseVisible', 1);
                  setTimeout(() => {
                    this.activityPurchaseVisible = true;
                  }, 3000);
                  div.remove();
                } else {
                  window.location.replace(res.data);
                }
              })
              .catch((error) => {
                setTimeout(() => {
                  this.$toast(error.message);
                });
              })
              .finally(() => {
                this.btnLoading = false;
              });
          }
        })
        .catch((error) => {
          this.$toast(error.message);
          this.btnLoading = false;
        });

      // function
    },
    sort_ASCII(obj) {
      var arr = [];
      var num = 0;
      for (const i in obj) {
        arr[num] = i;
        num++;
      }
      var sortArr = arr.sort();
      var sortObj = {};
      for (var i in sortArr) {
        sortObj[sortArr[i]] = obj[sortArr[i]];
      }
      return sortObj;
    },
    jiaqian(content) {
      console.log(content);
      const PrivateKey =
        '-----BEGIN PRIVATE KEY-----MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKCIK/zTSJCP4XhNsb7Mc5lALog+oAja/spMjg8U6rAmVzRtKv8qhw1HK0CRbW/XV66uM+kY7fhjaYbjbbzu2PMMfs2GVpG15jCWLug9fn2hvPT1wkXfooJX61yHK7+inxAXPi4vPNi263mSQGbhZTeqbU5p7nLeRGbdFyBQXVKpAgMBAAECgYAu/475RxZAlI8rPHvkY1EYteypoMQTs6HSslUI31PSXHc9dxSWfenqHkLwdWM30jDuiDvUa6MIDHrRrfXr0XWcQ0IJ93jT7ABkFCdxcKEOG1WE8f1kZ5JyPDJjeQiI9R4jJCukpGU0DdzO7ORvRb4oTFQ15quM+3+SjnK5TtfUsQJBAOLLk03D2s7t2R0GPLZq+WL/ebowbRSy4VHP/IQi4K1bJrll0HLznov60m9UML1ATlS2ub98fBRFXEAaAwJE2O0CQQC1NDEWhrAPU5o3xjjcxIUbbYskskbhjaiX/1Vz0UzS4XfYek4SL68WBWPGWTrSbgbvXtaXj0gmcChF5jxOHtUtAkA4mPsqxfy99UdgYeUW1P1lgkH7gAhIyRdH1nK6+wU83el9DPaHKVrgrfiEBeuf3wNtSqhyK/u/B0wtRxCHKW1FAkAXfwcGdryJoDuVE9z3s3vXDKNIRN2wDaBY5UD9XZxqk9XoeiN5dDltz5EafSOFecLocxG8YVXntg9i0PHs506ZAkEAge9AKaXisZ4jCNHRn1LR2R82RtHTLb2mN3Cc6sGo+SnAKczwRwVg9RgnmaLG4Z/7kJpq0ALgEBlkOmy+9joxAw==-----END PRIVATE KEY-----';
      const signature = new RSA.KJUR.crypto.Signature({
        alg: 'SHA256withRSA',
      });
      signature.init(PrivateKey);
      signature.updateString(content);
      const signData = signature.sign();
      // 将内容转成base64
      return RSA.hex2b64(signData);
    },
    toAgreement() {
      sessionStorage.setItem('currentData', JSON.stringify(this.currentData));
      sessionStorage.setItem('active', this.active);
      sessionStorage.setItem('stepper', this.stepper);
      this.$router.push(
        '/claimCloudPhone/agreement?agreementCoding=XYPZYHXY2002',
      );
    },
    goBack() {
      this.$router.push('/claimCloudPhone/inviteeExits');
    },
    confirm(bool) {
      if (bool) return this.$router.replace('/claimCloudPhone/confirmation');
      this.activityPurchaseVisible = false;
      localStorage.removeItem('activityPurchaseVisible');
    },
  },
};
</script>

<style lang="less" scoped>
.purchase {
  height: 100%;
  box-sizing: border-box;
  padding-top: 210px;
  .purchase-privilege {
    padding: 16px;
    height: 102px;
    background: #ffffff;
    box-shadow: 0px 2px 4px 0px #f6e5d3;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    & > div {
      opacity: 0;
      animation: purchase 0.3s forwards linear;
      text-align: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #1c2023;
      line-height: 20px;
      font-style: normal;
      & > img {
        width: 42px;
        height: 42px;
        display: block;
        margin: 0 auto;
      }
    }
  }

  .payment-container {
    border-radius: 10px 10px 0 0;
    padding: 16px;
    display: flex;
    flex-direction: column;
    background: #f4f6f8;
    overflow-y: auto;
    .payment-container-title {
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #0a132b;
      line-height: 20px;
      text-align: center;
      font-style: normal;
    }

    .payment-container-info {
      margin-top: 16px;
      height: 100px;
      background: #ffffff;
      border-radius: 16px;
      display: flex;
      justify-content: center;
      align-items: center;
      .payment-container-info_value {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 28px;
        color: #0a132b;
        line-height: 32px;
        text-align: center;
        font-style: normal;
        span {
          font-size: 18px;
        }
      }

      .payment-container-info_name {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: #0a132b;
        line-height: 18px;
        text-align: center;
        font-style: normal;
      }
    }

    .payment-container-num {
      margin-top: 16px;
      padding: 16px;
      box-sizing: border-box;
      height: 50px;
      background: #ffffff;
      border-radius: 16px;
      font-family: PingFangSC, PingFang SC;
      font-weight: bold;
      font-size: 14px;
      color: #0a132b;
      line-height: 18px;
      text-align: left;
      display: flex;
      font-style: normal;
      .van-stepper {
        margin-left: 10px;
      }
    }

    .payment-container-method {
      .payment-container-method_title {
        font-family: PingFangSC, PingFang SC;
        font-weight: bold;
        font-size: 14px;
        color: #0a132b;
        line-height: 18px;
        text-align: left;
        font-style: normal;
        margin: 16px 0;
      }

      .payment-container-method_select {
        display: grid;
        grid-gap: 10px;
        grid-template-columns: repeat(3, 1fr);
        & > div {
          height: 54px;
          line-height: 54px;
          background: #edeef0;
          border-radius: 6px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-family: PingFangSC, PingFang SC;
          color: #666666;
          border: 1px solid transparent;
          font-style: normal;
          font-weight: 500;
          font-size: 14px;
          line-height: 18px;
          font-style: normal;
          &.active {
            background: #ffffff;
            border-radius: 6px;
            border: 1px solid #3b7fff;
            position: relative;
            .active-icon {
              position: absolute;
              top: 0;
              right: 0;
              width: 26px;
              height: 15px;
              background: #3a86fe;
              border-radius: 0px 6px 0px 6px;
              display: flex;
              justify-content: center;
              align-items: center;
              .van-icon-success {
                color: #fff;
              }
            }
          }
          & > img {
            width: 24px;
            height: 24px;
            margin-right: 4px;
          }
        }
      }
    }

    .payment-container-amount {
      background: #ffffff;
      box-shadow: 0px 0px 13px 0px rgba(206, 206, 206, 0.5);
      border-radius: 16px;
      display: flex;
      justify-content: space-between;
      margin-top: 24px;
      & > div:first-of-type {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 14px;
        color: #0a132b;
        line-height: 20px;
        font-style: normal;
        padding: 16px 0 16px 16px;
        & > span {
          font-weight: 500;
          font-size: 24px;
          color: #f04646;
          line-height: 20px;
          text-align: left;
          font-style: normal;
          span {
            font-size: 14px;
          }
        }
      }

      & > div:last-of-type {
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 16px;
        color: #ffffff;
        line-height: 22px;
        text-align: center;
        font-style: normal;
        line-height: 55px;
        height: 55px;
        width: 136px;
        background: linear-gradient(90deg, #38aefc 0%, #3b7fff 100%);
        border-radius: 16px;
      }
    }

    .payment-container-agreement {
      margin-top: 9px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 12px;
      color: #bbbbbb;
      line-height: 16px;
      text-align: center;
      font-style: normal;
      span {
        color: #3a86fe;
      }
    }
  }
}

.payment-tips {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  padding-top: 10px;
  &:last-of-type {
    padding-bottom: 10px;
  }
}

.disabled {
  opacity: 0.3;
}

@keyframes purchase {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
</style>
