import fetch from '@/utils/fetch'
import { getBaseUrl, getApiUrl } from '@/utils/index';
import { mapGetters, mapActions } from 'vuex';
import { setCookie, getCookie, delCookie } from '@/utils/index';

// import store from '../store';

module.exports = {
    data: function () {
        return {
            token: '',
        }
    },
    created: function () {
        let query;
        if (this.$route !== undefined) {
            query = this.$route.query
        }
        // console.log('this.token' + this.token)
        this.token = this.getUrlKey('token') || (query && query.token)
    },
    computed: {
        ...mapGetters(["userInfo", "canRunNext"])
    },

    mounted() {
    },

    methods: {
        ...mapActions(["setUserInfo", "goLogin"]),

        getUrlPara(obj) {
            let dataStr = ''
            let list = [];
            for (let attr in obj) {
                if (obj.hasOwnProperty(attr) && attr != 'data') {
                    list.push(attr + '=' + obj[attr])
                }
            }
            dataStr = list.join('&')
            if (dataStr !== '') {
                return '?' + dataStr
            }
            return ''
        },
        // 埋点
        pageBurialPoin(options) {
            rocNative.appBuryingPointEntrust(options)
        },

        setRouterParm(paramList) {
            let parm = {};
            if (paramList.length <= 1) {
                return '';
            }
            for (let i = 1; i < paramList.length; i++) {
                parm[paramList[i].key] = paramList[i].value;
            }
            return parm;
        },

        // 拼接多个参数
        getUrlParmByCode(paramList) {
            if (paramList.length <= 1) {
                return ''
            }
            let dataStr = ''
            let list = [];
            for (let i = 1; i < paramList.length; i++) {
                list.push(paramList[i].key + '=' + paramList[i].value)
            }
            dataStr = list.join('&')
            if (dataStr !== '') {
                return '?' + dataStr
            }
            return ''
        },
        //处理五分钟数据 初始化播放状态
        handelFive(d) {
            for (let i = 0; i < d.length; i++) {
                d[i].play = '0';
            }
            return d;
        },

        setEventByModuleCode(itemData) {
            let modeCode = itemData.appModuleInfo.code || '';
            let paramList = itemData.appModuleInfo.paramList ? itemData.appModuleInfo.paramList : ''

            if (modeCode === 'M001' || modeCode === 'M002' || modeCode === 'M003') {
                paramList = ''
            } else if (modeCode === 'M100' || modeCode === 'M300') {
                // 支持多个参数
                let urlPara = this.getUrlParmByCode(paramList);
                if (paramList[0]) {
                    if (paramList[0].value.indexOf("?") == -1) {
                        paramList[0].value += urlPara
                    }
                }
            } else if (modeCode === 'M400') {
                let path = paramList[0]['key'];
                let v = paramList[0]['value'];
                let query = this.setRouterParm(paramList);
                paramList = [{
                    url: v,
                    query: query
                }]
                this.$router.push({
                    path: v,
                    query: query
                })
                return 'NO'
            }
            if (typeof paramList === 'string' && !paramList) {
                paramList = []
            }
            return paramList;
        },

        // 通用GET请求
        GET(api, para, callback, str) {
            // debugger
            let token = para.token || this.token || this.$store.state.common.userInfo.userToken;
            para.token = token;
            delete para.token;
            delete para.setEntry;
            let url = api + this.getUrlPara(para)
            return fetch({
                url: getBaseUrl(url),
                method: 'get',
                data: para,
                headers: { token }
            })
        },

        NEW_GET(api, para, callback, str) {
            para.token = para.token || this.token || ''
            let url = api + this.getUrlPara(para)
            return fetch({
                url: getBaseUrl(url),
                method: 'get',
                data: para
            })
        },

        // 通用GET2请求
        GET2(api, para, callback, str) {
            para.token = para.token || this.token || '4B43CD3CD5DB4979AC1B5B3F508391CA'
            // let url = api + this.getUrlPara(para)
            // let url = 'http://192.168.140.38:12801' + api
            let url = 'https://dev-sc.yunqueyi.com' + api
            return fetch({
                url: url,
                method: 'get',
                data: para
            })
        },

        // 通用POST请求
        POST(api, para, callback) {
            let token = para.token || this.token || this.$store.state.common.userInfo.userToken;
            para.token = token;
            delete para.token;
            delete para.setEntry;
            return fetch({
                url: getBaseUrl(api),
                method: 'post',
                data: para,
                headers: { token }
            })
        },

        // 通用POST请求
        NEW_POST(api, para, callback) {
            // para.token = para.token || this.token || this.$store.state.common.userInfo.userToken;
            return fetch({
                url: getBaseUrl(api),
                method: 'post',
                data: para
            })
        },

        // 通用GET请求
        API_GET(api, para, callback) {
            para.token = para.token || this.token || this.$store.state.common.userInfo.userToken; //'AF3DFCF2DD4B4115AC47ACA25D5420E9''F90DF48D3EFA49DFAE1267A67DBEFB18'//token
            let url = api + this.getUrlPara(para)
            return fetch({
                url: getApiUrl(url),
                method: 'get',
                data: para
            })
        },

        // 通用POST请求
        API_POST(api, para, callback) {
            para.token = para.token || this.token || this.$store.state.common.userInfo.userToken; //'AF3DFCF2DD4B4115AC47ACA25D5420E9''F90DF48D3EFA49DFAE1267A67DBEFB18'//token
            return fetch({
                url: getApiUrl(api),
                method: 'post',
                data: para
            })
        },

        // 从html参数
        getUrlKey(name) {
            if (decodeURIComponent && location.href) {
                return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
            } else {
                return null
            }
        },
        getUrlSearch(url, name) {
            if (typeof name == 'undefined') {
                name = url
                url = location.href
            }
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = url.slice(url.indexOf('?') + 1).match(reg);
            if (r != null) {
                try {
                    return decodeURIComponent(r[2]);
                } catch (_e) {
                    return null
                }
            }
            return null
        },
        onAvatarError(e) {
            e.target.src = 'https://file.yunqueyi.com/File/doctor_default.png';
        },

        // 校验token，有效则调用回调函数，否则调起原生登陆页面
        commonCheckToken(cb) {
            console.log('5555 this.token', this.token);
            let param = {
                token: this.token || this.$store.state.common.userInfo.userToken || localStorage.getItem("couponToken") || getCookie("couponToken"),
                // token: this.token || this.$store.state.common.userInfo.userToken,
                setEntry: true
            };
            console.log('this.token || this.$store.state.common.userInfo.userToken', this.token, this.$store.state.common.userInfo.userToken);
            this.GET("campaign/admin/task/checkToken", param).then(res => {
                if (res.code !== "000000") {
                    console.log('commonCheckToken', window.__isWeb);
                    if(window.__isWeb) {
                        this.goLogin();
                    } else {
                        rocNative.gotoLogin();
                    }
                } else {
                    cb && cb()
                }
            });
        },

        // 校验token，有效则调用回调函数，否则使用调起原生登陆页面
        checkTokenForNative(cb) {
            let param = {
                token: this.token || this.$store.state.common.userInfo.userToken,
                setEntry: true
            };
            this.GET("campaign/admin/task/checkToken", param).then(res => {
                if (res.code !== "000000") {
                    rocNative.gotoLogin();
                } else {
                    cb && cb()
                }
            });
        },

        // 防止重复点击的最简单实现
        canRun(delayTime = 500){
            if(this.canRunNext) {
                this.$store.commit('SET_CAN_RUN_NEXT', false);
                setTimeout( () => {
                    this.$store.commit('SET_CAN_RUN_NEXT', true)
                }, delayTime);
                console.log('in canRan ', this.canRunNext);
                return true;
            } else {
                console.log('in canRan', this.canRunNext);
                return false;
            }
        }
    }
}
