zhouhao
2021-11-03 01138b4c3bfd1a69d3a3327e26c371f51fe46978
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
 * @Descripttion: 工具函数 以 _ 符号作为函数前缀
 * @Author: TM丶
 * @LastEditors: 小明丶
 * @Date: 2019-03-10 22:05:50
 * @LastEditTime: 2020-03-27 14:17:45
 */
 
/**
 * @Descripttion: 函数节流
 * @param {method} 执行的方法
 * @param {delay} 延迟时间
 * @param {context} 绑定的this值
 * @return: Function
 */
export function _throller(method, delay, context) {
    var begin = new Date();
    return function () {
        var args = arguments,
            current = new Date();
        if (current - begin >= delay) {
            method.apply(context, args);
            begin = current;
        }
    }
}
 
/**
 * @Descripttion: 函数防抖
 * @param {method} 执行的方法
 * @param {delay} 延迟时间
 * @return: Function
 */
export function _debounce(method, delay) {
    let timer = null;
    return function () {
        let context = this,
            args = arguments;
 
        clearTimeout(timer);
        timer = setTimeout(function () {
            method.apply(context, args);
        }, delay);
    }
}
 
/**
 * @Descripttion: 字符串参数解析
 * @demo '?demo=123&test=test'
 * @return: {demo:123,test:'test'}
 */
export function _getQueryArgs(str) {
    if (str.indexOf('?') === -1) {
        throw Error('参数错误')
    }
    let args = new URLSearchParams(str);
    return args;
}
 
/**
 * @Descripttion: 将base64转换为文件
 * @param {dataurl} base64
 * @param {filename} 要创建的文件名
 * @return: file
 */
export function _dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {
        type: mime
    });
}
 
 
/**
 * @Descripttion: 文字复制到设备的剪切板
 * @param {text} 要复制的文字
 * @return: Boolean
 */
export function _copyToClipboard(text) {
    var textArea = document.createElement('textarea');
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;
    textArea.style.width = '2em';
    textArea.style.height = '2em';
    textArea.style.padding = 0;
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';
    textArea.value = text ? text : "";
    document.body.appendChild(textArea);
    if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//区分iPhone设备
      window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效
      // var Url2=document.getElementById("biaoios");//要复制文字的节点
      var range = document.createRange();
      // 选中需要复制的节点
      range.selectNode(textArea);
      // 执行选中元素
      window.getSelection().addRange(range);
      // 执行 copy 操作
      var successful = document.execCommand('copy');
      // 移除选中的元素
      window.getSelection().removeAllRanges();
    } else {
      textArea.select();
      var msg = document.execCommand("Copy");
    }
    document.body.removeChild(textArea);
}
 
 
/**文件转换base64
 * @param { 文件对象 } file 
 * @return { Promise }
 */
export function _fileToBase64(file) {
    if (Object.prototype.toString.call(file) !== "[object File]") {
        console.warn(`file 必须是 文件! >>>${file}`);
        return
    }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    return new Promise((resolve, reject) => {
        reader.onload = function () {
            resolve(this.result);
        }
    })
}
 
 
/**
 * @Descripttion: 图片压缩
 * @param {path} 图片路径 || base64 
 * @param {options} {quality:图片质量0-1,width,height}
 * @return: base64
 */
export function _imgCompress(path, options = {}) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.src = path;
        img.onload = function () {
            let that = this,
                w = that.width,
                h = that.height,
                scale = w / h, // 默认按比例压缩
                quality = options.quality || 0.3,
                canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');
 
            w = options.width || w;
            h = options.height || (w / scale);
            canvas.width = w;
            canvas.height = h;
            ctx.drawImage(that, 0, 0, w, h);
            if (options.quality && options.quality <= 1 && options.quality > 0) {
                quality = options.quality;
            }
            let base64 = canvas.toDataURL('image/jpeg', quality);
            resolve(base64);
        }
    })
}
 
// 使input=number的maxlength有效
export function disabledInputStr() {
    window.addEventListener('input', (event) => {
        let el = event.target,
            val = el.value,
            tagName = el.tagName.toUpperCase();
        if (tagName === 'INPUT' && el.getAttribute('type') === 'number') {
            let maxlength = el.getAttribute('maxlength');
            if (val.length >= maxlength) {
                el.value = val.slice(0, maxlength);
                event.preventDefault();
            }
        }
    })
}
 
//移动端判断设备类型:安卓 或 ios
export function judegeDevice() {
    let type = {
        isIos: false,
        isAndroid: false,
    }
    var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) { //安卓手机
        type.isAndroid = true;
    } else if (u.indexOf('iPhone') > -1) { //苹果手机
        type.isIos = true;
    }
    return type;
}
 
//解决安卓中键盘弹起时顶起页面,导致元素不在可视区内的问题
export function scrollElement() {
    if (judegeDevice.isAndroid) {
        window.addEventListener("resize", function () {
            let el = document.activeElement;
            if (el.tagName == "INPUT" || el.tagName == "TEXTAREA") {
                setTimeout(function () {
                    // el.scrollIntoViewIfNeeded();
                    el.scrollIntoView({
                        behavior: 'smooth',
                    });
                }, 16.7);
            }
        })
    }
}
 
 
 
/**
 * @description: 禁止右键、选择、复制
 */
export function a() {
    ['contextmenu', 'selectstart', 'copy'].forEach(function (ev) {
        document.addEventListener(ev, function (event) {
            return event.returnValue = false
        })
    });
}
 
// 根据 用户的机构类型 获取参数
export function getParams(orgType, id) {
    if(!id) return {};
    let obj = {}
    switch (orgType) {
        case 1:
        case 2:
            // 代理、渠道
            obj.merList = [id]
            break;
        case 3:
            //商户
            obj.storeList = [id]
            break;
    }
    return obj
}
 
// 解析地区
export function calcArea(arr){
    let province_list =[],
        city_list = [],
        county_list = [];
 
    function parseArea(arr) {
        let obj = {}
        arr.forEach(item => {
            obj[item.value] = item.name;
        })
        return obj;
    }
    
    arr.forEach(item => {
        item.value = +item.value;
        let value = item.value;
        if (!item.parent) {
            province_list.push(item)
        } else if (item.parent % 10000 === 0) {
            city_list.push(item)
        } else {
            county_list.push(item)
        }
    })
    return {
        province_list:parseArea(province_list),
        city_list:parseArea(city_list),
        county_list:parseArea(county_list)
    }
}
// 解析地区
export function calcAreaTwo(arr){
    let province_list =[],
        city_list = [],
        county_list = [];
 
    function parseArea(arr) {
        let obj = {}
        arr.forEach(item => {
            obj[item.value] = item.name;
        })
        return obj;
    }
    
    arr.forEach(item => {
        item.value = +item.value;
        let value = item.value;
        if (item.value%10000 ===0 ) {
            province_list.push(item)
        } else if (item.value % 100 === 0) {
            city_list.push(item)
        } else {
            county_list.push(item)
        }
    })
    return {
        province_list:parseArea(province_list),
        city_list:parseArea(city_list),
        county_list:parseArea(county_list)
    }
}
 
export function compress(img){
    // 用于压缩图片的canvas
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
 
    //    瓦片canvas
    var tCanvas = document.createElement('canvas');
    var tctx = tCanvas.getContext('2d');
 
    let width = img.width;
    let height = img.height;
 
    // 如果图片大于四百万像素,计算压缩比并将大小压至400万以下
    var ratio;
    if ((ratio = width * height / 4000000) > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
    } else {
        ratio = 1;
    }
    canvas.width = width * 2;
    canvas.height = height * 2;
    // 铺底色
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    // 如果图片像素大于100万则使用瓦片绘制
    var count;
    if ((count = width * height / 1000000) > 1) {
        count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片
        // 计算每块瓦片的宽和高
        var nw = ~~(width / count);
        var nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (var i = 0; i < count; i++) {
            for (var j = 0; j < count; j++) {
                tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio * 2, nh * ratio * 2, 0, 0, nw, nh);
                ctx.drawImage(tCanvas, i * nw, j * nh, nw * 2, nh * 2);
            }
        }
    } else {
        ctx.drawImage(img, 0, 0, width * 2, height * 2);
    }
    // 进行最小压缩
    let ndata = canvas.toDataURL('image/jpeg', 0.8);
    return ndata;
}