<!--
 * @Date: 2022-03-29 16:57:58
 * @LastEditors: JinxChen
 * @LastEditTime: 2023-05-07 13:16:55
 * @FilePath: \TelpoH5FrontendWeb\src\views\package-list\index.vue
 * @description: TODO 小台风充值h5
-->
<template>
    <div class="package-list-container">
        <van-nav-bar :left-arrow="false" :border="true">
            <template #title>
                <h5 style="font-size: 16px">{{ topupTitle }}</h5>
            </template>
        </van-nav-bar>
        <!-- 灰色线条 -->
        <div class="gray-line"></div>
        <!-- 套餐列表 -->
        <div class="topup-container">
            <div class="main">
                <!-- 无套餐时显示 -->
                <div class="noData_container" v-show="packageOrderList.length === 0 && !isShowNoData">
                    <p>暂无相关套餐数据,请您联系管理员~</p>
                </div>
                <!-- 套餐订购 -->
                <div class="package-order-container" v-for="(item, index) in packageOrderList" :key="index">
                    <!-- 推荐 -->
                    <div class="recom" v-show="false">
                        <div class="shape"></div>
                        <div class="square">
                            <p>推荐</p>
                        </div>
                    </div>
                    <!-- 套餐内容 -->
                    <div class="order-content">
                        <div class="title">
                            <p>{{ item.packageName }}<!-- ：{{(item.packagesPrice/item.packageIssue).toFixed(0)}}元/月 -->
                            </p>
                        </div>
                        <div class="remark">
                            <p>每月200分钟通话时长，1G流量</p>
                        </div>
                        <div class="details">
                            <p>

                                <span class="orange large">￥{{ (item.packagesPrice / (item.packageIssue === 0 ? 1 :
                                    item.packageIssue)).toFixed(0)}}</span>元/月，
                            </p>
                            <p class="total">
                                <span>合计</span><span class="orange price">{{ item.packagesPrice }}元</span>
                            </p>
                        </div>
                        <!-- <div class="package-buy">
                            <div class="buy-btn" @click="onBuy(item)">
                                <p>第一步：充值话费</p>
                            </div>
                        </div> -->
                        <div class="radios-con">
                            <div class="pay-type">
                                <p>支付方式：</p>
                            </div>
                            <van-radio-group v-model="radio" direction="horizontal" @change="onRaidoChange">
                                <van-radio name="1">
                                    <template #default>
                                        <div class="radio-con">
                                            <span>微信</span>
                                            <img src="../../assets/wx-pay.png" />
                                        </div>
                                    </template>
                                </van-radio>
                                <van-radio name="2">
                                    <template #default>
                                        <div class="radio-con">
                                            <span>支付宝</span>
                                            <img src="../../assets/alipay.png" />
                                        </div>
                                    </template>
                                </van-radio>
                                <van-radio name="3">
                                    <template #default>
                                        <div class="radio-con">
                                            <span>12期花呗</span>
                                            <img src="../../assets/antpay.png" />
                                        </div>
                                    </template>
                                </van-radio>
                            </van-radio-group>
                        </div>
                        <div class="package-buy">
                            <div class="buy-btn" @click="onBuy(item)">
                                <p>第一步：充值话费</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import APIWx from "@/api/wx";
import AppId from "@/config/appId";
import { APIPay } from "@/api/pay";
import APICore from "@/api/core";
let wx = require("weixin-js-sdk"); // TODO 再封装，可拦截错误提示等操作
import { isNotNull } from "@/utils/index";
import { VERSION_MODEL } from '@/config/models';
export default {
    name: "packageList",
    data() {
        return {
            topupTitle: "请选择套餐充值电话卡", //充值页面标题
            // 套餐列表， todo 需要从接口获取
            packageOrderList: [
                /* {
                    packageName: '语音卡套餐(1年)',
                    packagePayType: 1,
                    packagesPrice: 240,
                    packageIssue: 12,
                    payWxPayProductId: process.env.NODE_ENV === "production" ? '1635123463911587840' : '1635122887959592960', //微信支付
                    payAliPayProductId: process.env.NODE_ENV === "production" ? '1629407413618294784' : '1629405716684029952', //支付宝全额支付
                    payAntPayProductId: process.env.NODE_ENV === "production" ? '1629407705558630400': '1629405558344859648', //支付宝花呗支付
                } */
            ],
            outTradeNo: "", //订单号
            price: "", //价格,
            isShowNoData: false, //是否显示无套餐内容, 默认false
            // 获取从路由的参数，import 调取激活接口需要用到
            params: {
                imei: '',
                iccid: '',
                manufactorId: '', //厂商id，一般用来获取core接口token
                appId: '', //公众号appId，需要对接多个不同公众号时动态从页面路由获取，

            },
            radio: '1', //支付方式单选按钮默认值
            payProductId: null, //套餐id
            packageIssue: null, //套餐分期
            payType: '1', //支付方式 1 微信， 2 支付宝，支付宝又分为花呗和全额支付，全额支付分期数传0 或者1 ，花呗则传 3 6 12
            openId: '',
            code: ''
        };
    },
    computed: {
        isWeChat() {
            const ua = window.navigator.userAgent.toLowerCase();
            return /micromessenger/.test(ua);
        }

    },
    created() {
        this.getAuth();
        this.getToken();
        this.getParams();
        this.getCode();
        //this.getWxAutograph();
        //  套餐列表
        this.getDevicePayPackage();
        console.log("当前版本", VERSION_MODEL);
    },
    methods: {
        // 根据code获取openId
        getOpenId(code) {
            APIPay.getOpenId(code).then(res => {
                let data = res.data;
                if (data.code === 20000) {
                    this.openId = data.data.openId;
                    this.$store.commit("openId", data.data.openId);
                } else if (data.state === false) {
                    console.log("token过期");
                    this.getToken();
                    this.getOpenId(this.code);
                }
            })
        },
        // 获取b端接口的token
        getAuth() {
            let manufactorId = "5bf13062-a41e-4d00-ba14-1101aad12650";
            APICore.getAuth({ manufactorId: manufactorId }).then(res => {
                this.$store.commit("gatewayToken", res.data.data);
            });
        },
        // 获取token
        getToken() {
            let manufacturerNo = '9f166b07-ff83-4991-84dc-ca6ad4a6b95b';
            APIPay.getToken(manufacturerNo).then(res => {
                console.log("token的数据", res.data)
                let data = res.data;
                if (data.code === 20000) {
                    this.$store.commit("token", data.token);
                    console.log("token的数据", localStorage.getItem('token'))
                }
            })
        },
        getCode() {
            let url = window.location.href.split("?code=")[1];
            console.log("url", url);
            if (isNotNull(url) || window.location.href.indexOf("code") > -1) {
                let code = url.split("&")[0];
                this.code = code;
                if (isNotNull(code)) {
                    this.getOpenId(code);
                } else {
                    this.$dialog.confirm({
                        message: '系统错误，请重新进入',
                        showCancelButton: false
                    })
                }
            }
        },
        // 获取url传过来的参数
        getParams() {
            let params = this.$route.query;
            console.log("params", params);
            if (params) {
                this.params = { ...params };
            }
        },
        // 获取基本套餐信息
        getDevicePayPackage() {
            this.$toast.loading({
                message: "加载中",
                duration: 1500
            });
            APICore.devicePayPackage(this.params.imei)
                .then(res => {
                    console.log("data", res.data);
                    if (res.data.code === 106 || res.data.code === 104) {
                        // token过期
                        this.getAuth();
                        setTimeout(() => {
                            this.getDevicePayPackage();
                        }, 1500);
                    } else if (res.data.code === 0 && res.data.data === null) {
                        this.isShowNoData = true;
                    } else {
                        if (res.data.data === null) {
                            this.isShowNoData = false;
                        } else {
                            let data = res.data.data.packagesList;
                            // 处理获取套餐的逻辑
                            // 筛选 基础套餐，producModelId 1 是基础套餐；2 是加油包
                            let packageList = data.filter(item => {
                                return item.producModelId === 1
                            });
                            this.packageOrderList = packageList;
                            console.log("套餐数据::", packageList);
                        }
                        this.$toast.success({
                            message: "加载完成",
                            duration: 1500
                        });
                    }
                })
                .catch(error => {
                    this.$dialog.confirm({
                        title: "获取套餐数据失败",
                        message: error.message,
                        showCancelButton: false,
                    });
                })
                .finally(() => {
                    setTimeout(() => {
                        this.$toast.clear();
                    }, 1500);
                });
        },
        //   返回
        onNavBack() {
        },
        //   获取微信jssdk
        getWxAutograph() {
            let that = this;
            return new Promise((resolve, reject) => {
                APIWx.createJSSDK({
                    sUrl: window.location.href.split("#")[0],
                    userId: '',
                    appId: this.params.appId || AppId
                })
                    .then(res => {
                        let item = res.data.data;
                        wx.config({
                            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                            appId: item.appId, // 必填，公众号的唯一标识
                            timestamp: item.timeStamp, // 必填，生成签名的时间戳
                            nonceStr: item.nonceStr, // 必填，生成签名的随机串
                            signature: item.signature, // 必填，签名
                            jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表
                        });

                        wx.ready(() => {
                            resolve(true);
                        });
                    })
                    .catch(err => {
                        reject(false);
                        console.log(err);
                    });
            });
        },
        // 话费充值
        onBuy(data) {
            this.price = data.packagesPrice;
            // 遍历数据找到属于三种支付方式对应的套餐id， 1 微信 2 支付宝全额 3 支付宝分期
            let payTypeToPackAgeId = data.payTypeList;
            console.log("购买的套餐数据data", payTypeToPackAgeId);
            if (!this.isWeChat) {
                return this.$dialog.confirm({
                    message: '请用微信客户端打开此页。',
                    showCancelButton: false,
                })
            }
            // 需要区分是要用微信支付还是支付宝花呗支付
            if (this.payType === '2') {
                // 全额
                this.payProductId = payTypeToPackAgeId.filter(item => {
                    return item.payType === '2' || item.payType === 2
                })[0].productId;
                this.packageIssue = 0;
                console.log("this.payProductId", this.payProductId);
                this.aliPay(data);
            } else if (this.payType === '3') {
                // 分期
                this.payProductId = payTypeToPackAgeId.filter(item => {
                    return item.payType === '3' || item.payType === 3
                })[0].productId;
                this.packageIssue = 12;
                this.payType = '2';
                console.log("this.payProductId2", this.payProductId);
                this.aliPay(data);
            } else {
                // 微信
                let openId = this.openId;
                this.payProductId = payTypeToPackAgeId.filter(item => {
                    return item.payType === '1' || item.payType === 1
                })[0].productId;
                this.packageIssue = 0;
                console.log("this.payProductId3", this.payProductId);
                if (openId === null || openId === 'null') {
                    this.$dialog.confirm({
                        message: '获取OpenId失败，请您重新进入',
                        showCancelButton: false,
                    })
                } else {
                    this.wxPay(data);
                }
            }
        },
        // 微信支付
        wxPay(data) {
            this.$toast.loading({
                message: "加载中"
            });
            console.log("微信支付", data);
            let orderData = data;
            let reqBody = {
                openId: this.openId, //openId
                imei: this.params.imei, //imei
                iccid: this.params.iccid,
                productId: this.payProductId, //套餐id
                packageName: /* data.productModel */ data.packagesName, //套餐名字
                packagePayType: Number(this.payType), //支付类型
                packageIssue: 0, //分期
                pkId: data.packagesCardId,
                packagePrice: process.env.NODE_ENV === "production" ? data.packagesPrice * 100 : 1  //总金额单位为分，测试环境写死
            };
            this.$toast.clear();
            APICore.payLiveBaseDevice(reqBody)
                .then(res => {
                    if (res.data.code === 104 || res.data.code === 106) {
                        this.getAuth();
                        setTimeout(() => {
                            this.wxPay(orderData);
                        }, 1000);
                    } else if (res.data.code === 104) {
                        return this.$dialog.confirm({
                            message: `${res.data.message}`,
                            showCancelButton: false
                        })
                    } else if (res.data.code !== 0) {
                        return this.$dialog.confirm({
                            message: `请反馈给一线人员,\n${res.data.message}`,
                            showCancelButton: false
                        })
                    }
                    let that = this;
                    let wxData = res.data.data;
                    that.outTradeNo = wxData.out_trade_no;
                    console.log("wxData", wxData);
                    // 本地测试
                    /* that.$router.push({
                        name: "payResult",
                        query: {
                            outTradeNo: that.outTradeNo,
                            price: that.price,
                            rechargeUrl: data.rechargeUrl || '',
                            iccid: this.params.iccid,
                            isAdmin: this.$route.query.isAdmin,
                            serialNo: this.params.imei,
                            routerName: this.params.routerName,
                            issue: data.packageIssue
                        }
                    }); */
                    /* wx.chooseWXPay({
                        timestamp: wxData.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
                        nonceStr: wxData.nonceStr, // 支付签名随机串，不长于 32 位
                        package: wxData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                        signType: wxData.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
                        paySign: wxData.paySign, // 支付签名
                        success: function(res) {
                            // 支付成功后的回调函数
                            that.$router.replace({
                                name: "payResult",
                                query: {
                                    outTradeNo: that.outTradeNo,
                                    price: that.price,
                                    rechargeUrl: data.rechargeUrl,
                                    iccid: that.params.iccid,
                                    isAdmin: that.$route.query.isAdmin || false,
                                    serialNo: that.params.imei,
                                    issue: that.packageIssue
                                }
                            });
                            console.log("微信支付成功::", res);
                        },
                        fail: err => {
                            console.log("支付出错了::", err);
                            that.$dialog.confirm({
                                title: "温馨提示",
                                message: "出错了，请您重新进入",
                                showCancelButton: false
                            });
                        },
                        cancel: function(err) {
                            // 用户取消支付
                            that.$dialog.confirm({
                                title: "温馨提示",
                                message: "请点击“ 一键办理”支付",
                                showCancelButton: false
                            });
                            console.log("用户取消了支付::", err);
                        }
                    }); */
                    this.onWxPay(wxData);
                })
                .catch(error => {
                    console.log("error", error);
                })
                .finally(() => {
                    this.$toast.clear();
                });
        },
        onWxPay(data) {
            let that = this;
            function onBridgeReady() {
                WeixinJSBridge.invoke(
                    "getBrandWCPayRequest",
                    {
                        appId: AppId, //公众号ID，由商户传入
                        timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
                        nonceStr: data.nonceStr, //随机串
                        package: data.package,
                        signType: data.signType, //微信签名方式：
                        paySign: data.paySign //微信签名
                    },
                    function (res) {
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            // 使用以上方式判断前端返回,微信团队郑重提示：
                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                            that.$router.replace({
                                name: "payResult",
                                query: {
                                    outTradeNo: that.outTradeNo,
                                    price: that.price,
                                    rechargeUrl: data.rechargeUrl,
                                    iccid: that.params.iccid,
                                    isAdmin: that.$route.query.isAdmin || false,
                                    serialNo: that.params.imei,
                                    issue: that.packageIssue
                                }
                            });
                        } else {
                            that.$dialog.confirm({
                                message: "请点击“ 第一步：充值话费”支付",
                                showCancelButton: false
                            });
                        }
                    }
                );
            }
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener(
                        "WeixinJSBridgeReady",
                        onBridgeReady,
                        false
                    );
                } else if (document.attachEvent) {
                    document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
                    document.attachEvent(
                        "onWeixinJSBridgeReady",
                        onBridgeReady
                    );
                }
            } else {
                onBridgeReady();
            }
        },
        // 跳转到支付宝花呗外部链接
        aliPay(data) {
            console.log("选择了支付宝::", data);
            this.$toast.loading({
                message: "加载中"
            });
            let orderData = data;
            let reqBody = {
                openId: this.openId, //openId
                imei: this.params.imei, //imei
                iccid: this.params.iccid,
                productId: this.payProductId, //套餐id
                packageName: /* data.productModel + ',' +  */data.packagesName, //套餐名字
                packagePayType: Number(this.payType), //支付类型
                pkId: data.packagesCardId,
                packageIssue: this.packageIssue, //分期
                packagePrice: process.env.NODE_ENV === "production" ? data.packagesPrice * 100 : 1 //总金额单位为分，测试环境写死
            };
            this.$toast.clear();
            APICore.payLiveBaseDevice(reqBody)
                .then(res => {
                    if (res.data.code === 104 || res.data.code === 106) {
                        this.getAuth();
                        setTimeout(() => {
                            this.aliPay(orderData);
                        }, 1000);
                    }
                    let that = this;
                    let alipayData = res.data.data.xmlStrMap;
                    that.outTradeNo = alipayData.outTradeNo;
                    let alipayForm = decodeURI(alipayData.payXmlStr);
                    that.$store.commit("isFromWx", true);
                    let alipayUserId = process.env.NODE_ENV === "production" ? 69 : 18;
                    this.$router.replace({
                        name: "payResult",
                        query: {
                            rechargeUrl:
                                data.rechargeUrl ||
                                `https://id.ssjlai.com/frontend/#/alipay`,
                            outTradeNo: that.outTradeNo,
                            price: that.price,
                            alipayForm: alipayForm,
                            iccid: that.params.iccid,
                            isAdmin: that.$route.query.isAdmin || false,
                            serialNo: that.params.imei,
                            alipayUserId: alipayUserId,
                            productId: this.payProductId
                        }
                    });
                })
                .catch(error => {
                    console.log("error", error);
                    this.$dialog.confirm({
                        message: `${error.message}`,
                        showCancelButton: false
                    })
                })
                .finally(() => {
                    this.$toast.clear();
                });
        },
        // 支付类型切换
        onRaidoChange(value) {
            console.log("选择的支付类型是", value);
            this.payType = value;
        }
    }
};
</script>
<style lang="scss">
.van-nav-bar__title {
    max-width: 80% !important;
    font-size: 16px;
}
</style>
<style lang="scss" scoped>
.package-list-container {
    background-color: white;
    height: 100vh;

    .topup-container {
        position: relative;
        /* margin: 20px; */
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-direction: column;
        background-color: white;
        overflow: scroll;
        height: calc(100vh - 88px);

        .main {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;

            .tips {
                padding: 10px;
            }

            .noData_container {
                margin: 100px auto 0;
                height: 120px;
                /* background: url(../../../assets/img/news-noData.png) center no-repeat; */
                background-size: 165px 120px;
                display: flex;
                justify-content: center;
                align-items: flex-end;
                font-size: 16px;
                color: #999;

                p {
                    font-size: 16px;
                }

                /* @include colorAndFont(#999, 28); */
            }

            p {
                padding: 10px;
                font-size: 16px;
            }

            .cancel-button {
                width: 30vw;
                border-radius: 5px;
                background-color: #2599ff;
                color: #fff;
                min-height: 40px;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 16px;
            }

            .package-order-container {
                position: relative;
                margin: 10px 0;
                /* padding: 0 20px; */
                z-index: 999;
                box-shadow: rgba(14, 30, 37, 0.12) 0 3px 5px 0,
                    rgba(14, 30, 37, 0.32) 0 2px 16px 0;

                .recom {
                    position: absolute;
                    top: -7px;
                    left: -26px;
                    border-style: solid;
                    border-width: 0 40px 40px;
                    border-color: transparent transparent red;
                    transform: rotate(-45deg);
                    text-align: center;
                    z-index: 9999;

                    p {
                        padding: 0;
                        color: white;
                        font-size: 14px;
                    }

                    .shape {
                        position: absolute;
                        top: -1px;
                        left: -21px;
                        border-style: solid;
                        border-width: 0 21px 21px;
                        border-color: transparent transparent white;
                    }

                    .square {
                        height: 15px;
                        width: 35px;
                        position: absolute;
                        top: 21px;
                        left: -20px;
                        background: red;
                        font-size: 14px;
                    }
                }

                .order-content {
                    padding: 15px 10px;

                    .title {
                        display: flex;
                        justify-content: flex-start;

                        p {
                            font-size: 16px;
                            font-weight: bold;
                        }
                    }

                    .details {
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;

                        p {
                            height: 40px;
                            @include center();
                            font-size: 14px;
                            padding: 5px 0 5px 10px;
                        }

                        .total {
                            font-size: 16px;
                            padding: 0;
                        }

                        .orange {
                            color: orange;
                        }

                        .large {
                            font-size: 26px;
                            margin: 0 2px;
                        }

                        .price {
                            font-size: 16px;
                        }

                        /* .buy-btn {
                            height: 30px;
                            width: 100px;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            background: orange;
                            border-radius: 45px;
                            p {
                                font-size: 16px;
                                padding: 0;
                                color: red;
                            }
                        } */
                    }

                    .remark {
                        display: flex;
                        justify-content: flex-start;

                        p {
                            font-size: 14px;
                            padding: 5px 10px;
                            /* font-weight: bold; */
                        }
                    }

                    .package-buy {
                        @include center();
                        padding: 5px 8px;
                        @include center();

                        .buy-btn {
                            height: 40px;
                            width: 200px;
                            padding: 0 5px;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            background: orange;
                            border-radius: 20px;

                            p {
                                font-size: 16px;
                                padding: 0;
                                color: white;
                            }
                        }
                    }

                    .radios-con {
                        /* padding: 20px 10px; */
                        /* @include center(); */
                        /* align-items: center; */
                        padding: 10px 0 10px 10px;
                        font-size: 14px;

                        /* box-shadow: rgba(14, 30, 37, 0.12) 0 3px 5px 0,
                                rgba(14, 30, 37, 0.32) 0 2px 16px 0; */
                        img {
                            height: 20px;
                            width: 20px;
                            margin: 2px;
                        }

                        .pay-type {
                            text-align: left;

                            p {
                                font-size: 14px;
                                padding: 0 0 10px 0;
                            }
                        }

                        .radio-con {
                            @include center();
                        }

                        .van-cell-text {
                            display: flex;
                            justify-content: flex-start;
                            align-items: center;

                            span {
                                font-size: 14px;
                                padding: 0 5px;
                            }
                        }
                    }
                }

                .content {
                    font-size: 14px;
                }
            }
        }
    }

    .gray-line {
        height: 10px;
        width: 100%;
        background: #f2f4f5;

    }

    .order-description {
        height: 60px;
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        flex-direction: column;
        padding: 5px 0 10px 10px;

        h5 {
            font-size: 14px;
            padding: 10px 0 0 0;
        }
    }

    .pay-radios {
        position: relative;
        top: 0;
        width: 100%;

        /* background-color: red; */
        /* padding: 0 15px; */
        .radios-con {
            padding: 20px 10px;
            /* @include center(); */
            align-items: center;
            font-size: 18px;
            box-shadow: rgba(14, 30, 37, 0.12) 0 3px 5px 0,
                rgba(14, 30, 37, 0.32) 0 2px 16px 0;

            img {
                height: 35px;
                width: auto;
            }

            .van-cell-text {
                display: flex;
                justify-content: flex-start;
                align-items: center;

                span {
                    padding: 0 5px;
                }
            }
        }
    }
}
</style>
