<script setup lang="ts">
import { showConfirm } from '@/components/Toast'
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { openPay, getOrderInfo, wxLogin } from '@/api/api'
import { useRoute } from 'vue-router'
import { GetRequest, getWeChatCode, getRemark } from '@/utils/index'
import { useI18n } from 'vue-i18n'
const route = useRoute()
const orderDetal = ref({
  payStatus:0
})
const orderSn = ref(route.query.id || GetRequest('id'))
const { locale: language, t } = useI18n()
const userStore = useUserStore();
const isEur = userStore.isEur
const payType = ref(isEur?'5':'0')
const openId = computed(() => userStore.getOpenId);
const is_zfb = ref(false)
const is_weixn = ref(false)
var browser = navigator.userAgent.toLowerCase();
  if(isEur){
    payType.value = '5'
  }else if(browser.match(/Alipay/i)=="alipay"){
    console.log("支付宝app的浏览器");
    is_zfb.value = true
    payType.value = '4'
  }else if(browser.match(/MicroMessenger/i)=="micromessenger"){
    console.log("微信app的浏览器");
    is_weixn.value = true
  }
// const is_weixn = computed(() => {
//   var wx = window.navigator.userAgent.toLowerCase()
//   if (wx.match(/MicroMessenger/i) == 'micromessenger') {
//     return true // 是微信端
//   } else {
//     return false
//   }
// })
// let PAYSID = {
//   wechatPay: is_weixn.value ? 1 : 0,
//   alipay: 4,
//   paypal: 5
// }
//判断是否微信
onMounted(() => {
  getDetial()
})
async function handelPay() {
  let apiData = {
    orderSn: orderSn.value,
    payType: is_weixn.value ? '1' : payType.value,
    openId:openId.value,
    productName: getRemark(orderDetal.value.goodsInfo, orderDetal.value.orderType, t),
  }
  const res = await openPay(apiData)

  if (is_weixn.value) {
    //微信内支付
    onBridgeReady(res)
  } else if (res.form || res.h5Url || res.redirect) {
    console.log('payType', res.form || res.h5Url)
    window.location.href = res.form || res.h5Url || res.redirect
  } else {
    showConfirm({
      text: t('payInfo.userName'),
      type: 'err',
      callback: (val) => {
      }
    })
  }
}
// 调微信支付
function onBridgeReady(obj) {
  var that = this
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      appId: obj.appid,
      //公众号名称，由商户传入
      timeStamp: obj.timeStamp + '',
      //时间戳，自1970年以来的秒数
      nonceStr: obj.nonceStr,
      //随机串
      package: `prepay_id=${obj.prepayId}`,
      signType: obj.signType,
      //微信签名方式：
      paySign: obj.paySign
    },
    function (res) {
      if (res.err_msg == 'get_brand_wcpay_request:ok') {
        orderDetal.value.payStatus = 1
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        handlePayresult()
      } else {
        orderDetal.value.payStatus = 2
        handlePayresult()
      }
    }
  )
}
function handleType(params: string) {
  payType.value = params
}
function getDetial() {
  getOrderInfo(orderSn.value).then((res) => {
    orderDetal.value = res
    if(res.payStatus != 0){
      handlePayresult()
      return
    }else{
      setTimeout(()=>{
        renewStatus()
      },2000)
    }
    if(is_weixn.value){
      handleWxlogin(res.wxAppId)
    }
  })
}

function renewStatus() {
  getOrderInfo(orderSn.value).then((res) => {
    orderDetal.value = res
    if(res.payStatus != 0){
      handlePayresult()
      return
    }else{
      setTimeout(()=>{
        renewStatus()
      },2000)
    }
  })
}
async function handlePayresult(){
  let item = orderDetal.value
  if(!item.orderType){
    orderDetal.value = await getOrderInfo(orderSn.value)
    item = orderDetal.value
  }
  showConfirm({
        text: item.autoPay? t('payInfo.autoPayTips', {paytype: item.payType == 5 ? 'PayPal' : 'Stripe'}) : item.payStatus === 2 ? t('payInfo.payfail') : t('mall.paySuccessTip'),
        type: item.payStatus == 2 ? 'err' : 'success',
        callback: () => {
        if(item.orderType == 'incrementOrder'){
          location.replace(`/mobile.html#/information`)
        }else{
          location.replace(`/mobile.html#/payresult/${item.payStatus == 2?'fail':'success'}`)
        }
        }
      })
}
async function handleWxlogin(wxAppId: string) {
  // userStore.setUserOpenId('o3S0L1Hyd3O0vYI2Kr1lFDEtEO2k')
  const code = GetRequest('code')
  if (!openId.value && !code) {
    //微信登录
    getWeChatCode(wxAppId)
  } else if (code) {
    //存在code 换取openid
    const res = await wxLogin({ code, orderSn: orderSn.value })
    if (res.openid) {
      userStore.setUserOpenId(res.openid)
    }
  }
}
async function handleOpenPay() {
  openPay({
    orderSn: GetRequest('orderSn'),
    payType: payType.value,
    openId:openId.value,
  }).then((res) => {
    let url = res.qrCodeUrl
  })
}
</script>
<template>
  <div class="mobilePage">
    <div class="pageTitle">{{$t('payInfo.payCenter')}}</div>
    <div class="contentInfo">
      <div class="info">
        <div class="cell">
          <span>{{$t('payInfo.userName')}}{{ getOpenId }}</span>
          <span>{{orderDetal.userName}}</span>
        </div>
        <div class="cell" v-if="orderDetal.orderType == 'incrementOrder'">
          <span>{{$t('payInfo.membership')}}</span>
          <span v-if="orderDetal.goodsInfo && orderDetal.goodsInfo[0]">
            {{ orderDetal.goodsInfo[0].type==1?$t('payInfo.gjhy'):isEur?$t('payInfo.zyhys'):$t('payInfo.zyhy') }}
            <span>× {{orderDetal.goodsInfo[0].count}}</span>
            <!-- <span v-else>1</span> -->
            <span v-if="orderDetal.orderType == 'incrementOrder'">，{{ orderDetal.goodsInfo[0].type==1?$t(`payInfo.expirationmon`,{num:orderDetal.goodsInfo[0].monthQy || 1}):$t(`payInfo.expiration`,{num:1}) }}</span>
            </span>
        </div>
        <div class="item" v-if="orderDetal.orderType == 'partOrder'">
          <div class="cell" style="border:none">
            <span style="max-width:85px">{{ $t(`mall.goqy`) }}</span>
            <span></span>
          </div>
          <div class="cell" v-for="(item,index) in orderDetal.goodsInfo" :key="index" style="border:none">
          <span style="max-width:230px;line-height: 16px;">{{ language === 'zh' ?item.name:item.nameEn }}</span>
          <span>
            × {{item.count}}
          </span>
        </div>
        </div>
        <div class="item" v-else-if="orderDetal.orderType == 'cooperationOrder'">
          <div class="cell" style="border:none">
            <span style="max-width:85px">{{ $t(`mall.cooperationOrder`) }}</span>
            <span></span>
          </div>
          <div class="cell" v-for="(item,index) in orderDetal.goodsInfo" :key="index" style="border:none">
          <span style="max-width:230px;line-height: 16px;">{{ $t('mall.cooperationOrderName',{count: item.count }) }}</span>
        </div>
        </div>
        <div class="cell" v-else>
          <span style="min-width:85px">{{ $t(`mall.${orderDetal.orderType == 'downOrder'?'downdesc':'goqy'}`) }}</span>
          <span>
            <span v-for="(item,index) in orderDetal.goodsInfo" :key="index">
              <span v-if="index != 0">、</span>
                  <span style="margin-right:5px" v-if="orderDetal.orderType != 'incrementOrder'">
                    {{ orderDetal.orderType == 'downOrder'?`${item.name} (${item.sceneNum})`:language === 'zh' ?item.name:item.nameEn }}
                  </span>
                  <span style="margin-right:5px" v-else>
                    {{ item.type==1?$t('payInfo.gjhy'):isEur?$t('payInfo.zyhys'):$t('payInfo.zyhy') }}
                  </span>
                   <span v-if="orderDetal.orderType != 'downOrder'">× {{item.count}}</span>
                
            </span>
          </span>
        </div>
      </div>
      <div class="payType">
        <div class="cell" @click="handleType('0')" v-if="!is_zfb && !isEur">
          <span>
            <img class="payTypeImg" src="@/assets/images/wechat56.png" alt="" />
            {{$t('payInfo.wx')}}
          </span>
          <div class="select" :class="{ active: payType == '0' }"></div>
        </div>
        <div class="cell" @click="handleType('4')" v-if="!is_weixn && !isEur">
          <span>
            <img class="payTypeImg" src="@/assets/images/alipay56.png" alt="" />
            {{$t('payInfo.zfb')}}
          </span>
          <div class="select" :class="{ active: payType == '4' }"></div>
        </div>
        <div class="cell" @click="handleType('5')" v-if="isEur">
          <span>
            <img style="height:26px;width:100px" class="payTypeImg" src="@/assets/images/paypal.png" alt="" />
            <!-- {{$t('payInfo.paypal')}} -->
          </span>
          <div class="select" :class="{ active: payType == '5' }"></div>
        </div>
        <!-- <div class="cell" @click="handleType('6')" v-if="isEur">
          <span>
            <img style="height:26px;width:62px" class="payTypeImg" src="@/assets/images/stripe.png" alt="" />
          </span>
          <div class="select" :class="{ active: payType == '6' }"></div>
        </div> -->
      </div>
    </div>
    <div class="bottomInfo">
      <div class="price">
        {{$t('payInfo.payPrice')}}<span style="margin-left:10px">{{isEur?'$':$t('payInfo.priceUnit')}}{{ orderDetal?.orderMoney || 0.0 }}</span>
      </div>
      <div class="payBut" @click="handelPay">{{ orderDetal.autoPay == 1?$t('payInfo.autoRenew'):$t('payInfo.payOrder') }}</div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.mobilePage {
  background: #f7f7f7;
  min-height: calc(100vh - 50px);
  max-width: 100vw;
  display: block;
  color:#202020;
  .pageTitle {
    width: calc(100% - 40px);
    padding: 23px 20px;
    background: #ffffff;
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
    border: 1px solid #e6e6e6;
    margin-bottom: 10px;
  }
  .contentInfo {
    .cell {
      display: flex;
      justify-content: space-between;
      background-color: #fff;
      padding: 15px 20px;
      border-bottom: 1px solid #ebedf0;
      align-items: center;
      &:last-child {
        border-bottom: none;
      }
      .select {
        border-radius: 50%;
        height: 20px;
        width: 20px;
        border: 1px solid #d5d8de;
      }
      .active {
        background: url('@/assets/images/active.png');
        background-position: center center;
        background-size: 22px;
        height: 22px;
        width: 22px;
        border: none;
      }
      .payTypeImg {
        height: 18px;
        width: 20px;
        margin-right: 8px;
        position: relative;
        top: 3px;
      }
    }
  }
  .bottomInfo {
    height: 56px;
    width: 100%;
    border-radius: 0px 0px 0px 0px;
    display: flex;
    align-items: center;
    background-color: #fff;
    justify-content: space-between;
    position: fixed;
    bottom: 0px;
    .price {
      padding: 5px 20px;
      span {
        font-size: 16px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #ff0000;
        line-height: 19px;
        // letter-spacing: 4px;
      }
    }
    .payBut {
      background: @primary-color;
      border-radius: 0px 0px 0px 0px;
      opacity: 1;
      width: 120px;
      line-height: 56px;
      height: 100%;
      color: #fff;
      text-align: center;
    }
  }
  .info {
    margin-bottom: 10px;
    font-size: 16px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #202020;
    line-height: 19px;
  }
}
</style>
