zhitong.yu
7 天以前 7fc9c42987a13c1d8d2159591a5803e70518827f
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
package com.hxzk.gps.service.impl.Company;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzk.gps.controller.Company.Results.*;
import com.hxzk.gps.controller.System.SystemLogUtil;
import com.hxzk.gps.entity.Company.TbCompany;
import com.hxzk.gps.entity.Department.TbDepartment;
import com.hxzk.gps.entity.Department.TbDepartMentIcon;
import com.hxzk.gps.entity.Map.TbMarsHomeset;
import com.hxzk.gps.entity.Menu.Menu;
import com.hxzk.gps.entity.Person.TbPerson;
import com.hxzk.gps.entity.Role.Rolemenu;
import com.hxzk.gps.entity.ThreeModel.TbThreemodel;
import com.hxzk.gps.entity.User.TbUser;
import com.hxzk.gps.entity.Role.Role;
import com.hxzk.gps.entity.WarnTongJi.WarnTongjiCompany;
import com.hxzk.gps.mapper.Company.TbCompanyMapper;
import com.hxzk.gps.service.Company.TbCompanyService;
import com.hxzk.gps.service.Department.TbDepartmentService;
import com.hxzk.gps.service.Department.TbDepartMentIconService;
import com.hxzk.gps.service.Map.TbMarsHomesetService;
import com.hxzk.gps.service.Menu.MenuService;
import com.hxzk.gps.service.Person.TbPersonService;
import com.hxzk.gps.service.Role.RoleMenuService;
import com.hxzk.gps.service.ThreeModel.TbThreemodelService;
import com.hxzk.gps.service.User.TbUserService;
import com.hxzk.gps.service.Role.IRoleService;
import com.hxzk.gps.service.WarnTongJi.WarnTongjiCompanyService;
import com.hxzk.gps.util.AuToComplete;
import com.hxzk.gps.util.GetUser.UserInfoUtil;
import com.hxzk.gps.util.MessageUtils.MessageUtils;
import com.hxzk.gps.util.Result.ReturnMessage;
import com.hxzk.gps.util.Result.TableDto;
import com.hxzk.gps.util.Time.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 公司服务实现类
 * </p>
 *
 * @author YuZhiTong
 * @since 2025-04-17
 */
@Service
@Slf4j
public class TbCompanyServiceImpl extends ServiceImpl<TbCompanyMapper, TbCompany> implements TbCompanyService {
//
    @Autowired
    TbCompanyMapper companyMapper;
    @Autowired
    TbDepartMentIconService tbDepartMentIconService;
    @Autowired
    TbDepartmentService departmentService;
    @Autowired
    TbPersonService personService;
    @Autowired
    TbUserService userService;
    @Autowired
    IRoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    TbMarsHomesetService marsHomesetService;
    @Autowired
    WarnTongjiCompanyService warnTongjiCompanyService;
    @Autowired
    TbThreemodelService tbThreemodelService;
    @Value("${upload.dir-IP}")
    private String uploadIp;
    @Value("${upload.dir-Map-Three}")
    private String dirMapThree;
    /*
    * 公司列表信息
    * */
    @Override
    public CompanyResult FindCompanyInfo(CompanyTreeTableDto companyTreeTableDto) {
        // 创建查询包装器
        QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
 
        // 处理部门 ID 为空的情况
        if (StringUtils.isEmpty(companyTreeTableDto.getDepartmentId())) {
            List<Long> list = getChildCompanyIds(UserInfoUtil.getUserCompanyId());
            queryWrapper.in("parentid", list);
        } else {
            queryWrapper.eq("parentid", companyTreeTableDto.getDepartmentId());
        }
 
        // 处理公司名称查询条件
        Optional.ofNullable(companyTreeTableDto.getCompanyname()).ifPresent(companyname ->
                queryWrapper.like("companyname", companyname));
 
        // 使用PageHelper进行分页查询
        Page<TbCompany> page = PageHelper.startPage(companyTreeTableDto.getPageNum(), companyTreeTableDto.getPageSize())
                .doSelectPage(() -> baseMapper.selectList(queryWrapper));
 
        // 封装公司列表
        TableDto tableDto = new TableDto(page.getResult(), page.getPageNum(), page.getPageSize(), page.getTotal());
 
        // 获取成功消息
        String message = MessageUtils.getMessage("Success");
 
        // 返回结果 - 需要根据CompanyResult的构造函数调整参数
        return new CompanyResult(200, message, tableDto);
    }
 
    @Override
    public CompanyDepartmentResult FindUserDepartmentCompany() {
        // 获取当前登录公司
        TbCompany currentCompany = getCurrentCompany();
        if (currentCompany == null) {
            return new CompanyDepartmentResult(404, new ArrayList<>(), "未找到公司");
        }
 
        // 获取所有相关公司
        List<TbCompany> allCompanies = getAllRelatedCompanies(currentCompany);
        // 构建子项列表
        List<ChildItem> childItems = buildChildItems(allCompanies, currentCompany.getId());
        // 构建数据项
        DataItem dataItem = buildDataItem(currentCompany, childItems);
        // 构建最终结果
        List<DataItem> dataItems = new ArrayList<>();
        dataItems.add(dataItem);
        return new CompanyDepartmentResult(200, dataItems, "查询成功");
    }
    private List<ChildItem> buildChildItems(List<TbCompany> allCompanies, int parentId) {
        List<ChildItem> childItems = new ArrayList<>();
        for (TbCompany company : allCompanies) {
            if (company.getParentid() == parentId) {
                // 递归获取子公司列表
                List<ChildItem> children = buildChildItems(allCompanies, company.getId());
                // 创建 ChildItem 对象并正确赋值子列表
                childItems.add(new ChildItem(String.valueOf(company.getId()), company.getCompanyname(),company.getLogo(),children));
            }
        }
        return childItems;
    }
    private DataItem buildDataItem(TbCompany currentCompany, List<ChildItem> childItems) {
        return new DataItem(String.valueOf(currentCompany.getId()), UserInfoUtil.getUserCompany(),currentCompany.getLogo(), childItems);
    }
    //获取递归子公司的ID
    @Override
    public List getChildCompanyIds(String companyid) {
        QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", companyid);
        TbCompany company = baseMapper.selectOne(queryWrapper);
        List<TbCompany> allCompanies = getAllRelatedCompanies(company);
        List list = new ArrayList<>();
        for (TbCompany tbCompany : allCompanies) {
            list.add(tbCompany.getId());
        }
        return list;
    }
    @Override
    public List getChildCompanyNames(String companyname) {
        QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("companyname", companyname);
        TbCompany company = baseMapper.selectOne(queryWrapper);
        List<TbCompany> allCompanies = getAllRelatedCompanies(company);
        List list = new ArrayList<>();
        for (TbCompany tbCompany : allCompanies) {
            list.add(tbCompany.getCompanyname());
        }
        return list;
    }
    /*
    * 根据参数ID查询公司名称
    * @return 返回公司名称
    * @author YuZhiTong
    * @since 2025-05-19
    * */
    @Override
    public String getChildCompanyName(String id) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        return baseMapper.selectOne(queryWrapper).getCompanyname();
    }
 
 
    /*
    * 公司下拉列表
    * @param company 公司信息
    * @return 公司下拉列表
    * @author YuZhiTong
    * @since 2025-05-19
    * */
    @Override
    public List<AuToComplete> CompanyAutocomplete(TbCompany company) {
        List<Long> list = getChildCompanyIds(String.valueOf(Optional.ofNullable(company.getId()).orElse(Integer.valueOf(UserInfoUtil.getUserCompanyId()))));
        QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
 
        queryWrapper.in("parentid", list).or().eq("id",Optional.ofNullable(company.getId()).orElse(Integer.valueOf(UserInfoUtil.getUserCompanyId())));
 
        List<TbCompany> companyList = baseMapper.selectList(queryWrapper);
        List<AuToComplete> addCustomerList = companyList.stream()
                .map(companys -> {
                    AuToComplete addCustomer = new AuToComplete();
                    addCustomer.setValue(companys.getCompanyname());
                    addCustomer.setLink(String.valueOf(companys.getId()));
                    return addCustomer;
                })
                .collect(Collectors.toList());
 
        return addCustomerList;
    }
 
    @Override
    public List<AuToComplete> FenceCompanyAutocomplete() {
        List<Long> list = getChildCompanyIds(UserInfoUtil.getUserCompanyId());
        QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
 
        queryWrapper.in("parentid", list).or().eq("id",UserInfoUtil.getUserCompanyId());
 
        List<TbCompany> companyList = baseMapper.selectList(queryWrapper);
        List<AuToComplete> addCustomerList = companyList.stream()
                .map(companys -> {
                    AuToComplete addCustomer = new AuToComplete();
                    addCustomer.setValue(companys.getCompanyname());
                    addCustomer.setLink(String.valueOf(companys.getId()));
                    return addCustomer;
                })
                .collect(Collectors.toList());
 
        return addCustomerList;
    }
 
    @Override
    @Transactional
    public ReturnMessage add(TbCompany company) {
        boolean isSuccess = false;
        try {
            // 检查公司是否已存在
            if (isCompanyExist(company)) {
                return ReturnMessage.ReturnMessageError("CompanyRepeat");
            }
 
            // 设置公司基本信息
            setCompanyBasicInfo(company);
            baseMapper.insert(company);
 
            // 获取新创建的公司信息
            TbCompany companyMars = getNewCreatedCompany(company.getCompanyname());
 
            // 初始化相关配置
            initCompanyConfigurations(company, companyMars);
            // 初始化默认角色
            initCompanyRoles(companyMars);
            // 初始化部门和图标
            initDepartmentsAndIcons(company, companyMars);
//            initThreeModel(companyMars);
 
            isSuccess = true;
        } catch (Exception e) {
            log.error("新增公司失败: {}", e);
            throw new RuntimeException("新增公司失败", e);
        }
        return SystemLogUtil.handleAddResult(isSuccess, "CompanyAdd", company.getCompanyname());
    }
 
    @Override
    public ReturnMessage update(TbCompany company) {
         /*
        声明操作状态
        * */
        boolean isSuccess = false;
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",company.getId());
        try {
            company.setAddtime(TimeUtil.GetTime());
            baseMapper.update(company,queryWrapper);
            isSuccess = true;
        }catch (Exception e){
 
        }
        return SystemLogUtil.handleUpdateResult(isSuccess,"CompanyUpdate",company.getCompanyname());
    }
 
    @Override
    @Transactional
    public ReturnMessage delete(TbCompany company) {
        try {
            // 先检查公司是否可以删除
            ReturnMessage checkResult = checkCompanyCanDelete(company.getId());
            if (!checkResult.getCode().equals(200)) {
                return checkResult;
            }
 
            // 执行删除操作
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", company.getId());
            boolean isSuccess = baseMapper.delete(queryWrapper) > 0;
            
            if (isSuccess) {
                // 删除成功,记录日志
                return SystemLogUtil.handleDeleteResult(true, "CompanyDelete", company.getCompanyname());
            } else {
                return ReturnMessage.ReturnMessageError("CompanyDeleteFailed");
            }
        } catch (Exception e) {
            log.error("删除公司失败: {}", e.getMessage(), e);
            return ReturnMessage.ReturnMessageError("CompanyDeleteException");
        }
    }
 
    @Override
    public ReturnMessage checkCompanyCanDelete(Integer companyId) {
        try {
            // 创建绑定数据汇总对象
            CompanyDeleteCheckResult.BindingDataSummary bindingData = new CompanyDeleteCheckResult.BindingDataSummary();
            
            // 检查是否存在子部门
            QueryWrapper<TbDepartment> deptQuery = new QueryWrapper<>();
            deptQuery.eq("companyid", companyId);
            Long deptCount = departmentService.getBaseMapper().selectCount(deptQuery);
            bindingData.setDepartmentCount(deptCount);
            
            // 检查是否存在人员
            QueryWrapper<TbPerson> personQuery = new QueryWrapper<>();
            personQuery.eq("companyid", companyId);
            Long personCount = personService.getBaseMapper().selectCount(personQuery);
            bindingData.setPersonCount(personCount);
            
            // 检查是否存在用户
            QueryWrapper<TbUser> userQuery = new QueryWrapper<>();
            userQuery.eq("companyid", companyId);
            Long userCount = userService.getBaseMapper().selectCount(userQuery);
            bindingData.setUserCount(userCount);
            
            // 检查是否存在角色
            QueryWrapper<Role> roleQuery = new QueryWrapper<>();
            roleQuery.eq("companyid", companyId);
            Long roleCount = roleService.getBaseMapper().selectCount(roleQuery);
            bindingData.setRoleCount(roleCount);
            
            // 检查是否存在部门图标
            QueryWrapper<TbDepartMentIcon> iconQuery = new QueryWrapper<>();
            iconQuery.eq("companyid", companyId);
            Long iconCount = tbDepartMentIconService.getBaseMapper().selectCount(iconQuery);
            bindingData.setIconCount(iconCount);
            
            // 检查是否存在车辆(如果有车辆服务)
            try {
                QueryWrapper<Object> carQuery = new QueryWrapper<>();
                carQuery.eq("companyid", companyId);
                // 这里需要根据实际的车辆实体类来查询
                bindingData.setCarCount(0L);
            } catch (Exception e) {
                bindingData.setCarCount(0L);
            }
            
            // 检查是否存在物资(如果有物资服务)
            try {
                QueryWrapper<Object> materialQuery = new QueryWrapper<>();
                materialQuery.eq("companyid", companyId);
                // 这里需要根据实际的物资实体类来查询
                bindingData.setMaterialCount(0L);
            } catch (Exception e) {
                bindingData.setMaterialCount(0L);
            }
            
            // 检查是否存在地图
            try {
                QueryWrapper<Object> mapQuery = new QueryWrapper<>();
                mapQuery.eq("companyid", companyId);
                // 这里需要根据实际的地图实体类来查询
                bindingData.setMapCount(0L);
            } catch (Exception e) {
                bindingData.setMapCount(0L);
            }
            
            // 检查是否存在警告统计
            try {
                QueryWrapper<Object> warningQuery = new QueryWrapper<>();
                warningQuery.eq("companyid", companyId);
                // 这里需要根据实际的警告统计实体类来查询
                bindingData.setWarningCount(0L);
            } catch (Exception e) {
                bindingData.setWarningCount(0L);
            }
            
            // 判断是否可以删除
            if (bindingData.hasAnyBindingData()) {
                // 有绑定数据,无法删除
                // 将绑定数据信息放在data字段中,使用标准的错误消息码
                CompanyDeleteCheckResult result = new CompanyDeleteCheckResult(false, "CompanyHasBindingData", bindingData);
                // 创建一个自定义的ReturnMessage,包含绑定数据
                ReturnMessage returnMessage = new ReturnMessage(500, MessageUtils.getMessage("CompanyHasBindingData"));
                // 这里我们需要扩展ReturnMessage来支持data字段,或者使用其他方式
                // 暂时使用字符串拼接的方式,但避免作为消息码
                String bindingInfo = String.format("部门(%d),人员(%d),用户(%d),角色(%d),图标(%d),车辆(%d),物资(%d),地图(%d),警告(%d)",
                    bindingData.getDepartmentCount(), bindingData.getPersonCount(), bindingData.getUserCount(),
                    bindingData.getRoleCount(), bindingData.getIconCount(), bindingData.getCarCount(),
                    bindingData.getMaterialCount(), bindingData.getMapCount(), bindingData.getWarningCount());
                
                // 使用自定义的返回方式,避免国际化消息查找错误
                return new ReturnMessage(200, "CompanyHasBindingData:" + bindingInfo);
            } else {
                // 没有绑定数据,可以删除
                return ReturnMessage.ReturnMessageSuccess("CompanyCanDelete");
            }
            
        } catch (Exception e) {
            log.error("检查公司删除条件失败,公司ID: {}, 错误: {}", companyId, e.getMessage(), e);
            return ReturnMessage.ReturnMessageError("CheckCompanyDeleteFailed");
        }
    }
 
    @Override
    public Integer FindCompanyOnlineCount(List companyid) {
        return companyMapper.FindCompanyOnlineCount(companyid);
    }
 
    @Override
    public Integer FindCompanyNoOnlineCount(List companyid) {
        return companyMapper.FindCompanyNoOnlineCount(companyid);
    }
 
    @Override
    public Integer FindCompanyOnlineCarCount(List companyid) {
        return companyMapper.FindCompanyOnlineCarCount(companyid);
    }
 
    @Override
    public Integer FindCompanyNoOnlineCarCount(List companyid) {
        return companyMapper.FindCompanyNoOnlineCarCount(companyid);
    }
 
    @Override
    public Integer FindCompanyOnlineAchorCount(String company) {
        return companyMapper.FindCompanyOnlineAchorCount(company);
    }
 
    @Override
    public Integer FindCompanyNoOnlineAchorCount(String company) {
        return companyMapper.FindCompanyNoOnlineAchorCount(company);
    }
 
    @Override
    public Integer FindCompanyWarningCount1(List companyid) {
        return companyMapper.FindCompanyWarningCount1(companyid);
    }
 
    @Override
    public Integer FindCompanyWarningCount2(List companyids) {
        return companyMapper.FindCompanyWarningCount2(companyids);
    }
 
    @Override
    public Integer FindCompanyWarningCount3(List companyids) {
        return companyMapper.FindCompanyWarningCount3(companyids);
    }
 
    @Override
    public Integer FindCompanyWarningCount4(List companyids) {
        return companyMapper.FindCompanyWarningCount4(companyids);
    }
 
    @Override
    public Integer FindCompanyWarningCount5(List companyids) {
        return companyMapper.FindCompanyWarningCount5(companyids);
    }
 
    @Override
    public Integer FindCompanyWarningCount6(List companyids) {
        return companyMapper.FindCompanyWarningCount6(companyids);
    }
 
    @Override
    public Integer FindCompanyWarningCount7(List companyids) {
        return companyMapper.FindCompanyWarningCount7(companyids);
    }
 
    @Override
    public Integer FindCompanyWarningCount8(List companyids) {
        return companyMapper.FindCompanyWarningCount8(companyids);
    }
 
    @Override
    public Integer FindCompanyWarningCount9(List companyids) {
        return companyMapper.FindCompanyWarningCount9(companyids);
    }
 
 
    @Override
    public List<WarnTongjiCompany> findCompanyWarn(String company) {
        return companyMapper.findCompanyWarn(company);
    }
 
    @Override
    public Integer UpCompanyWarnCount(String company, Integer count, String title) {
        return companyMapper.UpCompanyWarnCount(company, count, title);
    }
 
 
    // 获取当前公司
    private TbCompany getCurrentCompany() {
        try {
            String companyId = UserInfoUtil.getUserCompanyId();
            if (companyId == null || companyId.isEmpty()) {
                return null;
            }
            return baseMapper.selectById(companyId);
        } catch (Exception e) {
            log.error("获取当前公司失败: {}", e.getMessage(), e);
            return null;
        }
    }
 
    // 获取所有相关公司
    private List<TbCompany> getAllRelatedCompanies(TbCompany company) {
        if (company == null) {
            return new ArrayList<>();
        }
        
        List<TbCompany> allCompanies = new ArrayList<>();
        allCompanies.add(company);
        
        // 递归获取子公司
        getAllChildCompanies(company.getId(), allCompanies);
        
        return allCompanies;
    }
 
    // 递归获取子公司
    private void getAllChildCompanies(Integer parentId, List<TbCompany> allCompanies) {
        try {
            QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parentid", parentId);
            List<TbCompany> childCompanies = baseMapper.selectList(queryWrapper);
            
            for (TbCompany childCompany : childCompanies) {
                allCompanies.add(childCompany);
                // 递归获取子公司的子公司
                getAllChildCompanies(childCompany.getId(), allCompanies);
            }
        } catch (Exception e) {
            log.error("获取子公司失败: {}", e.getMessage(), e);
        }
    }
 
    private boolean isCompanyExist(TbCompany company) {
        QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("companyname", company.getCompanyname())
                .eq("parentid", UserInfoUtil.getUserCompanyId());
        return baseMapper.selectCount(queryWrapper) > 0;
    }
 
    private void setCompanyBasicInfo(TbCompany company) {
        company.setParentid(Integer.parseInt(UserInfoUtil.getUserCompanyId()));
        company.setAddusername(UserInfoUtil.getUserName());
        company.setAddtime(TimeUtil.GetTime());
    }
 
    private TbCompany getNewCreatedCompany(String companyName) {
        QueryWrapper<TbCompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("companyname", companyName);
        return baseMapper.selectOne(queryWrapper);
    }
 
    private void initCompanyConfigurations(TbCompany company, TbCompany companyMars) {
        marsHomesetService.InsertMarsHomeSet(company.getCompanyname(), String.valueOf(companyMars.getId()));
        warnTongjiCompanyService.InsertWarnTongJi(companyMars.getCompanyname());
    }
 
    private void initDepartmentsAndIcons(TbCompany company, TbCompany companyMars) {
        String[] departmentNames = new String[] {
                MessageUtils.getMessage("AllDepartments"),
                MessageUtils.getMessage("TechnicalDepartment"),
                MessageUtils.getMessage("ProductionDepartment"),
                MessageUtils.getMessage("SecurityDepartment"),
                MessageUtils.getMessage("MaintenanceDepartment"),
                MessageUtils.getMessage("RnDDepartment")
        };
 
        for (int i = 0; i < departmentNames.length; i++) {
            createDepartmentIcon(company, companyMars, i);
            createDepartment(company, companyMars, departmentNames[i],i);
        }
    }
 
    private void initThreeModel(TbCompany companyMars) {
        TbThreemodel tbThreemodel = new TbThreemodel();
        tbThreemodel.setCompanyid(String.valueOf(companyMars.getId()));
        tbThreemodel.setCompany(companyMars.getCompanyname());
        tbThreemodel.setAddtime(TimeUtil.GetTime());
        tbThreemodel.setLat("0");
        tbThreemodel.setLng("0");
        tbThreemodel.setAlt("0");
        tbThreemodel.setFilename(companyMars.getCompanyname()+"_"+MessageUtils.getMessage("XiTongMoRen"));
        String FileAdress = dirMapThree+tbThreemodel.getFilename();
 
        // 创建文件夹
        File folder = new File(FileAdress);
        if (!folder.exists()) {
            folder.mkdirs();
        }
 
        tbThreemodelService.getBaseMapper().insert(tbThreemodel);
    }
 
    private void createDepartmentIcon(TbCompany company, TbCompany companyMars, int index) {
        TbDepartMentIcon icon = new TbDepartMentIcon();
        icon.setCompanyid(String.valueOf(companyMars.getId()));
        icon.setCompany(company.getCompanyname());
        icon.setUsername(UserInfoUtil.getUserName());
        icon.setAddtime(TimeUtil.GetTime());
        icon.setIconname(MessageUtils.getMessage("Icon") + (index + 1));
        icon.setIconadress(uploadIp + "Department/department" + (index + 1) + ".png");
        tbDepartMentIconService.getBaseMapper().insert(icon);
    }
 
    private void createDepartment(TbCompany company, TbCompany companyMars, String departmentName,int index) {
        TbDepartment department = new TbDepartment();
        department.setCompanyid(String.valueOf(companyMars.getId()));
        department.setCompany(company.getCompanyname());
        department.setDepartmentname(departmentName);
        department.setAddtime(TimeUtil.GetTime());
        department.setBaoliu3(uploadIp + "Department/department" + (index + 1) + ".png");
        departmentService.getBaseMapper().insert(department);
    }
 
    /**
     * 初始化公司基础角色
     * @param company 公司信息
     */
    private void initCompanyRoles(TbCompany company) {
        try {
            // 1. 创建超级管理员角色
            Role superAdminRole = new Role();
            superAdminRole.setName(MessageUtils.getMessage("Admin"));
            superAdminRole.setAddrole(true);
            superAdminRole.setEditrole(true);
            superAdminRole.setDeleterole(true);
            superAdminRole.setUsername(MessageUtils.getMessage("XiTongMoRen"));
            superAdminRole.setAddtime(TimeUtil.GetTime());
            superAdminRole.setCompanyname(company.getCompanyname());
            superAdminRole.setCompanyid(String.valueOf(company.getId()));
            roleService.save(superAdminRole);
            initCompanyUserRoleMenu(company.getCompanyname(),MessageUtils.getMessage("Admin"));
            // 2. 创建普通管理员角色
            Role staffRole = new Role();
            staffRole.setName(MessageUtils.getMessage("PuAdmin"));
            staffRole.setAddrole(true);
            staffRole.setEditrole(true);
            staffRole.setDeleterole(false);
            staffRole.setUsername(MessageUtils.getMessage("XiTongMoRen"));
            staffRole.setAddtime(TimeUtil.GetTime());
            staffRole.setCompanyname(company.getCompanyname());
            staffRole.setCompanyid(String.valueOf(company.getId()));
            roleService.save(staffRole);
            initCompanyUserRoleMenu(company.getCompanyname(),MessageUtils.getMessage("PuAdmin"));
            // 3. 创建访客角色
            Role guestRole = new Role();
            guestRole.setName(MessageUtils.getMessage("FangKe"));
            guestRole.setAddrole(false);
            guestRole.setEditrole(false);
            guestRole.setDeleterole(false);
            guestRole.setUsername(MessageUtils.getMessage("XiTongMoRen"));
            guestRole.setAddtime(TimeUtil.GetTime());
            guestRole.setCompanyname(company.getCompanyname());
            guestRole.setCompanyid(String.valueOf(company.getId()));
            roleService.save(guestRole);
            initCompanyUserRoleMenu(company.getCompanyname(),MessageUtils.getMessage("FangKe"));
            log.info("公司[{}]基础角色初始化成功", company.getCompanyname());
        } catch (Exception e) {
            log.error("初始化公司角色失败: {}", e.getMessage(), e);
            throw new RuntimeException("初始化公司角色失败", e);
        }
    }
    /**
     * 初始化公司角色基础导航权限
     * @param company 公司角色基础导航权限
     */
    private void initCompanyUserRoleMenu(String companyName,String roleName) {
        try {
            Role role = roleService.getBaseMapper().selectOne(new QueryWrapper<Role>().eq("name", roleName).eq("companyname",companyName));
            List<Menu> menus = new ArrayList<>();
            if (roleName.equals(MessageUtils.getMessage("Admin"))){
                QueryWrapper queryWrapper = new QueryWrapper<>();
                menus = menuService.getBaseMapper().selectList(queryWrapper);
            }
            if (roleName.equals(MessageUtils.getMessage("PuAdmin"))){
                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.ne("rolename","超级管理员");
                menus = menuService.getBaseMapper().selectList(queryWrapper);
            }
            if (roleName.equals(MessageUtils.getMessage("FangKe"))){
                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.ne("rolename","超级管理员");
                menus = menuService.getBaseMapper().selectList(queryWrapper);
            }
            for (Menu menu : menus) {
                Rolemenu rolemenu = new Rolemenu();
                rolemenu.setRoleId(role.getId());
                rolemenu.setMenuId(menu.getId());
                roleMenuService.save(rolemenu);
            }
        } catch (Exception e) {
            log.error("初始化公司角色基础导航权限失败: {}", e.getMessage(), e);
            throw new RuntimeException("初始化公司角色基础导航权限失败", e);
        }
    }
}