// 引入vux
import {
    changeUserid,
    changeBsiteUserid,
    changeUseridToBsite,
    postByte,
    byteApi
} from '../api/index'
import util from "../util";
import store from '../store'
import Toast from 'vant/lib/toast'

let pageData = store.state.pageData

// 创建调用外部js的函数 
export const outsideJs = () => {
    if (pageData.remarks.dispose && pageData.remarks.dispose !== '') {
        let temp = pageData.remarks.dispose
        temp.split(',').forEach(val => {
            if (val === 'bili' && window.location.hash.substr(1).lastIndexOf('track_id') > -1 && window.bilicm !== undefined) {
                window.bilicm.mbase.report_data()
                console.log('B站信息流')
            } else if (val === 'kuaishou' && _ks_trace !== undefined) {
                _ks_trace.push({
                    event: 'form',
                    convertId: 320216,
                    cb: () => {
                        console.log('Your callback function here!')
                    }
                })
                console.log('快手客户端信息流')
            } else if (val === 'ksInfo' && window._ks_trace !== undefined) {
                _ks_trace.push({
                    event: 'form',
                    convertId: 320216,
                    cb: () => {
                        console.log('Your callback function here!')
                    }
                })
                console.log('快手信息流')
            } else if (val === 'zijie') {
                postApi()
                console.log('字节信息流')
            } else if (val === 'zijieStart') {
                postByteApi()
                console.log('字节星图信息流')
            }
        })
    }
}

// 腾讯视频流量激活
const tencentJihuo = async () => {
    console.log('调用激活')
    let res = await useridCode();
    let url =
        "https://mcgi.v.qq.com/unicom/check_user_order?usermob=" +
        res.data +
        "&otype=json&platform=5&_t=" +
        Math.random() +
        "&callback=test";
    myJsonp(
        url,
        (data) => {
            console.log('jsonp:', data)
            let params = data;
            QQVideoBridge.saveResult("saveSubscriptionStatus", params).done(
                (result) => {
                    console.log('qq激活:', result)
                    let res = JSON.parse(result);
                    if (res.errcode === 0) {
                        Toast.success("激活成功");
                    } else {
                        Toast.fail("激活失败");
                    }
                }
            );
        },
        "test"
    );
}

const useridCode = () => {
    console.log('转换手机号')
    let cpid = "tencent";
    let userid = store.state.user.userid;
    return changeUserid({
        cpid,
        userid
    });
}

const myJsonp = (url, callback, callbackname) => {
    console.log('创建外部jsonp')
    window[callbackname] = callback;
    let script = document.createElement("script");
    script.src = url;
    script.type = "text/javascript";
    document.head.appendChild(script);
}


// B站免流激活
const biliJihuo = () => {
    if (store.state.user.userid) {
        postUserid({
            eventName: "onActive",
            userid: store.state.user.userid
        });
    } else {
        Toast.fail("请先领取专属流量");
    }
}

const postUserid = (data) => {
    if (data.eventName === "onOK") {
        window.parent.postMessage({
            type: "onOK"
        }, "*");
        console.log(window.parent)
    } else {
        changeUseridToBsite({
            userid: data.userid,
        }).then((res) => {
            window.parent.postMessage({
                    type: data.eventName,
                    data: {
                        eventName: data.eventName,
                        userid: res.data
                    },
                    callbackId: `${data.eventName}Callback`,
                },
                "*"
            );
        });
    }
}
// 免登录userid转换  B站=》我方
export const biliUser = () => {
    console.log('调用B站免登录')
    return new Promise(function (resolve, reject) {
        let {
            bUid
        } = util.query2obj(location.search);
        postUserid({
            eventName: "onOK"
        });
        if (bUid) {
            let userid = decodeURIComponent(bUid);
            changeBsiteUserid({
                userid: userid,
            }).then((res) => {
                store.commit("setUser", {
                    userid: res.data.userid,
                    phone: res.data.phone,
                });
                resolve(res.data);
            });
        }
    });
}

// 客户端流量激活方式
export const activation = () => {
    if (pageData.remarks.dispose && pageData.remarks.dispose !== '') {
        let temp = pageData.remarks.dispose
        temp.split(',').forEach(val => {
            if (val === 'bili') {
                biliJihuo()
                console.log('调用B站激活')
            } else if (val === 'tencent') {
                tencentJihuo()
                console.log('调用腾讯激活')
            } else if (val === 'ksJhuo' || val === 'kuaishou') {
                if (window.ksBridge !== undefined) {
                    window.ksBridge.register(
                        "emitFreeTrafficUpdate",
                        "emitFreeTrafficUpdate"
                    );
                    window.ksBridge.emitFreeTrafficUpdate({
                        complete: (res) => {
                            console.log(res);
                        },
                    });
                    console.log('调用快手激活')
                } else {
                    Toast.fail('激活失败')
                }
            } else {
                window.location.href = pageData.mainProduct.flowJumpUrl
            }
        })
    } else {
        window.location.href = pageData.mainProduct.flowJumpUrl
    }
}

// 字节埋点回传
const postApi = () => {
    let apiQuery = util.query2obj(location.search)
    if (apiQuery) {
        let nowTime = new Date().getTime()
        let params = {
            event_type: "form",
            context: {
                ad: {
                    callback: apiQuery.clickid
                },
            },
            timestamp: nowTime
        }
        postByte(params)
    }
}

// 字节星图回传
const postByteApi = () => {
    let url = window.location.href
    let params = {
        eventType: "3",
        link: url,
        source: ""
    }
    byteApi(params)
}