<template>
  <div class="mianBox">
    <van-row class="headerBox">
      <van-icon name="arrow-left" @click="$router.go(-1)" />
      选择充值方式
    </van-row>
    <van-row class="contentBox">
      <van-row>
        <!-- <van-col @click="openApp({app:'weixin://dl/scan',downA:'https://dldir1.qq.com/weixin/android/weixin8011android1980_arm64.apk',downI:'https://itunes.apple.com/cn/app/wei/id414478124',})"></van-col> -->
        <van-col @click="openApp({app: 'weixin://scanqrcode',downA:'https://dldir1.qq.com/weixin/android/weixin8011android1980_arm64.apk',downI: 'https://itunes.apple.com/cn/app/wei/id414478124',})">
          <van-image :src="require('../../assets/image/wx.png')" />
        </van-col>
        <van-col @click="openApp({app: 'alipayqr',downA:'https://t.alipayobjects.com/L1/71/100/and/alipay_wap_main.apk',downI: 'https://itunes.apple.com/cn/app/id333206289?mt=8',})">
          <van-image :src="require('../../assets/image/zfb.png')" />
        </van-col>
        <!-- 隐藏<van-col @click="openApp({app:'alipayqr://platformapi/startapp?saId=20000067&url=https://blog.csdn.net/sun5769675/article/details/89634633',downA:'https://t.alipayobjects.com/L1/71/100/and/alipay_wap_main.apk',downI:'https://itunes.apple.com/cn/app/id333206289?mt=8',})"></van-col>
          隐藏<van-col @click="openApp({app:'ysf',downA:'https://youhui.95516.com/app/app/software/unionpay-wallet-v2.apk',downI:'https://dl.95862788.com/52/77785',})"></van-col>
          <van-col @click="openApp({app:'ysf',downA:'https://youhui.95516.com/app/app/software/unionpay-wallet-v2.apk',downI:'https://youhui.95516.com/hybrid_v4/html/help/download.html?code=ctoc00000000022',})">
			      <van-image :src="require('../../assets/image/ysf.png')" />
		      </van-col> -->
      </van-row>
      <van-row> 请选择微信、支付宝进行充值。</van-row>
        <van-row style="color:red;margin-top:4px;" v-if="user && version || user && huawei">(华为、Android10系统在选择微信支付时，需要开启微信的“浮窗”和“允许在其他上层应用上打开”这两个权限) </van-row>
      <van-loading
        size="24px"
        v-if="loading"
        vertical
        style="z-index: 999999; position: fixed; top: 40%; left: 0; right: 0"
        >加载中...</van-loading
      >
      <van-overlay :show="loading" style="z-index: 100; position: fixed" />
    </van-row>
  </div>
</template>
<script>
import axios from "axios";
import { Dialog, Notify, Toast } from "vant";
// import { getPayApi} from "@/plugins/common";
export default {
  components: {
    [Notify.Component.name]: Notify.Component,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      iosApp: "",
      url: "",
      loading: false,
      money: null,
      channelId: undefined,
      userId:undefined,
      version:false,
      huawei:false,
    };
  },
  mounted() {
    //判断安卓版本
    var ua = navigator.userAgent.toLowerCase();
    if (/android/i.test(navigator.userAgent)) {
      var test = /android\s([\w.]+)/;//IE
      var match = test.exec(ua);
      var version = match[1].split(".")[0];
      if(version >= 10){
        this.version = true
      }
    }
    var brand = this.judgeBrand(navigator.userAgent.toLowerCase()); //调用机型判断
    if(brand == "huawei"){
      this.huawei = true
    }
  
    // window.document.addEventListener('message', function (e) {
    //     /*
    //     * e.data 是APP返回的JSON字符串，字段：
    //     * eventType 事件类型
    //     * source    来源
    //     * data      业务参数 - 返回数据放这里
    //     * */
    //     const res = JSON.parse(e.data); // 报文参数
    //     if(res){
    //       Toast(res)
    //       if(res.extMsg == "已支付"){
    //         window.history.go(-999)
    //       }
    //     }
    //     switch (res.eventType) {
    //         case "com.launchMiniProgram": { // 扫描二维码成功后的消息
    //           // Do Something ...
    //           document.getElementById("text").innerHTML = res.data.data;
    //           break
    //         }
    //     }
    // })
  },
  created() {
    this.money = this.$route.query.money;
    this.channelId = this.$route.query.channelId;
    if(localStorage.getItem("user")){
      this.user = localStorage.getItem("user")
    }
  },
  methods: {
      judgeBrand(sUserAgent) {
        var isIphone = sUserAgent.match(/iphone/i) == "iphone";
        var isHuawei = sUserAgent.match(/huawei/i) == "huawei";
        var isHonor = sUserAgent.match(/honor/i) == "honor";
        var isOppo = sUserAgent.match(/oppo/i) == "oppo";
        var isOppoR15 = sUserAgent.match(/pacm00/i) == "pacm00";
        var isVivo = sUserAgent.match(/vivo/i) == "vivo";
        var isXiaomi = sUserAgent.match(/mi\s/i) == "mi ";
        var isXiaomi2s = sUserAgent.match(/mix\s/i) == "mix ";
        var isRedmi = sUserAgent.match(/redmi/i) == "redmi";
        var isSamsung = sUserAgent.match(/sm-/i) == "sm-";

        if (isIphone) {
            return 'iphone';
        } else if (isHuawei || isHonor) {
            return 'huawei';
        } else if (isOppo || isOppoR15) {
            return 'oppo';
        } else if (isVivo) {
            return 'vivo';
        } else if (isXiaomi || isRedmi || isXiaomi2s) {
            return 'xiaomi';
        } else if (isSamsung) {
            return 'samsung';
        } else {
            return 'default';
        }
    },
    randomString() {
      let len = 32;
      let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = $chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    async pay(money, topPayType, payType, channelId,userId) {
      if(userId){
        //("返回支付宝app支付链接")
        axios.get("dxtop/staff/one",{
          params:{
            id:localStorage.getItem("user")
          }
        }).then(res =>{
          //console.log(res)
          if(res.data?.data?.sid){
            //console.log(res.data.data.sid)
            axios.post('/dxtop/order/callUnifiedPay', {
              "money": money,
              "topPayType": topPayType,
              "payType": payType,
              "scene": 3,
              "userId": res.data.data.sid
            }).then(res2 => {
              this.loading = false;
              //console.log(res2)
              if(res2.data.code == 500){
                Toast(res2.data.msg)
              }else{
                window.location.href = res2.data.msg
              }
            }).catch(() => {
              this.loading = false;
            })
          }else{
            Toast("用户sid不存在")
          }
        })
        
      } else if(localStorage.getItem("type")){//返回支付宝微信支付连接
        //console.log("返回支付宝微信支付链接 用于扫码url进入 带渠道参数")
        axios.post('/dxtop/order/topScanPayApi', {
            "money": money,
            "topPayType": topPayType,
            "payType": payType,
            "channelId": localStorage.getItem("type"),
            "scene": 2,
        }).then(res => {
          if(res.data.code == 500){
            Toast(res.data.msg)
          }else{
            window.location.href = res.data.msg
          }
        }).catch(() => {
        })
      }else{//返回支付宝微信支付连接
       // console.log("返回支付宝微信支付链接 用于url进入 不带渠道参数")
        axios.post('/dxtop/order/topScanPayApi', {
            "money": money,
            "topPayType": topPayType,
            "payType": payType,
            "channelName":"H5链接进入",
            "scene": 2,
        }).then(res => {
          if(res.data.code == 500){
            Toast(res.data.msg)
          }else{
            window.location.href = res.data.msg
          }
        }).catch(() => {
        })
      }
    },
    weixin(){
      // 正式版:0，测试版:1，体验版:2 
      let params =  {
        "eventType": "com.launchMiniProgram",
        "data": {
            userName: 'gh_e9f7d5c76d18',
            miniProgramType: 0,
            path:  `/pages/index/index?money=${this.money}&scene=3&userId=${localStorage.getItem("user")}&channelId=null&openid=null`
          }
      }
      window.ReactNativeWebView.postMessage(JSON.stringify(params));
      this.loading = false;
    },
    async openApp(url = "") {
      if (!url) return;
      //if (url.app === 'ysf') return Notify({ type: 'primary', message: '暂不可用' });
      //if (this.iosApp) return Notify({ type: 'primary', message: '请使用浏览器打开' });
      //非微信浏览器
      window.navigator.userAgent.toLowerCase();
      if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
        if(this.channelId){//游客支付，A01/W06 不用传
          if (url.app === "alipayqr") {
            //console.log("苹果游客支付宝url")
            this.pay(this.money, "A01", "3", this.channelId);
          }else if(url.app === "weixin://scanqrcode"){
            //console.log("苹果游客微信支付url")
            this.pay(this.money, "W06", "2", this.channelId);
          }else{
          }
        }else if(localStorage.getItem("user")){ //app微信支付
          if (url.app === "alipayqr") {
            this.loading = true;
            //console.log("苹果app支付宝")
            this.pay(this.money, "A01", "3", "", localStorage.getItem("user"))
          }else if(url.app === "weixin://scanqrcode"){
            this.loading = true;
            //console.log("苹果app微信小程序")
            this.weixin()
          }else{

          }
        }else{
          if (url.app === "alipayqr") {
            this.pay(this.money, "A01", "3", '');
            //console.log("苹果游客支付宝url")
          }else if(url.app === "weixin://scanqrcode"){
            //console.log("苹果游客微信支付url")
            this.pay(this.money, "W06", "2", '');
          }else{

          }
        }
        // window.setTimeout(() => {
        //   const timeOutDateTime = +new Date();
        //   if (timeOutDateTime - loadDateTime > 2000) {
        //     window.location.href = url.downI;
        //     this.loading = false;
        //   } else {
        //     window.close();
        //     this.loading = false;
        //     Dialog.confirm({
        //       title: "提示",
        //       message: "是否已完成充值？",
        //     })
        //     .then(() => {
        //       this.$router.push("/record");
        //     })
        //     .catch((e) => {
        //       console.log(e);
        //     });
        //   }
        // }, 3000);
      } else if (navigator.userAgent.match(/android/i)) {
        if(this.channelId){
          if (url.app === "alipayqr") {
            //console.log("安卓游客支付宝url")
            this.pay(this.money, "A01", "3", this.channelId);
          }else if(url.app === "weixin://scanqrcode"){
            // console.log("安卓游客微信支付url")
             this.pay(this.money, "W06", "2", this.channelId);
          }else{
          }
        }else if(localStorage.getItem("user")){
          if (url.app === "alipayqr") {
            //console.log("苹果app支付宝")
            this.pay(this.money, "A01", "3", "",localStorage.getItem("user"));
            this.loading = false;
          }else if(url.app === "weixin://scanqrcode"){
            //console.log("安卓app微信小程序")
            this.weixin()
          }else{
          }
        }else{
          if (url.app === "alipayqr") {
            this.pay(this.money, "A01", "3", 56);
            //console.log("苹果游客支付宝url")
          }else if(url.app === "weixin://scanqrcode"){
            //console.log("苹果游客微信支付url")
            this.pay(this.money, "W06", "2", 56);
          }else{

          }
        }
        // window.setTimeout(() => {
        //   const timeOutDateTime = +new Date();
        //   if (timeOutDateTime - loadDateTime > 2000) {
        //     window.location.href = url.downI;
        //     this.loading = false;
        //   } else {
        //     window.close();
        //     this.loading = false;
        //     Dialog.confirm({
        //       title: "提示",
        //       message: "是否已完成充值？",
        //     })
        //     .then(() => {
        //       this.$router.push("/record");
        //     })
        //     .catch((e) => {
        //       console.log(e);
        //     });
        //   }
        // }, 3000);
      }else{
        Toast("请使用手机端支付")
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.mianBox {
  height: 100%;
  width: 100%;
  color: #000;
  padding-top: 44px;
  box-sizing: border-box;
  .contentBox {
    width: 100%;
    height: auto;
    padding: 15px 10px;
    box-sizing: border-box;
    & > .van-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // height: 86px;
      width: 100%;
      &::after {
        display: none;
      }
      // & > .van-col {
      //   width: 100%;
      //   justify-content: space-between;
      //   & > .van-image {
      //     width: 70%;
      //     margin: 0%;
      //   }
      // }
      // & > .van-col:nth-child(1) {
      //   & > .van-image {
      //     margin-left: 0%;
      //   }
      // }
      // & > .van-col:nth-child(2) {
      //   & > .van-image {
      //     margin-left: 15%;
      //   }
      // }
      // & > .van-col:nth-child(3) {
      //   & > .van-image {
      //     margin-left: 30%;
      //   }
      // }

      & > .van-col {
        width: 100%;
        justify-content: space-between;
        & > .van-image {
          width: 50%;
          margin: 0%;
        }
      }
      & > .van-col:nth-child(1) {
        & > .van-image {
          margin-left: 25%;
        }
      }
      & > .van-col:nth-child(2) {
        & > .van-image {
          margin-left: 25%;
        }
      }
     
    }
    & > .van-row:nth-child(2) {
      font-size: 16px;
      color: #ccc;
      margin-top: 10px;
    }
  }
}
.van-loading--vertical {
  color: #fff;
}
</style>