<template>
  <Theme>
    <view class="wrap">
      <Navbar
        title="支付方式"
        fixed
        border
        autoBack
        :leftShow="isIosPay"
        @leftClick="leftClick"
      >
        <template #right v-if="!isIosPay">
          <navMenu :options="{ icon: 'icon-home', text: '主页' }" />
        </template>
      </Navbar>
      <view class="content">
        <view class="logo-container">
          <image
            class="logo"
            src="@/static/login/login_logo.png"
            mode="aspectFit"
          ></image>
        </view>
        <view class="cont">
          <view class="payable_price">
            {{ symbol.symbol }}
            <text>{{ Moneyhtml(payInfo.totalAmt) }}</text>
          </view>
          <view class="logistics_step" v-if="type == 'order'">
            <trans _t="请在" />
            <text class="step_time">{{
              useGlobal().$format(payInfo.enddate || "")
            }}</text>
            <trans _t="取消付款提示" />
          </view>
          <view class="wallet_pay" v-if="!isAPPIOS">
            <template v-if="type != 'recharge'">
              <view class="wallet_title">
                <trans _t="用余额支付" />
                <view class="tag">
                  <trans _t="推荐" />
                </view>
              </view>
            </template>
            <view class="wallet_content">
              <view class="wallet_top" v-if="type != 'recharge'">
                <up-radio-group v-model="radioValue" activeColor="var(--black)">
                  <up-radio name="wallet">
                    <template #label>
                      <view style="display: flex; align-items: center">
                        <view class="wallet_img">
                          <image
                            src="../../static/shop/balance.png"
                            class="_img"
                          ></image>
                        </view>
                        <view class="payment_text">
                          <view class="payment_title">
                            <trans _t="钱包" />
                          </view>
                          <view class="wallet_amount"
                            >{{ symbol.symbol }}&nbsp;{{
                              Moneyhtml(totalAmt)
                            }}</view
                          >
                        </view>
                      </view>
                    </template>
                  </up-radio>
                </up-radio-group>
              </view>
              <view class="wallet_bottom" v-if="differenceMoney < 0">
                <view class="bottom_left">
                  <trans _t="余额不足需充值" />
                  <text class="money">¥{{ Math.abs(differenceMoney) }}</text>
                </view>
                <view class="bottom_right" @click="toRecharge">
                  <trans _t="充值" />
                </view>
              </view>
            </view>
            <view
              class="wallet_content"
              v-for="(item, index) in bankList"
              :key="index"
            >
              <view class="wallet_top">
                <up-radio-group v-model="radioValue" activeColor="var(--black)">
                  <up-radio :name="item.name">
                    <template #label>
                      <view style="display: flex; align-items: center">
                        <view class="wallet_img">
                          <image
                            :src="`../../static/shop/${item.icon}`"
                            class="_img"
                          ></image>
                        </view>
                        <view class="payment_text">
                          <view class="payment_title">
                            <trans :_t="item.title" />
                          </view>
                        </view>
                      </view>
                    </template>
                  </up-radio>
                </up-radio-group>
              </view>
            </view>
            <!-- <DropInPay :oid="oid" ref="dropInPayRef"></DropInPay> -->
          </view>
          <view class="order-status" v-if="isAPPIOS">
            <trans _t="订单处理中" />
          </view>
          <couponModel
            :item="couponList"
            @change="changeId"
            v-if="type == 'package'"
            class="coupon"
          />
        </view>

        <view class="footer">
          <view class="tips">
            <trans _t="您将在安全的环境下付款给" />VAVABUY
          </view>
          <view class="handling_fee">
            <trans _t="手续费" />&nbsp;:&nbsp;{{ symbol.symbol }}&nbsp;0
          </view>
          <view class="amount">
            <text>{{ symbol.symbol }}&nbsp;</text>
            <text>{{ Moneyhtml(payInfo.totalAmt) }}</text>
          </view>
          <view class="footer_btn" @click="openPassword" v-if="!isAPPIOS">
            <trans _t="支付" />
            <text>{{ symbol.symbol }}</text>
            <text>{{ Moneyhtml(payInfo.totalAmt) }}</text>
          </view>
        </view>
      </view>
      <successModel ref="successModels" @open="handleSuccessModelOpen">
        <template #footer v-if="type == 'service' || isIosPay">
          <view></view>
        </template>
      </successModel>
    </view>
    <PasswordModal ref="passwordModal" @complete="completePassword" />
    <!-- #ifdef H5 -->
    <SplitCardPay
      ref="splitCardPayModalRef"
      :paramsObj="paramsObj"
      @on-success="handleAairwallexSuccess"
    />
    <GooglePayModal
      ref="googlePayRef"
      :paramsObj="paramsObj"
      @success="handleAairwallexSuccess"
    />
    <ApplePayModal
      ref="applePayModalRef"
      :paramsObj="paramsObj"
      @on-success="handleAairwallexSuccess"
    />
    <!-- #endif -->
    <!-- #ifdef APP-PLUS -->
    <cardPaymentApp
      ref="cardpaymentAppRef"
      :paramsObj="paramsObj"
      @on-success="handleAairwallexSuccess"
    />
    <googlePaymentApp ref="googlepaymentAppRef" :paramsObj="paramsObj" />
    <!-- #endif -->
  </Theme>
</template>
<script setup>
import Navbar from "@/components/navbar";
import navMenu from "@/components/nav_menu";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { ref, nextTick, computed, onMounted, onUnmounted } from "vue";
import {
  SHOP_PAY_INFO,
  SHOP_SUBMIT_PAY,
  SHOP_PACKAGES_PAY,
  SHOP_GET_CANCOUPON,
  SHOP_PAY_STATUS,
} from "@/api";
import { useSystemStore, useUserStore, useTabbarStore } from "@/store";
import { useGlobal, Toast, Moneyhtml, query, systemInfo } from "@/utils";
import PasswordModal from "@/components/passwordModal";

// #ifdef H5
import SplitCardPay from "@/components/paymentModal/splitCardPay";
import GooglePayModal from "@/components/paymentModal/googlePay";
import ApplePayModal from "@/components/paymentModal/applePay";
// #endif
// #ifdef APP-PLUS
import cardPaymentApp from "@/components/paymentModal/cardPayment_app";
import googlePaymentApp from "@/components/paymentModal/googlePayment_app";
// #endif

// import DropInPay from "@/components/paymentModal/dropInPay"
import successModel from "./components/successModel";
import couponModel from "./components/couponModel";

const systemInfoName = systemInfo();

const useSystem = useSystemStore();
const useUser = useUserStore();
const useTabbar = useTabbarStore();

const oid = ref("");
const payInfo = ref({});
const radioValue = ref("wallet");
const successModels = ref(null);
const cardpaymentAppRef = ref(null);
const googlepaymentAppRef = ref(null);

const symbol = computed(() => useSystem.getSymbol);
const userInfo = computed(() => useUser.getuserInfo);
const differenceMoney = computed(() => {
  let infoPrice = Number(userInfo.value.money);
  let payPrice = Number(payInfo.value.totalAmt);
  if (infoPrice > payPrice || infoPrice == payPrice) {
    return 0;
  } else {
    return infoPrice - payPrice;
  }
});

const totalAmt = computed(() => {
  if (payInfo.value.payList?.length) {
    return payInfo.value.payList[0].moeny;
  }
  return 0;
});

const bankList = [
  {
    name: "airwallex",
    title: "银行卡",
    icon: "bank_card.png",
  },
  // #ifndef APP-PLUS
  {
    name: "google",
    title: "Google支付",
    icon: "google.png",
  },
  {
    name: "ABA",
    title: "ABA KHQR",
    icon: "KHQR.png",
  },
  // #endif
];
if (useGlobal().$adjustPosition) {
  const applePayConf = {
    name: "apple",
    title: "Apple支付",
    icon: "applepay.png",
  };
  const i = bankList.findIndex((item) => item.name == applePayConf.name);
  i < 0 && bankList.push(applePayConf);
}
const isAPPIOS = ref(false);

const issubnum = ref(0);
const isPage = ref("");
const type = ref("");
const couponList = ref([]);
const checkDate = ref(null);

const passwordModal = ref(null);
const cardPayModalRef = ref(null);
const splitCardPayModalRef = ref(null);
const applePayModalRef = ref(null);
const googlePayRef = ref(null);
const paramsObj = ref(null);
const isIosPay = ref(false);
const isIosPayParams = ref({});
const lunxunTimeout = ref(null);
// const dropInPayRef = ref(null);

const openPassword = () => {
  const isShipping = type.value === "package";
  paramsObj.value = {
    [isShipping ? "id" : "oid"]: oid.value,
    type: type.value,
  };
  if (isShipping && payInfo.value.couponId) {
    paramsObj.value.couponId = payInfo.value.couponId;
  }
  // #ifdef APP-PLUS
  if (isAPPIOS.value) {
    if (systemInfoName.osName == "ios") {
      let queryParams = "isIosPay=true";
      for (let key in isIosPayParams.value) {
        queryParams = `${queryParams}${
          queryParams.length > 0 ? "&" : ""
        }${key}=${isIosPayParams.value[key]}`;
      }
      lunxunTimeout.value = setInterval(() => {
        checkPayStatusByLunxun();
      }, 1000 * 5);
      plus.runtime.openURL(
        "https://vavabuy.net/#/pages/shop/payment?" + queryParams
      );
    } else {
      cardpaymentAppRef.value && cardpaymentAppRef.value.open(paramsObj.value);
    }
    return;
  }
  // #endif
  if (radioValue.value == "wallet") {
    if (isIosPay.value) {
      passwordModal.value && passwordModal.value.open();
    } else {
      if (userInfo.value.setpaypass) {
        passwordModal.value && passwordModal.value.open();
      } else {
        uni.navigateTo({ url: "/pages/setting/account-safety" });
      }
    }

    return;
  }
  // if (radioValue.value == 'airwallex') return cardPayModalRef.value && cardPayModalRef.value.open();
  // #ifdef H5
  if (radioValue.value == "airwallex")
    return splitCardPayModalRef.value && splitCardPayModalRef.value.open();
  if (radioValue.value == "google")
    return googlePayRef.value && googlePayRef.value.open();
  if (radioValue.value == "apple")
    return applePayModalRef.value && applePayModalRef.value.open();
  // #endif
  // #ifdef APP-PLUS
  // if (radioValue.value == 'airwallex') return cardpaymentAppRef.value && cardpaymentAppRef.value.open(paramsObj.value);
  if (radioValue.value == "airwallex") {
    if (systemInfoName.osName == "ios") {
      let queryParams = "isIosPay=true";
      for (let key in isIosPayParams.value) {
        queryParams = `${queryParams}${
          queryParams.length > 0 ? "&" : ""
        }${key}=${isIosPayParams.value[key]}`;
      }
      console.log("queryParams", queryParams);
      lunxunTimeout.value = setInterval(() => {
        checkPayStatusByLunxun();
      }, 1000 * 5);
      plus.runtime.openURL(
        "https://vavabuy.net/#/pages/shop/payment?" + queryParams
      );
    } else {
      cardpaymentAppRef.value && cardpaymentAppRef.value.open(paramsObj.value);
    }
    return;
  }
  if (radioValue.value == "google")
    return googlepaymentAppRef.value && googlepaymentAppRef.value.open();
  // #endif
};
const completePassword = (password) => {
  paySubmit(password);
};

const paySubmit = async (password) => {
  try {
    const isShipping = type.value === "package";

    const params = {
      type: type.value,
      payType: radioValue.value,
      paypass: password,
      [isShipping ? "id" : "oid"]: oid.value,
    };
    if (isShipping && payInfo.value.couponId) {
      params.couponId = payInfo.value.couponId;
    }
    const res = await SHOP_PACKAGES_PAY(params);
    // useUser.getUserInfo();
    passwordModal.value && passwordModal.value.close();
    useTabbar.getPageCur("shop");
    successModels.value && successModels.value.open();
    // setTimeout(() => {
    //   uni.$emit("on-open");
    //   uni.navigateBack();
    // }, 1000);
  } catch (error) {
    Toast(error.msg);
  }
};

const checkPayStatusByLunxun = () => {
  const params = {
    oid: oid.value,
    type: type.value,
  };
  SHOP_PAY_STATUS(params)
    .then((result) => {
      console.log("轮询 result", JSON.stringify(result));
      useTabbar.getPageCur("shop");
      successModels.value && successModels.value.open();
      removePayStatusLunxun();
    })
    .catch((err) => {
      console.log("轮询 err", JSON.stringify(err));
    });
};
const removePayStatusLunxun = () => {
  clearInterval(lunxunTimeout.value);
  lunxunTimeout.value = null;
};

// #ifdef H5
const handleAairwallexSuccess = (dataInfo) => {
  switch (radioValue.value) {
    case "airwallex":
      // cardPayModalRef.value && cardPayModalRef.value.close();
      splitCardPayModalRef.value && splitCardPayModalRef.value.close();
      break;
    case "google":
      googlePayRef.value && googlePayRef.value.close();
      break;
    case "apple":
      applePayModalRef.value && applePayModalRef.value.close();
      break;
    default:
      break;
  }
  useTabbar.getPageCur("shop");
  successModels.value && successModels.value.open();
};
// #endif

// #ifdef APP-PLUS
const handleAairwallexSuccess = (dataInfo) => {
  console.log("----- on-success dataInfo ----", dataInfo);
  switch (radioValue.value) {
    case "airwallex":
      cardpaymentAppRef.value && cardpaymentAppRef.value.close();
      break;
    case "google":
      googlepaymentAppRef.value && googlepaymentAppRef.value.open();
      break;
    case "apple":
      break;
    default:
      break;
  }
  useTabbar.getPageCur("shop");
  successModels.value && successModels.value.open();
};
// #endif

const toRecharge = () => {
  uni.navigateTo({ url: "/pages/bank/recharge" });
};
const leftClick = () => {
  if (isPage.value == "order") {
    uni.switchTab({ url: "/pages/order/index" });
    useTabbar.getPageCur("shop");
  } else {
    uni.navigateBack();
  }
};
onLoad((options) => {
  oid.value = options.oid;
  isPage.value = !!options.page ? options.page : "";
  type.value = !!options.type ? options.type : "";
  isIosPay.value =
    options.isIosPay == true || options.isIosPay == "true" ? true : false;

  isIosPayParams.value = {
    oid: options.oid,
    page: !!options.page ? options.page : "",
    type: !!options.type ? options.type : "",
    money: !!options.money ? options.money : "",
  };

  if (type.value == "recharge") {
    radioValue.value = "airwallex";
  }
  nextTick(() => {
    getPayInfo();
  });
});

onUnload(() => {
  removePayStatusLunxun();
});
onUnmounted(() => {
  removePayStatusLunxun();
});

function handleSuccessModelOpen() {
  console.log(isIosPay.value, "isIosPay.value");
  if (isIosPay.value) {
    setTimeout(() => {
      uni.navigateBack({
        success: () => {
          uni.$emit("on-service-open");
        },
      });
    }, 1000);
  }
}

const getPayInfo = async () => {
  try {
    const res = await SHOP_PAY_INFO({
      oid: oid.value,
      type: type.value,
      couponId: payInfo.value.couponId,
    });
    payInfo.value = res.data;
    couponList.value = res.data.coupons || [];
  } catch (error) {}
};

const getCoupon = async (money) => {
  try {
    const res = await SHOP_GET_CANCOUPON(money);
    couponList.value = res.data || [];
  } catch (error) {}
};
const changeId = (id, data) => {
  if (id) {
    payInfo.value.couponId = id;
    checkDate.value = data;
  } else {
    delete payInfo.value.couponId;
    checkDate.value = null;
  }
  getPayInfo();
};

onMounted(() => {
  // #ifdef APP-PLUS
  if (useGlobal().$adjustPosition) {
    isAPPIOS.value = true;
    nextTick(() => {
      openPassword();
    });
  }
  // #endif
});
</script>
<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  max-height: 100vh;
  background-color: var(--bg);
  .flex();
  flex-direction: column;
  overflow: hidden;
  .content {
    position: relative;
    flex-grow: 1;
    .flex();
    flex-direction: column;
    height: calc(100dvh - 44px);
    overflow: hidden scroll;
    z-index: 1;
    .logo-container {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 1;
      opacity: 0.3;
      pointer-events: none;

      .logo {
        width: 570rpx;
        height: 496rpx;
      }
    }

    .cont {
      flex-grow: 1;
      overflow: hidden scroll;
      .coupon {
        margin: 0 30rpx;
      }
      .order-status {
        text-align: center;
        .size(36rpx);
        color: var(--black);
      }

      .payable_price {
        color: var(--text);
        .size(48rpx);
        font-weight: 700;
        line-height: 60rpx;
        padding-top: 24rpx;
        text-align: center;
      }

      .logistics_step {
        color: var(--text-01);
        .size(28rpx);
        line-height: 40rpx;
        padding: 32rpx 24rpx 0;

        .step_time {
          margin: 0 8rpx;
          display: inline-block;
          color: var(--text);
          font-weight: 700;
        }
      }

      .wallet_pay {
        margin: 24rpx;
        padding: 24rpx;
        border-radius: 16rpx;
        background-color: var(--light);

        .wallet_title {
          .ver();
          .size(36rpx);
          font-weight: 700;
          height: 60rpx;
          color: var(--text);

          .tag {
            background-color: var(--danger);
            border-radius: 8rpx;
            color: var(--light);
            .size(24rpx);
            font-weight: 500;
            line-height: 40rpx;
            margin-left: 8rpx;
            padding: 0 8rpx;
          }
        }

        .wallet_content {
          margin-top: 24rpx;

          .wallet_top {
            /deep/ .u-radio-group {
              flex: none;

              .u-radio__icon-wrap {
                margin-right: 0;
              }
            }

            .ver();

            .wallet_img {
              width: 72rpx;
              height: 72rpx;
              margin: 0 24rpx;

              ._img {
                width: inherit;
                height: inherit;
              }
            }

            .payment_text {
              .ver(flex-end);
              color: var(--text);
              .size();
              font-weight: 500;

              .wallet_amount {
                margin-left: 8rpx;
                font-weight: 700;
              }
            }
          }

          .wallet_bottom {
            margin-top: 16rpx;
            padding: 16rpx 24rpx;
            background-color: var(--bg);
            border-radius: 8rpx;
            .flex_position(space-between);

            .bottom_left {
              color: var(--text-02);
              .size(24rpx);
              margin-right: 16rpx;

              .money {
                color: var(--primary);
              }
            }

            .bottom_right {
              height: 64rpx;
              background-color: var(--black);
              color: var(--light);
              border-radius: 16rpx;
              padding: 16rpx 30rpx;
              .flex_center();
              .size(24rpx);
              line-height: 1;
            }
          }
        }
      }
    }

    .footer {
      padding: 0 24rpx 24rpx;
      background-color: var(--bg);
      .tips {
        color: var(--black);
        .size(28rpx);
        font-weight: 600;
        line-height: 60rpx;
        text-align: center;
      }
      .handling_fee {
        color: var(--text-01);
        .size(28rpx);
        line-height: 60rpx;
        text-align: center;
      }

      .amount {
        color: var(--red);
        .size(48rpx);
        font-weight: 700;
        line-height: 80rpx;
        text-align: center;
      }

      &_btn {
        background-color: var(--black);
        color: var(--light);
        padding: 16rpx 30rpx;
        height: 96rpx;
        .flex_center();
        border-radius: 16rpx;
        font-weight: 700;
        .size(28rpx);
        column-gap: 8rpx;
      }
    }
  }
}
</style>