gaoshp
2024-06-11 e87012567c674cd69f7a8f87df7202eac60a8208
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: sakuya
 * @LastEditTime: 2022年5月24日00:28:56
 */
 
import CryptoJS from 'crypto-js';
import sysConfig from "@/config";
 
const tool = {}
 
/* localStorage */
tool.data = {
    set(key, data, datetime = 0) {
        //加密
        if(sysConfig.LS_ENCRYPTION == "AES"){
            data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
        }
        let cacheValue = {
            content: data,
            datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
        }
        return localStorage.setItem(key, JSON.stringify(cacheValue))
    },
    get(key) {
        try {
            const value = JSON.parse(localStorage.getItem(key))
            if (value) {
                let nowTime = new Date().getTime()
                if (nowTime > value.datetime && value.datetime != 0) {
                    localStorage.removeItem(key)
                    return null;
                }
                //解密
                if(sysConfig.LS_ENCRYPTION == "AES"){
                    value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
                }
                return value.content
            }
            return null
        } catch (err) {
            return null
        }
    },
    remove(key) {
        return localStorage.removeItem(key)
    },
    clear() {
        return localStorage.clear()
    }
}
 
/*sessionStorage*/
tool.session = {
    set(table, settings) {
        var _set = JSON.stringify(settings)
        return sessionStorage.setItem(table, _set);
    },
    get(table) {
        var data = sessionStorage.getItem(table);
        try {
            data = JSON.parse(data)
        } catch (err) {
            return null
        }
        return data;
    },
    remove(table) {
        return sessionStorage.removeItem(table);
    },
    clear() {
        return sessionStorage.clear();
    }
}
 
/*cookie*/
tool.cookie = {
    set(name, value, config={}) {
        var cfg = {
            expires: null,
            path: null,
            domain: null,
            secure: false,
            httpOnly: false,
            ...config
        }
        var cookieStr = `${name}=${escape(value)}`
        if(cfg.expires){
            var exp = new Date()
            exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
            cookieStr += `;expires=${exp.toGMTString()}`
        }
        if(cfg.path){
            cookieStr += `;path=${cfg.path}`
        }
        if(cfg.domain){
            cookieStr += `;domain=${cfg.domain}`
        }
        document.cookie = cookieStr
    },
    get(name){
        var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"))
        if(arr != null){
            return unescape(arr[2])
        }else{
            return null
        }
    },
    remove(name){
        var exp = new Date()
        exp.setTime(exp.getTime() - 1)
        document.cookie = `${name}=;expires=${exp.toGMTString()}`
    }
}
 
/* socket */
tool.socket = {
    url:'ws://116.63.155.153:83/ws/info',
    websocket: null,
    connectToWebSocket(token) {  //建立链接
        this.websocket = new WebSocket(this.url + "?access_token=" + token);  
    },
    sendDataToWebSocket(data) {  //发送
        if(!data) return;   //没有入参不发送
        if (this.websocket.readyState === this.websocket.OPEN) {    
            this.websocket.send(JSON.stringify(data));  
        } 
        // this.websocket.onmessage = function(event) {  
        //     // 当从服务器收到消息时  
        //     console.error("WebSocket Error: ", event.data);  
        // };  
      
        // this.websocket.onerror = function(error) {  
        //     // 当WebSocket连接发生错误时  
        //     console.error("WebSocket Error: ", error);  
        // };  
      
        // this.websocket.onclose = function(event) {  
        //     // 当WebSocket连接关闭时  
        //     console.log("WebSocket is closed now.");  
        //     // 可以在这里重试连接或其他逻辑...  
        // };
        return this;
    }
}
/* Fullscreen */
tool.screen = function (element) {
    var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
    if(isFull){
        if(document.exitFullscreen) {
            document.exitFullscreen();
        }else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }else{
        if(element.requestFullscreen) {
            element.requestFullscreen();
        }else if(element.msRequestFullscreen) {
            element.msRequestFullscreen();
        }else if(element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        }else if(element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        }
    }
}
 
/* 复制对象 */
tool.objCopy = function (obj) {
    return JSON.parse(JSON.stringify(obj));
}
 
/* 日期格式化 */
tool.dateFormat = function (date, fmt='yyyy-MM-dd hh:mm:ss') {
    date = new Date(date)
    var o = {
        "M+" : date.getMonth()+1,                 //月份
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //小时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S"  : date.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}
 
/* 千分符 */
tool.groupSeparator = function (num) {
    num = num + '';
    if(!num.includes('.')){
        num += '.'
    }
    return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
        return $1 + ',';
    }).replace(/\.$/, '');
}
 
/* 常用加解密 */
tool.crypto = {
    //MD5加密
    MD5(data){
        return CryptoJS.MD5(data).toString()
    },
    //BASE64加解密
    BASE64: {
        encrypt(data){
            return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
        },
        decrypt(cipher){
            return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
        }
    },
    //AES加解密
    AES: {
        encrypt(data, secretKey, config={}){
            if(secretKey.length % 8 != 0){
                console.warn("[SCUI error]: 秘钥长度需为8的倍数,否则解密将会失败。")
            }
            const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
                iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
                mode: CryptoJS.mode[config.mode || "ECB"],
                padding: CryptoJS.pad[config.padding || "Pkcs7"]
            })
            return result.toString()
        },
        decrypt(cipher, secretKey, config={}){
            const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
                iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
                mode: CryptoJS.mode[config.mode || "ECB"],
                padding: CryptoJS.pad[config.padding || "Pkcs7"]
            })
            return CryptoJS.enc.Utf8.stringify(result);
        }
    }
}
 
tool.qsStringify = function(obj) {
    return Object.keys(obj).map(key => {
      if (Array.isArray(obj[key])) {
        return obj[key]
          .map(arrayValue => `${encodeURIComponent(key)}=${encodeURIComponent(arrayValue)}`)
          .join('&');
      }
      return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`;
      }).join('&');
}
 
export default tool