// import getJDSDK from "@/assets/js/jdsdk";
// import wx from "weixin-js-sdk";
var wx = require('weixin-js-sdk');

import store from "../store/store";
import apis1 from "./apis1.js";
let { getPageShareConfig } = apis1;
import {
    getCookie
} from "./tools";
import { getUrlQueryValueByKey } from '../util/tools.js';

// eslint-disable-next-line no-undef
const JDSDK = jmfe;
let {
    getSimpleActInfoVo
} = apis1;

//京东测试环境
const CONFIG_TEST_APP = {
    domain: process.env.ACTIVITY_HOST, //'https://lzss1-isv.isvjcloud.com',
    bizType: process.env.bizTypeAPP //"jm-business-center"
};
//微信测试环境
const CONFIG_TEST_WX = {
    domain: process.env.ACTIVITY_HOST, //'https://lzss1-isv.isvjcloud.com',
    bizType: process.env.bizTypeWX
};

const TEST_CF_REQUEST = process.env.ACTIVITY_HOST //"https://lzss1-isv.isvjcloud.com" //process.env.ACTIVITY_HOST
console.log(TEST_CF_REQUEST, 'TEST_CF_REQUEST')

let CONFIG_WX, CONFIG_APP;

CONFIG_WX = CONFIG_TEST_WX;
CONFIG_APP = CONFIG_TEST_APP;
let CONFIG = CONFIG_WX;

const getClientType = () => {
    let type = "";
    //获取客户访问端类型


    if (JDSDK.isApp('jd')) {
        type = "APP";
    } else if (JDSDK.isApp('wx')) {
        type = "WeChat";
    } else if (JDSDK.isApp('qq')) {
        type = "QQ";
    }
    // console.log("JDSDK.Client.isJDApp(): ", JDSDK.Client.isJDApp());
    // console.log("client type round1: ", type);

    //增加二次判断
    if (type == "") {
        if (JDSDK.isApp('jd')) {
            type = "APP";
        } else if (JDSDK.isApp('wx')) {
            type = "WeChat";
        } else if (JDSDK.isApp('qq')) {
            type = "QQ";
        }
    }
    // console.log("client type round2: ", type);

    //更换方式判断

    if (type == "") {
        let ua = navigator.userAgent;
        let isJd = /jdapp/i.test(ua);
        if (isJd) {
            type = "APP";
        } else {
            let isWx = /MicroMessenger/i.test(ua);
            if (isWx) {
                type = "WeChat";
            } else {
                let isQq = /MQQBrowser/i.test(ua);
                if (isQq) {
                    type = "QQ";
                }
            }
        }
    }


    this.setClientType = type

    switch (type) {
        case 'APP':
            store.commit("setClientType", '01');
            break;
        case 'WeChat':
            store.commit("setClientType", '02');
            break;
        default:
            store.commit("setClientType", '03');
            break;
    }
};

const isPC = () => {
    // 判断是否是PC端(区分pc端模拟)
    if (
        navigator.platform.indexOf("Win") == 0 ||
        navigator.platform.indexOf("Mac") == 0
    ) {
        return true;
    }
    return false;
};

//获取token成功之后
const afterGetToken = callback => {
    // alert(store.state.clientType)
    console.log(store.state.clientType, "zzppppp")
    if (store.state.clientType == '02') {
        console.log('微信获取token成功')
        console.log(location.href)
        let cur_url = location.href;
        callback & callback('success')
    } else {
        console.log('h5获取token成功')
        callback & callback()
    }
};
// const extractToken = (url)=>{
//     console.log(url,"liuyisong测试");

//     const regex = /[?&]token=([^&]+)/;
//     const match = url.match(regex);
//     return match ? match[1] : null;
// }

const weChatLogin = callback => {
    console.log(location.href)
    // alert(location.href)
    let cur_url = location.href;
    let index = cur_url.indexOf('?');
    let paramStr = cur_url.substring(index + 1, cur_url.length);
    let params = paramStr.split('&');
    let tokenName = 'token' //活动类型
    params.forEach(element => {
        if (element.indexOf(tokenName) >= 0) {
            if (cur_url.toLowerCase().includes('wx_sdk_uid')) {
                console.log('lys微信分享进入');
                const regex = /[?&]token=([^&]+)/;
                const match = cur_url.match(regex);
                var token = match ? match[1] : null;
                sessionStorage.setItem('lz_wq_auth_token', token)
            } else {
                var token = element.substring(element.indexOf('=') + 1, element.length);
                console.log(token, '京东token')
                sessionStorage.setItem('lz_wq_auth_token', token)
            }
        }
    })

    let url = location.href //location.href.split("#")[0];
    let lzToken = sessionStorage.getItem('lz_wq_auth_token')

    if (!lzToken) {
        // let tokenUrl = TEST_C_REQUEST + "/common/saveWqToken2?url=" + url;
        //https://lzss1-isv.isvjcloud.com
        // let tokenUrl = TEST_CF_REQUEST + "/#/?url=" + url;
        // activityId=1518414726164897793&templateId=13066aa1-520c-40c2-8371-51fe53d50b60&nodeId=101001&prd=cjwx

        let queryData = {
            activityType: sessionStorage.getItem('activityType'),
            templateId: sessionStorage.getItem('templateId'),
            activityId: sessionStorage.getItem('activityId'),
            nodeId: sessionStorage.getItem('nodeId'),
            teamId: sessionStorage.getItem('teamId'),
            giftType: sessionStorage.getItem("giftType"),
            isGiftTrue: sessionStorage.getItem("isGiftTrue"),
            shareUserId: sessionStorage.getItem('shareUserId'),
            prd: sessionStorage.getItem("prd"),
        };
        for (let i in queryData) {
            if (!queryData[i] || queryData[i] == "null") {
                // this.$delete(queryData, i);
                delete queryData[i]
            }
        }
        var aa = '';
        var lastkey = '';
        for (let i in queryData) {
            lastkey = i;
        }
        for (let i in queryData) {
            if (lastkey == i) {
                aa = aa + `${i}=${queryData[i]}`;
            } else {
                aa = aa + `${i}=${queryData[i]}&`;
            }
        }

        let tokenUrl = TEST_CF_REQUEST + "/#/?" + aa + "&url=" + url


        //       let tokenUrl = TEST_CF_REQUEST + "/#/?url=" + url + "&activityId="+activityId+"&templateId="+templateId+"&nodeId="+nodeId+"&prd="+prd+"&activityType="+activityType+"&teamId="+teamId+"&giftType="+giftType+"&shareUserId="+shareUserId;
        //       console.log(tokenUrl,'tokenUrlaaaa')

        location.href =
            "//wq.jd.com/pinbind/pinTokenRedirect?biz=" +
            CONFIG.bizType +
            "&url=" +
            encodeURIComponent(tokenUrl);
    } else {
        store.commit("setToken", lzToken);
        afterGetToken(callback)
    }
};

getClientType();

// 导出login方法
export default callback => {
    let clientType = this.setClientType; //store.state.clientType;
    console.log(22222290909090, clientType)
    console.log(location.href, "location.href");

    // PC/QQ端：fordevpclogin不等于12138时直接跳转，不依赖getPageShareConfig接口
    if ((clientType == "QQ" || isPC()) && sessionStorage.getItem('fordevpclogin') != '12138') {
        localStorage.setItem('actlink', encodeURIComponent(location.href));
        location.href = 'https://lzkj-isv.isvjcloud.com/yunying/viewSpecialTopicPage/openAppPage';
        return;
    }

    //TODO 调用接口判断分享方式 0为京口令，1为H5，2为小程序 京口令跳转中转页面不进行任何操作，h5 直接在微信打开h5页面，小程序 直接弹出打开小程序弹框
    getPageShareConfig(getPageShareConfigData => {
        if (getUrlQueryValueByKey(location.href, 'hdc_src') && getUrlQueryValueByKey(location.href, 'hdc_src') == 'hdc_mini') {
            console.log("lys1111");
            let weynum = 99;
            sessionStorage.setItem('weynum', weynum); //0为京口令，1为H5，2为小程序
        } else {
            console.log("lys2222");
            let weynum = getPageShareConfigData.data.shareType;
            sessionStorage.setItem('weynum', weynum); //0为京口令，1为H5，2为小程序
        }
        if (clientType == "APP") {
            CONFIG = CONFIG_APP;
            //先判断用户是否登陆
            JDSDK.isJDAppLogin().then(res => {
                console.log(res, 'JDSDK.isJDAppLogin');
                console.log(sessionStorage.getItem('weynum'), "weynumLys");
                console.log(CONFIG.domain, 'CONFIG.domain');

                if (res.data == 1) {
                    JDSDK.requestIsvToken(CONFIG.domain).then(res => {
                        store.commit("setClientType", "01");
                        store.commit("setToken", res.data);
                        sessionStorage.setItem('lz_wq_auth_token', res.data)
                        afterGetToken(callback)
                    })
                } else {
                    JDSDK.toLogin().then(res => {
                        if (res.data == 1) {
                            JDSDK.requestIsvToken(CONFIG.domain).then(res => {
                                store.commit("setClientType", "01");
                                store.commit("setToken", res.data);
                                sessionStorage.setItem('lz_wq_auth_token', res.data)
                                afterGetToken(callback)
                            })
                        }
                    })
                }
            });
        } else if (clientType == "WeChat") {
            store.commit("setClientType", "02");
            console.log(process.env.ENV_CONFIG, 'ENV_CONFIG');
            // if (process.env.ENV_CONFIG == 'test' || process.env.ENV_CONFIG == 'crm-ie') {
            //     var headUrl = process.env.ACTIVITY_HOST
            // } else {
            //     var headUrl = location.origin
            // }
            var headUrl = process.env.ACTIVITY_HOST
            if (wx && wx.miniProgram) {
                wx.miniProgram.getEnv(function (result) {
                    if (!store.state.shareUserId) {
                        var acUrl = headUrl + '/index?activityType=' + sessionStorage.getItem('activityType') + '&activityId=' +
                            store.state.activityId + '&templateId=' + sessionStorage.getItem('templateId') + "&nodeId=" +
                            sessionStorage.getItem(
                                'nodeId') +
                            "&prd=" + sessionStorage.getItem('prd')
                    } else {
                        var acUrl = headUrl + '/index?activityType=' + sessionStorage.getItem('activityType') + '&activityId=' +
                            store.state.activityId + '&shareUserId=' + store.state.shareUserId + '&templateId=' + sessionStorage.getItem(
                                'templateId') + "&nodeId=" + sessionStorage.getItem('nodeId') +
                            "&prd=" + sessionStorage.getItem('prd')
                    }
                    if (result.miniprogram) {
                        console.log('是小程序')
                        store.commit("setMiniProgram", true);
                        // 调用京东wq链接，第一次用户进入生成带有token=的链接，微信小程序复制活动链接会把这个链接复制带过来带有上一个用户的token链接，我们无法干掉，原因是如果链接带有分享人id时页同步干掉了
                        location.href = headUrl + '/redirect-jd.html#/?activityId=' + store
                            .state.activityId + '&appType=dz&pageTitle=' + '&mpUrl=' + encodeURIComponent(acUrl)
                        return;
                    } else {
                        if (sessionStorage.getItem('weynum') == 0) {
                            //京口令
                            location.href = headUrl + '/redirect-jd.html#/?activityId=' + store
                                .state.activityId + '&appType=dz&pageTitle=' + '&mpUrl=' + encodeURIComponent(acUrl)
                            return;
                        }

                        if (sessionStorage.getItem('weynum') == 2) {
                            // //小程序分享
                            // location.href = headUrl + '/redirect-mp.html#/?activityId=' + store
                            //     .state.activityId + '&appType=dz&pageTitle=' + '&mpUrl=' + encodeURIComponent(acUrl)
                            // return;
                        }
                    }
                    weChatLogin(callback);
                })
            } else {
                //不是微信
                if (!store.state.shareUserId) {
                    var acUrl = headUrl + '/index?activityType=' + sessionStorage.getItem('activityType') + '&activityId=' +
                        store.state.activityId + '&templateId=' + sessionStorage.getItem('templateId') + "&nodeId=" +
                        sessionStorage.getItem('nodeId') + "&prd=" + sessionStorage.getItem('prd')
                } else {
                    var acUrl = headUrl + '/index?activityType=' + sessionStorage.getItem('activityType') + '&activityId=' +
                        store.state.activityId + '&shareUserId=' + store.state.shareUserId + '&templateId=' +
                        sessionStorage.getItem('templateId') + "&nodeId=" + sessionStorage.getItem('nodeId') +
                        "&prd=" + sessionStorage.getItem('prd')
                }
                weChatLogin(callback);

            }
        } else if (clientType == "QQ" || isPC()) {
            // if (url.indexOf(CONFIG_APP.domain) != -1) {
            //   let target = url.replace(CONFIG_APP.domain, CONFIG_WX.domain);
            //   location.href = target;
            //   return;
            // }
            store.commit("setClientType", "03");
            weChatLogin(callback);
        } else {

            //微博打开京东APP
            // if (process.env.ENV_CONFIG == 'test' || process.env.ENV_CONFIG == 'crm-ie') {
            //     var headUrl = process.env.ACTIVITY_HOST
            // } else {
            //     var headUrl = location.origin
            // }
            var headUrl = process.env.ACTIVITY_HOST

            if (!store.state.shareUserId) {
                var acUrl = headUrl + '/index?activityType=' + sessionStorage.getItem('activityType') + '&activityId=' +
                    store.state.activityId + '&templateId=' + sessionStorage.getItem('templateId') + "&nodeId=" +
                    sessionStorage.getItem('nodeId') + "&prd=" + sessionStorage.getItem('prd')
            } else {
                var acUrl = headUrl + '/index?activityType=' + sessionStorage.getItem('activityType') + '&activityId=' +
                    store.state.activityId + '&shareUserId=' + store.state.shareUserId + '&templateId=' +
                    sessionStorage.getItem('templateId') + "&nodeId=" + sessionStorage.getItem('nodeId') +
                    "&prd=" + sessionStorage.getItem('prd')
            }
            localStorage.setItem('actlink', encodeURIComponent(acUrl))
            location.href = 'https://lzkj-isv.isvjcloud.com/yunying/viewSpecialTopicPage/openAppPage';

        }
    })

};
