<!--
 * @Date: 2023-02-24 14:18:25
 * @LastEditors: JinxChen
 * @LastEditTime: 2023-10-30 14:51:45
 * @FilePath: \TelpoH5FrontendWeb\src\views\package-home\index.vue
 * @description:
-->
<template>
    <div class="package-home">

    </div>
</template>

<script>
import { APIPay } from "@/api/pay";
import APICore from "@/api/core";
import APIWx from "@/api/wx";
import { isNotNull } from "@/utils/index";
import AppId from "@/config/appId";
export default {
    name: "",
    data() {
        return {
            params: {}, //获取路由的参数
            isRecharge: null, //是否已经支付
            isHasBasePackage: null, //是否存在基础套餐
            whiteTitleList: ['小台风', '零川'], //白名单物联网卡列表
            currentIotTitle: '', //当前设备所属物联网名字
        };
    },
    created() {
        this.getAuth();
    },
    mounted() {
        this.getParams();
    },
    methods: {
        // 2023.09.20 修改需求 进入首页同时查套餐和充值状态
        // 1.无基础套餐卡不是零川或者小台风，跳转错误页面
        // 2.无基础套餐卡但是零川或者小台风，跳转话费查询页面
        // 3.如果有基础套餐并且已充值，跳转费查询页面
        // 4.如果有基础套餐但未充值，跳转套餐充值页面
        getDevicePayPackage() {
            APICore.devicePayPackage(this.params.imei)
                    .then(res => {
                        let data = res.data;
                        if (data.code === 106 || data.code === 104) {
                            this.getAuth();
                            setTimeout(() => {
                                this.getDevicePayPackage();
                            }, 1500);
                        } else {
                            // 筛选是否存在基础套餐, producModelId = 1 是基础套餐， 2 是加油包
                            this.isHasBasePackage = data.data.packagesList.some(res => {
                                return res.producModelId === 1;
                            });
                        }
                    }).catch(() => {})
        },
        checkImei() {
            let reqBody = {
                imei: this.params.imei,
                iccid: this.params.iccid || ''
            };
            APIWx.CheckImei(reqBody).then(res =>{
                this.isRecharge = res.data.isRecharge;
                this.currentIotTitle = res.data.title;
                this.getWxCode();
            }).catch(e => {
                console.log("e", e.message);
            })
        },

        // checkBrowser 检查扫码的浏览器内核
        checkBrowser() {
            const userAgent = window.navigator.userAgent;
            console.log("浏览器内核", userAgent);
            if (/AlipayClient/.test(userAgent)) {
                console.log("支付宝");
            } else if (/MicroMessenger/.test(userAgent)) {
                console.log("微信");
                let url = window.location.href.split("?code=")[1];
                console.log("获取授权code的url", url);
                this.getWxCode();
               /*  if (
                    isNotNull(url) ||
                    window.location.href.indexOf("code") > -1
                ) {
                    let timeStamp = new Date().getTime();
                    let code = url.split("&")[0];
                    console.log("code", code);
                    if (isNotNull(code)) {
                        this.getWxCode();
                    }
                } else {
                    this.getWxCode();
                } */
            } else {
                this.getWxCode();
                console.log("当前浏览器内核并非支付宝或者微信");
            }
        },
        // 获取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'))
                }
            })
        },
        // 根据code获取openId
        getOpenId(code) {
            //let code = this.$store.getters.wxAuthCode;
            APIPay.getOpenId(code).then(res => {
                let data= res.data;
                if(data.code === 20000) {
                    this.$store.commit("openId", data.data.openId);
                }
            })
        },
        // 获取微信code
        getWxCode() {
            let params = this.params;
            let commonUrl = process.env.VUE_APP_BASE_API;
            let isWhiteTitle = this.whiteTitleList.includes(this.currentIotTitle) > 0;
            let cardInfoBaseUrl = encodeURIComponent(`${commonUrl}/h5-frontendweb/#/cardInfo?imei=${params.imei}&iccid=${params.iccid}`);
            let toupBaseUrl = encodeURIComponent(`${commonUrl}/h5-frontendweb/#/${params.routerName}?imei=${params.imei}&iccid=${params.iccid}`);
            if(this.isHasBasePackage) {
                // 有套餐
                if(this.isRecharge) {
                    // 已支付，跳转话费查询页面
                    console.log("有套餐跳转话费查询页面");
                    let wxRedUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${AppId}&redirect_uri=${cardInfoBaseUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
                    window.location.href = wxRedUrl;
                } else if (!this.isRecharge) {
                    // 未支付， 跳转套餐充值页面
                     console.log("跳转套餐充值页面");
                   let wxRedUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${AppId}&redirect_uri=${toupBaseUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
                    window.location.href = wxRedUrl;
                }
            } else {
                // 无套餐
                if(isWhiteTitle) {
                    // 是零川或者小台风，跳转话费查询页面
                    let wxRedUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${AppId}&redirect_uri=${cardInfoBaseUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
                    window.location.href = wxRedUrl;
                    console.log("无套餐跳转话费查询页面");
                } else {
                    // 跳转错误页面;
                    this.$router.replace({
                        name: 'iotcardError'
                    })
                    console.log("跳转错误页面");
                }
            }
            // 2023.09.20 废弃
            /* if(this.isRecharge) {
                let redUrl = encodeURIComponent(`${commonUrl}/h5-frontendweb/#/cardInfo?imei=${params.imei}&iccid=${params.iccid}`);
                let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${AppId}&redirect_uri=${redUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
                window.location.href = url;
            } else {
                let redUrl = encodeURIComponent(`${commonUrl}/h5-frontendweb/#/${params.routerName}?imei=${params.imei}&iccid=${params.iccid}`);
                let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${AppId}&redirect_uri=${redUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
                window.location.href = url;
            } */

        },
        // 获取url传过来的参数
        getParams() {
            let params = this.$route.query;
            if (params) {
                this.params = {...params};
                this.$store.commit("appId", AppId);
                if(params.reqUrl) {
                    const reqUrl = encodeURI(params.reqUrl);
                    window.location.href = reqUrl;
                } else {
                    this.getDevicePayPackage();
                    this.checkImei();
                }
            }
        },
    }
};
</script>

<style scoped lang="scss">
</style>
