<template>
  <div class="container">
    <cr-button block type="danger" @click="login" v-if="!mongoToken">登录</cr-button>
    <cr-divider />
    <cr-button block @click="generateOrder('JSAPI')">生成订单（微信JSAPI支付）</cr-button>
    <cr-button block @click="generateOrder('MWEB')">生成订单（微信H5支付）</cr-button>
    <cr-button block @click="generateOrder('THRID')">生成订单（第三方收银台支付）</cr-button>
    <cr-divider />
    <cr-button type="warning" block @click="goPay">调起支付</cr-button>
    <cr-divider />
    <div class="state">
      <h5>基本信息：</h5>
      <p>当前环境：{{ browerEnv }}</p>
      <p>登录状态：{{ !!mongoToken }}</p>
      <p>支付方式：{{ tradeType }}</p>
      <p>支付支付状态：{{ payState }}</p>
      <p v-if="browerEnv === 'weixin'">微信openId：{{ openId }}</p>
      <cr-divider />
      <h5>登录信息：</h5>
      <p v-for="(item, key) in loginInfo" :key="key">{{ key }}: {{ item }}</p>
      <cr-divider />
      <h5>支付信息：</h5>
      <p v-for="(item, key) in payInfo" :key="key">{{ key }}: {{ item }}</p>
      <cr-divider />
      <h5>订单信息：</h5>
      <p v-for="(item, key) in orderInfo" :key="key">{{ key }}: {{ item }}</p>
      <cr-divider />
      <h5>保险订单信息：</h5>
      <p
        v-for="(item, key) in insuredOrderInfo"
        :key="key"
        v-html="`${key}: ${brFilter(item)}`"
      ></p>
    </div>
  </div>
</template>

<script>
/**
 * @description: 支付测试页面
 * @param {type}
 * @return:
 */
import { loginByPhone, getwxOpenId } from "@/api/user";
import { placeOrder } from "@/api/order";
import cfg from "@/config";
import { payByWay } from "@/service/pay";
let pollTimer = null;
export default {
  name: "paytest",
  data() {
    return {
      browerEnv: "",
      xyqbToken: "",
      mongoToken: localStorage.getItem("mongoToken"),
      loginInfo: {
        phoneNo: "18611428880",
        verifyCode: "123456",
        loginChannel: "1"
      },
      insuredOrderInfo: {
        insuredUserInfo: {
          phoneNo: "15715416416",
          userName: "龚秀兰",
          idNo: "640181198708118231",
          longTerm: false,
          validEnd: "2021-03-15",
          relation: "2",
          socialSecurity: true,
          email: "r.icj@crtzzkdr.is",
          annualIncome: "71067",
          addressCode: "110100",
          addressDetail: "六安市",
          occupation: "7",
          height: 183,
          weight: 66,
          bankCardCode: "ICBC",
          bankCardNo: "1815137475347541839"
        },
        productNo: "HTYLX001",
        holderUserInfo: {
          phoneNo: "15664415945",
          userName: "郭平",
          idNo: "640181198708118231",
          longTerm: true,
          validEnd: "2021-12-03",
          socialSecurity: true,
          email: "y.dcqoic@bkfygg.fo",
          annualIncome: "50401",
          addressCode: "110100",
          addressDetail: "通化市",
          occupation: "3",
          height: 169,
          weight: 66,
          bankCardCode: "ICBC",
          bankCardNo: "9397487291495249077"
        },
        productItem: {
          insuredAmount: "30万",
          policyPeriod: "至60岁",
          paymentPeriod: "20年"
        },
        paymentType: 4,
        effectiveDate: "2020-08-16 12:44:18",
        autoRenewPolicy: false
      },
      orderInfo: {},
      tradeType: "",
      openId: localStorage.getItem("openId"),
      payInfo: {},
      payState: "未支付",
      payBack: 0 // 0未调起支付，1已调起支付
    };
  },
  mounted() {
    this.getCurrentBrowerEnv();
    this.payBack = this.$route.query.state;
    if (this.payBack) {
      const { payOrderNo, payType, tradeType, orderNo } = this.$route.query;
      this.orderInfo = { payOrderNo, payType, orderNo };
      this.tradeType = tradeType;
      this.getPayState();
    }
  },
  destroyed() {
    clearTimeout(pollTimer);
  },
  methods: {
    async login() {
      const res = await loginByPhone(this.loginInfo);
      if (res.code === "0") {
        this.mongoToken = res.data.token;
        localStorage.setItem("mongoToken", res.data.token);
      }
    },
    getCurrentBrowerEnv() {
      const ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        this.browerEnv = "weixin";
        this.getWxOpenId();
      } else if (ua.match(/xyqb/i) == "xyqb") {
        this.browerEnv = "xyqb";
      } else {
        this.browerEnv = "h5";
      }
    },
    async getWxOpenId() {
      if (this.openId) return;
      const code = this.$route.query.code;
      const res = await getwxOpenId({ code, appId: cfg.wxAppId });
      if (res.code === "0") {
        this.openId = res.data.openId;
        localStorage.setItem("openId", res.data.openId);
      }
    },
    getUserState() {
      this.mongoToken = localStorage.getItem("mongoToken");
    },
    brFilter(txt) {
      let val = JSON.stringify(txt);
      val = val.replace(/[{},]/g, "<br />").replace(/"/g, "");
      return val;
    },
    async generateOrder(tradeType) {
      if (!this.mongoToken) {
        this.$toast("请登录");
        return;
      }
      this.tradeType = tradeType;
      const res = await placeOrder.create(this.insuredOrderInfo);
      if (res.code === "0") {
        this.orderInfo = res.data;
      }
    },
    async goPay() {
      const { payOrderNo, payType } = this.orderInfo;
      const { tradeType, orderInfo } = this;
      if (!payOrderNo) {
        this.$toast("请先生成订单");
        return;
      }
      const res = await placeOrder.pay({ payOrderNo, payType, tradeType });
      if (res.code === "0") {
        let payInfo = {
          url: res.data.payUrl,
          params: {
            ...orderInfo,
            tradeType,
            state: 1
          }
        };
        if (tradeType === "JSAPI") {
          payInfo = res.data.payInfo;
          // payInfo.appId = cfg.wxAppId;
        }
        payByWay(tradeType, payInfo).then(() => {
          this.payBack = 1;
        });
      }
    },
    getPayState() {
      pollTimer = setTimeout(() => {
        const { payOrderNo, payType } = this.orderInfo;
        placeOrder.polling({ payOrderNo, payType }).then(res => {
          if (res.code === "0") {
            const { result, payState } = res.data;
            if (result) {
              this.$toast("支付成功");
              this.payState = "支付成功";
              return;
            } else if (payState) {
              this.payState = "支付中。。。";
              this.getPayState();
            } else {
              this.payState = "支付失败";
              return;
            }
          }
        });
      }, 3000);
    }
  }
};
</script>
<style lang="less" scoped>
.container {
  padding: 5px 15px;
  font-size: 14px;
  background-color: #fff;
}
.state {
  line-height: 24px;
  margin-bottom: 15px;
  height: 44vh;
  overflow: scroll;
  background-color: #fcfcfc;
  box-shadow: inset 0 0 9px 0px rgba(0, 0, 0, 0.1);
  padding: 0 10px;
  border-radius: 8px;
  h5 {
    font-weight: bold;
    margin: 15px 0;
  }
}
.cr-button {
  margin-bottom: 15px;
}
</style>
