<!--
 * @Date: 2022-03-29 16:57:58
 * @LastEditors: JinxChen
 * @LastEditTime: 2023-02-27 09:53:05
 * @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="order-description" v-show="packageOrderList.length">
            <h5>套餐说明：</h5>
            <h5>每月200分钟通话时长，1G流量。</h5>
        </div> -->
        <!-- 套餐列表 -->
        <div class="topup-container">
            <div class="main">
                <!-- <div class="tips" v-show="!isCanTopup">
                    <p>非本公司发行的SIM卡，</p>
                    <p>无此服务。</p>
                    <div class="cancel-button" @click="onNavBack">返回</div>
                </div> -->
                <!-- 无套餐时显示 -->
                <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.packagePrice/item.packageIssue).toFixed(0)}}元/月 --></p>
                        </div>
                        <div class="details">
                            <p>
                                低至
                                <span
                                    class="orange"
                                >{{(item.packagePrice/(item.packageIssue === 0 ? 1: item.packageIssue)).toFixed(0)}}</span>元/月
                            </p>
                            <p class="orange">
                                <span class="orange price">{{item.packagePrice}}元</span>
                            </p>
                            <div class="buy-btn" @click="onBuy(item)">
                                <p>话费充值</p>
                            </div>

                        </div>
                        <div class="remark">
                            <p>每月200分钟通话时长，1G流量。</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 底部支付类型选择 -->
        <div class="pay-radios">
            <div class="radios-con">
                <!-- <van-radio-group v-model="radio" direction="horizontal"  @change="onRaidoChange">
                    <van-radio name="1">
                        <template #default>
                            <span>微信支付</span>
                            <img src="../../assets/wx_pay_icon.png"/>
                        </template>
                    </van-radio>
                    <van-radio name="2">
                        <template #default>
                            <span>支付宝</span>
                            <img src="../../assets/alipay.png"/>
                        </template>
                    </van-radio>
                    <van-radio name="3">
                        <template #default>
                            <span>花呗</span>
                            <img src="../../assets/antpay.png"/>
                        </template>
                    </van-radio>
                </van-radio-group> -->
                <van-radio-group v-model="radio" @change="onRaidoChange">
                    <van-cell-group border >
                        <van-cell clickable @click="radio = '1'"  center>
                            <template #default>
                                <div class="van-cell-text">
                                    <img src="../../assets/wx-pay.png" alt="">
                                    <span class="custom-title">微信支付</span>
                                </div>
                            </template>
                            <template #right-icon>
                                <van-radio name="1" />
                            </template>
                        </van-cell>
                        <van-cell  clickable @click="radio = '2'">
                            <template #default>
                                <div class="van-cell-text">
                                    <img src="../../assets/alipay.png"/>
                                    <span class="custom-title">支付宝支付</span>
                                </div>
                            </template>
                            <template #right-icon>
                                <van-radio name="2" />
                            </template>
                        </van-cell>
                        <van-cell  clickable @click="radio = '3'" >
                            <template #default >
                                <div class="van-cell-text">
                                    <img src="../../assets/antpay.png"/>
                                    <span class="custom-title">花呗支付</span>
                                </div>
                            </template>
                            <template #right-icon>
                                <van-radio name="3" />
                            </template>
                        </van-cell>
                    </van-cell-group>
                </van-radio-group>
            </div>
        </div>
    </div>
</template>

<script>
import APIWx from "@/api/wx";
import { APIPay } from "@/api/pay";
let wx = require("weixin-js-sdk"); // TODO 再封装，可拦截错误提示等操作
import APICore from "@/api/core";
import axios from "axios";
import { isNotNull } from "@/utils/index";
export default {
    name: "packageList",
    data() {
        return {
            topupTitle: "请选择套餐充值激活电话卡",
            wxItem: "",
            packageOrderList: [
                {
                    packageName: '移动语音卡套餐(1年)',
                    packagePayType: 1,
                    packagePrice: 240,
                    packageIssue: 12,
                    payWxPayProductId: process.env.NODE_ENV === "production" ? '1629407413618294784' : '1629405716684029952', //微信支付
                    payAliPayProductId: process.env.NODE_ENV === "production" ? '1629407413618294784' : '1629405716684029952', //支付宝全额支付
                    payAntPayProductId: process.env.NODE_ENV === "production" ? '1629407705558630400': '1629405558344859648', //支付宝花呗支付
                }
            ],
            outTradeNo: "", //订单号
            price: "", //价格,
            isShowNoData: false, //是否显示无套餐内容, 默认false
            params: {
                imei: '',
                iccid: '',
                manufactorId: '',
                appId: '',

            },
            radio: '1',
            payProductId: null,
            packageIssue: null,
            payType: '1',
        };
    },
    computed: {
        isCanTopup() {
            return this.$route.query.isCanTopup;
        },
        serialNo() {
            return this.$route.query.serialNo;
        }
    },
    created() {
        this.getAuth();
        this.getParams();
        this.getWxAutograph();
        /* this.getLiveBasePackage(); */
    },
    /* mounted() {
        this.getParams();
        this.getWxAutograph();
        this.getLiveBasePackage();
    }, */
    methods: {
        // 根据code获取openId
        getOpenId() {
            let code = this.$store.getters.wxAuthCode;
            let openId = this.$store.getters.openId;
            if(isNotNull(openId)) {
                console.log("已经存在openId");
            } else {
                APIPay.getOpenId(code).then(res => {
                    let data= res.data;
                    if(data.code === 20000) {
                        this.$store.commit("openId", data.data.openId);
                    }
                })
            }
        },
         // 获取b端接口的token
        getAuth() {
            let manufactorId = "5bf13062-a41e-4d00-ba14-1101aad12650";
            APICore.getAuth({ manufactorId: manufactorId }).then(res => {
                this.$store.commit("gatewayToken", res.data.data);
            });
        },
        // 获取url传过来的参数
        getParams() {
            let params = this.$route.query;
            if (params) {
                let url = window.location.href.split("?code=")[1];
                if ( isNotNull(url) || window.location.href.indexOf("code") > -1) {
                    let timeStamp = new Date().getTime();
                    let code = url.split("&")[0];
                    if (isNotNull(code)) {
                        this.$store.commit("wxAuthCode", `${code}`);
                        this.getOpenId();
                    }
                }
                this.params = {...params};
            }
        },
        // 获取基本套餐信息
        getLiveBasePackage() {
            this.$toast.loading({
                message: "获取套餐中",
                duration: 1500
            });
            let reqBody = {
                manufactorId:"",
                productModelId:0,
                iccid:"",
                pageNumber:1,
                begNumber:20
            }
            APICore.cardPackageList(reqBody)
                .then(res => {
                    console.log("data", res.data);
                    if (res.data.code === 106 || res.data.code === 104) {
                        // token过期
                        this.getAuth();
                        setTimeout(() => {
                            this.getLiveBasePackage();
                        }, 1500);
                    } else if (res.data.code === 0 && res.data.data === null) {
                        this.isShowNoData = true;
                    }else {
                        let data = res.data.data.list;
                        if(data === null) {
                            this.isShowNoData = true;
                        } else {
                            this.packageOrderList = data.filter(item => {
                                return item.pechargeUrl === '1629405716684029952' || item.pechargeUrl === '1629405558344859648';
                            });
                            console.log("套餐数据::", data);
                        }
                    }
                    this.$toast.success({
                        message: "成功获取套餐",
                        duration: 1500
                    });
                })
                .catch(error => {
                    this.$dialog.confirm({
                        title: "获取套餐数据失败",
                        message: error,
                        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
                })
                    .then(res => {
                        let item = res.data.data;
                        this.wxItem = 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);
                            /* that.canScan = true; */
                        });
                    })
                    .catch(err => {
                        reject(false);
                        console.log(err);
                    });
            });
        },
        // 话费充值
        onBuy(data) {
            this.price = data.packagePrice;
            // 需要区分是要用微信支付还是支付宝花呗支付
            if (this.payType === '2') {
                this.payProductId =  process.env.NODE_ENV === "production" ? '1629407413618294784' : '1629405716684029952', //支付宝全额支付
                this.packageIssue = 1;
                this.aliPay(data);
            } else if (this.payType === '3') {
                this.payProductId =  process.env.NODE_ENV === "production" ? '1629407705558630400': '1629405558344859648', //支付宝花呗支付
                this.packageIssue = 12;
                this.payType = '2'
                this.aliPay(data);
            } else {
                let openId = this.$store.getters.openId;
                if(openId === null || openId === 'null') {
                    this.$dialog.confirm({
                        message: '微信支付在调整中，请选择其它支付方式',
                        showCancelButton: false,
                    })
                } else {
                    this.packageIssue = 1;
                    // todo 暂时取消开放微信支付
                    //this.wxPay(data);
                    console.log("openid为空");
                }
            }
        },
        // 微信支付
        wxPay(data) {
            this.$toast.loading({
                message: "加载中"
            });
            console.log("微信支付", data);
            let orderData = data;
            let reqBody = {
                openId: this.$store.getters.openId, //openId
                imei: this.params.imei, //imei
                productId: this.payProductId, //套餐id
                packageName: /* data.productModel */ + ',' + data.packageName, //套餐名字
                packagePayType: Number(this.payType), //支付类型
                packageIssue: this.packageIssue, //分期
                packagePrice: process.env.NODE_ENV === "production" ? data.packagePrice * 100 : 1  //总金额单位为分，测试环境写死
            };
            APICore.payLiveBaseDevice(reqBody)
                .then(res => {
                    this.$toast.clear();
                    if (res.data.code === 104 || res.data.code === 106) {
                        this.getAuth();
                        setTimeout(() => {
                            this.wxPay(orderData);
                        }, 1000);
                    }
                    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.push({
                                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);
                        }
                    });
                })
                .catch(error => {
                    console.log("error", error);
                })
                .finally(() => {
                    this.$toast.clear();
                });
        },
        // 跳转到支付宝花呗外部链接
        aliPay(data) {
            console.log("选择了支付宝::", data);
            this.$toast.loading({
                message: "加载中"
            });
            let orderData = data;
            let reqBody = {
                openId: this.$store.getters.openId, //openId
                imei: this.params.imei, //imei
                productId: this.payProductId, //套餐id
                packageName: /* data.productModel + ',' +  */data.packageName, //套餐名字
                packagePayType: Number(this.payType), //支付类型
                packageIssue: this.packageIssue, //分期
                packagePrice: process.env.NODE_ENV === "production" ? data.packagePrice * 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" ? 42 : 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);
                })
                .finally(() => {
                    this.$toast.clear();
                });
        },
        // 转换类型
        shiftType(type) {
            switch (type) {
                case "微信":
                    return "1"
                    /* break; */
                case "支付宝花呗":
                    return "2"
                    /* break; */
            }
        },
        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;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-direction: column;
        background-color: white;
        overflow: scroll;
        /* height: calc(100vh - 4rem); */
        .main {
            padding: 0 10px;
            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;
                height: 140px;
                width: 300px;
                padding: 5px 20px;
                margin: 10px 0;
                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-top: 25px;
                    .title {
                        display: flex;
                        justify-content: flex-start;
                        p {
                            font-size: 14px;
                            font-weight: bold;
                        }
                    }
                    .details {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        p {
                            font-size: 14px;
                        }
                        .orange {
                            color: orange;
                        }
                        .price {
                            font-size: 14px;
                            font-weight: bold;
                            padding-right: 5px;
                        }
                        .buy-btn {
                            height: 30px;
                            width: 90px;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            background: orange;
                            border-radius: 20px;
                            p {
                                padding: 0;
                                color: white;
                            }
                        }
                    }
                    .remark {
                        display: flex;
                        justify-content: flex-start;
                        p {
                            font-size: 14px;
                            /* font-weight: bold; */
                        }
                    }
                }
                .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 25px;
        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>
