forked from gzzfw/frontEnd/gzDyh

dminyi
2024-09-12 8b85935713b34cc167c7f4ba9225bd08687134ae
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
/*
 * @Company: hugeInfo
 * @Author: ldh
 * @Date: 2022-02-16 11:57:54
 * @LastEditTime: 2024-09-12 10:55:38
 * @LastEditors: dminyi 1301963064@qq.com
 * @Version: 1.0.0
 * @Description: 公共模块方法
 */
import React, { useState } from 'react';
import CryptoJS from 'crypto-js';
import { Modal, message, Empty } from 'antd';
import * as apiHandler from '../api/apiHandler';
import { debug, web } from '../api/appUrl';
import moment from 'moment';
import { pdf, jpg, file, word, excel } from '../assets/images/icon';
 
export const isDebug = true; // 是否测试环境
 
export const appUrl = isDebug ? debug : web; // api
 
const province = ['19']; // 当前用户省id, 默认广东19,海南23
 
export const myMoment = moment;
 
// 省市区(县)街道社区的下拉框,地理信息文件通过html引入
export const locationOption = () => {
    // eslint-disable-next-line no-undef
    return province.map((x) => locationSelect[x][0]);
};
 
// aes加密,接口请求数据加密,数据返回解密
const aes_key = 'tVTShp12fFVkNBxV';
 
const aes_iv = 'PKCS5Padding';
 
// 下拉框
export { default as options } from './selectOption';
export { default as caseTypeSelect } from './caseTypeSelect';
export { default as caseOptions } from './caseCauseSelect';
 
// icon 对照表
export { default as iconContrast } from './icon';
 
// 加密
export function aes_encrypt(text) {
    let value = text ? text : '';
    return CryptoJS.AES.encrypt(value, CryptoJS.enc.Utf8.parse(aes_key), {
        iv: CryptoJS.enc.Utf8.parse(aes_iv),
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
    }).toString();
}
 
// 解密
export function aes_decrypt(text) {
    let value = text ? text : '';
    let decrypted = CryptoJS.AES.decrypt(value, CryptoJS.enc.Utf8.parse(aes_key), {
        iv: CryptoJS.enc.Utf8.parse(aes_iv),
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
    });
    return JSON.parse(decrypted.toString(CryptoJS.enc.Utf8) || 'null');
}
 
// axios
export const ax = apiHandler;
 
// 缓存
export function setLocal(name, value) {
    localStorage.setItem(name, JSON.stringify(value || ''));
}
 
export function getLocal(name) {
    let data = localStorage.getItem(name);
    return !data ? null : JSON.parse(data);
}
 
export function clearLocal(name) {
    return name ? localStorage.removeItem(name) : localStorage.clear();
}
 
export function setSessionStorage(name, value) {
    sessionStorage.setItem(name, JSON.stringify(value || ''));
}
 
export function getSessionStorage(name) {
    let data = sessionStorage.getItem(name);
    return !data ? null : JSON.parse(data);
}
 
export function clearSessionStorage(name) {
    return name ? sessionStorage.removeItem(name) : sessionStorage.clear();
}
 
// 地址栏截取
export function getQueryString(name) {
    let result = window.location.href.match(new RegExp('[?&]' + name + '=([^&]+)', 'i'));
    if (!result || result.length < 1) {
        return null;
    }
    return decodeURI(result[1]);
}
 
// 逗号隔开数字
export function thousands(num) {
    if (num) {
        var str = num.toString();
        var reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
        return str.replace(reg, '$1,');
    } else {
        return 0;
    }
}
 
 
//
export function getQueryObj(obj) {
    let strs = '';
    for (var str in obj) {
        strs += str + '=' + obj[str] + '&';
    }
    return strs;
}
 
// api错误提示
let errorNum = false; // 控制错误信息不重复弹出
export function catchApiError({ content, loginStatus }) {
    if (errorNum) return false;
    errorNum = true;
    let handleOkFunc =
        loginStatus === 'lose'
            ? () => {
                    clearLocal('customerSystemUser');
                    clearSessionStorage();
                    errorNum = false;
                    window.location.href = '#/customerSystem/login';
              }
            : () => (errorNum = false);
    if (content && content?.indexOf('无操作权限') !== -1) {
        handleOkFunc = () => window.history.back();
    }
    return Modal.error({ title: '错误提示', okText: '知道了', cancelText: null, onOk: handleOkFunc, content });
}
 
export function modalInfo({ type = 'confirm', title = '提示', content, okText = '确定', cancelText = '取消操作', onCancel, onOk }) {
    return Modal[type]({
        title: title,
        content: content,
        onCancel: onCancel,
        onOk: onOk,
        okText: type !== 'confirm' ? '我知道了' : okText,
        cancelText,
        closable: true,
        maskClosable: true,
    });
}
 
// 全局提示
export function info({ type, content, duration, onClose }) {
    return message[type](content, duration || 3, onClose);
}
 
export function infoSuccess({ content }) {
    return info({ type: 'success', content });
}
 
 
 
// 手机号码正则
export const mobileRegExp = new RegExp('^1([0-9][0-9]|[0-9][0-9]|[0-9][0-9]|[0-9][0-9]|[0-9][0-9])\\d{8}$', 'g');
 
// 只能输入数字和英文
export const accRegExp = new RegExp('^[A-Za-z0-9]+$', 'g');
 
// 生成案件,当事人,代理人等随机唯一的id
export function getBusinessId() {
    let four = `${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}`;
    return `${moment().format('YYYYMMDDHHmmss')}${four}`;
}
 
// 时间格式化
export function timeFormat(value, isValue) {
    return !!value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : isValue ? '' : '-';
}
 
export function minuteFormat(value, isValue) {
    return !!value ? moment(value).format('YYYY-MM-DD HH:mm') : isValue ? '' : '-';
}
 
export function dateFormat(value) {
    return !!value ? moment(value).format('YYYY-MM-DD') : '-';
}
 
export function myTimeFormat(value, str) {
    return !!value ? moment(value).format(str) : '-';
}
 
// moment时间格式转 标准格式 并拆分为开始和结束字段
export function changeTimeFormat(obj, timeN, timeS, timeE) {
    const timeArr = obj[timeN] || [];
    obj[timeS] = timeArr[0]?.format('YYYY-MM-DD') || '';
    obj[timeE] = timeArr[1]?.format('YYYY-MM-DD') || '';
    delete obj[timeN];
}
 
// 标准格式转moment  把开始和结束字段合并成一个字段 用于回显表单时间范围
export function changeTimeMoment(obj, timeN, timeS, timeE) {
    if (typeof obj[timeS] === 'string' && typeof obj[timeE] === 'string' && !!obj[timeS] && !!obj[timeE]) {
        obj[timeN] = [];
        obj[timeN][0] = moment(obj[timeS], 'YYYY-MM-DD');
        obj[timeN][1] = moment(obj[timeE], 'YYYY-MM-DD');
        delete obj[timeS];
        delete obj[timeE];
    }
}
 
// 自动退回剩余小时数
export function getHours(endTime, startTime = new Date()) {
    if (!endTime) return { hours: 0, min: 0 };
    let end = moment(endTime),
        start = moment(startTime),
        minDiff = end.diff(start, 'minute'),
        hoursDiff = minDiff / 60,
        min = minDiff % 60;
    return { isNegativeNum: hoursDiff < 12 ? true : false, hours: Math.floor(hoursDiff) < 0 ? 0 : Math.floor(hoursDiff), min };
}
 
// 计算两个时间差
export function getFunnel(startTime, endTime = new Date()) {
    let end = moment(endTime),
        start = moment(startTime),
        timeDiff = end.diff(start, 'seconds');
    return timeDiff;
}
 
// 秒数换算为时分秒
export function getDuration(second) {
    let hours = Math.floor(second / 3600);
    let minutes = Math.floor((second % 3600) / 60);
    let seconds = Math.floor((second % 3600) % 60);
    hours = hours < 10 ? `0${hours}` : hours;
    minutes = minutes < 10 ? `0${minutes}` : minutes;
    seconds = seconds < 10 ? `0${seconds}` : seconds;
    let duration = hours + ':' + minutes + ':' + seconds;
    return duration;
}
 
// 内容输入长度超出判断 小框64字节 大框512字节 特殊字段特殊匹配
export function isLengthExceeded(str, type, special) {
    const specialList = [{ key: 'addr', length: 3 }];
    let len = 0,
        chrLen = 0,
        result = false;
    if (!!special) {
        specialList.map((item) => {
            if (special === item.key) {
                len = item.length;
            }
        });
    } else {
        if (type === 'Input' || type === 'Select' || type === 'RangePicker' || type === 'TreeSelect') {
            len = 64;
        } else if (type === 'TextArea') {
            len = 512;
        }
    }
    chrLen = str.replace(/[^\x00-\xff]/g, '**').length;
    if (chrLen > len) {
        result = true;
    } else {
        result = false;
    }
    return result;
}
 
// 公共empty
export function MyEmpty(value = {}) {
    return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={value.description || '暂无数据'} style={value.style} />;
}
 
// 睡眠
export function sleep(timeout = 500) {
    return new Promise((resolve) => setTimeout(resolve, timeout));
}
 
// 判断文件格式
export function fileType(value, isName) {
    let result = '';
    let name = '';
    if (!value || value === '22_00017-6') {
        result = pdf;
        name = 'PDF';
    } else if (value === '22_00017-3') {
        result = jpg;
        name = '图片';
    } else if (value === '22_00017-4') {
        result = word;
        name = 'Word';
    } else if (value === '22_00017-4') {
        result = excel;
        name = 'Excel';
    } else {
        result = file;
    }
    return isName ? name : result;
}
 
// 超出文字使用省略号
export function ellipsis(value, len) {
    if (!value) return '';
 
    if (value.length > len) {
        return value.slice(0, len) + '...';
    }
 
    return value;
}
 
// 显示99+
export function showMoreNum(value) {
    return Number(value || 0) > 99 ? '99+' : value || 0;
}
 
// 清除字符串中的空格,用于判断是否为空
export function verifyEmpty(value) {
    return value?.replace(/\s+/g, '');
}
 
// 获取元素距离可视区域顶部、左部的距离
export const getOffset = (ele) => {
  var top = ele.offsetTop
  var left = ele.offsetLeft
  while (ele.offsetParent) {
    ele = ele.offsetParent
    if (window.navigator.userAgent.indexOf('MSTE 8') > -1) {
      top += ele.offsetTop
      left += ele.offsetLeft
    } else {
      top += ele.offsetTop + ele.clientTop
      left += ele.offsetLeft + ele.clientLeft
    }
  }
  return {
    left: left,
    top: top,
  }
}
 
export const getSize = () => {
  let windowW, windowH, contentH, contentW, scrollT;
  windowH = window.innerHeight;
  windowW = window.innerWidth;
  scrollT = document.documentElement.scrollTop || document.body.scrollTop;
  contentH =
    document.documentElement.scrollHeight > document.body.scrollHeight ?
      document.documentElement.scrollHeight :
      document.body.scrollHeight;
  contentW =
    document.documentElement.scrollWidth > document.body.scrollWidth ?
      document.documentElement.scrollWidth :
      document.body.scrollWidth;
  return {
    windowW,
    windowH,
    contentH,
    contentW,
    scrollT
  };
};