UNPKG

9.8 kBPlain TextView Raw
1import { RefBean, Selectable, RefBeanTreeNode } from './models';
2
3
4declare var langMap: any;
5declare function unescape(str: any): any;
6declare function escape(str: any): any;
7
8export class Utils {
9 /**
10 * 把Error Object中的错误消息解析出友好的消息
11 * @param err Error Object
12 * @return 友好的消息
13 */
14 public static resolveJsonErrorMessage(err: any): string {
15 let rn = "<br/>";
16 /* Spring MVC Sample: {headers: HttpHeaders, status: 500, statusText: "Internal Server Error",
17 url: "http://localhost:8080/cgd-web/rest/iisp-access-log/logs?x=1&pageNumber=1&pageSize=20",
18 ok: false,
19 error: {code: "IISP_AUTH_ROLE_003"
20 defaultMessage: "Default"
21 localizedMessage: "要删除的角色不存在!"
22 messageKey: "err.IISP_AUTH_ROLE_003"
23 type: "I18nAppException"}
24 } */
25 let msg = Utils.resolveLocalizedMessage("msg.errorOccurred");
26 if (err.error || err._body) {
27
28 if (err.error) {
29 //SpringMVC
30 err = err.error;
31 } else {
32 //JAXRS
33 err = err.json();
34 }
35 if (err.defaultMessage) {
36 if (err.code) {
37 msg = msg + rn + Utils.resolveLocalizedMessage("msg.errorCode") + ":" + err.code;
38 }
39 if (err.localizedMessage) {
40 msg = msg + rn + Utils.resolveLocalizedMessage("msg.errorMessage") + ":" + err.localizedMessage;
41 } else {
42 msg = msg + rn + Utils.resolveLocalizedMessage("msg.errorMessage") + ":" + err.defaultMessage;
43 }
44 if (err.cause) {
45 msg = msg + rn + Utils.resolveLocalizedMessage("msg.rootMessage") + ":" + err.cause;
46 }
47 //Utils.showMessage(msg);
48 return msg;
49 }
50 }
51 if (err.localizedMessage) {
52 msg = msg + rn + Utils.resolveLocalizedMessage("msg.errorMessage") + ":" + err.localizedMessage;
53 } else if (err.message) {
54 msg = msg + rn + Utils.resolveLocalizedMessage("msg.errorMessage") + ":" + err.message;
55 }
56 if (err.status) {
57 msg = msg + rn + Utils.resolveLocalizedMessage("msg.httpStatus") + err.status;
58 msg = msg + rn + Utils.resolveLocalizedMessage("msg.returnMessage") + err.statusText;
59 }
60 return msg;
61 }
62 static showMessage(msg: string): void {
63 alert(msg);
64 }
65 static showMessageByKey(key: string): void {
66 Utils.showMessage(Utils.resolveLocalizedMessage(key));
67 }
68 static cloneObject(src: Object, dist: Object): void {
69 for (let prop in src) {
70 dist[prop] = src[prop];
71 }
72 }
73 /**根据key和参数,找到相应的语言标签
74 * @param key the message key
75 * @param params parameters to replace the placeholder in message. If params is not an array, then treat it as the first parameter.
76 * @return resolved localized message. return the key if message not found.
77 */
78 public static resolveLocalizedMessage(key: string, params?: string[]) {
79 let msg = langMap[key];
80 if (msg == undefined) {
81 return key;
82 }
83 if (params) {
84 if (params.length) {
85 for (let i = 0; i < params.length; i++) {
86 msg = msg.replace("{" + i + "}", params[i]);
87 }
88 } else {
89 msg = msg.replace("{0}", params);
90 }
91 }
92 return msg;
93 }
94 /** 对比两个数组的内容是否一样.
95 * @param array1 数组1
96 * @param array2 数组2
97 * @param property 要比较的属性值
98 * @return true if same.
99 */
100 public static compareArrays(array1: Array<any>, array2: Array<any>, property: string): boolean {
101 if (array1.length != array2.length) {
102 return false;
103 }
104 for (let i = 0; i < array1.length; i++) {
105 let obj1 = array1[i];
106 let found = false;
107 for (let k = 0; k < array2.length; k++) {
108 let obj2 = array2[k];
109 if (property) {
110 if (obj2[property] == obj1[property]) {
111 found = true;
112 break;
113 }
114 } else {
115 if (obj2 == obj1) {
116 found = true;
117 break;
118 }
119 }
120 }
121 if (!found) {
122 return false;
123 }
124 }
125 return true;
126 }
127
128
129 /**
130 * 取得当前数据日期
131 */
132 static getCurrentDataDate(): string {
133 return Utils.getCookie("currentDataDate");
134 }
135
136 /**
137 * 取得当前的出帐机构号
138 */
139 static getCurrentNodeCode(): string {
140 return Utils.getCookie("currentNodeCode");
141 }
142 /**
143 * 取得指定的cookie变量值
144 */
145 static getCookie(name: string): any {
146 let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
147 if (arr = document.cookie.match(reg)) {
148 return unescape(arr[2]);
149 }
150 else {
151 return null;
152 }
153 }
154
155 /**
156 * 设置指定的cookie变量值以及有效时间(毫秒)
157 */
158 static setCookie(name: string, value: string, msec?: number): void {
159 let cs = name + '=' + escape(value);
160 if (msec) {
161 let exp = new Date();
162 exp.setTime(exp.getTime() + msec * 1);
163 cs += ";expires=" + exp.toUTCString();
164 }
165 document.cookie = cs;
166 }
167 /**
168 * 删除指定的cookie变量
169 */
170 static delCookie(name: string): void {
171 let exp = new Date();
172 exp.setTime(exp.getTime() - 1);
173 let cval = Utils.getCookie(name);
174 if (cval != null) {
175 document.cookie = name + "=" + cval + ";expires=" + exp.toUTCString();
176 }
177 }
178 /**
179 * 获取可选取列表中选中的项目
180 * @param array 可选项目列表
181 * @param property 返回的选中项目属性,如列表是TreeNode类型,而要返回的选中项可能是TreeNode.data,那么porperty就应该是“data”,如果不提供porperty,将返回列表中选中的TreeNode。
182 */
183 static getSelectedBeans(array: Selectable[], property?: string): any[] {
184 let rst = new Array<any>();
185 for (let s of array) {
186 if (s.isSelected) {
187 if (property) {
188 rst.push(s[property]);
189 } else {
190 rst.push(s);
191 }
192 }
193 }
194 return rst;
195 }
196 /**
197 * 格式化数字显示方式
198 * 用法
199 * formatNumber(12345.999,'#,##0.00');
200 * formatNumber(12345.999,'#,##0.##');
201 * formatNumber(123,'000000');
202 * @param num 要格式化的数字
203 * @param pattern 想要的格式
204 */
205 static formatNumber(num: number, pattern: string): string {
206 let strarr = num ? num.toString().split('.') : ['0'];
207 let fmtarr = pattern ? pattern.split('.') : [''];
208 let retstr = '';
209
210 // 整数部分
211 let str = strarr[0];
212 let fmt = fmtarr[0];
213 let i = str.length - 1;
214 let comma = false;
215 for (let f = fmt.length - 1; f >= 0; f--) {
216 switch (fmt.substr(f, 1)) {
217 case '#':
218 if (i >= 0) retstr = str.substr(i--, 1) + retstr;
219 break;
220 case '0':
221 if (i >= 0) retstr = str.substr(i--, 1) + retstr;
222 else retstr = '0' + retstr;
223 break;
224 case ',':
225 comma = true;
226 retstr = ',' + retstr;
227 break;
228 }
229 }
230 if (i >= 0) {
231 if (comma) {
232 let l = str.length;
233 for (; i >= 0; i--) {
234 retstr = str.substr(i, 1) + retstr;
235 if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
236 }
237 }
238 else retstr = str.substr(0, i + 1) + retstr;
239 }
240
241 retstr = retstr + '.';
242 // 处理小数部分
243 str = strarr.length > 1 ? strarr[1] : '';
244 fmt = fmtarr.length > 1 ? fmtarr[1] : '';
245 i = 0;
246 for (let f = 0; f < fmt.length; f++) {
247 switch (fmt.substr(f, 1)) {
248 case '#':
249 if (i < str.length) retstr += str.substr(i++, 1);
250 break;
251 case '0':
252 if (i < str.length) retstr += str.substr(i++, 1);
253 else retstr += '0';
254 break;
255 }
256 }
257 return retstr.replace(/^,+/, '').replace(/\.$/, '');
258 }
259 /**
260 * 将日期串转换成日期类型的变量
261 * @param dateStr 日期串,支持如2018-10-31, 20181031, 31/10/2018等格式
262 *
263 */
264 static parseDate(dateStr: string): Date {
265 if (dateStr.length == 8) {
266 //yyyyMMdd格式
267 let year = parseInt(dateStr.substr(0, 4));
268 let month = parseInt(dateStr.substr(4, 2));
269 let day = parseInt(dateStr.substr(6, 2));
270 return new Date(year, month - 1, day);
271 }
272 //其它格式
273 return new Date(dateStr);
274 }
275 /**
276 * 将日期按照指定的格式格式化成字符串用于显示
277 * @param date 日期
278 * @param fmt 想要的格式,如:“yyyy-MM-dd hh:mm:ss S”, “yyyy年第q季度”
279 */
280 static formatDate(date: Date, fmt: string): string {
281 var o = {
282 "M+": date.getMonth() + 1, //月份
283 "d+": date.getDate(), //日
284 "h+": date.getHours(), //小时
285 "m+": date.getMinutes(), //分
286 "s+": date.getSeconds(), //秒
287 "q+": Math.floor((date.getMonth() + 3) / 3), //季度
288 "S": date.getMilliseconds() //毫秒
289 };
290 if (/(y+)/.test(fmt))
291 fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
292 for (var k in o)
293 if (new RegExp("(" + k + ")").test(fmt))
294 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
295 return fmt;
296 }
297 /**
298 * 获取请求参数的值,如var=1,则返回"1"
299 * @param name 参数名
300 */
301 static getParameter(name: string): string {
302 let val = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
303 if (val && val.length > 0) {
304 return decodeURI(val[1]);
305 }
306 return null;
307 };
308 /**
309 * 获取同名多个请求参数的值数组,如var=1&var=2,返回["1","2"]
310 * @param name 参数名
311 */
312 getParameterValues( name: string ): string[] {
313 let rsts: string[] = location.search.match( new RegExp( "[\?\&]" + name + "=([^\&]+)", "g" ) );
314 if ( rsts && rsts.length > 0 ) {
315 let vals = new Array( rsts.length );
316 for ( let i = 0; i < rsts.length; i++ ) {
317 vals[i] = decodeURI(rsts[i].substring( rsts[i].indexOf( "=" ) + 1 ) );
318 }
319 return vals;
320 }
321 return null;
322 };
323
324}
\No newline at end of file