tanghaolin
2025-04-20 fe4b76e24c82abf35afaaa07f3e681ba14ee2d80
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import axios from "axios";
import { ElMessage } from "element-plus";
var utils = {
  uniqueInArray(arr) {
    if (arr == null || arr.length == 0) return arr;
    //去重
    var n = {},
      r = [];
    for (var i = 0; i < arr.length; i++) {
      if (!n[arr[i]]) {
        n[arr[i]] = true;
        r.push(arr[i]);
      }
    }
    return r;
  },
  uniqueArrayByObj(array, key) {
    const _set = [...new Set(array.map((e) => e[key]))];
    let deArray = [];
    _set.map((item) => {
      deArray.push(array[array.findIndex((val) => val[key] === item)]);
    });
    return deArray;
  },
  getLabelInArray(arr, key) {
    let label = null;
    arr.forEach((item) => {
      if (item.value == key) {
        label = item.label;
      }
    });
    return label;
  },
  getValueInArray(arr, key) {
    let value = null;
    arr.forEach((item) => {
      if (item.label == key) {
        value = item.value;
      }
    });
    return value;
  },
  //给图片添加水印
  getImgWaterMark({ url = "", cb = null } = {}) {
    if (url == null || url == "") return;
    // 创建所需要添加水印的img图片
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
 
    const img_origin = new Image();
    img_origin.src = url;
    img_origin.crossOrigin = "anonymous";
    img_origin.onload = function () {
      // 创建canvas,并将创建的img绘制成canvas
      canvas.width = img_origin.width;
      canvas.height = img_origin.height;
 
      ctx.drawImage(img_origin, 0, 0);
 
      //textAlign = 'left',
      //textBaseline = 'middle',
      //font = '18px Microsoft Yahei',
      //fillStyle = 'rgba(0, 0, 0, 0.15)',
      // fillStyle = '#aaaaaa',
      //content = 'Eventech',
      //ctx.textAlign = textAlign
      //ctx.textBaseline = textBaseline
      //ctx.font = font
      //ctx.fillStyle = fillStyle
      //ctx.globalAlpha = 0.3;
      // ctx.rotate((Math.PI / 180) * 15)
 
      // 循环绘制水印
      // ctx.fillText(content, img_origin.width - textX, img_origin.height - textY)
      let watermark = new Image();
      watermark.src = "./static/img/watermark.png";
      ctx.drawImage(watermark, img_origin.width / 2, img_origin.height / 2);
 
      // 将绘制完成的canvas转换为base64的地址
      const base64Url = canvas.toDataURL();
      cb && cb(base64Url);
    };
  },
  /**
   * 防抖
   * @param {*} fn
   * @param {*} delay
   * @returns
   */
  _debounce(func, wait) {
    let timeout;
    return function (...args) {
      const context = this;
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        func.apply(context, args);
      }, wait);
    };
  },
  /**
   * 节流函数
   * @param {*} func
   * @param {*} delay
   * @returns
   */
  _throttle(func, delay) {
    let lastCall = 0;
    return function (...args) {
      const now = new Date().getTime();
      if (now - lastCall < delay) return;
      lastCall = now;
      return func(...args);
    };
  },
 
  /**
   *树形数据扁平化
   * @param {Array} arrs 树形数据
   * @param {string} childs 树形数据子数据的属性名,常用'children'
   * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)(可不写)
   * @returns
   */
  extractTree(arrs, childs, attrArr) {
    let attrList = [];
    if (!Array.isArray(arrs) && !arrs.length) return [];
    if (typeof childs !== "string") return [];
    if (
      !Array.isArray(attrArr) ||
      (Array.isArray(attrArr) && !attrArr.length)
    ) {
      attrList = Object.keys(arrs[0]);
      attrList.splice(attrList.indexOf(childs), 1);
    } else {
      attrList = attrArr;
    }
    let list = [];
    let getObj = (arr, pid = 0) => {
      arr.forEach(function (row, index) {
        let obj = {};
        obj.ParentID = pid;
        attrList.forEach((item) => {
          obj[item] = row[item];
        });
        list.push(obj);
        if (row[childs] && row[childs].length > 0) {
          obj.ParentID = 0;
          getObj(row[childs], (pid = row.AssemConfigID));
        }
      });
      return list;
    };
    return getObj(arrs);
  },
  /**
   *树形数据扁平化
   * @param {Array} arrs 树形数据
   * @param {string} childs 树形数据子数据的属性名,常用'children'
   * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)(可不写)
   * @returns
   */
  extractTreeByHasParent(arrs, childs, attrArr) {
    let attrList = [];
    if (!Array.isArray(arrs) && !arrs.length) return [];
    if (typeof childs !== "string") return [];
    if (
      !Array.isArray(attrArr) ||
      (Array.isArray(attrArr) && !attrArr.length)
    ) {
      attrList = Object.keys(arrs[0]);
      attrList.splice(attrList.indexOf(childs), 1);
    } else {
      attrList = attrArr;
    }
    let list = [];
    let getObj = (arr, pid = 0) => {
      arr.forEach(function (row, index) {
        let obj = {};
        attrList.forEach((item) => {
          obj[item] = row[item];
        });
        list.push(obj);
        if (row[childs] && row[childs].length > 0) {
          getObj(row[childs], (pid = row.AssemConfigID));
        }
      });
      return list;
    };
    return getObj(arrs);
  },
  arrayToTree(arr, pid, idField = "ID", pidField = "ParentID") {
    return arr.reduce((res, current) => {
      if (current[pidField] === pid) {
        current.children = this.arrayToTree(arr, current[idField]);
        return res.concat(current);
      }
      return res;
    }, []);
  },
  /**
   * 获取数据类型
   * @param {All} [o] 需要检测的数据
   * @returns {String}
   */
  getType(o) {
    return Object.prototype.toString.call(o).slice(8, -1);
  },
 
  /**
   * 判断是否是指定数据类型
   * @param {All} [o] 需要检测的数据
   * @param {String} [type] 数据类型
   * @returns {Boolean}
   */
  isKeyType(o, type) {
    return utils.getType(o).toLowerCase() === type.toLowerCase();
  },
 
  /**
   * 深拷贝,支持常见类型 object Date Array等引用类型
   * @param {Any} sth
   * @return {Any}
   */
  deepClone(sth) {
    let copy;
    if (null == sth || "object" != typeof sth) return sth;
    if (utils.isKeyType(sth, "date")) {
      copy = new Date();
      copy.setTime(sth.getTime());
      return copy;
    }
    if (utils.isKeyType(sth, "array")) {
      copy = [];
      for (let i = 0, len = sth.length; i < len; i++) {
        copy[i] = utils.deepClone(sth[i]);
      }
      return copy;
    }
    if (utils.isKeyType(sth, "object")) {
      copy = {};
      for (let attr in sth) {
        if (sth.hasOwnProperty(attr)) copy[attr] = utils.deepClone(sth[attr]);
      }
      return copy;
    }
    return null;
  },
  /**
   * 判断服务的文件是否存在
   * @param filepath 文件地址
   * @param filename
   * @returns {Boolean}
   */
  isExistFile(filepath) {
    if (filepath == null || filepath === "") {
      return false;
    }
    let xmlhttp;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", filepath, false);
    xmlhttp.send();
    if (xmlhttp.readyState === 4) {
      if (xmlhttp.status === 200) return true; //url存在
      else if (xmlhttp.status === 404) return false; //url不存在
      else return false; //其他状态
    }
  },
  /**
   * 生成随机的GUID
   * @returns
   */
  getGUID() {
    let guid = "";
    for (let i = 1; i <= 32; i++) {
      let flag = Math.floor(Math.random() * 10);
      //如果是偶数就设置成为
      if (flag % 2 == 0) {
        //全大写
        let n = Math.floor(flag * 2.4) + 65;
        n = String.fromCharCode(n);
        guid += n;
      } else {
        guid += flag;
      }
    }
    return guid;
  },
  /** 校验特殊字符 */
  validateSpecialSymbol(str) {
    const reg = /['()*]/;
    return reg.test(str);
  },
  /* 手机号码和固定电话 */
  validatePhTelNumber(str) {
    const reg = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/;
    return reg.test(str);
  },
  /* 电子邮箱 */
  validateEmail(str) {
    const reg =
      /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    return reg.test(str);
  },
  /**
   * 检查图片资源是否存在
   * @param {String} ImgPath //图片路径
   */
  isExistImgPath(ImgPath) {
    if (ImgPath == null || ImgPath === "") {
      return false;
    }
    return new Promise(async (resolve, reject) => {
      try {
        const response = await fetch(ImgPath, { method: "HEAD" });
        // 如果状态码是200-399之间,通常表示成功获取到了资源
        if (response.ok) {
          resolve(true);
        } else {
          // 其他状态码可能表示资源未找到(404)或其他错误
          resolve(false);
        }
      } catch (error) {
        // 网络错误或其他问题
        console.error("Error:", error);
        resolve(false);
      }
    });
  },
  // 根据语言检查是否有对应的图片
  async checkImgPathByLang(lang, path, cb = null) {
    if (lang == "CN") {
      cb && cb(path);
      return;
    }
    if (lang == "EN") {
      let en_Path = path.replace(".png", `-${lang}.png`);
      let enPath_exist = await this.isExistImgPath(en_Path);
      if (enPath_exist) {
        cb && cb(en_Path);
        return;
      }
      cb && cb(path);
      return;
    }
    if (lang == "RU") {
      let ru_Path = path.replace(".png", `-${lang}.png`);
      let en_path = path.replace(".png", `-EN.png`);
      let ruPath_exist = await this.isExistImgPath(ru_Path);
      let enPath_exist = await this.isExistImgPath(en_path);
      if (ruPath_exist) {
        cb && cb(ru_Path);
        return;
      } else if (enPath_exist) {
        cb && cb(en_path);
        return;
      } else {
        cb && cb(path);
        return;
      }
    }
  },
  /**
   * 下载文件
   * @param {*} url
   * @param {*} filename
   */
  downloadFile(url, filename) {
    axios({
      method: "get",
      url: url,
      responseType: "blob",
    }).then((res) => {
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement("a");
      link.href = url;
      let fileName = filename;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
 
      window.URL.revokeObjectURL(url);
    }).catch(err=>{
      ElMessage.error(err)
    })
  },
  extractFileExtension(path) {
    var parts = path.split("/");
    if (parts.length > 1) {
      return parts[parts.length - 1];
    }
  },
 
  /**
   * 格式化价格
   * @param {*} price
   * @returns
   */
  formatMoney(price) {
    if (price < 0) {
      return price;
    }
    // return price
    let result = String(Number(price).toFixed(2)).split("."); //按小数点分成2部分
    result[0] = result[0].replace(
      new RegExp("(\\d)(?=(\\d{3})+$)", "ig"),
      "$1,"
    ); //只将整数部分进行逗号分割
    return result.join("."); //再将小数部分合并进来
  },
 
  /**
   * 处理下拉多选回显
   * 当前多选的value
   * @param selValueArr
   * 当前多选的下拉列表数据
   * @param selListData
   */
  viewMultipleSelLabel(selValueArr, selListData) {
    if (selListData.length == 0) return "";
    let text = "";
    selValueArr.forEach((item) => {
      selListData.forEach((selItem) => {
        if (item == selItem.value) {
          text += selItem.label + ",";
        }
      });
    });
    return text.substring(0, text.length - 1);
  },
  /**
   * 数据列表
   * @param {*} list
   * 页数
   * @param {*} curIndex
   * 条数
   * @param {*} curSize
   */
  pagination(list, curIndex, curSize) {
    let data = [];
    list = this.deepClone(list);
    data = list.slice((curIndex - 1) * curSize, curIndex * curSize);
    return data;
  },
};
 
export default utils;