import store           from '@/store';
import axios            from 'axios';

const TenantCodeKey = 'TENANT_CODE';
const KaoshiId = 'KAOSHI_ID';
const KaoshiReplyPgKey = 'KAOSHI_REPLY_PG';
const PageDataKey = 'MTA_PAGE_DATA';


const classifyArr = [
    { id: 1, code: 'danxuan', name: '单选题' },
    { id: 2, code: 'duoxuan', name: '多选题' },
    { id: 3, code: 'panduan', name: '判断题' },
    { id: 4, code: 'tiankong', name: '填空题' },
    { id: 5, code: 'jianda', name: '简答题' },
    { id: 6, code: 'yuedu', name: '阅读题' },
];

export function getTenantCode() {
    if (!store.state.tenantCode) {
        let tenantCode = JSON.parse(window.localStorage.getItem(TenantCodeKey));
        store.commit({
                         type:         'setTenantCode'
                         , tenantCode: tenantCode,
                     });
        return tenantCode;
    } else {
        return store.state.tenantCode;
    }
}

export function setTenantCode(tenantCode) {
    // console.log(store);
    window.localStorage.setItem(TenantCodeKey, JSON.stringify(tenantCode));
    store.commit({
                     type:         'setTenantCode'
                     , tenantCode: tenantCode,
                 });
    // store.state.auth = auth;
}

export function removeTenantCode() {
    window.localStorage.removeItem(TenantCodeKey);
    delete store.state.tenantCode;
}


export function setSystemConfig(data, text = 'SystemConfig') {
    /**
     * 系统配置对象拓展，增加功能可配置
     * 不重新覆盖，只覆盖已设置属性
     * data 为传入对象 key值相同即覆盖已有
     * @date 2019/11/20
     */
    if (getSystemConfig(text)) {
        let c = Object.assign(getSystemConfig(text), data);
        window.localStorage.setItem(text, JSON.stringify(c));
        store.commit(`SYSTEMCONFIG`, c);
    } else {
        window.localStorage.setItem(text, JSON.stringify(data));
        store.commit(`SYSTEMCONFIG`, data);
    }
}

export function getSystemConfig(text = 'SystemConfig') {
    const data = JSON.parse(window.localStorage.getItem(text));
    if (!store.state.replaceContent) {
        store.commit(`SYSTEMCONFIG`, data);
    }
    return store.state.replaceContent;
}

//个人头像-start
export function setUserIcon(data, text = 'UserIcon') {
    // console.log('data', data);
    window.localStorage.setItem(text, JSON.stringify(data));
    store.dispatch('setUserIcon', data);
}

export function getUserIcon(text = 'UserIcon') {
    const data = JSON.parse(window.localStorage.getItem(text));
    if (!store.state.replaceIcon) {
        store.dispatch('setUserIcon', data);
    }
    return store.state.replaceIcon;
}

//个人头像-end
export function removeSystemConfig() {
    window.localStorage.removeItem('SystemConfig');
    delete store.state.replaceContent;
}


export function setKsStatus(ksId, ksType) {
    // console.log(store);
    window.localStorage.setItem('cur-ksId', ksId);
    window.localStorage.setItem('page-' + ksId + '-ks-status', JSON.stringify({
                                                                                  ksId:   ksId,
                                                                                  ksType: ksType,
                                                                              }));
    store.commit({
                     type:       'setKsStatus'
                     , ksStatus: JSON.stringify({
                                                    ksId:   ksId,
                                                    ksType: ksType,
                                                }),
                 });
}

export function getKsStatus() {
    if (!store.state.ksStatus) {
        let ksId = window.localStorage.getItem('cur-ksId');
        let ksStatus = JSON.parse(window.localStorage.getItem('page-' + ksId + '-ks-status'));
        store.commit({
                         type:       'setKsStatus'
                         , ksStatus: JSON.stringify(ksStatus),
                     });
        return ksStatus;
    } else {
        return JSON.parse(store.state.ksStatus);
    }
}

export function getLxId() {
    if (!store.state.lxId) {
        let lxId = JSON.parse(window.localStorage.getItem(`getLxId_key`));
        store.commit({
                         type:   'setLxId'
                         , lxId: lxId,
                     });
        return lxId;
    } else {
        return store.state.lxId;
    }
}

export function setLxId(data) {
    // console.log(store);
    window.localStorage.setItem(`getLxId_key`, JSON.stringify(data));
    store.commit({
                     type:   'setLxId'
                     , lxId: data,
                 });
}

export function removeKsId() {
    window.localStorage.removeItem(KaoshiId);
    delete store.state.ksId;
}


/**
 * 工具函数整理树 数据
 * @param data 当前数组数据
 * @param pId 根据的id
 * @param compareString 需要判断的字段
 * @returns {Array} 树的数据结构
 */
export function getTreeData(data, compareString, pid) {

    if (data === null || data === undefined || data.length === 0) {
        return data;
    }

    function doFilter(data, compareString, pid) {
        const ret = [];

        function handleDataFun(o) {


            o.children = doFilter(data, compareString, o[compareString]).child;
            // 删除待选项

            // 排序
            o.children.sort((a, b) => {
                if (a.number === b.number) {
                    return a[compareString] - b[compareString];
                }
                return a.number - b.number;
            });
            o.label = o.name;
            o.ooo = 1;
            // 判断flag属性是否存在
            if (o.flag === 0) {
                o.disabled = true;
            }
            ret.push(o);
        }

        for (const o of data) {
            o.label = o.name;
            // console.log('过滤后数组222', other);
            // other = other.filter(item => item[compareString] !== o[compareString]);
            // console.log('过滤后数组', other);
            if (!o[compareString]) {
                throw new Error(`getTreeData函数参数${compareString === '' ? 'id' : compareString}未发现`);
            }
            if (pid) {
                if (o.parentId === pid) {

                    handleDataFun(o);
                }
            } else {
                if (o.parentId === data[0].parentId) {

                    handleDataFun(o);
                }
            }

        }

        return {
            child: ret,
            data:  data,
        };
    }

    let _data = doFilter(data, compareString, pid);
    let _newData = _data.child;
    if (_data.data.length) {
        _data.data.map(item => {
            if (item.ooo === undefined) {
                if (item.flag === 0) {
                    item.disabled = true;
                }
                _newData.push(item);
            }
        });
    }
    return _newData;

}

export function checkData(data, typeString) {
    switch (typeString) {
        case 'string' :
            break;
    }
}

export function getLetterByIndex(index) {
    let letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (index < 0 || index > 26) {
        return '?';
    }
    return letters.charAt(index);
}

/**
 * 设置页面缓存
 * @param textCode 识别字段
 * @param data 数据
 */
export function setPageDataHistory(textCode, data) {
    window.localStorage.setItem(`page-${textCode}-operation`, JSON.stringify(data));
}

export function getPageDataHistory(textCode) {
    return JSON.parse(window.localStorage.getItem(`page-${textCode}-operation`));
}

export function removePageDataHistory(textCode) {
    window.localStorage.removeItem(`page-${textCode}-operation`);
}

/**
 * 获取html标签之间的内容
 * @param data
 * @returns {string}
 */
function getHtmlStr(data) {
    let str = data;
    let arr = str.match(/<[^>]+>([^<]+)<\/[^>]+>/g);
    let result = [];
    arr.forEach((item, index) => result.push(item.match(/>([^<]+)</)[1]));
    return `${result.join('。')}。`;
}


/**
 * 通过属性取试题分类详细
 * @param obj ex.{id: 1}
 * @returns {{code, name, id}|*}
 */
export function getClassifyByProp(obj) {
    let index = _.findIndex(classifyArr, obj);
    return classifyArr[index];
}

/**
 * 页面用
 * @param html
 * @return {string}
 */
export function getStringByHtml(html) {
    /*return html ? html.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '')
                      .replace(/<[^>]+?>/g, '')
                      .replace(/\s+/g, ' ')
                      .replace(/ /g, ' ')
                      .replace(/>/g, ' ') : '';*/
    return html ? html.replace(/<?br>/g, '').replace(/<img [^.]*">/g, '').replace(/<?img[^>]*>/g, '') : '';
}
export function getStringByHtml3(html) {
    return html ? html.replace(/<img [^.]*">/g, '')
                      .replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '')
                      .replace(/<[^>]+?>/g, '')
                      .replace(/\s+/g, ' ')
                      .replace(/ /g, ' ')
                      .replace(/>/g, ' ')
                      .replace(/<?img[^>]*>/g, '') : '';
}
/**
 * 组件用
 * @param html
 * @return {*}
 */
export function getStringByHtml2(html) {
    return html;
}

/**
 * 串联加载指定的脚本
 * 串联加载[异步]逐个加载，每个加载完成后加载下一个
 * 全部加载完成后执行回调
 * @param array|string 指定的脚本们
 * @param function 成功后回调的函数
 * @return array 所有生成的脚本元素对象数组
 */

function seriesLoadScripts(scripts, callback) {
    if (typeof (scripts) != 'object') {
        var scripts = [scripts];
    }
    var HEAD = document.getElementsByTagName('head').item(0) || document.documentElement;
    var s = new Array(), last = scripts.length - 1, recursiveLoad = function (i) { //递归
        s[i] = document.createElement('script');
        s[i].setAttribute('type', 'text/javascript');
        s[i].onload = s[i].onreadystatechange = function () { //Attach handlers for all browsers
            if (!/*@cc_on!@*/0 || this.readyState == 'loaded' || this.readyState == 'complete') {
                this.onload = this.onreadystatechange = null;
                this.parentNode.removeChild(this);
                if (i != last) {
                    recursiveLoad(i + 1);
                } else if (typeof (callback) == 'function') {
                    callback();
                }
            }
        };
        s[i].setAttribute('src', scripts[i]);
        HEAD.appendChild(s[i]);
    };
    recursiveLoad(0);
}

/**
 * 1~20
 * @param num
 * @returns {string}
 */
export function convertNum2Roma(num) {
    let arr = [
        'Ⅰ', 'Ⅱ', 'Ⅲ', 'Ⅳ', 'Ⅴ', 'Ⅵ', 'Ⅶ', 'Ⅷ', 'Ⅸ', 'Ⅹ',
        'Ⅺ', 'Ⅻ', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX',
    ];

    if (num > 0 || num < 21) {
        return arr[num - 1];
    }
    return null;
}

export function checkRouterScore(path) {

    const WhiteList = ['/a/kaoshi/shitiManager', '/c/kecheng/courseInfo'];

    if (_.indexOf(WhiteList, path) > -1) {
        return false;
    }
    return true;
}

export function checkRouterModel(path) {

    const WhiteList = ['/a/kaoshi/shijuanManager', '/a/kaoshi/kaoshiConfig', '/a/kaoshi/shitiManager'];

    if (_.indexOf(WhiteList, path) > -1) {
        return true;
    }

    return false;
}

export function shitiStatusControl(to) {
    if (checkRouterScore(to.path)) {
        store.commit({
                         type:   'CHANGESHOWSCORE'
                         , data: true,
                     });
    } else {
        store.commit({
                         type:   'CHANGESHOWSCORE'
                         , data: false,
                     });
    }
    if (checkRouterModel(to.path)) {

        store.commit({
                         type:   'SETMODELSTATUS'
                         , data: true,
                     });
    } else {
        store.commit({
                         type:   'SETMODELSTATUS'
                         , data: false,
                     });
    }
}

/*export function saveExamPageData(ksId, replyPg) {
    // console.log('saveExamPageData', ksId, replyPg);
    let kaoshiReplyPg;
    if (window.localStorage.getItem(KaoshiReplyPgKey)) {
        kaoshiReplyPg = JSON.parse(window.localStorage.getItem(KaoshiReplyPgKey));
    } else {
        kaoshiReplyPg = {};
    }

    // console.log(kaoshiReplyPg);
    kaoshiReplyPg[ksId] = replyPg;
    window.localStorage.setItem(KaoshiReplyPgKey, JSON.stringify(kaoshiReplyPg));
    store.commit({
                     type:            'setKaoshiReplyPg'
                     , kaoshiReplyPg: kaoshiReplyPg,
                 });

}

export function clearExamPageData(ksId) {
    /!*window.localStorage.removeItem(KaoshiReplyPgKey);
    store.commit({
                     type: 'clearKaoshiReplyPg',
                 });*!/


    if (ksId) {
        let kaoshiReplyPg = JSON.parse(window.localStorage.getItem(KaoshiReplyPgKey));
        if (!kaoshiReplyPg) {
            return;
        }
        delete kaoshiReplyPg[ksId];
        window.localStorage.setItem(KaoshiReplyPgKey, JSON.stringify(kaoshiReplyPg));
        store.commit({
                         type:   'setKaoshiReplyPg'
                         , data: kaoshiReplyPg,
                     });
    } else {
        window.localStorage.removeItem(KaoshiReplyPgKey);
        delete store.state.pageData;
    }

}

export function getKaoshiReplyPg(ksId) {
    if (!store.state.kaoshiReplyPg) {
        let kaoshiReplyPg = JSON.parse(window.localStorage.getItem(KaoshiReplyPgKey));
        store.commit({
                         type:            'setKaoshiReplyPg'
                         , kaoshiReplyPg: kaoshiReplyPg,
                     });
        return kaoshiReplyPg ? kaoshiReplyPg[ksId] : null;
    } else {
        return store.state.kaoshiReplyPg[ksId];
    }
}*/
export function getNoticeId() {
    if (!store.state.noticeId) {
        let noticeId = JSON.parse(window.localStorage.getItem(`getNoticeId_key`));
        store.commit({
                         type:       'setNoticeId'
                         , noticeId: noticeId,
                     });
        return noticeId;
    } else {
        return store.state.noticeId;
    }
}

//////////////////// PageData start ////////////////////////////

/**
 *                   saveCache
 *
 * @author 宿
 * @summary 保存页面缓存
 * @param pageId 页面唯一识别  必须的
 * @param key   功能唯一识别  可缺省 缺省值为default
 * @param value 值
 * @return none
 * @example saveCache('QuestionStore', 'condition', opt);
 *          saveCache('QuestionStore', opt);
 */
export function saveCache() {
    let pageId, key, value;
    if (arguments.length === 3) {
        pageId = arguments[0];
        key = arguments[1];
        value = arguments[2];
    } else if (arguments.length === 2) {
        pageId = arguments[0];
        key = 'default';
        value = arguments[1];
    } else {
        console.log('saveCache 参数非法');
        return;
    }

    let auth = JSON.parse(window.localStorage.getItem('MTA-Auth'));
    if (!auth) {
        console.log('系统逻辑错误：saveCache 缓存 MTA-Auth 为空');
        return;
    }
    let userId = auth.userId;
    if (!userId) {
        console.log('系统逻辑错误：saveCache 缓存 MTA-Auth userId 为空');
        return;
    }
    let pageData = JSON.parse(window.localStorage.getItem(PageDataKey));
    if (!pageData) {
        pageData = {};
    }
    if (!pageData[userId]) {
        pageData[userId] = {};
    }
    if (!pageData[userId][pageId]) {
        pageData[userId][pageId] = {};
    }

    let oriVal = pageData[userId][pageId][key];
    if (oriVal !== null && !Array.isArray(oriVal) && typeof oriVal === 'object') {
        Object.assign(oriVal, value);
        pageData[userId][pageId][key] = oriVal;
    } else {
        pageData[userId][pageId][key] = value;
    }
    pageData[userId][pageId]['markTime'] = new Date().getTime();

    window.localStorage.setItem(PageDataKey, JSON.stringify(pageData));
    store.commit({
                     type:   'setCache'
                     , data: pageData,
                 });
}

/**
 *                   getCache
 *
 * @author 宿
 * @summary 取得页面缓存
 * @param pageId 页面唯一识别  必须的
 * @param key   功能唯一识别  可缺省 缺省值为default
 * @return the value of setCache
 * @example getCache('QuestionStore', 'condition', opt);
 *          getCache('QuestionStore', opt);
 */
export function getCache() {
    let pageId, key;
    if (arguments.length === 2) {
        pageId = arguments[0];
        key = arguments[1];
    } else if (arguments.length === 1) {
        pageId = arguments[0];
        key = 'default';
    } else {
        console.log('getCache 参数非法');
        return;
    }

    let auth = JSON.parse(window.localStorage.getItem('MTA-Auth'));
    if (!auth) {
        console.log('系统逻辑错误：getCache 缓存 MTA-Auth 为空');
        return;
    }
    let userId = auth.userId;
    if (!userId) {
        console.log('系统逻辑错误：getCache 缓存 MTA-Auth userId 为空');
        return;
    }
    if (!store.getters.getCache) {
        let pageData = JSON.parse(window.localStorage.getItem(PageDataKey));
        store.commit({
                         type:   'setCache'
                         , data: pageData,
                     });
        let pageCache = store.getters.getCache;
        if (!pageCache || !pageCache[userId] || !pageCache[userId][pageId]) {
            return null;
        }
        return pageCache[userId][pageId][key];
    } else {
        let pageCache = store.getters.getCache;
        if (!pageCache || !pageCache[userId]
            || !pageCache[userId][pageId]) {
            return null;
        }
        return pageCache[userId][pageId][key];
    }

}

/**
 *                   removeCache
 *
 * @author 宿
 * @summary 取得页面缓存
 * @param pageId 页面唯一识别  必须的
 * @param key   功能唯一识别  可缺省 缺省时  页面缓存全部删除
 * @return the value of setCache
 * @example removeCache('QuestionStore', 'condition');
 *          removeCache('QuestionStore');
 */
export function removeCache() {
    let pageId, key;
    if (arguments.length === 2) {
        pageId = arguments[0];
        key = arguments[1];
    } else if (arguments.length === 1) {
        pageId = arguments[0];
    } else {
        console.log('removeCache 参数非法');
        return;
    }

    let auth = JSON.parse(window.localStorage.getItem('MTA-Auth'));
    if (!auth) {
        console.log('系统逻辑错误：removeCache 缓存 MTA-Auth 为空');
        return;
    }
    let userId = auth.userId;
    if (!userId) {
        console.log('系统逻辑错误：removeCache 缓存 MTA-Auth userId 为空');
        return;
    }
    if (pageId) {
        let pageData = JSON.parse(window.localStorage.getItem(PageDataKey));
        if (!pageData) {
            return;
        }
        if (!pageData[userId]) {
            return;
        }

        if (arguments.length === 1) {
            delete pageData[userId][pageId];
            window.localStorage.setItem(PageDataKey, JSON.stringify(pageData));
            store.commit({
                             type:   'setCache'
                             , data: pageData,
                         });
        } else if (arguments.length === 2) {
            if (!pageData[userId][pageId]) {
                return;
            }
            delete pageData[userId][pageId][key];
            window.localStorage.setItem(PageDataKey, JSON.stringify(pageData));
            store.commit({
                             type:   'setCache'
                             , data: pageData,
                         });
        }


    } else {
        console.log('系统逻辑错误：removeCache pageId为空');
        return;
    }
}

//////////////////// PageData end ////////////////////////////


export function setNoticeId(data) {
    window.localStorage.setItem(`getNoticeId_key`, JSON.stringify(data));
    store.commit({
                     type:       'setNoticeId'
                     , noticeId: data,
                 });
}

export function getCreateTime() {
    if (!store.state.createTime) {
        let createTime = JSON.parse(window.localStorage.getItem(`getCreateTime_key`));
        store.commit({
                         type:         'setCreateTime'
                         , createTime: createTime,
                     });
        return createTime;
    } else {
        return store.state.createTime;
    }
}

export function setCreateTime(data) {
    window.localStorage.setItem(`getCreateTime_key`, JSON.stringify(data));
    store.commit({
                     type:         'setCreateTime'
                     , createTime: data,
                 });
}

export function getHisId() {
    if (!store.state.hisId) {
        let hisId = JSON.parse(window.localStorage.getItem(`getHisId_key`));
        store.commit({
                         type:    'setHisId'
                         , hisId: hisId,
                     });
        return hisId;
    } else {
        return store.state.hisId;
    }
}

export function setHisId(data) {
    window.localStorage.setItem(`getHisId_key`, JSON.stringify(data));
    store.commit({
                     type:    'setHisId'
                     , hisId: data,
                 });
}

//   describe: 模糊查询url author: Wgy date:2019-07-24
export function getFuzzySearchUrl() {
    let fuzzySearchUrl = JSON.parse(window.localStorage.getItem(`getFuzzySearchUrl_key`));
    return fuzzySearchUrl;
}

export function checkMenuListForLogin(data) {
    let status = _.findIndex(data, function (o) {
        return o.menuId === 1;
    });
    return status !== -1;
}

// 遍历树的各项根据id找到当前id的当前对象数据
export function findTreeObj(children, idName, id) {
    // console.log(children, idName, id);
    for (const node of children) {
        // console.log(node[idName], id)
        if (parseInt(node[idName]) === parseInt(id)) {
            return node;
        }
        if (node.children instanceof Array) {
            let _node = findTreeObj(node.children, idName, id);
            if (_node) {
                return _node;
            }
        }
    }
    return null;

}

// 获取浏览器放缩比例
function ChangeRatio() {
    var ratio = 0;
    var screen = window.screen;
    var ua = navigator.userAgent.toLowerCase();

    if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
        }

    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
    }

    if (ratio) {
        ratio = Math.round(ratio * 100);
    }
    return ratio;
}

export function customIntro(introInstance, providedCallback) {
    if (introInstance) {
        introInstance.setOptions({
                                     showStepNumbers:    false,
                                     showBullets:        true,
                                     nextLabel:          '>',
                                     prevLabel:          '<',
                                     skipLabel:          '跳过',
                                     doneLabel:          '完成',
                                     exitOnOverlayClick: false,
                                     disableInteraction: true,
                                 });
        introInstance.onexit(providedCallback);
        return introInstance;
    } else {
        return null;
    }
}

/**
 *  获取全局变量值
 * @returns {string}
 */
export function getBaseUrlFromCommon() {
    // return `https://saas-mta.oss-cn-beijing.aliyuncs.com`;
    return process.env.VUE_APP_BASE_API;

}

//动态返回项目名称
export function getWords() {
    return `麦塔`;
}

//动态获取项目图片并区分,type为图片后缀
export function getImg(param, type) {
    return require(`@/assets/images/` + param + `-sa.` + type);
}

/**
 * 获取根的 样式数据
 * @param colors
 * @param theme
 */
export function getColorObj(colors, theme) {
    let strColors = colors['color-' + theme];
    let arrTemp = strColors.split(',');
    let ret = {};
    for (const temp of arrTemp) {
        let kv = temp.trim().split(' ');
        // console.log(kv);
        ret[kv[0]] = kv[1];
    }
    return ret;
}

/**
 * 引导函数获取 数据
 * @param code 分类识别码 String
 * @returns {*[]}
 */
export function getuserGuide(code) {
    /**
     * welcome1
     * 初始化数据
     */
    let d1 = [
        {
            title:    '建立机构组织架构1 video',
            content:  '建立各部门1',
            mode:     'video',
            videoUrl: 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm',
        },
        {
            title:    '建立机构组织架构2 video',
            content:  '建立各部门2',
            mode:     'video',
            videoUrl: 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm',
        },
        /*{
            title:    '建立机构组织架构3 video',
            content:  '建立各部门3',
            mode:     'video',
            videoUrl: 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm',
        },*/
        {
            title:    '建立机构组织架构4 pic',
            content:  '建立各部门4',
            mode:     'image',
            imageUrl: require(`@/assets/images/404.jpg`),
        },
    ];
    /**
     * welcome2
     * 初始化数据
     */
    let d2 = [
        {
            title:    '建立机构组织架构1 pic',
            content:  '建立各部门1',
            mode:     'image',
            imageUrl: require(`@/assets/images/404.jpg`),
        },
        {
            title:    '建立机构组织架构2 pic',
            content:  '建立各部门2',
            mode:     'image',
            imageUrl: require(`@/assets/images/be_careful.png`),
        },
        {
            title:    '建立机构组织架构3 pic',
            content:  '建立各部门3',
            mode:     'image',
            imageUrl: require(`@/assets/images/404.jpg`),
        },
        {
            title:    '建立机构组织架构4 pic',
            content:  '建立各部门4',
            mode:     'image',
            imageUrl: require(`@/assets/images/404.jpg`),
        },
    ];

    let questionStore = [
        {
            title:    '建立考试用题分类',
            content:  '通过建立考试用题分类，可以更快捷分组管理试题',
            mode:     'video',
            videoUrl: 'https://saas-mta.oss-cn-beijing.aliyuncs.com/test/24.mp4',
        },
        {
            title:    '添加试题',
            content:  '支持试题的单个/批量的导入、导出，支持试题预览、编辑、状态设置',
            mode:     'video',
            videoUrl: 'https://saas-mta.oss-cn-beijing.aliyuncs.com/test/71.mp4',
        },
        {
            title:    '开始建立考试用题分类后添加试题吧',
            content:  '您已经掌握了考试-试题管理模块的使用。若遇到问题可以点击帮助获取更多支持！',
            mode:     'image',
            imageUrl: require(`@/assets/images/admin/guide-last.png`),
        },
    ];

    let examineStore = [
        {
            title:    '建立试卷分类',
            content:  '通过建立试卷用题分类，可以更快捷分组管理试题',
            mode:     'video',
            videoUrl: 'https://saas-mta.oss-cn-beijing.aliyuncs.com/test/24.mp4',
        },
        {
            title:    '添加试题',
            content:  '支持试题的单个/批量的导入、导出，支持试题预览、编辑、状态设置',
            mode:     'video',
            videoUrl: 'https://saas-mta.oss-cn-beijing.aliyuncs.com/test/71.mp4',
        },
        {
            title:    '开始建立试卷用题分类后添加试题吧',
            content:  '您已经掌握了试卷-试题管理模块的使用。若遇到问题可以点击帮助获取更多支持！',
            mode:     'image',
            imageUrl: require(`@/assets/images/admin/guide-last.png`),
        },
    ];

    let d4 = [
        {
            title:    '建立考试用题分类',
            content:  '通过建立考试用题分类，可以更快捷分组管理试题',
            mode:     'video',
            videoUrl: 'https://saas-mta.oss-cn-beijing.aliyuncs.com/test/24.mp4',
        },
        {
            title:    '添加试题',
            content:  '支持试题的单个/批量的导入、导出，支持试题预览、编辑、状态设置',
            mode:     'video',
            videoUrl: 'https://saas-mta.oss-cn-beijing.aliyuncs.com/test/71.mp4',
        },
        {
            title:    '开始建立考试用题分类后添加试题吧',
            content:  '您已经掌握了考试-试题管理模块的使用。若遇到问题可以点击帮助获取更多支持！',
            mode:     'image',
            imageUrl: require(`@/assets/images/admin/guide-last.png`),
        },
    ];

    let opt = null;
    switch (code) {
        case 'welcome':
            opt = d1;
            break;
        case 'welcome2':
            opt = d2;
            break;
        case 'questionStore':
            opt = questionStore;
            break;
        case 'examineStore':
            opt = examineStore;
            break;
        case 'organizational':
            opt = questionStore;
            break;
    }

    if (opt === null) {
        throw new Error('未找到引导页标识符, 请检查入参code是否正确！');
    }

    return opt;
}


export function getTodayDate() {
    const weekday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const opt = {
        date: '',
        week: '',
    };
    const d = new Date();
    opt.week = weekday[d.getDay()];
    opt.date = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;

    return opt;
}

export function checkMenuListForDisable(data) {
    const menulist = store.state.auth.menuList;
    if (menulist.length) {
        const status = menulist.filter((element) => {

            return element.url === data;
        });
        let c = status.length > 0;
        return !c;
    }
    return false;
}

// 判断路径是否为相对路径
export function checkUrlIsNotHttpUrl(str) {
    /**
     * 参数校验
     * 为空则return
     * 为null则return
     */
    if (str === null) {
        return true;
    }

    if (str === '') {
        return true;
    }

    const Expression = /^(http|https):\/\//;
    const patt = new RegExp(Expression);

    if (patt.test(str)) {
        return false;
    } else {
        return true;
    }
}


export function isObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]';
}


export function clone(obj) {
    // Handle the 3 simple types, and null or undefined or function
    if (null == obj || 'object' != typeof obj) {
        return obj;
    }

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }
    // Handle Array or Object
    if (obj instanceof Array | obj instanceof Object) {
        var copy = (obj instanceof Array) ? [] : {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) {
                copy[attr] = clone(obj[attr]);
            }
        }
        return copy;
    }
    throw new Error('Unable to clone obj! Its type isn\'t supported.');
}

export function appendScript(url) {
    var script = document.createElement('script');
    script.src = url;
    script.async = true;
    document.head.appendChild(script);
}

/**
 * 秒转${h}时${m}分${s}秒
 * @param value 输入值 long
 * @param isNoZero true/false 是否去零
 * @return 去零: 5时45分   不去零:05时45分00秒
 */
export function formatSecondsToCnhms(value, isNoZero) {
    if (!value || value == 0) {
        return '';
    }
    let result = parseInt(value);
    let h = isNoZero ? Math.floor(result / 3600) : Math.floor(result / 3600) < 10
                                                   ? '0' + Math.floor(result / 3600)
                                                   : Math.floor(result / 3600);
    let m = isNoZero ? Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60)) < 10
                                                        ? '0' + Math.floor((result / 60 % 60))
                                                        : Math.floor((result / 60 % 60));
    let s = isNoZero ? Math.floor((result % 60)) : Math.floor((result % 60)) < 10
                                                   ? '0' + Math.floor((result % 60))
                                                   : Math.floor((result % 60));
    if (isNoZero) {
        result = '';
        if (h !== 0) {
            result += `${h}时`;
        }
        if (m !== 0) {
            result += `${m}分`;
        }
        if (s !== 0) {
            result += `${s}秒`;
        }
    } else {
        result = `${h}时${m}分${s}秒`;
    }
    return result;
}


export function getImgByType(type) {
    // 文件类型 1:视频 2:音频 3:word 4:excel 5:ppt 6:pdf 7:视频服务器链接 8:第三方链接
    if (type == 1) {
        return require(`@/assets/images/icons/px-video.svg`);
    } else if (type == 2) {
        return require(`@/assets/images/icons/px-audio.svg`);
    } else if (type == 3) {
        return require(`@/assets/images/icons/px-word.svg`);
    } else if (type == 4) {
        return require(`@/assets/images/icons/px-excel.svg`);
    } else if (type == 5) {
        return require(`@/assets/images/icons/px-ppt.svg`);
    } else if (type == 6) {
        return require(`@/assets/images/icons/px-pdf.svg`);
    } else if (type == 7) {
        return require(`@/assets/images/icons/px-video-serve-link.svg`);
    } else if (type == 8) {
        return require(`@/assets/images/icons/px-thirdpartylink.svg`);
    }
}

export function getZhcnOption() {
    return {
        'Play':                                                                                                                        '播放',
        'Pause':                                                                                                                       '暂停',
        'Current Time':                                                                                                                '当前时间',
        'Duration':                                                                                                                    '时长',
        'Remaining Time':                                                                                                              '剩余时间',
        'Stream Type':                                                                                                                 '媒体流类型',
        'LIVE':                                                                                                                        '直播',
        'Loaded':                                                                                                                      '加载完毕',
        'Progress':                                                                                                                    '进度',
        'Fullscreen':                                                                                                                  '全屏',
        'Non-Fullscreen':                                                                                                              '退出全屏',
        'Mute':                                                                                                                        '静音',
        'Unmute':                                                                                                                      '取消静音',
        'Playback Rate':                                                                                                               '播放速度',
        'Subtitles':                                                                                                                   '字幕',
        'subtitles off':                                                                                                               '关闭字幕',
        'Captions':                                                                                                                    '内嵌字幕',
        'captions off':                                                                                                                '关闭内嵌字幕',
        'Chapters':                                                                                                                    '节目段落',
        'Close Modal Dialog':                                                                                                          '关闭弹窗',
        'Descriptions':                                                                                                                '描述',
        'descriptions off':                                                                                                            '关闭描述',
        'Audio Track':                                                                                                                 '音轨',
        'You aborted the media playback':                                                                                              '视频播放被终止',
        'A network error caused the media download to fail part-way.':                                                                 '网络错误导致视频下载中途失败。',
        'The media could not be loaded, either because the server or network failed or because the format is not supported.':          '视频因格式不支持或者服务器或网络的问题无法加载。',
        'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.': '由于视频文件损坏或是该视频使用了你的浏览器不支持的功能，播放终止。',
        'No compatible source was found for this media.':                                                                              '无法找到此视频兼容的源。',
        'The media is encrypted and we do not have the keys to decrypt it.':                                                           '视频已加密，无法解密。',
        'Play Video':                                                                                                                  '播放视频',
        'Close':                                                                                                                       '关闭',
        'Modal Window':                                                                                                                '弹窗',
        'This is a modal window':                                                                                                      '这是一个弹窗',
        'This modal can be closed by pressing the Escape key or activating the close button.':                                         '可以按ESC按键或启用关闭按钮来关闭此弹窗。',
        ', opens captions settings dialog':                                                                                            ', 开启标题设置弹窗',
        ', opens subtitles settings dialog':                                                                                           ', 开启字幕设置弹窗',
        ', opens descriptions settings dialog':                                                                                        ', 开启描述设置弹窗',
        ', selected':                                                                                                                  ', 选择',
        'captions settings':                                                                                                           '字幕设定',
        'Audio Player':                                                                                                                '音频播放器',
        'Video Player':                                                                                                                '视频播放器',
        'Replay':                                                                                                                      '重播',
        'Progress Bar':                                                                                                                '进度条',
        'Volume Level':                                                                                                                '音量',
        'subtitles settings':                                                                                                          '字幕设定',
        'descriptions settings':                                                                                                       '描述设定',
        'Text':                                                                                                                        '文字',
        'White':                                                                                                                       '白',
        'Black':                                                                                                                       '黑',
        'Red':                                                                                                                         '红',
        'Green':                                                                                                                       '绿',
        'Blue':                                                                                                                        '蓝',
        'Yellow':                                                                                                                      '黄',
        'Magenta':                                                                                                                     '紫红',
        'Cyan':                                                                                                                        '青',
        'Background':                                                                                                                  '背景',
        'Window':                                                                                                                      '视窗',
        'Transparent':                                                                                                                 '透明',
        'Semi-Transparent':                                                                                                            '半透明',
        'Opaque':                                                                                                                      '不透明',
        'Font Size':                                                                                                                   '字体尺寸',
        'Text Edge Style':                                                                                                             '字体边缘样式',
        'None':                                                                                                                        '无',
        'Raised':                                                                                                                      '浮雕',
        'Depressed':                                                                                                                   '压低',
        'Uniform':                                                                                                                     '均匀',
        'Dropshadow':                                                                                                                  '下阴影',
        'Font Family':                                                                                                                 '字体库',
        'Proportional Sans-Serif':                                                                                                     '比例无细体',
        'Monospace Sans-Serif':                                                                                                        '单间隔无细体',
        'Proportional Serif':                                                                                                          '比例细体',
        'Monospace Serif':                                                                                                             '单间隔细体',
        'Casual':                                                                                                                      '舒适',
        'Script':                                                                                                                      '手写体',
        'Small Caps':                                                                                                                  '小型大写字体',
        'Reset':                                                                                                                       '重置',
        'restore all settings to the default values':                                                                                  '恢复全部设定至预设值',
        'Done':                                                                                                                        '完成',
        'Caption Settings Dialog':                                                                                                     '字幕设定视窗',
        'Beginning of dialog window. Escape will cancel and close the window.':                                                        '开始对话视窗。离开会取消及关闭视窗',
        'End of dialog window.':                                                                                                       '结束对话视窗',
        'Seek to live, currently behind live':                                                                                         '试图直播，当前延时播放',
        'Seek to live, currently playing live':                                                                                        '试图直播，当前实时播放',
        'progress bar timing: currentTime={1} duration={2}':                                                                           '{1}/{2}',
        '{1} is loading.':                                                                                                             '正在加载 {1}。',
        'Picture-in-Picture':                                                                                                          '画中画',
        'Now Playing':                                                                                                                 '正在播放',
        'Up Next':                                                                                                                     '播放下一个',
        'Untitled Video':                                                                                                              '无标题视频',
    };
}

export function getSection(objKC, iChapter, iSection) {
    let arrChapter = objKC;
    if (arrChapter) {
        let i1 = 0;
        for (const chapter of arrChapter) {
            if (i1 === iChapter) {
                if (chapter.children) {
                    let i2 = 0;
                    for (const section of chapter.children) {
                        if (i2 === iSection) {
                            return section;
                        }
                        i2++;
                    }
                }
            }
            i1++;
        }
    }
    return {};
}


/**
 * 同步缓存进度
 */
export function updateSectionProgress() {
    function needSubmit(kjJson) {
        kjJson = JSON.parse(kjJson);
        if (kjJson && kjJson.length > 0) {
            for (const chapter of kjJson) {
                for (const section of chapter.children) {
                    for (const kejian of section.kejianArr) {
                        if (!kejian.curProcess || kejian.curProcess !== kejian.maxProcess || kejian.curProcess !== 100) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    // console.log('updateSectionProgress start');
    let sectionPage = getCache('CourseInfo', 'sectionPage');
    let arrKecheng = getCache('CourseInfo', 'arrKecheng');
    // console.log(arrKecheng);
    if (!sectionPage){
        console.log('CourseInfo 不存在, 当前不是培训');
        return;
    }

    let operId = sectionPage.operId;
    let needPost = false;
    if (arrKecheng) {
        loop1: for (const chapter of arrKecheng) {
            if (chapter.children) {
                for (const section of chapter.children) {
                    if (section.kejianArr) {
                        for (const kejian of section.kejianArr) {
                            if (kejian.kjId === sectionPage.kjId) {
                                if (kejian['curProcess'] === kejian['maxProcess']) {
                                    // 第一次到100
                                    if (kejian['curProcess'] === 100) {
                                        if (!kejian['hasFinished']) {
                                            kejian['hasFinished'] = true;
                                            needPost = true;
                                        } else {
                                            needPost = false;
                                        }
                                    } else {
                                        needPost = true;
                                    }
                                }
                                break loop1;
                            }
                        }
                    }
                }
            }
        }
    }

    let kjJson = JSON.stringify(arrKecheng);
    if (needPost) {
        console.log('kechengApi.kcCSave');
        kechengApi.kcCSave({
                               kjJson: kjJson,
                               operId: operId,
                           }).then(res => {
            if (res.code === 0) {
                console.log('kcCSave success');
                saveCache('CourseInfo', 'arrKecheng', arrKecheng);
                if (needSubmit(kjJson)) {
                    console.log('needSubmit 3434423423423');
                    kechengApi.kcCSubmit({
                                             'kjJson': kjJson,
                                             'operId': operId,
                                         }).then(res => {
                        if (res.code === 0) {
                            console.log('kcCSubmit success');
                        }
                    });

                }
            }
        });
    }
}

export function checkIsEmpty(data) {
    const status = (data !== null && data !== undefined && data !== '');
    return !status;
}

export function toChinesNum(num) {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    let unit = ["", "十", "百", "千", "万"];
    num = parseInt(num);
    let getWan = (temp) => {
        let strArr = temp.toString().split("").reverse();
        let newNum = "";
        for (var i = 0; i < strArr.length; i++) {
            newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
        }
        return newNum;
    }
    let overWan = Math.floor(num / 10000);
    let noWan = num % 10000;
    if (noWan.toString().length < 4) {
        noWan = "0" + noWan;
    }
    return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}

export function saveHistoryPaths(to, from, next) {
    /*console.log('saveHistoryPaths');*/
    // console.log(to, from, next);
    let arrPaths = getCache('Breadcrumb', 'arrPaths');
    if (!arrPaths || !to.meta.parentPath || to.meta.parentPath === 'croot') {
        arrPaths = [];
    }
    if (arrPaths[arrPaths.length - 1] !== to.path) {
        arrPaths.push(to.path);
    }
    // save path to history
    saveCache('Breadcrumb', 'arrPaths', arrPaths);
}

/**
 * 深度克隆
 * @param source
 * @return {*}
 * @example let a = {aa: 1, b:2}; let b = deepClone(a); a.aa = 3; b.aa(out:1)
 */
export function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys])
        } else {
            targetObj[keys] = source[keys]
        }
    })
    return targetObj
}

/**
 * 格式化 数据 去空格
 * @param data
 * @returns {*}
 */
export function getTrimData(data) {
    if (!checkIsEmpty(data)) {
        return data.trim();
    }
    return data;
}

export function handleErr(that, err) {
    console.log(err);
    if (typeof err === 'string') {
        if (err.indexOf('error500') > -1) {
            // console.log(err);
        } else if (err.indexOf('error1001') > -1) {
            setTimeout(()=>{
                that.$router.go(-1);
            }, 2000);
        }
    } else if (typeof err === 'object') {
        that.$toast('处理失败，网络异常');
    }
}
