fs-danaus
2022-10-12 cef3ae7ec31b68823e75fc1e4f989565c226d9fa
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
package com.yc.action;
 
import com.yc.action.grid.GridUtils;
import com.yc.action.grid.PoiExcelWriter;
import com.yc.currentThreadInfo.CurrentLocal;
import com.yc.entity.attachment.AttachmentWhereEntity;
import com.yc.exception.ApplicationException;
import com.yc.factory.FactoryBean;
import com.yc.sdk.shopping.util.SettingKey;
import com.yc.service.excel.ExcelIfc;
import com.yc.service.grid.TableMetaData;
import com.yc.service.upload.AttachmentIfc;
import com.yc.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.SessionAttributes;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.Type;
import java.sql.Types;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * 基类,封装gt-grid返回json的处理
 * 
 * @author 邓文峰 2010-2-25
 * **/
@SessionAttributes("success")
// 定义保存跨页面提示信息
public class BaseAction {
    private final static Object lock=new Object();//锁对象
    protected Map<String, String> env=new HashMap<String,String>();
    /**
     * 处理分页信息
     * **/
    protected Logger log = LoggerFactory.getLogger(this.getClass()); //Logger.getLogger(this.getClass());
 
    public static void clearDuplicateSubmitUNID(){//删除指定的key
        RedisTemplate redisTemplate= (RedisTemplate) FactoryBean.getBean("redisTemplate");
        if(CurrentLocal.getunidLocal()!=null) {
            redisTemplate.delete(CurrentLocal.getunidLocal());
        }
    }
 
    protected com.yc.utils.Page setPageInfo(HttpServletRequest request) {
        return com.yc.utils.JOSNUtils.init(request);
    }
 
    protected com.yc.utils.Page setPageInfoTree(HttpServletRequest request) {
        return com.yc.utils.JOSNUtils.initTree(request);
    }
 
    /**
     * 输出验证结果
     * 
     * **/
    protected boolean getErrors(ModelMap model, BindingResult result) {
 
        StringBuilder sb = new StringBuilder();
        if (result.hasErrors()) {// 未通过验证
            sb.append("验证出错,请填写完整\\n");
            for (FieldError f : result.getFieldErrors()) {
                sb.append(f.getDefaultMessage()).append("\\n");
            }
            model.addAttribute("success", sb.toString());
            return true;
        }
        return false;
    }
 
    /**
     * 输出操作结果提示
     * 
     * **/
    protected void printInfo(HttpServletResponse resp, boolean bl, String str) {
        try {
            PrintWriter out = resp.getWriter();
            StringBuffer outData = new StringBuffer();
            outData.append("{");
            outData.append("gt_success: ").append(bl);
            outData.append("}");
            out.print(outData.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 输出操作结果提示
     * 
     * **/
    protected void print(HttpServletResponse resp, String str, String contentType) {
        try {
            resp.setContentType(contentType + ";charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 输出操作结果提示
     * 
     * **/
    protected void print(HttpServletResponse resp, String str) {
        try {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 向页面输出json
     * 
     * **/
    protected void printJson(HttpServletResponse resp, String s) {
        try {
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.print(s);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 向页面输出json
     * 
     * **/
    protected void printJsonInfo(HttpServletResponse resp, com.yc.utils.Page page, Type dataType) {
        try {
            PrintWriter out = resp.getWriter();
            out.print(JOSNUtils.toJosn(page, dataType));
            out.flush();
            out.close();
            page = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    protected List<?> getDelEntity(HttpServletRequest request) {
        return com.yc.utils.JOSNUtils.del(request);
    }
 
    /**
     * InputStream转换为InputStreambyte[] 
     * @param inStream
     * @return 字符串
     * @throws IOException
     */
    protected static final String input2bytet(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        // return in2b;
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < in2b.length; n++) {
            stmp = Integer.toHexString(in2b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }       
        }
        return sb.toString();
    }
 
    /**
     * 
     * 获得异常信息
     * */
    protected String getErrorMsg(Exception e){
        String msg="";
        if(e.getCause()!=null){
            msg=e.getCause().getMessage();
        }else{
            msg=e.getMessage();
        }
        return msg;
    }
protected Map printErrorMsgToJson(Exception e,Map otherMsg){
        String msg=this.getErrorMsg(e);
        Map root=new HashMap(5);
        Map map=new HashMap(5);
        map.put("error",msg);
        if(otherMsg!=null) {
            map.putAll(otherMsg);
        }
        root.put("state",-1);
        root.put("info",map);
        return root;
}
 
    protected int getTypeByMetaData(Map<String,TableMetaData>  tableMetaDatas, String id) {
 
        String dataType=tableMetaDatas.get(id.toLowerCase())==null?"":tableMetaDatas.get(id.toLowerCase()).getDataType();
        switch (dataType) {
            case "tinyint":
            case "int":
            case "decimal":
            case "double":
            case "float":
            case "numeric":
            case "bigint":
            case "real":
            case "smallint":
            case "money":
            case "smallmoney":
                return 1;
            case "binary":
            case "blob":
            case "clob":
            case "nclob":
                return 2;
            case "date":
            case "time":
            case "timestamp":
            case "datetime":
            case "smalldatetime":
                return 4;// 日期
            case "bit":
                return 5;
            case "longnvarchar":// varchar(MAX)
            case "longvarchar":
                return 3;
            default:
                return 3;
        }
    }
    /**
     * 根据列名查找列的数据类型是否需要去掉双引号, 因为客户端传过来的json经过转换都加上双引号,但到写入数据库时需要区分数据类型 <br>
     * 1 --表示数值型<br>
     * 2---表示text,ntext,image之类<br>
     * 3---字符
     *  4---日期
     * */
    protected int getType(SqlRowSetMetaData md, String id) {
        int s = 3;
        for (int i = 1; i <= md.getColumnCount(); i++) {
            if (id.equalsIgnoreCase(md.getColumnName(i))) {
                s = md.getColumnType(i);
                break;
            }
        }
        switch (s) {
        case Types.TINYINT:
        case Types.INTEGER:
        case Types.DECIMAL:
        case Types.DOUBLE:
        case Types.FLOAT:
        case Types.NUMERIC:
        case Types.BIGINT:
        case Types.REAL:
        case Types.SMALLINT:
        case 0:
            return 1;
        case Types.BINARY:
        case Types.BLOB:
        case Types.CLOB:
        case Types.NCLOB:
            return 2;
        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            return 4;// 日期
        case Types.BIT:
            return 5;
        case Types.LONGNVARCHAR:// varchar(MAX)
        case Types.LONGVARCHAR:
            return 3;
        default:
            return 3;
        }
    }
 
    /*
     * 得到服务器地址xiangluan2010-04-15
     */
    protected String getURI(HttpServletRequest req) {
        return req.getProtocol().substring(0, 4).toLowerCase() + "://" + req.getRemoteHost() + ":" + req.getLocalPort() + req.getContextPath();
    }
 
    /**
     * 初始化系统一些全局变量值
     * 
     * @formid 当前功能号
     *@user 登录用户代码
     *@usercode 登录用户代码
     *@username 登录用户名
     *@today 今天日期 YYYY-MM-DD
     *@day 今天日期 YYYY-MM-DD
     *@space 空格
     *@date 今天日期 YYYY-MM-DD
     *@treename 树节点名称 ,例:matgroupname
     *@companyid 当前登录的公司代码
     *@host 登录主机名(C/S) #表示有值传值,没值传空
     * @param flag TODO
     * **/
    protected Map<String, String> initEnv(HttpServletRequest request, int formid, String doccode, boolean flag) {
        if(request==null) return env;
        return GridUtils.getSessionAttributes(request.getSession(), formid, doccode, flag);
    }
 
    /**
     * 重新根据css设置把page类的sql组合
     * 
     * @param String expr 形式:a|b;c|d...
     * @return String 形式:新的sql
     * */
    protected String cssexprTOSql(String expr, String sql,String name) {
        if (expr == null || expr.isEmpty()) return sql;
        String[] temp = expr.replaceAll("&lt;", "<").replaceAll("&gt;", ">").split(";");
        for (String str : temp) {
            String[] qt = str.split("\\|");
            if (getColumnNum(qt[0], sql)) {
                //dist|! case when dist>0 then 'color:red' else '' end
                qt[1]=qt[1].replaceAll("~", ";");//把转义的;还
                if(qt[1].startsWith("!")){//动态css样式
                    if (qt.length>1&&qt[1].indexOf("@") > -1) {
                        Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词                
                        java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
                        while (propsMatcher.find()) {
                            qt[1]=qt[1].replaceAll(propsMatcher.group(), env.get(propsMatcher.group().toLowerCase()));
                        }
                    }
                    //case when '@cccode' in ('D','G') then 1 else 0 end //_cssexpr
                    String s = "["+qt[0].toLowerCase() + "], (" + qt[1].replaceFirst("!", "") +" ) as [" + qt[0].toLowerCase() + name+"]";
                    sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
                }else{
                    String s =  "["+ qt[0].toLowerCase() + "], '"+qt[1]+"' as [" + qt[0].toLowerCase() + name+"]";
                    sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
                }
            }else{//静态css样式
                String s =  "["+ qt[0].toLowerCase() + "], '"+qt[1]+"' as [" + qt[0].toLowerCase() + name+"]";
                sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
            }
        }
        return sql;
    }
 
    /**
     * 替换前台传过来的权限表达式
     * 
     * @param String expr 形式:a|b;c|d...
     * @return String 形式:新的sql
     * */
    protected String getExprTOSql(String expr) {
        StringBuffer sb=new StringBuffer();
        if (expr == null || expr.isEmpty()) return expr;
        sb.append(" select ");
        String[] temp = expr.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&").split(";");
        int inx=0;
        for (String str : temp) {
            if(inx!=0) sb.append(",");
            String[] qt = str.split("\\|");
            //case when 'YC'=companyid then 1 else 0 end
            // case when '@cccode' = 'CW' then salary then '--HideColumn--' end as salary
            if (qt.length>1&&qt[1].indexOf("@") > -1) {
                Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
                java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
                while (propsMatcher.find()) {
                    qt[1]=qt[1].replaceAll(propsMatcher.group(), env.get(propsMatcher.group().toLowerCase()));
                }
            }
            //去掉没权限时返回null的条件,"case when (" + qt[1] + ") = 0  then null else   " + qt[0].toLowerCase() + " end as
            sb.append("case when (" + qt[1] + ") =1 then 1   when (" + qt[1] + ") =2 then 2 else 0 end as [" + qt[0].toLowerCase()+"]");
            inx++;  
        }
        return sb.toString();
    }
 
    /**
     * 重新根据权限设置把page类的sql组合
     * 
     * @return String 形式:新的sql
     * */
    protected String exprTOSql(Page page, String sql) {
        String expr=page.getExpr();
        if (expr == null || expr.isEmpty()) return sql;
        Map<String,String> strs=new HashMap<String,String>();//保存权限表达式,给统计列使用
        String[] temp = expr.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&").split(";");
        for (String str : temp) {
            String[] qt = str.split("\\|");
            if (getColumnNum(qt[0], sql)) {
                //case when 'YC'=companyid then 1 else 0 end
                // case when '@cccode' = 'CW' then salary then '--HideColumn--' end as salary
                if (qt.length>1&&qt[1].indexOf("@") > -1) {
                    Pattern p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词        
                    java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
                    while (propsMatcher.find()) {
                        qt[1]=qt[1].replaceAll(propsMatcher.group(), env.get(propsMatcher.group().toLowerCase()));
                    }
                }
                //去掉没权限时返回null的条件,"case when (" + qt[1] + ") = 0  then null else   " + qt[0].toLowerCase() + " end as
                String s =  "[" + qt[0].toLowerCase() + "],case when (" + qt[1] + ") =1 then 1   when (" + qt[1] + ") =2 then 2 else 0 end as [" + qt[0].toLowerCase() + "_expr]";
                strs.put(qt[0].toLowerCase(), " case when (" + qt[1] + ") = 0  then 0 else   " + qt[0].toLowerCase() + " end ");
                if(page.getType()!=null&&page.getWinType().equals("38")){
                    if(sql.toLowerCase().contains(" as "+qt[0].toLowerCase())){
                        sql = sql.replaceAll(" as "+qt[0].toLowerCase(), " as "+s);
                    }else {
                        sql = sql.replaceAll(qt[0].toLowerCase(), s);
                    }
                }else {
                    sql = sql.replaceAll("\\[" + qt[0].toLowerCase() + "\\]", s);
                }
            }
        }
        page.setTbExpr(strs);
        return sql;
    }
 
    protected String exprTOSql( String expr,String sql,HttpSession session) {//42类型控件使用    
        if (expr == null || expr.isEmpty()) return sql;
        String[] temp = expr.replaceAll("#", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&").split(";");
        sql+=",";//增加,号是为了处理替换方便
        for (String str : temp) {
            if("".equalsIgnoreCase(str)) continue;
            String[] qt = str.split("\\|");
            if (getColumnNum(qt[0], sql)) {
                if (qt.length>1){
                    qt[1]=qt[1].replaceAll("\\*","#");
                    Pattern p = Pattern.compile("\\/##.*?##\\/");// 去除 /**...**/的注释
                    java.util.regex.Matcher propsMatcher = p.matcher(qt[1]);
                    while (propsMatcher.find()) {
                        qt[1]=qt[1].replace(propsMatcher.group(),"");
                    }
                    qt[1]=qt[1].replaceAll("#","*");
                if(qt[1].indexOf("@") > -1) {
                     p = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
                     propsMatcher = p.matcher(qt[1]);
                    while (propsMatcher.find()) {
                        qt[1]=qt[1].replaceAll(propsMatcher.group(), session.getAttribute(propsMatcher.group().toLowerCase())+"");
                    }
                }
            }
                //去掉没权限时返回null的条件,"case when (" + qt[1] + ") = 0  then null else   " + qt[0].toLowerCase() + " end as
                String s =  "[" + qt[0].toLowerCase() + "],case when (" + qt[1] + ") =1 then 1   when (" + qt[1] + ") =2 then 2 else 0 end as [" + qt[0].toLowerCase() + "_expr]";
                sql = sql.replaceAll(","+qt[0].toLowerCase()+",", ","+s+",");
            }
        }
        return sql.lastIndexOf(",")>0?sql.substring(0, sql.length()-1):sql;
    }
 
    /**
     * 查找字符串中是否存在指定的内容
     * 
     * */
    protected boolean getColumnNum(String colName, String gridcaption) {
        // int num=0;
        Pattern p = Pattern.compile("\\b" + colName.toLowerCase() + "\\b");
        java.util.regex.Matcher propsMatcher = p.matcher(gridcaption.toLowerCase());
        while (propsMatcher.find()) {
            return true;
        }
        return false;
    }
 
    /**
     * 判断字符串是否为空或null
     * **/
    protected boolean isNullOrEmptry(String s) {
        return s != null && s != "" && "".equalsIgnoreCase("") && s.length() != 0 ? false : true;
    }
 
    // 去除字符串中的换行符等
    public String replaceBlank(String str) {
        if (str == null || str == "") { return ""; }
        Matcher m = null;
        try {
            Pattern p = Pattern.compile("\t|\r|\n");
            m = p.matcher(str);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException(str + "-解析出错,存在有特殊字符");
        }
        return m.replaceAll(" ").replaceAll("\\$", "\\\\\\$");
    }
 
    /***
     * 
     * 检测9802设置中的格式会存在连续输入多一个分隔符的情况:yyyy--mm-dd
     * 出错返回false;
     * */
    public  boolean checkFormat(String str){
        if(str==null||str.length()==0) return true;
            char temp='0';
            boolean flg=true;
            boolean ft=false;
            for(char c:str.toCharArray()){
                if(temp==c&&ft){
                      flg=false;
                      break;
                  }else{
                      if(c=='-'||c=='.'||c=='/'||c==':'){
                          temp=c;
                          ft=true;
                      }else{
                          ft=false;
                      }
                  }
            }
            return flg;
    }
    protected static boolean isBase64(String str) {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        return Pattern.matches(base64Pattern, str);
    }
    @SuppressWarnings("unchecked")
    protected void print2Excel(HttpServletRequest request,HttpServletResponse resp, Page page, Object object,int formid,String type)  {
          try {
              //读取当前功能号哪些字段是需要导出的
              String s=FileUtil.readFile(request.getServletContext().getRealPath("/")+request.getSession().getAttribute(SessionKey.PAGE_PATH)+File.separator+formid+File.separator+type+File.separator+"data");//
              if(request.getSession().getAttribute(SessionKey.USERCODE)==null){
                    this.printJson(resp, "error;会话过期,请重新登录!");
                    return;
                }
              if("".equalsIgnoreCase(s)||s==null){
                  this.printJson(resp, "error;未在9802设置有需要导出的内容或找不到相关的文件");
                  return;
              }
              Map<String,Object> map=null;
              String[] panel_name=null;
              String[] panel_tfiled=null;
              String local="";
            //    StringBuffer fileName=new StringBuffer();//生成下载的文件名
              if(object!=null){
                  map=(Map<String,Object>)object;
                  String[] panel_names=((String)map.get("desc")).split("-")[0].split(";");//内容
                  local=((String)map.get("desc")).split("-")[3];
                  Map<String,String> pmap=getTitle(page,0);//0表示取面板
                int lens=panel_names.length;
                panel_name=new String[lens];//字段标题
                  panel_tfiled=new String[lens];//字段名
                  setDyTtile(pmap, panel_names, panel_name, panel_tfiled);
          
//              if(((String)map.get("desc")).split("-").length==5){
//                  String[] title_names=((String)map.get("desc")).split("-")[4].split(";");//文件名称
//                  Map<String,String> tmap=((List<Map<String, String>>) map.get("plist")).get(0);
//                  for(String st:title_names) {
//                     try {
//                         String temp=this.replaceBlank(st);
//                         fileName.append(tmap.get(temp.trim())).append("-");
//                     }catch(Exception e) {          
//                     }
//                  }
//              }
              }
            Map<String, String> gmap = getTitle(page,1);//1表示取格线       
              String[] str=s.split("-");
              String[] temp=str[1].split(";");
              int len=temp.length;
              String[] name=new String[len];//字段说明
              String[] filed=new String[len];//字段名
              setDyTtile(gmap, temp, name, filed);
              //然后写入excel文件
              page.setExcelTitle(str.length==4?str[3]:"");
              //处理生成文件名
              // fileName.append(str[0]);
            String dbid =request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"";
            String hostUrl = SettingKey.getHostUrl(request);
              PoiExcelWriter poi=new PoiExcelWriter();
              Map m=poi.writeExcel( dbid,str[0], page, name, filed,panel_name, panel_tfiled,
              map!=null?(List<?>)map.get("plist"):null,str[0],local,
              map!=null?(((String)map.get("desc")).split("-").length==5?this.replaceBlank(((String)map.get("desc")).split("-")[4]):""):"",hostUrl);
              SXSSFWorkbook wb=(SXSSFWorkbook)m.get("wb");
              String fileName=m.get("title")+"";
              if(wb!=null){
                  File file1=new File(request.getServletContext().getRealPath("/")+"excel"+File.separator+dbid+File.separator+formid+File.separator+type);
                if(!file1.exists()){
                    file1.mkdirs();
                }
                String path=request.getServletContext().getRealPath("/")+"excel"+File.separator+dbid+File.separator+formid+File.separator+type+File.separator+fileName.replace("/","_").replace("*","")+".xlsx";
                File file=new File(path);    
                  resp.setContentType("application/msexcel");
                  resp.setHeader("Content-Disposition", "attachment;Filename=" +new String(fileName.getBytes("utf-8"), "ISO8859-1")+ ".xlsx");
 
                  //写到磁盘生成文件,为了给审计用 by danaus 2020/11/10 16:12
                FileOutputStream fileOut = new FileOutputStream(file);
                wb.write(fileOut);
                fileOut.flush();
                fileOut.close();
                //通过流输出到页面
                OutputStream os = resp.getOutputStream();
                try (FileInputStream fis = new FileInputStream(file)) {
                    int lens;
                    byte[] buffer = new byte[4096];
                    while ((lens = fis.read(buffer)) > 0) {
                        os.write(buffer, 0, lens);
                    }
                    os.flush();
 
                } catch (IOException e) {
                    e.printStackTrace();
                    this.printJson(resp, "error;"+e.getMessage());
                }finally {
                    os.close();
                }
                excelRecords(formid,type,map,file,request,page);//导出数据审计记录执行方法
                wb.dispose();
              }
              page = null;       
          }catch (ParseException e) {
              // TODO Auto-generated catch block
            e.printStackTrace();
            this.printJson(resp, "error;"+e.getMessage());   
          } catch (Exception e) {
              e.printStackTrace();
              this.printJson(resp, "error;"+e.getMessage());
          }
    }
 
    /**
     * 导出数据审计记录执行方法
     * @param formid
     * @param type
     * @param map
     * @param reque
     * @return
     */
    public int  excelRecords(int formid,String type,Map<String, Object> map,File file,HttpServletRequest request,Page page){
        Date now = new Date(); 
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置显示格式    
    //    int types=Integer.parseInt(type.split("\\|")[0]);
        //int formid=Integer.parseInt(reque.getParameter("formidd").toString());
    //    String doccode=reque.getParameter("doccode");
    //    int type=Integer.parseInt(reque.getParameter("formidtyped").toString().split("\\|")[0]);
        String doccode=page.getWhere();//((Map)((List)map.get("plist")).get(0)).get("DocCode").toString();    
        if(doccode.toLowerCase().indexOf("doccode")!=-1){
            try{
                doccode=doccode.split("doccode='")[1].split("'")[0];
            }catch (Exception e) {
                doccode="";
            } 
        }else{
            doccode="";
        }
        int cont =0;
        String unid=UUID.randomUUID().toString().toUpperCase();//生成uuid
        try {
            InputStream inStream = new FileInputStream(file);    
            AttachmentIfc attachmentIfc=(AttachmentIfc)FactoryBean.getBean("AttachmentImpl");
            AttachmentWhereEntity attachmentWhereEntity=attachmentIfc.saveAttachment(unid, formid,input2byte(inStream),file.getName(),"xls","1");//保存导出的数据到指定数据库里面
            if(attachmentWhereEntity!=null && attachmentWhereEntity.getSeq() != null && !attachmentWhereEntity.getSeq().equals(0)){
                ExcelIfc excelIfc=(ExcelIfc)FactoryBean.getBean("com.yc.service.excel.ExcelImpl");
                String  ActionStatus="Success";
                String ActionMemo="";
                cont= excelIfc.excelRecord(formid, doccode, request.getSession().getAttribute(SessionKey.USERCODE).toString(), request.getSession().getAttribute(SessionKey.USERNAME).toString(), "Out", df.format(now), unid+";"+attachmentWhereEntity.getSeq(), "", type,ActionStatus,ActionMemo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(file!=null&&file.exists()&&file.isFile()) {
                log.info("del>>userCode:"+request.getSession().getAttribute(SessionKey.USERCODE)+"|dbid:"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"|"+file.getAbsolutePath());
                file.delete();
            }
        }    
        return cont;
    }
 
    public void setDyTtile(Map<String, String> gmap, String[] temp, String[] name, String[] filed) {//替换以!开头的动态内容
        int i=0;
        for(String st:temp){
            if(st.length()>1){
                String[] ss=st.split("#");
                if(ss.length>1){
                    if(StringUtils.isNotBlank(ss[1])) {
                        //标题存在复合标题的情况,需要处理
                        String[] value = ss[1].split("\\|");
                        if (value.length > 1) {
                            StringJoiner newTitle = new StringJoiner("|");
                            for (String s : value) {
                                if (s.trim().startsWith("!"))//如果是动态标题则替换
                                    newTitle.add(gmap.get(ss[0].toLowerCase()));
                                else
                                    newTitle.add(s);
                            }
                            name[i] = newTitle.toString();
                        } else {
                            name[i] = value[0];
                        }
                    }
                    }else{
                        name[i]="";
                    }
                    if(ss.length>2)
                        filed[i]=ss[0]+";"+ss[2];
                    else
                        filed[i]=ss[0];
                        i++;
            }
        }
    }
 
    public static Map<String, String> getTitle(Page page,int index) {//取得页面传过来的动态标题内容,以便替换excel对应的标题
        String[] tit=null;
        Map<String,String> gmap=new HashMap<String,String>();
        try {
            tit = EncodeUtil.base64Decode(page.getExcelTitle()).split("~");
            if(tit.length>0){
                String[] temp=tit[index].split("&#039;");//动态标题内容
                if(temp.length>1){
                    for(String st:temp){
                        String[] tt=st.split("&#040;");
                          gmap.put(tt[0], tt[1]);
                      }
                }
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return gmap;
    }
 
    public static final byte[] input2byte(InputStream inStream) {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        try{
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = inStream.read(buff, 0, buff.length)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] in2b = swapStream.toByteArray();  
            inStream.close();
            swapStream.close();
            return in2b;  
        }catch(Exception e){
            return null;
        }finally{
            try {
                swapStream.close();
                inStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
    public void checkDuplicateSubmit(String unid){
 
        RedisTemplate redisTemplate= (RedisTemplate) FactoryBean.getBean("redisTemplate");
        if(unid.equals("excel")){return;}//导入的跳出
        if(unid!=null&&!"".equalsIgnoreCase(unid)) {
            synchronized(lock) {
                Object object = redisTemplate.opsForValue().get(unid);
                if (object == null) {
                    //不存在,加到redis里,过期时间设置为2分钟
                    final int OVERTIME = 2;
                    redisTemplate.opsForValue().set(unid, 1, OVERTIME, TimeUnit.MINUTES);
                    CurrentLocal.setUnidLocal(unid);
 
                } else {
                    throw new ApplicationException("正在处理中...请不要重复提交");
                }
            }
        }else{
            throw new ApplicationException("参数unid不能为空,请确认前端是否有传递过来");
        }
    }
}