<!--
 * @Date: 2023-02-24 16:47:33
 * @LastEditors: JinxChen
 * @LastEditTime: 2023-03-02 10:58:55
 * @FilePath: \TelpoH5FrontendWeb\src\views\pay-result\index.vue
 * @description:
-->
<!--
 * @Date: 2022-05-29 10:23:28
 * @LastEditors: JinxChen
 * @LastEditTime: 2023-02-25 10:34:31
 * @FilePath: \TelpoH5FrontendWeb\src\views\pay-result\index.vue
 * @description:
-->
<template>
    <div class="pay-result-container">
        <div class="check-container" v-show="pageShow">
            <van-nav-bar title="支付结果" :left-arrow="false" :border="true" ></van-nav-bar>
            <!-- 头部 -->
            <div class="header pos-center">
                <img src="../../assets/img/ssjl.jpg" alt />
                <p>随手精灵</p>
            </div>
            <!-- 详细 -->
            <div class="details">
                <div class="details-item">
                    <p class="left-text">订单状态</p>
                    <p v-if="payStatus">支付成功</p>
                    <p v-else class="error">查询失败</p>
                </div>
                <div class="details-item">
                    <p class="left-text">订单尾号</p>
                    <p>{{outTradeNo}}</p>
                </div>
                <div class="details-item price">
                    <p class="left-text">支付总额</p>
                    <p>￥ {{price}}元</p>
                </div>
            </div>
            <!-- 返回 -->
            <div class="footer pos-center">
                <!-- <div class="back-btn" @click="onNavBack" v-show="!payStatus">
                    <p>返回重新选择套餐购买</p>
                </div> -->
                <!-- <div class="back-btn" @click="onNext" v-show="payStatus">
                    <p>激活电话卡</p>
                </div> -->
                <div class="back-btn" @click="onBackHome">
                    <p>第{{isAliPay ? '三' : '二'}}步：继续使用功能</p>
                </div>
            </div>
        </div>
        <!-- <div class="flush" v-show="isIos">
            <div class="back-btn" @click="onFlush">
                <p>查询</p>
            </div>
        </div> -->
    </div>
</template>

<script>
import { isNotNull} from "@/utils/index";
import { APIPay } from "@/api/pay";
import APIWx from "@/api/wx";
import axios from "axios";
export default {
    name: "payResult",
    data() {
        return {
            pageShow: false, //是否显示页面，备注：需要在查询结果出来后才显示页面
            count: 0, //轮询接口时间次数
            timer: "", //轮询支付结果定时器
            payStatus: null, //支付状态
            price: this.$route.query.price, //价格
            outTradeNo: this.$route.query.outTradeNo, //支付订单号
            isIos: null, //是否是ios,
        };
    },
    created() {
        this.checkParams();
        this.closeTime();
    },
    computed: {
        isAliPay() {
            return this.$route.query.alipayForm
        }
    },
    mounted() {
        //this.checkParams();
        //this.closeTime();
    },
    methods: {
        // checkIosOrAndroid
        checkIosOrAndroid() {
            let userAgent = navigator.userAgent;
            if (userAgent.indexOf("iPhone") > -1) {
                this.isIos = true;
            }
        },
        onNavBack() {
            this.$router.replace({
                name: "packageList",
                query: {
                    serialNo: this.$route.query.serialNo,
                    isAdmin: this.$route.query.isAdmin,
                    iccid: this.$route.query.iccid,
                    routerName: this.$route.query.routerName,
                }
            });
        },
        // 下一步激活
        onNext() {
            console.log("激活", );
            //this.$toast.loading("激活中");
            /* this.effective(); */
            this.$router.replace({
                name: 'activeStatus',
                query: {
                    serialNo: this.$route.query.serialNo,
                    iccid: this.$route.query.iccid,
                    issue: Number(this.$route.query.issue) || 0
                }
            })
        },
        // 激活接口
        effective() {
            this.$toast.loading('激活中,请稍候...');
            let reqBody = {
                imei: this.$route.query.serialNo,
                iccid: this.$route.query.iccid || '',
                issue: Number(this.$route.query.issue) || 0
            };
            APIWx.Effective(reqBody)
                .then(res => {
                    console.log("res", res);
                    let data = res.data;
                    console.log("data", data);
                    this.$toast.clear();
                    if(data.stateCode !== 1) {
                        this.$dialog.confirm({
                            title: '温馨提示',
                            message: `${data.message}`,
                            showCancelButton: false
                        })
                    } else if(data.stateCode === 0 && data.message !== null) {
                         this.$dialog.confirm({
                            title: '温馨提示',
                            message: `电话卡激活失败！请进行实名认证与绑定SIM卡。如您已实名认证，请5分钟后，再进行设备绑定。`,
                            showCancelButton: false
                        })
                        } else if (data.stateCode === 1 && data.message !== 'ok') {
                            this.$dialog.confirm({
                                title: "SIM卡激活成功",
                                message: '卡激活成功，5分钟后则可正常使用。',
                                showCancelButton: false,
                                confirmButtonText: '返回首页'}).then(() => {
                                    document.location.replace(" https://xrpt.jiankangtongxue.cn/WCUParentWebUI.WX/Home/")
                                });
                        } else if (data.stateCode === 1 && data.message === 'ok') {
                            this.$dialog.confirm({
                                title: "SIM卡激活成功",
                                message: '卡激活成功，5分钟后则可正常使用。',
                                showCancelButton: false,
                                confirmButtonText: '返回首页'
                                }).then(() => {
                                    document.location.replace(" https://xrpt.jiankangtongxue.cn/WCUParentWebUI.WX/Home/")
                                });
                    }
                })
                .catch(error => {
                    console.log("出错了:;", error);
                    this.$dialog.confirm({
                        title: '温馨提示',
                        message: `${error.message}`,
                        showCancelButton: false
                    })
                }).finally(() => {
                    this.$toast.clear();
                })
        },
        // ios需要手动点击按钮查询
        onFlush() {
            this.isIos = false;
            this.checkParams();
        },
        // storeParams
        checkParams() {
            let params = this.$route.query;
            let isFromWx = this.$store.getters.isFromWx;
            if (params.rechargeUrl  && isFromWx === true) {
                // 如果存在支付宝跳转链接，则打开外部浏览器跳到支付宝h5
                console.log("支付宝");
                this.$toast.loading({
                    message: "跳转中",
                });
                setTimeout(() => {
                    this.$store.commit("isFromWx", "");
                    let alipayForm = encodeURIComponent(params.alipayForm); //对接口返回的form进行编码
                    let url =
                        process.env.NODE_ENV === "production"
                            ? `https://ai.ssjlai.com/frontend/#/alipay?goodsNo=${params.productId}&userId=${params.alipayUserId}&isWx=true&alipayForm=${alipayForm}`
                            : `https://id.ssjlai.com/frontend/#/alipay?goodsNo=${params.productId}&userId=${params.alipayUserId}&isWx=true&alipayForm=${alipayForm}`;
                    window.location.href = url;
                }, 1500);
            } else if (params.rechargeUrl && isFromWx === null) {
                // todo 轮询支付宝的支付结果
                let that = this;
                console.log("支付宝结果");
                this.$toast.loading({
                    message: "支付结果查询中"
                });
                let reqBody = {
                    outTradeNo: params.outTradeNo
                };
                let url =
                    process.env.NODE_ENV === "production"
                        ? "https://ai.ssjlai.com/telpopay/alipay/order/detail/callback"
                        : "https://id.ssjlai.com/telpopay/alipay/order/detail/callback";
                if (that.count >= 30) {
                    if (that.timer) {
                        clearInterval(that.timer);
                        this.payStatus = false;
                        this.pageShow = true;
                        this.$toast.clear();
                        console.log("关闭轮询1");
                    }
                }
                that.timer = setInterval(() => {
                    that.count++;
                    APIPay.getWxPayResult(reqBody)
                        .then(res => {
                            if (res.data.code === 20000) {
                                this.pageShow = true;
                                this.payStatus = true;
                                this.$toast.clear();
                                console.log("关闭轮询2");
                                if (that.timer) {
                                    clearInterval(that.timer);
                                }
                            }
                        })
                        .catch(e => {
                            console.log(e);
                        });
                }, 2000);
            } else {
                // todo  轮询微信支付的订单，支付成功则激活 （只有直播基地的imei才激活操作）
                let that = this;
                console.log("微信");
                this.$toast.loading({message: "支付结果查询中"});
                let reqBody = {
                    outTradeNo: params.outTradeNo
                };
                let url =
                    process.env.NODE_ENV === "production"
                        ? " https://ai.ssjlai.com/telpopay/api/wx/order/callback"
                        : "https://id.ssjlai.com/telpopay/api/wx/order/callback";
                if (that.count >= 30) {
                    if (that.timer) {
                        clearInterval(that.timer);
                        this.payStatus = false;
                        this.pageShow = true;
                        this.$toast.clear();
                        console.log("关闭轮询3");
                    }
                }
                that.timer = setInterval(() => {
                    that.count++;
                    APIPay.getWxPayResult(reqBody)
                        .then(res => {
                            if (res.data.code === 20000) {
                                this.pageShow = true;
                                this.payStatus = true;
                                this.$toast.clear();
                                console.log("关闭轮询4");
                                if (that.timer) {
                                    clearInterval(that.timer);
                                }
                            }
                        })
                        .catch(e => {
                            console.log(e);
                        });
                }, 2000);
            }
        },
        // 获取微信支付接口
        getWxPayResult() {
            this.$toast.loading({
                message: "正在获取支付结果",
                duration: 3000
            });
            setTimeout(() => {
                this.pageShow = true;
            }, 3000);
        },
        closeTime() {
            let params = this.$route.query;
            let isFromWx = this.$store.getters.isFromWx;
            setTimeout(() => {
                clearInterval(this.timer);
                console.log("即将关闭轮询");
                this.$toast.clear();
                if (this.pageShow === false) {
                    this.pageShow = true;
                }
            }, 31000);
        },
        onBackHome() {
            /* document.location.replace(" https://xrpt.jiankangtongxue.cn/WCUParentWebUI.WX/Home/"); */
            document.location.replace("https://xrpt.jiankangtongxue.cn/WCUParentWebUI.WX/Home/SmartDigitalSsjl");
            // https://xrpt.jiankangtongxue.cn/WCUParentWebUI.WX/Home/SmartDigitalSsjl
        }
    }
};
</script>

<style scoped lang="scss">
.pay-result-container {
    height: 100vh;
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;
    background-color: white;
    overflow: scroll;
    .check-container {
        width: 100%;
    }
    .pos-center {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-direction: column;
    }
    .header {
        width: 100%;
        padding: 10px 0;
        img {
            height: 60px;
            width: 60px;
            margin: 10px 0;
            border-radius: 50%;
        }
        p {
            font-size: 18px;
        }
    }
    .details {
        padding: 20px 0;
        width: 100%;
        p {
            font-size: 16px;
        }
        .details-item {
            width: 80%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-left: 10%;
            padding: 10px 0;
            .left-text {
                color: gray;
            }
            .error {
                color: red;
                font-size: 24px;
            }
        }
        .price {
            padding: 20px 0;
            border-bottom: 5px solid $background;
            .left-text {
                color: gray;
            }
        }
        .details-item:nth-child(2) {
            border-bottom: 5px solid $background;
        }
    }
    .footer {
        height: 75px;
        .back-btn {
            height: 45px;
            width: 275px;
            display: flex;
            justify-content: center;
            align-items: center;
            background: $blue;
            border: 1px solid $blue;
            border-radius: 25px;
            p {
                font-size: 18px;
                padding: 0;
                color: white;
            }
        }
    }
}
.flush {
    height: calc(100vh - 2.3784rem);
    display: flex;
    justify-content: center;
    align-items: center;
    .back-btn {
        height: 45px;
        width: 275px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: $blue;
        border: 1px solid $blue;
        border-radius: 25px;
        p {
            font-size: 18px;
            padding: 0;
            color: white;
        }
    }
}
</style>