fs-danaus
2021-12-13 625716c9f4e76e49430af4d82b9e3973c1efedd3
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
package com.yc.action.login;
 
import com.google.gson.Gson;
import com.yc.action.BaseAction;
import com.yc.action.grid.GridUtils;
import com.yc.api.bean.Gfrom;
import com.yc.api.bean.QrScanType;
import com.yc.api.bean.attendance.AppSalesSetting;
import com.yc.api.controller.QrCodeController;
import com.yc.api.service.QrServiceIfc;
import com.yc.api.utils.VersionUtils;
import com.yc.entity.*;
import com.yc.entity.attachment.AttachmentEntity;
import com.yc.exception.ApplicationException;
import com.yc.exception.CallBackMessage;
import com.yc.factory.FactoryBean;
import com.yc.factory.InitSystem;
import com.yc.listener.SessionListener;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.password.action.ChangePassword;
import com.yc.sdk.shopping.action.api.InvitationCode;
import com.yc.sdk.shopping.util.SettingKey;
import com.yc.sdk.weixinopen.entity.OpenComponentAppSetting;
import com.yc.service.BaseService;
import com.yc.service.demo.DemoIfc;
import com.yc.service.role.RoleIfc;
import com.yc.service.upload.AttachmentIfc;
import com.yc.service.user.LoginRecordIfc;
import com.yc.service.user.UserAccountServiceIfc;
import com.yc.utils.*;
import me.chanjar.weixin.common.util.http.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
//@Scope("request")
@Controller
public class LoginAction extends BaseAction {
    @Autowired
    private UserAccountServiceIfc userAccountService;
    @Autowired
    private LoginRecordIfc record;
    @Autowired
    private RoleIfc rIfc;
    @Autowired
    private DemoIfc demoIfc;
    //@Autowired
    //RedisClusterClient redisClusterClient;
    final Logger log = LoggerFactory.getLogger(this.getClass());
    private static String attachment_server = AttachmentConfig.get("attachment.server");
    ;
 
    private int prossSN(String cltsn) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            SpObserver.setDBtoDemo();
            list = demoIfc.getInfoByCltSn(cltsn);
        } finally {
            SpObserver.setDBtoInstance();
        }
        int r = 0;
        if (list != null && list.size() > 0) {
            r = 1;
        }
        return r;
    }
 
    @RequestMapping("/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String userCode = request.getParameter("account");
        if (userCode == null || "".equals(userCode)) {
            userCode = (request.getAttribute("account") == null ? "" : (String) request.getAttribute("account"));
        }
        String password = request.getParameter("pwd");
        if (password == null || "".equals(password)) {
            password = (request.getAttribute("pwd") == null ? "" : (String) request.getAttribute("pwd"));
        }
        if (password != null && !"".equals(password)) {
            password = EncodeUtil.replaceUrlChar(password);
        }
 
        String code = request.getParameter("code");
        if (code == null || "".equals(code)) {
            code = (request.getAttribute("code") == null ? "" : (String) request.getAttribute("code"));
        }
        boolean ch_userid = (request.getAttribute("isch_userid") == null ? false
                : (Boolean) request.getAttribute("isch_userid"));
        if (ch_userid)
            password = "***";// 避开与密码相关
        String dbId = "";
        String dataBaseDis = "";
        String isone = "";
        Boolean isApp = false;
        CallBackMessage callBackMessage = new CallBackMessage();
        if (request.getParameter("isApp") != null || request.getAttribute("isApp") != null) {
            isApp = true;// 手机app传过来 ;
        }
        String redirect = request.getParameter("redirect"); // 登录后重定向页面,Added by Johns Wang, 2016-02-17
        // 处理通行证的情况
        StringBuilder sb = new StringBuilder();
        String cltsn = request.getParameter("cltsn");
        if (cltsn == null)
            cltsn = (String) request.getAttribute("cltsn"); // Added by Johns Wang, 2015-12-06。。……。。……..……
        if (cltsn != null && !"".equalsIgnoreCase(cltsn)) {
            int k = this.prossSN(cltsn);
            if (k == 0) {
                callBackMessage.setError("通行证已失效,请联络服务提供商!");
                this.printJson(response, callBackMessage.toString());
                return null;// 验证出错返回'
            }
        } else {
 
            dbId = request.getParameter("dataName");// 数据源id
            dataBaseDis = request.getParameter(SessionKey.DATABASE_DIS);
            isone = request.getParameter("isone");// 只有一个数据源的情况
            if (dbId == null)
                dbId = (String) request.getAttribute("dataName"); // Added by Johns Wang, 2015-12-06
            if (dataBaseDis == null)
                dataBaseDis = (String) request.getAttribute(SessionKey.DATABASE_DIS); // Added by Johns Wang, 2015-12-06
 
            // 从数据源取 系统名称 dataBaseDis ,added by Johns Wang, 2017-07-02
            if (dataBaseDis == null) {
                DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(dbId);
                if (dataSourceEntity != null) {
                    dataBaseDis = dataSourceEntity.getSystemID();
                }
            }
 
            if (isone == null)
                isone = (String) request.getAttribute("isone"); // Added by Johns Wang, 2015-12-06
        }
        if (userCode != null && userCode.length() > 30) {//解密为明文
            try {
                userCode = ChangePassword.getDecryptPassword(EncodeUtil.replaceUrlChar(userCode));
            } catch (Exception e) {
                e.printStackTrace();
                print2(response, this.getErrorMsg(e), redirect, isApp);
                return null;// 验证出错返回'
 
            }
        }
        HttpSession session = request.getSession();
        String domain = request.getParameter("domain") != null ? request.getParameter("domain")
                : (String) request.getAttribute("domain");
        UserAccountEntity userAccount = null;
        // -------处理原生APP登录,通过手机号,注册时的密码 by danaus 2018-8-24
        // 1---有dbid的情况表明是通过选择一个数据源进行登录操作
        if (VersionUtils.getAPPTypeName(request) != null) {// ios,adnroid调用
            try {
                InvitationCode invitationCode = (InvitationCode) FactoryBean.getBean("invitationCode");
                // userCode代表手机号 (在方法 invitationCode.getDbList() 切换数据源 )
                invitationCode.checkPasswordByTelephone(userCode, password, dbId);
                // 通过数据源id和手机号取得用户usercode进行登录,这时候不需要密码验证
                SpObserver.setDBtoInstance("_" + dbId);
                userAccount = userAccountService.getUserInfoByTelephone(userCode);//userCode 手机号
                if (userAccount != null) {
                    userAccount.setApp_userCode(userCode);
                    userAccount.setApp_Password(password);
                    userCode = userAccount.getUserCode();//转成ERP的usercode进行登陆
                    password = userAccount.getPassword();//转成ERP的密码进行登陆
                    ch_userid = true;
                } else {
                    print2(response, "【" + userCode + "】手机号码在ERP系统没有对应的用户信息或已停用", redirect, isApp);
                    return null;// 验证出错返回'
                }
            } catch (DataAccessException e) {
                e.printStackTrace();
                print2(response, e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), redirect, isApp);
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                print2(response, e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), redirect, isApp);
                return null;
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
        //这里是短信登录 xin 2020-8-20 11:25:59
        String phone=request.getParameter("telephone");        
        phone=(phone==null?"":phone);
        String phoneCode=request.getParameter("phoneCode");
        phoneCode=(phoneCode==null?"":phoneCode);
        if(StringUtils.isBlank(userCode) && !StringUtils.isBlank(phone) && !StringUtils.isBlank(phoneCode)) {
            try {
                 @SuppressWarnings("rawtypes")
                RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
                if(!redisTemplate.hasKey("CODE:" + phone + ":" + dbId)) {
                    print2(response, "验证码已失效,请重新获取验证码。", redirect, isApp);
                    return null;
                }
                if(!phoneCode.equals(redisTemplate.opsForValue().get("CODE:" + phone + ":" + dbId)+"")) {
                    print2(response, "验证码错误,请输入正确的验证码", redirect, isApp);
                    return null;
                }
                redisTemplate.delete("CODE:" + phone + ":" + dbId);//删除
                SpObserver.setDBtoInstance("_" + dbId);
                userAccount = userAccountService.getUserInfoByTelephone(phone);//phone 手机号
                if (userAccount != null) {
                    userCode = userAccount.getUserCode();//转成ERP的usercode进行登陆
                    password = userAccount.getPassword();//转成ERP的密码进行登陆
                }else {
                     print2(response, "【" + phone + "】手机号码在ERP系统没有对应的用户信息或已停用", redirect, isApp);
                     return null;// 验证出错返回'
                }
            } catch (Exception e) {
                 print2(response, "【" + phone + "】手机号码在ERP系统没有对应的用户信息或已停用", redirect, isApp);
                 return null;// 验证出错返回'
            }finally {
                 SpObserver.setDBtoInstance();
            }
        }
        //----------------
        // --------
        if (StringUtils.isBlank(dbId) && StringUtils.isBlank(isone)) {
            sb.append("请选择一个系统!\\n");
        } else {
            if (!StringUtils.isBlank(isone))
                dbId = isone;
            session.setAttribute(SessionKey.DATA_BASE_ID, dbId);
            session.setAttribute(SessionKey.DATABASE_DIS, dataBaseDis);
            // 如果domain为空,则取默认的域名 by danaus 2021/4/12 11:18
            if(org.apache.commons.lang3.StringUtils.isBlank(domain)){
                domain= SettingKey.getHostUrl(request);
            }
            session.setAttribute(SessionKey.DOMAIN, domain);
        }
        if (StringUtils.isBlank(userCode)) {
            sb.append("账号不能为空\\n");
        }
        if (StringUtils.isBlank(password)) {
            sb.append("密码不能为空\\n");
        }
 
        // 判断进行验证码校验*********************
        boolean isValidateLogin = "true".equals(SystemConfig.getInstanse().get("isEnableValidateCode"));
        ;
        if (isValidateLogin) {// 是否进行验证码验证
            if (StringUtils.isBlank(code)) {
                sb.append("验证码不能为空\\n");
            } else {
                String rand = (String) session.getAttribute("rand");// 对照验证码
                if (!code.equalsIgnoreCase(rand)) {
                    sb.append("验证码不相符\\n");
                }
            }
        }
        // 判断进行验证码校验*********************
 
        if (sb.length() > 0) {
            print2(response, sb.toString(), redirect, isApp);
            return null;// 验证出错返回'
        }
        try {
            // --------------------
 
            // 判断是否超出人数限制
            if (SessionListener.checkUserLimit(request, dbId)) {
                String s = "当前登录人数已超过系统最大登录人数,如有需要增加登录人数,请联系软件公司";
                print2(response, s, redirect, isApp);
                session.invalidate();
                return null;// 验证出错返回'
            }
            // *** start ******* 读取加密锁的授权店铺数
 
//             int scount=0;
//             if(session.getAttribute(SessionKey.HAsP_sHOPCOUNT)!=null)
//             scount=(Integer)session.getAttribute(SessionKey.HAsP_sHOPCOUNT);
//             if(scount>0){
//             // by danaus 13-5-4
//             int shop=record.getShopCount();
//             if(shop>scount){
//             this.print(response, "<script>alert('检测到系统店铺数量超出所授权的店铺数量!');window.history.back();</script>");
//             return null;//验证出错返回'
//             }
//             }
 
            // *** end ***********
            int recordeCount = 0;
            try {
                SpObserver.setDBtoInstance("_" + dbId);
                recordeCount = record.getRecordCountIn10min(userCode); // 10分钟内不能登录
            } finally {
                SpObserver.setDBtoInstance();
            }
            String ip = IPUtil.getIpAddr(request);
            if (recordeCount >= 5) {
                try {
                    SpObserver.setDBtoInstance("_" + dbId);
                    record.loginRecord(userCode, password, ip);// 登录次数过多再行登陆作为登录失败处理
                } finally {
                    SpObserver.setDBtoInstance();
                }
                print2(response, userCode + "在短时间内登录错误次数过多!请耐心的等10分钟后再登录!", redirect, isApp);
                return null;// 验证出错返回
            }
            // 检查限制用户登录时间和登录IP
 
            int s = 0;
            try {
                SpObserver.setDBtoInstance("_" + dbId);
                s = userAccountService.checkUserLoginTimeAndIp(userCode, ip);
            } finally {
                SpObserver.setDBtoInstance();
            }
            if (s == 0) {
                print2(response, "该用户只能在工作时间或固定场所使用本系统[" + ip + "]", redirect, isApp);
                return null;
            }
            //
            // 设置session
 
            try {
                if (userAccount == null) {
                    SpObserver.setDBtoInstance("_" + dbId);
                    userAccount = userAccountService.getUserInfoByUserCode(userCode);
 
                    if (userAccount == null) {
                        userAccount = userAccountService.getUserInfoByTelephone(userCode);   //允许电话登录
                    }
 
                    if (userAccount == null) {
                        userAccount = userAccountService.getUserInfoByEmail(userCode);   //允许邮箱号登录
                    }
                }
            } finally {
                SpObserver.setDBtoInstance();
            }
            if (userAccount == null) {
                try {
                    SpObserver.setDBtoInstance("_" + dbId);
                    record.loginRecord(userCode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
                } finally {
                    SpObserver.setDBtoInstance();
                }
                if (ch_userid) {
                    return "{\"ch_error\":\"ch_user_error\",\"info\":\"用户账号不存在!\"}";
                } else {
                    this.print2(response, "用户账号不存在!", request.getParameter("redirect"), isApp);
                    return null;
                }
            }
            try {
                if (!ch_userid && !userAccount.checkPassword(password)) {
                    try {
                        SpObserver.setDBtoInstance("_" + dbId);
                        record.loginRecord(userCode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
                    this.print2(response, "用户密码不正确!", request.getParameter("redirect"), isApp);
                    return null;
                }
            } catch (Exception ex) {
                this.print2(response, ex.getMessage(), request.getParameter("redirect"), isApp);
                return null;
            }
            // 判断用户APP登录时是否禁用
            if (isApp && userAccount.getActiveApp() == 1) {
                this.print2(response, "用户APP端禁止登录!如有问题,请联系管理员", request.getParameter("redirect"), isApp);
                return null;
            }
            processLoginUserToSession(ip, dbId, session, userAccount);
 
 
            // --------------
            // String ucode = account + Math.random();// 是为了区分用户重复问题,同一用户可以多人使用。
            // session.setAttribute(SessionKey.SAIL_USERCODE, ucode);
            // OnLineUser.setOnlineUser(dataString, ucode, session);
            /*
             * WebApplicationContext webApplicationContext =
             * ContextLoader.getCurrentWebApplicationContext(); ServletContext
             * servletContext =
             * webApplicationContext.getServletContext();//取得ServletContext对象实例
             * if((OnLineUser)servletContext.getAttribute("onlineuserlistener")==null) {
             * OnLineUser onuser=new
             * OnLineUser();//只设置一次,不同于上面日志文件的记录每次会话均设置。即当第一个客户连接到服务器时启动一个全局变量,
             * 此后所有的客户将使用相同的上下文。 servletContext.setAttribute("onlineuserlistener",onuser);//
             * 将监听器对象设置成ServletContext的属性,具有全局范围有效性,即所有的客户均可以取得它的实例。 }
             * session.setAttribute("onlineuserlistener",(OnLineUser)servletContext.
             * getAttribute("onlineuserlistener"));//取出此全局对象,并且将此对象绑定到某个会话中,
             * 此举将促使监听器调用valueBound,计数器加一。
             */
            // session.setAttribute(SessionKey.ONLINE_USERS, new OnLineUser());// 在线人数统计
            // ------------------
            if (isApp) {
                QrServiceIfc qrServiceIfc= (QrServiceIfc) FactoryBean.getBean("qrService");
                try {
                    SpObserver.setDBtoInstance("_" + dbId);
                    AppSalesSetting appSalesSetting=qrServiceIfc.getAppSalesOrderStyle();
                    //加到会话
                    session.setAttribute(SessionKey.APP_SALESORDER_MATCODE_LIST,appSalesSetting.getAppSalesOrderMatCodeList());
                    session.setAttribute(SessionKey.APP_SALESORDER_STYLE,appSalesSetting.getAppSalesOrderStyle());
                }catch (Exception e){
                    e.printStackTrace();
                    throw new ApplicationException(e.getMessage());
                }finally {
                    SpObserver.setDBtoInstance();
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("success", "ok");
                map.put("sessionid", session.getId());
                map.put("userName", userAccount.getUserName());
                String avatarUnid = "";
                if (userAccount.getAvatarUnid() != null && !"".equals(userAccount.getAvatarUnid())) {
                    try {
                        SpObserver.setDBtoInstance("_" + dbId);
                        AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
                        String[] unids = userAccount.getAvatarUnid().split(";");
                        final AttachmentEntity attachmentEntity = attachmentIfc.getAttachmentEntity(unids[0], unids[1]);
                        avatarUnid = userAccount.getAvatarUnid() + ";" + attachmentEntity.getFileType();
                    } catch (Exception ex) {
                        callBackMessage.sendErrorMessage(ex.getMessage());
                        this.printJson(response, callBackMessage.toString());
                        return null;
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
                }
                map.put("avatarUnid", avatarUnid);
 
                map.put("attachment_server", attachment_server);
                map.put("url", domain == null ? "" : domain);
                if (request.getAttribute("postTokenV2") == null) {
                    map.put("token", genToken(userAccount.getApp_Password(), userAccount.getApp_userCode(), Integer.parseInt(dbId)));
                }
 
                //---增加扫码显示方式
 
                QrScanType qrScanType=null;
                //显示下单图标
                int appSalesMenuIcon=0;
                try {
                    SpObserver.setDBtoInstance("_" + dbId);
                    qrScanType= qrServiceIfc.getQrScanType(userAccount.getUserCode(), userAccount.getUserName());
 
                }catch (EmptyResultDataAccessException e){
                   //不处理,合理存在的情况
                    qrScanType=new QrScanType();
 
                }catch (Exception e){
                    e.printStackTrace();
                    throw new ApplicationException(e.getMessage());
                }finally {
                    SpObserver.setDBtoInstance();
                }
                //---增加是否可以显示下单图标
                try{
                    SpObserver.setDBtoInstance("_" + dbId);
                    BaseService baseService= (BaseService) FactoryBean.getBean("BaseService");
                    List<Gfrom> list = baseService.getJdbcTemplate().query("select a.formid,a.formname from gform a where exists(select 1 from gfield b where a.formid = b.formid and b.fieldid in ( 'matcode','barcode','qrcode') and b.ScanCodeField = 1 )",new BeanPropertyRowMapper<>(Gfrom.class));
 
                    if(list!=null&&list.size()>0){
                        QrCodeController qrCodeController= (QrCodeController) FactoryBean.getBean("qrCodeController");
                        List tempList=  qrCodeController.procFormLimit(request,list);
                        if(tempList!=null&&tempList.size()>0){
                            appSalesMenuIcon=1;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new ApplicationException(e.getMessage());
                }finally {
                    SpObserver.setDBtoInstance();
                }
 
                map.put("sessionInfo", getSessionInfo(session));
                map.put("isAdmin", session.getAttribute(SessionKey.SUPPER_USER));
                final DataSourceEntity dataSourceMap = MultiDataSource.getDataSourceMap(dbId);
                map.put("isShowAttendance", dataSourceMap.isShowAttendanceButton()?1:0);//打卡
                map.put("qrDisplayType", qrScanType.getScanMeterialAction());//扫码显示方式
                map.put("appSalesMenuIcon", appSalesMenuIcon);//是否显示下单图标,0不显示,1显示
                map.put("isRelatingMaterialWhenNewCustomer", qrScanType.getIsRelatingMaterialWhenNewCustomer());//是否关联客户
                OpenComponentAppSetting openComponentAppSetting=OpenComponentAppSetting.defaultSettings();
                map.put("mobileAppId", openComponentAppSetting==null?null:openComponentAppSetting.getMobileAppId());//小程序id
                map.put("mobileAppSecret", openComponentAppSetting==null?null:openComponentAppSetting.getMobileAppSecret());//小程序MobileAppSecret
                map.put("miniAppOrgId", dataSourceMap.getMiniAppOrgId());//小程序miniAppOrgId
                map.put("isModifyPriceWhenScanQrCode", session.getAttribute(SessionKey.ISMODIFYPRICEWHENSCANQRCODE));
                map.put("isModifyPriceWhenSalesOrder", session.getAttribute(SessionKey.ISMODIFYPRICEWHENSALESORDER));
                map.put("isModifyPriceWhenPurchaseOrder", session.getAttribute(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER));
                map.put("perssion", session.getAttribute(SessionKey.PERSSION));
                this.printJson(response, GridUtils.toJson(map));
                session.setAttribute(SessionKey.USER_LOGIN_TYPE, SessionKey.USER_LOGIN_TYPE_APP);//app 类型
                return null;
            } else if (redirect != null && !"".equals(redirect)) { // 增加登录后重定向页面功能,added by Johns Wang, 2016-02-17
                //return "redirect:" + redirect;
                callBackMessage.sendSuccessMessage("登录成功");
                callBackMessage.setData("{\"redirect\":\"" + redirect + "\"}");
                session.setAttribute(SessionKey.USER_LOGIN_TYPE, SessionKey.USER_LOGIN_TYPE_MINIAPP);//miniapp 类型
                this.printJson(response, callBackMessage.toString());
                return null;
            } else {
                session.setAttribute(SessionKey.USER_LOGIN_TYPE, SessionKey.USER_LOGIN_TYPE_WEB);//web 类型
                if (ch_userid)
                    return "{\"ok\":\"ch_user_ok\",\"info\":\"" + userCode + "\"}";
                else {
                    callBackMessage.sendSuccessMessage("登录成功");
                    this.printJson(response, callBackMessage.toString());
                    return null;
                }
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
            if (e.getMessage().contains("Session already invalidated")) {
                sb.append("会话已过期,请关闭浏览器再重新登录系统\\n");
                print2(response, sb.toString(), redirect, isApp);
                System.out.println(this.getClass() + " sessionid:" + session.getId());
                return null;// 会话已过期返回
            } else {
                e.printStackTrace();
                print2(response, this.getErrorMsg(e), redirect, isApp);
                return null;
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
            //SQLException sql = (SQLException) e.getCause();
            //return "/403.jsp?info=" + sql.getMessage();
            this.print2(response, e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), request.getParameter("redirect"), isApp);
            return null;
        } catch (NullPointerException e) {// 不存在此账号
            e.printStackTrace();
            proccError(userCode, password, request, response);
            return null;
        } catch (RuntimeException e) {
            e.printStackTrace();
            if (e.getMessage().equals(SessionKey.DEMO_REF)) {
                session.setAttribute(SessionKey.DEMO_REF, SessionKey.DEMO_REF);
                this.print(response, "<script>alert('请生成正确的配置信息');window.location.href='/demo/demoList.jsp';</script>");
            }
            return null;
        } catch (Exception e) {// 不存在此账号
            e.printStackTrace();
            proccError(userCode, password, request, response);
            return null;
        }
    }
 
    private String genToken(String pwd, String usercode, int dbid) {
        TokenInfo tokenInfo = new TokenInfo();
        tokenInfo.setUsercode(usercode);
        tokenInfo.setDbid(dbid);
        try {
            String key = "Lg_Token:" + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode();
 
            RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
            Object object = redisTemplate.opsForValue().get(key);
            //if (object == null) {
            //不存在则加到redis里,过期时间设置为12小时
            final int OVERTIME = 12;
            redisTemplate.opsForValue().set(key, pwd, OVERTIME, TimeUnit.HOURS);
            //}
 
            String token = AESUtils.encrypt(GridUtils.toJson(tokenInfo));//dbid+usercode加密返回给APP客户端保存
            return token;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }
 
    public boolean processLoginUserToSession(String ip, String dbId, HttpSession session, UserAccountEntity userAccount) throws Exception {
        // 设置权限
        PerssionEntity perssionEntity = new PerssionEntity();
        try {
            SpObserver.setDBtoInstance("_" + dbId);
            perssionEntity.setRole(rIfc.getRole(userAccount.getUserCode()));
        } finally {
            SpObserver.setDBtoInstance();
        }
        try {
            SpObserver.setDBtoInstance("_" + dbId);
            perssionEntity.setPerssion(userAccountService.getUserProfiles(userAccount.getUserCode()));
            // 保存会话 session信息
            setSessionValues(dbId, userAccount, session, perssionEntity);
            // 登录成功清除登录错误信息
            record.clearLoginRecord(userAccount.getUserCode());
 
            // 记录登录信息
            userAccountService.loginLog(userAccount.getUserCode(), userAccount.getUserName(), ip, session.getId());
        } finally {
            SpObserver.setDBtoInstance();
        }
        if (userAccount.getDefaultSet() != null && !"".equals(userAccount.getDefaultSet())) {
            try {
                SpObserver.setDBtoInstance("_" + dbId);
                perssionEntity.setDefaultSet(userAccountService.getDefaultSet(userAccount.getDefaultSet()));
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
        return true;
 
    }
 
    /**
     * APP 自动登录接口
     *
     * @param request
     * @param response
     */
    @RequestMapping("/autoLogin.do")
    public String autoLogin(String token, HttpServletRequest request, HttpServletResponse response) {
        if (token == null || "".equalsIgnoreCase(token)) {
            this.printJson(response, "{\"error\":\"token不能为空\"}");
            return "";
        }
        try {
            String value = AESUtils.decrypt(EncodeUtil.replaceUrlChar(token));//解密
            Gson gson = new Gson();
            TokenInfo tokenInfo = gson.fromJson(value, new com.google.gson.reflect.TypeToken<TokenInfo>() {
            }.getType());
 
            RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
            Object object = redisTemplate.opsForValue().get("Lg_Token:" + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode());
            if (object == null) {
                this.printJson(response, "{\"error\":\"token已失效,请重新登录\"}");
                return "";
            }
 
            String[] tokenStr = ((String) object).split("#");//0是密码,1是随机数
            //进行登录操作
            tokenInfo.setPwd(tokenStr[0]);
            request.setAttribute("account", tokenInfo.getUsercode());
            request.setAttribute("pwd", tokenInfo.getPwd());
            request.setAttribute("isApp", "1");
            request.setAttribute("dataName", tokenInfo.getDbid() + "");
            request.setAttribute("isone", tokenInfo.getDbid() + "");
        } catch (Exception ex) {
            this.printJson(response, "{\"error\":\"" + this.getErrorMsg(ex) + "\"}");
            return "";
        }
        return login(request, response);
    }
 
    @RequestMapping("/autoLoginV2.do")
    /**
     * by danaus 2020/1/13 9:59
     */
    public String autoLoginV2(String token, HttpServletRequest request, HttpServletResponse response) {
        CallBackMessage callBackMessage = new CallBackMessage();
        if (token == null || "".equalsIgnoreCase(token)) {
            this.printJson(response, callBackMessage.sendErrorMessage("token不能为空", -1));
            return "";
        }
        try {
            String value = AESUtils.decrypt(EncodeUtil.replaceUrlChar(token));//解密
            Gson gson = new Gson();
            TokenInfo tokenInfo = gson.fromJson(value, new com.google.gson.reflect.TypeToken<TokenInfo>() {
            }.getType());
            RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
            //System.out.println("aaaaaa>>>>"+value);
            //System.out.println("bbbbb>>>>"+InvitationCode.TOKEN_STR + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode());
            Object object = redisTemplate.opsForValue().get(InvitationCode.TOKEN_STR + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode());
            //System.out.println("cccc>>>>"+object);
            if (object == null) {
                //设置会话失效
                request.getSession().invalidate();
                this.printJson(response, callBackMessage.sendErrorMessage("token已失效,请重新登录", -1002));
                return "";
            }
            //405调用需要刷新过期时间
            if(request.getParameter("refresh")!=null&&"1".equalsIgnoreCase(request.getParameter("refresh"))) {
                //刷新key过期时间
                redisTemplate.opsForValue().getOperations().expire(InvitationCode.TOKEN_STR + tokenInfo.getDbid() + ":" + tokenInfo.getUsercode(), 12, TimeUnit.HOURS);
            }
            //验证token合法性,对比随机数
            String[] tokenStr = ((String) object).split("#");//0是密码,1是随机数 by danaus 2020/9/24 10:18
//            if (tokenStr[1] == null || "".equals(tokenStr[1]) || tokenInfo.getRand() != Double.parseDouble(tokenStr[1])) {
//                this.printJson(response, callBackMessage.sendErrorMessage("不是合法的token", -1001));
//                return null;
//            }
 
            //进行登录操作
            tokenInfo.setPwd(tokenStr[0]);
            request.setAttribute("account", tokenInfo.getUsercode());
            request.setAttribute("pwd", tokenInfo.getPwd());
            request.setAttribute("isApp", "1");
            request.setAttribute("dataName", tokenInfo.getDbid() + "");
            request.setAttribute("isone", tokenInfo.getDbid() + "");
            request.setAttribute("postTokenV2", "1");//说明是通过V2版提交,之后在登录成功后就不返回token。
        } catch (Exception ex) {
            this.printJson(response, callBackMessage.sendErrorMessage(this.getErrorMsg(ex), -1));
            return "";
        }
        return login(request, response);
    }
 
    private void print2(HttpServletResponse response, String sb, String redirect, Boolean isApp) {
        CallBackMessage callBackMessage = new CallBackMessage();
        // redirect Added by Johns Wang, 2016-03-06
        if (redirect != null && !"".equals(redirect)) {
            redirect = URIUtil.encodeURIComponent(redirect);
            callBackMessage.setData("{\"redirect\":\"" + redirect + "\"}");
        }
        callBackMessage.sendErrorMessage(sb);
        if (isApp != null && isApp) {
            if("密码错误".equalsIgnoreCase(sb)){
                //密码不正确 以状态码为-1004返回给app,弹出登录界面
                callBackMessage.sendErrorMessage(sb,-1004);
            }
            this.print(response, callBackMessage.toString());
        } else {
            this.print(response, callBackMessage.toString());
        }
//            // this.print(response, "<script>
//            // alert('"+sb+"');window.history.back();</script>");
//            if (redirect == null || redirect.equals(""))
//                this.print(response, "<script> alert('" + sb + "');window.history.back();</script>");
//            else
//                this.print(response, "<script> alert('" + sb + "');window.location='/login.jsp?redirect=" + redirect
//                        + "';</script>");
//        }
    }
 
    private Map<String, Object> getSessionInfo(HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(SessionKey.HRCODE.replace("@", ""), session.getAttribute(SessionKey.HRCODE));
        map.put(SessionKey.HRNAME.replace("@", ""), session.getAttribute(SessionKey.HRNAME));
        map.put(SessionKey.USERNAME.replace("@", ""), session.getAttribute(SessionKey.USERNAME));
        map.put(SessionKey.USER_NAME.replace("@", ""), session.getAttribute(SessionKey.USER_NAME));
        map.put(SessionKey.ORIGINAL_USERNAME.replace("@", ""), session.getAttribute(SessionKey.ORIGINAL_USERNAME));
        map.put(SessionKey.USER.replace("@", ""), session.getAttribute(SessionKey.USER));
        map.put(SessionKey.ORIGINAL_USERCODE.replace("@", ""), session.getAttribute(SessionKey.ORIGINAL_USERCODE));
        map.put(SessionKey.USERCODE.replace("@", ""), session.getAttribute(SessionKey.USERCODE));
        map.put(SessionKey.COMPANY_ID.replace("@", ""), session.getAttribute(SessionKey.COMPANY_ID));
        map.put(SessionKey.COMPANY_NAME.replace("@", ""), session.getAttribute(SessionKey.COMPANY_NAME));
        map.put(SessionKey.COMPANYMEMO.replace("@", ""), session.getAttribute(SessionKey.COMPANYMEMO));
        map.put(SessionKey.VERSION_ID.replace("@", ""), session.getAttribute(SessionKey.VERSION_ID));
        map.put(SessionKey.DEPARTMENT.replace("@", ""), session.getAttribute(SessionKey.DEPARTMENT));
        map.put(SessionKey.CCCODE.replace("@", ""), session.getAttribute(SessionKey.CCCODE));
        map.put(SessionKey.CCNAME.replace("@", ""), session.getAttribute(SessionKey.CCNAME));
        map.put(SessionKey.SUPPER_USER.replace("@", ""), session.getAttribute(SessionKey.SUPPER_USER));
        map.put(SessionKey.ROLE_NAME.replace("@", ""), session.getAttribute(SessionKey.ROLE_NAME));
        map.put(SessionKey.DEFAULT_SET.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_SET));
        map.put(SessionKey.LOGIN_TYPE.replace("@", ""), session.getAttribute(SessionKey.LOGIN_TYPE));
        map.put(SessionKey.isStopSystem.replace("@", ""), session.getAttribute(SessionKey.isStopSystem));
        map.put(SessionKey.OPEN_ID.replace("@", ""), session.getAttribute(SessionKey.OPEN_ID));
        map.put(SessionKey.CURRENCY.replace("@", ""), session.getAttribute(SessionKey.CURRENCY));
        map.put(SessionKey.SHOP_CCCDOE.replace("@", ""), session.getAttribute(SessionKey.SHOP_CCCDOE));
        ;
        map.put(SessionKey.SYSTEM_LANGUAGE.replace("@", ""), session.getAttribute(SessionKey.SYSTEM_LANGUAGE));
        map.put(SessionKey.DEFAULT_STCODE.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_STCODE));
        map.put(SessionKey.DEFAULT_ACCTCODE.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_ACCTCODE));
        map.put(SessionKey.UserCodePermission.replace("@", ""), session.getAttribute(SessionKey.UserCodePermission));
        map.put(SessionKey.COMPANY_PERMISSION.replace("@", ""), session.getAttribute(SessionKey.COMPANY_PERMISSION));
        map.put(SessionKey.AT_TODAY.replace("@", ""), session.getAttribute(SessionKey.AT_TODAY));
        map.put(SessionKey.AT_NOW.replace("@", ""), session.getAttribute(SessionKey.AT_NOW));
        map.put(SessionKey.DEFAULT_BRAND.replace("@", ""), session.getAttribute(SessionKey.DEFAULT_BRAND));
        map.put(SessionKey.CCCODEPERMISSION.replace("@", ""), session.getAttribute(SessionKey.CCCODEPERMISSION));
        map.put(SessionKey.USERTYPE.replace("@", ""), session.getAttribute(SessionKey.USERTYPE));
        map.put(SessionKey.ISMODIFYPRICEWHENSCANQRCODE, session.getAttribute(SessionKey.ISMODIFYPRICEWHENSCANQRCODE));
        map.put(SessionKey.ISMODIFYPRICEWHENSALESORDER, session.getAttribute(SessionKey.ISMODIFYPRICEWHENSALESORDER));
        map.put(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER, session.getAttribute(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER));
        map.put("day", DateUtil.getDay(0));
        map.put("month", DateUtil.getMonth(0));
        map.put("year", DateUtil.getYear(0));
        return map;
 
    }
 
    private void proccError(String account, String pwd, HttpServletRequest request, HttpServletResponse response) {
        Boolean isApp = Boolean.valueOf(request.getParameter("isApp") == null ? false : true);// 手机app传过来
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            record.loginRecord(account, pwd, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
        } catch (Exception e2) {
            this.print2(response, e2.getMessage().replace("\"", ""), request.getParameter("redirect"), isApp);
        } finally {
            SpObserver.setDBtoInstance();
        }
        this.print2(response, "用户账号或密码错误!", request.getParameter("redirect"), isApp);
    }
 
    @RequestMapping("/logout.do")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession();
            session.invalidate();
            this.printJson(response, "{\"success\":\"ok\"}");
        } catch (Exception e) {
            e.printStackTrace();
            this.printJson(response, "{\"error\":\"" + e.getMessage() + "\"}");
        }
    }
 
 
    @RequestMapping("/GetLoginUser.do")
    public void getLoginUser(HttpServletRequest request, HttpServletResponse response) {
        int pageSize = 0;
        int curPage = 0;
        int total = 0;
        List<Map<String, Object>> list = null;
        try {
            pageSize = Integer.parseInt(request.getParameter("rows"));// 每页大小
            curPage = Integer.parseInt(request.getParameter("page")); // 当前页
        } catch (Exception e) {
            return;
        }
 
        // 搜索条件
        String companyname = request.getParameter("companyname");
        String usercode = request.getParameter("usercode");
        String username = request.getParameter("username");
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (StringUtils.isBlank(companyname) && StringUtils.isBlank(usercode) && StringUtils.isBlank(username)) {
                total = userAccountService.getUserTotal();
                list = userAccountService.getLoginUser(curPage, pageSize);
            } else {
                total = userAccountService.getUserTotal(companyname, usercode, username);
                list = userAccountService.getLoginUser(curPage, pageSize, companyname, usercode, username);
            }
        } finally {
            SpObserver.setDBtoInstance();
        }
        Gson gson = new Gson();
        String data = gson.toJson(list);
 
        StringBuilder sb = new StringBuilder();
        sb.append("{\"total\":").append(total).append(",\"rows\":").append(data).append("}");
 
        try {
            printText(response, sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        data = null;
        sb = null;
        list = null;
        gson = null;
    }
 
    /**
     * 输出信息到客户端
     *
     * @param response
     * @param str
     * @throws IOException
     */
    public void printText(HttpServletResponse response, String str) throws IOException {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.write(str);
        out.flush();
        out.close();
    }
 
    /**
     * 设置session 相关值(添加新的session标识符时应在切换用户功能添加相应的session标识符com.yc.action.login.SwitchUserCodeAction)
     *
     * @param dbId
     * @param userAccount
     * @param session
     * @return
     * @throws Exception
     */
    public static String setSessionValues(String dbId, UserAccountEntity userAccount, HttpSession session,
                                          PerssionEntity perssionEntity) throws Exception {
        // ------------用SessionKey类来存储session标识符 避免大小写或者忘记session标识符的情况-------
        Map<String, Object> role = perssionEntity.getRole(); // rIfc.getRole(userAccount.getUserCode());
        String userCode = (String) userAccount.getUserCode();
        session.setAttribute(SessionKey.HRCODE, ((String) userAccount.getHrCode()).replaceAll("\\s", ""));// 用户ID
        session.setAttribute(SessionKey.HRNAME, ((String) userAccount.getHrName()).replaceAll("\\s", ""));// 用户ID
        String userName = (String) userAccount.getUserName();// 用户名
        session.setAttribute(SessionKey.USERNAME, userName.replaceAll("\\s", ""));
        session.setAttribute(SessionKey.USER_NAME, userName.replaceAll("\\s", ""));
        session.setAttribute(SessionKey.PASSWORD, userAccount.getPassword());
        session.setAttribute(SessionKey.ORIGINAL_USERNAME, userName.replaceAll("\\s", ""));
        session.setAttribute(SessionKey.USER, userCode.replaceAll("\\s", ""));// 用户ID
        session.setAttribute(SessionKey.ORIGINAL_USERCODE, userCode.replaceAll("\\s", ""));
        session.setAttribute(SessionKey.USERCODE, userCode.replaceAll("\\s", ""));// 用户ID
        session.setAttribute(SessionKey.COMPANY_ID, userAccount.getCompanyId());// 公司代码
        session.setAttribute(SessionKey.COMPANY_NAME, userAccount.getCompanyName());// 公司代码
        session.setAttribute(SessionKey.COMPANYMEMO, userAccount.getCompanyMemo());// 适合于多公司
        session.setAttribute(SessionKey.VERSION_ID, 0);// 版本号
        session.setAttribute(SessionKey.DEPARTMENT, userAccount.getCcName());
        session.setAttribute(SessionKey.CCCODE, userAccount.getCcCode());
        session.setAttribute(SessionKey.CCNAME, userAccount.getCcName());
        session.setAttribute(SessionKey.SUPPER_USER,
                "superuser".equalsIgnoreCase((userAccount.getUserType())) ? "1" : "0");// 系统管理员
        session.setAttribute(SessionKey.isStopSystem, userAccount.isStopSystem() ? "1" : "0");
        session.setAttribute(SessionKey.OPEN_ID, userAccount.getOpenId());// openid号
        session.setAttribute(SessionKey.CURRENCY, userAccount.getCurrency());
        session.setAttribute(SessionKey.SHOP_CCCDOE, userAccount.getShopCcCode());// shopcccode
        session.setAttribute(SessionKey.COMPANY_PERMISSION, userAccount.getCompanyPermission());// CompanyPermission
 
        session.setAttribute(SessionKey.ROLE_NAME,
                role == null ? "未设置" : role.get("RoleName") == null ? "" : role.get("RoleName"));// 如超级用户
 
        // 根据账号获取相关权限集合
        Map<String, Map<String, Object>> perssion = perssionEntity.getPerssion(); // userAccountService.getUserProfiles(userCode);
 
        // 获得缺省集合
        if (userAccount.getDefaultSet() != null && !"".equals(userAccount.getDefaultSet())) {
            // DefaultSet.defaultSet2Session(userAccountService.getDefaultSet(userAccount.getDefaultSet()),
            // session);
            DefaultSet.defaultSet2Session(perssionEntity.getDefaultSet(), session);
        }
 
        // 构建账号对应的系统菜单
        session.setAttribute(SessionKey.PERSSION, perssion);// 权限集合
        session.setAttribute(SessionKey.LOGIN_TYPE, userAccount.getLogonType() + "");
        session.setAttribute(SessionKey.SYSTEM_LANGUAGE, "cnzh");// 设置语言
        session.setAttribute(SessionKey.DIBANG, userAccount.isEnableLoadCollection() ? "1" : "0");// 设置地磅权限
        // 添加地磅需要信息 默认先给空白
        session.setAttribute(SessionKey.LOADER_NAME, "");
        session.setAttribute(SessionKey.IP_ADDRESS, "");
        session.setAttribute(SessionKey.HOSTNAME, "");
        session.setAttribute(SessionKey.MAC_ADDRESS, "");
        session.setAttribute(SessionKey.AT_TODAY, DateUtil.toDayDate());
        session.setAttribute(SessionKey.AT_NOW, DateUtil.toDay());
        session.setAttribute(SessionKey.DEFAULT_STCODE, userAccount.getDefaultStcode());
        session.setAttribute(SessionKey.DEFAULT_ACCTCODE, userAccount.getDefaultAcctCode());
        session.setAttribute(SessionKey.UserCodePermission, userAccount.getUserCodePermission());
        session.setAttribute(SessionKey.DEFAULT_BRAND, userAccount.getDefaultBrand());
        session.setAttribute(SessionKey.CCCODEPERMISSION, userAccount.getCcCodePermission());
        session.setAttribute(SessionKey.ISMODIFYPRICEWHENSCANQRCODE, userAccount.getIsModifyPriceWhenScanQrCode());
        session.setAttribute(SessionKey.ISMODIFYPRICEWHENSALESORDER, userAccount.getIsModifyPriceWhenSalesOrder());
        session.setAttribute(SessionKey.ISMODIFYPRICEWHENPURCHASEORDER, userAccount.getIsModifyPriceWhenPurchaseOrder());
        session.setAttribute(SessionKey.USERTYPE,userAccount.getUserType() );
 
        session.setAttribute(SessionKey.PAGE_PATH,
                File.separator + "app" + File.separator + session.getAttribute(SessionKey.DATA_BASE_ID) + File.separator
                        + session.getAttribute(SessionKey.VERSION_ID) + File.separator
                        + session.getAttribute(SessionKey.SYSTEM_LANGUAGE));
        String realpath = session.getServletContext().getRealPath("/") + session.getAttribute(SessionKey.PAGE_PATH);
        session.setAttribute(SessionKey.REAL_PATH, realpath.replaceAll("\\\\", "/"));
        session.setAttribute(SessionKey.DATA_PATH,
                File.separator + "app" + File.separator + session.getAttribute(SessionKey.DATA_BASE_ID) + File.separator
                        + session.getAttribute(SessionKey.VERSION_ID) + File.separator
                        + session.getAttribute(SessionKey.SYSTEM_LANGUAGE));
        InitSystem.getInstance().setMailSavePath(session.getServletContext()
                .getRealPath(File.separator + "WEB-INF" + File.separator + "MAIL" + File.separator));
        // 结束地磅所需信息
        // 增加读取授权门店数
        DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap(dbId);
        if (dataSourceEntity != null) {
            session.setAttribute(SessionKey.LimitDepartmentNumber, dataSourceEntity.getLimitDepartmentNumber());
            session.setAttribute(SessionKey.DATACHECK_PAGENUM, dataSourceEntity.getDataCheckPageNum());
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        session.setAttribute(SessionKey.LOGIN_TIME, df.format(new Date()));//登录时间 xin 2020-8-31 11:35:22
        
        return userName;
 
    }
 
    public void setRecord(LoginRecordIfc record) {
        this.record = record;
    }
 
    // 检查session是否失效
    @RequestMapping("/checkSession.do")
    public void sessionCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String result = "";
        if (session.getAttribute(SessionKey.HRCODE) == null) {
            // userAccountService.doQuitLog(request.getParameter("usercode")); by 2014-8-5
            // danaus 会话失效写插进数据无意义且会出错
            result = "fail";
        } else {
            result = "success";
        }
        printText(response, "{\"status\":\"" + result + "\"}");
    }
 
    /**
     * session失效后弹出登录框登录
     *
     * @param request
     * @param response 2012-09-20
     */
    @RequestMapping("/againLogin.do")
    public String againLogin(String usercode, String password, String dbid, String dbstr, String domain,
                             HttpServletRequest request, HttpServletResponse response) {
        // System.out.println("againLogin..."+request.getSession().getId()+",时间:"+request.getSession().getCreationTime());
        StringBuilder sb = new StringBuilder();
        HttpSession session = request.getSession();
        CallBackMessage callBackMessage = new CallBackMessage();
        if (dbid == null || "".equals(dbid)) {
            List<DataSourceEntity> dataSourceList = MultiDataSource.getDataSourceMapsByDomain(domain);
            if (dataSourceList != null && dataSourceList.size() > 0) {
                dbid = dataSourceList.get(0).getDbId() + "";
            }
        }
        try {
            if (dbid == null || "".equals(dbid)) {
                sb.append("数据库ID不能为空\\n");
            }
 
            if (StringUtils.isBlank(usercode)) {
                sb.append("账号不能为空\\n");
            }
            if (StringUtils.isBlank(password)) {
                sb.append("密码不能为空\\n");
            }
            if (sb.length() > 0) {
                callBackMessage.sendErrorMessage(sb.toString());
                this.printJson(response, callBackMessage.toString());
                return null;// 验证出错返回'
            }
 
            session.setAttribute(SessionKey.DATA_BASE_ID, dbid);
            session.setAttribute(SessionKey.DATABASE_DIS, dbstr);
            session.setAttribute(SessionKey.DOMAIN, request.getParameter("domain"));
 
            // --------------------
            // 判断是否超出人数限制
 
            if (SessionListener.checkUserLimit(request, dbid)) {
                String s = "当前登录人数已超过系统最大登录人数,如有需要增加登录人数,请联系软件公司";
                this.print2(response, s, null, null);
                session.invalidate();
                return null;// 验证出错返回'
            }
            Boolean isApp = Boolean.valueOf(request.getParameter("isApp") == null ? false : true);// 手机app传过来
            if (usercode != null && usercode.length() > 30) {//解密为明文
                try {
                    usercode = ChangePassword.getDecryptPassword(usercode);
                } catch (Exception e) {
                    e.printStackTrace();
                    print2(response, this.getErrorMsg(e), null, isApp);
                    return null;// 验证出错返回'
 
                }
            }
            // ----------------
            // String dbid=session.getAttribute(SessionKey.DATA_BASE_ID)+"";
            int recordeCount = 0;
            try {
                SpObserver.setDBtoInstance("_" + dbid);
                recordeCount = record.getRecordCountIn10min(usercode);
            } finally {
                SpObserver.setDBtoInstance();
            }
            if (recordeCount >= 5) {
                try {
                    SpObserver.setDBtoInstance("_" + dbid);
                    record.loginRecord(usercode, password, IPUtil.getIpAddr(request));// 登录次数过多再行登陆作为登录失败处理
                } finally {
                    SpObserver.setDBtoInstance();
                }
                this.print2(response, usercode + "在短时间内登录错误次数过多!请耐心的等10分钟后再登录!", null, null);
                return null;// 验证出错返回
            }
 
            // session.setAttribute(SessionKey.ONLINE_USERS, new
            // OnLineUser(usercode,userName,dbid,request.getParameter("domain")));//在线人数统计
            // 设置session
            String ip = IPUtil.getIpAddr(request);
            // 检查限制用户登录时间和登录IP
            int s = 0;
            try {
                SpObserver.setDBtoInstance("_" + dbid);
                s = userAccountService.checkUserLoginTimeAndIp(usercode, ip);
            } finally {
                SpObserver.setDBtoInstance();
            }
            if (s == 0) {
                print2(response, "该用户只能在工作时间或固定场所使用本系统[" + ip + "]", null, isApp);
                return null;
            }
            //
            // --------------
            // String ucode = usercode + Math.random();// 是为了区分用户重复问题,同一用户可以多人使用。
            // session.setAttribute(SessionKey.SAIL_USERCODE, ucode);
            // OnLineUser.setOnlineUser(dataString, ucode, session);
            // session.setAttribute(SessionKey.ONLINE_USERS, new OnLineUser());// 在线人数统计
            // ------------------
 
 
            UserAccountEntity userAccount = null;
            try {
                SpObserver.setDBtoInstance("_" + dbid);
                userAccount = userAccountService.getUserInfoByUserCode(usercode);
                if (userAccount == null) {
                    userAccount = userAccountService.getUserInfoByTelephone(usercode);   //允许电话登录
                }
 
                if (userAccount == null) {
                    userAccount = userAccountService.getUserInfoByEmail(usercode);   //允许邮箱号登录
                }
            } finally {
                SpObserver.setDBtoInstance();
            }
 
            if (userAccount == null) {
                try {
                    SpObserver.setDBtoInstance("_" + dbid);
                    record.loginRecord(usercode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
                } finally {
                    SpObserver.setDBtoInstance();
                }
 
                this.print2(response, "用户账号不存在!", request.getParameter("redirect"), isApp);
                return null;
            }
            try {
                if (!userAccount.checkPassword(password)) {
                    try {
                        SpObserver.setDBtoInstance("_" + dbid);
                        record.loginRecord(usercode, password, IPUtil.getIpAddr(request));// 记录登录登录失败的信息
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
                    this.print2(response, "用户密码不正确!", request.getParameter("redirect"), isApp);
                    return null;
                }
            } catch (Exception ex) {
                this.print2(response, ex.getMessage(), request.getParameter("redirect"), isApp);
            }
            // 设置权限
            processLoginUserToSession(ip, dbid, session, userAccount);
            callBackMessage.sendSuccessMessage("登录成功");
            this.printJson(response, callBackMessage.toString());
            return null;
        } catch (NullPointerException e) {// 不存在此账号
            e.printStackTrace();
            proccError(usercode, password, request, response);
            return null;
        } catch (RuntimeException e) {
            e.printStackTrace();
            if (e.getMessage().equals(SessionKey.DEMO_REF)) {
                session.setAttribute(SessionKey.DEMO_REF, SessionKey.DEMO_REF);
                this.print(response, "<script>alert('请生成正确配置信息');window.location.href='/demo/demoList.jsp';</script>");
            }
            return null;
        } catch (Exception e) {// 不存在此账号
            e.printStackTrace();
            proccError(usercode, password, request, response);
            return null;
        }
    }
 
    private class AppJsonObject {
        private boolean myResult;
        private HttpServletResponse mResponse;
        private String mUserCode;
        private String mPassword;
        private Boolean mIsApp;
        private String mRedirect;
        private List<Map<String, Object>> mList;
        private boolean mCh_userid;
        private String mDbId;
        private String mDataBaseDis;
        private String mDomain;
        private UserAccountEntity mUserAccount;
 
        public AppJsonObject(HttpServletResponse response, String userCode, String password, Boolean isApp, String redirect, List<Map<String, Object>> list) {
            mResponse = response;
            mUserCode = userCode;
            mPassword = password;
            mIsApp = isApp;
            mRedirect = redirect;
            mList = list;
        }
 
        boolean is() {
            return myResult;
        }
 
        public String getUserCode() {
            return mUserCode;
        }
 
        public String getPassword() {
            return mPassword;
        }
 
        public boolean isCh_userid() {
            return mCh_userid;
        }
 
        public String getDbId() {
            return mDbId;
        }
 
        public String getDataBaseDis() {
            return mDataBaseDis;
        }
 
        public String getDomain() {
            return mDomain;
        }
 
        public UserAccountEntity getUserAccount() {
            return mUserAccount;
        }
 
        public AppJsonObject invoke() {
            Map<String, Object> map = mList.get(0);
            mDbId = map.get("id") + "";
            mDataBaseDis = (String) map.get("systemid");
            mDomain = (String) map.get("domain");
            // 通过数据源id和手机号取得用户usercode进行登录,这时候不需要密码验证
            try {
                SpObserver.setDBtoInstance("_" + mDbId);
                mUserAccount = userAccountService.getUserInfoByTelephone(mUserCode);
                if (mUserAccount != null) {
                    mUserAccount.setApp_userCode(mUserCode);
                    mUserAccount.setApp_Password(mPassword);
                    mUserCode = mUserAccount.getUserCode();//转成ERP的usercode进行登陆
                    mPassword = mUserAccount.getPassword();//转成ERP的密码进行登陆
                    mCh_userid = true;
                } else {
                    print2(mResponse, "该手机号码没有对应用户信息", mRedirect, mIsApp);
                    myResult = true;
                    return this;
                }
            } finally {
                SpObserver.setDBtoInstance();
            }
            myResult = false;
            return this;
        }
    }
}