import fetch from '@/utils/fetch'
import { getBaseUrl, getReportUrl, getWorkApi } from '@/utils/index'
import { CryptoJS } from '@/plugins/aes'
import 'jsencrypt'

import { getPubKey } from '@/utils/account/accountApi';

let pubKey = "";

module.exports = {
    data: function () {
        return {
            token: null
        }
    },
    created: function () {
      //  let query = this.$router.query
        // this.token = this.getUrlSearch(location.href, 'token') || (query && query.token) || null
      //  this.token = this.getUrlKey('token') || (query && query.token) || null
    },
    mounted: function() {
      
    },
    methods: {

        // generate key
        getAesKey(len) {
            len = len || 16;
            var aesKey = "";
            var strList = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var strLen = strList.length;
            for(var i=0; i<len; i++){
            aesKey += strList.charAt( Math.floor( Math.random()*strLen ) );
            };
            return aesKey;
        },
        // 加密传参,发送请求
        sendEncryptRequest(content, cb){
            content = JSON.stringify(content);  // 后端要求转 string
            // debugger;
            if(pubKey){  // pubKey获取过就不用再获取了
                let params = this.formatContent(content, pubKey);
                cb && cb(params);
            }else{
                this.handleGetPubKey(content, cb);
            }
        },
        // get public key
        handleGetPubKey(content, cb){
            getPubKey().then(res => {
                console.log('>>>>>>>>>>>>>>>>>>>> publicKey: ', res)
                if(res.code == '000000'){
                    pubKey = res.data;
                    if(cb){
                        let params = this.formatContent(content, pubKey);
                        cb && cb(params);
                    }
                }else{
                    this.$message({  
                        message: (res && res.message) || '接口出错',
                        type: 'warning'
                    });
                }
            })
        },
        // format account params
        formatContent(content, pubKey) {  // obj为具体的json传参
            let aesKey = this.getAesKey(16);
            console.log('AES key::::::: ', aesKey)
            let params = {
                key: '',
                content: ''
            };
            // 开发阶段后端接口还没处理加密，先传 原始json数据 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 后端加密OK后 再用下面的注释代码
            // params.content = content;
            params.content = this.AesEncrypt(content, aesKey);
            params.key = this.RsaEncrypt(aesKey, pubKey);
            return params;
        },
        // AES encrypt
        AesEncrypt(content, aesKey) {
            let sKey = CryptoJS.enc.Utf8.parse(aesKey);
            let sContent = CryptoJS.enc.Utf8.parse(content);
            let encrypted = CryptoJS.AES.encrypt(sContent, sKey, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
            return encrypted.toString();
        },
        // RSA encrypt
        RsaEncrypt(aesKey, pubKey){  
            let _encrypt = new JSEncrypt();
            let boss_public_key = pubKey;
            _encrypt.setPublicKey(boss_public_key);
            let encrypted = _encrypt.encrypt(aesKey);
            return encrypted;
        },

        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 ''
        },

        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;
        },

        // 根据条件排序
        async searchForOrder(searchCategory = '1', searchValue = '', sortItem = 1, pageSize = 10, sourceData = []) {
            if(pageSize <=0 ) return;
            let str2 = (searchValue || '').replace(/[\-\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\L\<\>\?]/g, '');// 去掉特殊字符
            let _this = this,
                para = {
                    searchCategory: searchCategory,
                    searchValue: str2,
                    keywordColor: 'rgba(244,122,72,1)',
                    sortItem: sortItem,
                    pageNo: 1,
                    pageSize: pageSize,
                    token: _this.token,
                    setEntry: 'headers',
                }
            let url = 'contents/searchKeyword/searchContent'
      
            let csourceData = await this.GET(url, para).then(res => {
                // _this.searchText = ''
                if (res.code == '000000') {
                    // 课程
                    if(searchCategory.indexOf('1') >= 0) {
                        sourceData = (res.data && res.data.contentAppModels) || []
                    }
                    if(searchCategory.indexOf('2') >= 0) {
                        // sourceData = []
                        sourceData = this.handelFive(res.data.fiveMinutesMedicalContentList || [])
                    }
                    if(searchCategory.indexOf('3') >= 0) {
                        sourceData = (res.data && res.data.pCourseDoctorModels) || []
                    }
                    if(searchCategory.indexOf('4') >= 0) {
                        sourceData = res.data.educationContents
                    }
                }
                return sourceData || []
            })
            return csourceData
        },
      
        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') {
                debugger
                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
                })
                //alert(this.token);
               return 'NO'
            }
            if(typeof paramList === 'string' && !paramList){
                paramList = []
            }
            return paramList;
        },

        // 通用GET请求
        GET(api, para, callback,str) {
           // para.token = para.token || this.token || "343BCABC890349ACAF357FA79122F9FE"
            let url = api + this.getUrlPara(para)
            url = encodeURI(url);
            return fetch({
                url: getBaseUrl(url),
                method: 'get',
                data: para
            })
        },
        reportGET(api, para, callback,str) {
            // para.token = para.token || this.token || "343BCABC890349ACAF357FA79122F9FE"
             let url = api + this.getUrlPara(para)
             url = encodeURI(url);
             return fetch({
                 url: getReportUrl(url),
                 method: 'get',
                 data: para
             })
         },
        // saas-GET请求
        saasGET(api, para) {
          // para.token = para.token || this.token || "343BCABC890349ACAF357FA79122F9FE"
          return fetch({
            headers: {
              sysCode: 9,
            },
            url: getWorkApi(api),
            method: 'get',
            params: para
          })
        },

        // 通用DELETE请求
        DELETE(api, para, callback,str) {
            // para.token = para.token || this.token || "343BCABC890349ACAF357FA79122F9FE"
            let url = api + this.getUrlPara(para)
            return fetch({
                url: getBaseUrl(url),
                method: 'delete',
                data: para
            })
        },

        // 通用POST请求
        POST(api, para, callback) {
            // para.token = para.token || this.token || "343BCABC890349ACAF357FA79122F9FE"
            return fetch({
                url: getBaseUrl(api),
                method: 'post',
                data: para
            })
        },
        reportPOST(api, para, callback) {
            // para.token = para.token || this.token || "343BCABC890349ACAF357FA79122F9FE"
            return fetch({
                url: getReportUrl(api),
                method: 'post',
                data: para
            })
        },
        // 通用saas-POST请求
        saasPOST(api, para, cType) {
          // para.token = para.token || this.token || "343BCABC890349ACAF357FA79122F9FE"
          let header = {}
          if(cType) {
            header['Content-Type'] = cType;
          }
          return fetch({
            headers: {
              sysCode: 9,
              ...header
            },
            url: getWorkApi(api),
            method: 'post',
            data: para
          })
        },
      // 通用saas-PUT请求
      saasPUT(api, para) {
        return fetch({
          headers: {
            sysCode: 9,
          },
          url: getWorkApi(api),
          method: 'put',
          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
        }

    }
}
