<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.service";
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: "13209654413",
          userInfoSecId: "commodo",
          userName: "罗刚",
          idNo: "566254180010306614",
          longTerm: false,
          validEnd: "1978-11-18",
          relation: "1",
          socialSecurity: false,
          email: "s.yfyviye@mxxv.ki",
          annualIncome: "17159",
          addressCode: "110100",
          addressDetail: "海外",
          occupation: "5",
          height: 169,
          weight: 58,
          bankCardCode: "ICBC",
          bankCardNo: "6220549771082240618"
        },
        productNo: "1",
        holderUserInfo: {
          phoneNo: "13499177270",
          userInfoSecId: "eu in",
          userName: "崔静",
          idNo: "16479119920330003X",
          longTerm: false,
          validEnd: "1985-09-23",
          socialSecurity: false,
          email: "n.ata@ueccvun.bz",
          annualIncome: "35555",
          addressCode: "110100",
          addressDetail: "白城市",
          occupation: "1",
          height: 186,
          weight: 54,
          bankCardCode: "ICBC",
          bankCardNo: "667782802278796"
        },
        insuredAmount: "57",
        policyPeriod: "26",
        paymentType: 4,
        paymentPeriod: "et in",
        effectiveDate: "2003-07-06 23:11:44",
        autoRenewPolicy: true
      },
      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>
