liujie
2025-12-09 af17b0f5142f5b4a5c1c40cd0db814cacca6ceaf
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
package com.ruoyi.web.controller.api;
 
 
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.basic.PageInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.WebUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.dto.BranchAuditDTO;
import com.ruoyi.system.dto.TCrmBranchDTO;
import com.ruoyi.system.dto.UnbindDTO;
import com.ruoyi.system.dto.UnbindProcessingDTO;
import com.ruoyi.system.export.TCrmBranchAuditExport;
import com.ruoyi.system.export.TCrmBranchExport;
import com.ruoyi.system.export.TSysAppUserClinicExport;
import com.ruoyi.system.export.TSysAppUserExport;
import com.ruoyi.system.model.*;
import com.ruoyi.system.query.TCrmBranchAuditQuery;
import com.ruoyi.system.query.TCrmBranchQuery;
import com.ruoyi.system.query.TSysAppUserQuery;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.TCrmBranchLiftVO;
import com.ruoyi.system.vo.TCrmBranchVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * crm分公司管理 前端控制器
 * </p>
 *
 * @author xiaochen
 * @since 2025-08-20
 */
@Api(tags = "crm分公司管理")
@RestController
@RequestMapping("/t-crm-branch")
public class TCrmBranchController {
 
    private final TCrmBranchService crmBranchService;
    private final TCrmBranchAreaService crmBranchAreaService;
    private final TCrmBranchSalaryService crmBranchSalaryService;
    private final ISysUserService sysUserService;
    private final TCrmChangePointsService crmChangePointsService;
    private final TCrmPositionService crmPositionService;
    private final TCrmSalespersonService crmSalespersonService;
    private final TCrmBranchLiftService crmBranchLiftService;
    private final TRegionService regionService;
    private final TokenService tokenService;
    @Autowired
    public TCrmBranchController(TCrmBranchService crmBranchService, TCrmBranchAreaService crmBranchAreaService, TCrmBranchSalaryService crmBranchSalaryService, ISysUserService sysUserService, TCrmChangePointsService crmChangePointsService, TCrmPositionService crmPositionService, TCrmSalespersonService crmSalespersonService, TCrmBranchLiftService crmBranchLiftService, TRegionService regionService, TokenService tokenService) {
        this.crmBranchService = crmBranchService;
        this.crmBranchAreaService = crmBranchAreaService;
        this.crmBranchSalaryService = crmBranchSalaryService;
        this.sysUserService = sysUserService;
        this.crmChangePointsService = crmChangePointsService;
        this.crmPositionService = crmPositionService;
        this.crmSalespersonService = crmSalespersonService;
        this.crmBranchLiftService = crmBranchLiftService;
        this.regionService = regionService;
        this.tokenService = tokenService;
    }
 
    /**
     * 获取crm分公司管理管理列表
     */
    @ApiOperation(value = "获取crm分公司管理分页列表")
    @PostMapping(value = "/pageList")
    public R<PageInfo<TCrmBranchVO>> pageList(@RequestBody TCrmBranchQuery query) {
        Integer roleType = tokenService.getLoginUser().getUser().getRoleType();
        Long userId = tokenService.getLoginUser().getUserId();
        query.setRoleType(roleType);
        query.setUserId(userId);
        return R.ok(crmBranchService.pageList(query));
    }
 
    /**
     * 获取crm分公司管理管理列表
     */
    @ApiOperation(value = "获取crm分公司审核分页列表")
    @PostMapping(value = "/pageAuditList")
    public R<PageInfo<TCrmBranchVO>> pageAuditList(@RequestBody TCrmBranchAuditQuery query) {
        return R.ok(crmBranchService.pageAuditList(query));
    }
 
    /**
     * 获取crm分公司管理管理列表
     */
    @ApiOperation(value = "获取crm分公司解除绑定分页列表")
    @PostMapping(value = "/pageUnbindList")
    public R<PageInfo<TCrmBranchLiftVO>> pageUnbindList(@RequestBody TCrmBranchAuditQuery query) {
        return R.ok(crmBranchService.pageUnbindList(query));
    }
 
    /**
     * 获取crm分公司管理管理列表
     */
    @ApiOperation(value = "获取crm分公司省公司,地区经理管理列表")
    @GetMapping(value = "/listProvince")
    public R<List<TCrmBranch>> listProvince(@RequestParam Integer personType) {
        List<TCrmBranch> crmBranches = crmBranchService.list(Wrappers.lambdaQuery(TCrmBranch.class)
                .eq(TCrmBranch::getPersonType, personType)
                .eq(TCrmBranch::getStatus, 1)
                .orderByDesc(TCrmBranch::getCreateTime));
        return R.ok(crmBranches);
    }
 
    /**
     * 获取crm分公司管理管理列表
     */
    @ApiOperation(value = "获取crm分公司地区经理,城市经理管理列表")
    @GetMapping(value = "/listCity")
    public R<List<TCrmBranch>> listCity() {
        Long userId = tokenService.getLoginUser().getUserId();
        TCrmBranch crmBranch = crmBranchService.getOne(Wrappers.lambdaQuery(TCrmBranch.class)
                .eq(TCrmBranch::getUserId, userId)
                .eq(TCrmBranch::getStatus, 1)
                .last("LIMIT 1"));
        if(Objects.isNull(crmBranch)){
            return R.ok(new ArrayList<>());
        }
        if(crmBranch.getPersonType() == 1){
            List<TCrmBranch> crmBranches = crmBranchService.list(Wrappers.lambdaQuery(TCrmBranch.class)
                    .eq(TCrmBranch::getProvinceBranchId, crmBranch.getId())
                    .eq(TCrmBranch::getStatus, 1)
                    .orderByDesc(TCrmBranch::getCreateTime));
            crmBranches.add(crmBranch);
            return R.ok(crmBranches);
        }
        if(crmBranch.getPersonType() == 2){
            List<TCrmBranch> crmBranches = crmBranchService.list(Wrappers.lambdaQuery(TCrmBranch.class)
                    .eq(TCrmBranch::getCorrelationPersonId, userId)
                    .eq(TCrmBranch::getStatus, 1)
                    .orderByDesc(TCrmBranch::getCreateTime));
            crmBranches.add(crmBranch);
            return R.ok(crmBranches);
        }
        return R.ok();
    }
 
    /**
     * 获取crm分公司管理管理列表
     */
    @ApiOperation(value = "获取crm分公司管理列表")
    @PostMapping(value = "/list")
    public R<List<TCrmBranch>> list() {
        Integer roleType = tokenService.getLoginUser().getUser().getRoleType();
        Long userId = tokenService.getLoginUser().getUserId();
        LambdaQueryWrapper<TCrmBranch> wrapper = new LambdaQueryWrapper<>();
        if (roleType == 2) {
            wrapper.eq(TCrmBranch::getUserId, userId);
        }
        if(roleType == 3){
            // 查询业务员信息
            TCrmSalesperson crmSalesperson = crmSalespersonService.getOne(Wrappers.lambdaQuery(TCrmSalesperson.class)
                    .eq(TCrmSalesperson::getUserId, userId)
                    .last("LIMIT 1"));
            if(Objects.nonNull(crmSalesperson)){
                wrapper.eq(TCrmBranch::getId, crmSalesperson.getBranchId());
            }
        }
        wrapper.eq(TCrmBranch::getStatus,1)
                .eq(TCrmBranch::getAuditStatus,2)
                .orderByDesc(TCrmBranch::getCreateTime);
        return R.ok(crmBranchService.list(wrapper));
    }
 
    /**
     * 添加crm分公司管理管理
     */
    @Log(title = "crm分公司管理信息-新增crm分公司管理", businessType = BusinessType.INSERT)
    @ApiOperation(value = "添加crm分公司管理")
    @PostMapping(value = "/add")
    public R<Boolean> add(@Validated @RequestBody TCrmBranchDTO dto) {
        Integer roleType = tokenService.getLoginUser().getUser().getRoleType();
        if (roleType == 2) {
            dto.setAuditStatus(1);
        }
        if (roleType == 1) {
            dto.setAuditStatus(2);
        }
        return crmBranchService.addBranch(dto);
    }
 
    /**
     * 修改crm分公司管理
     */
    @Log(title = "crm分公司管理信息-修改crm分公司管理", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改crm分公司管理")
    @PostMapping(value = "/update")
    public R<Boolean> update(@Validated @RequestBody TCrmBranchDTO dto) {
        return crmBranchService.updateBranch(dto);
    }
 
    /**
     * 查看crm分公司管理详情
     */
    @ApiOperation(value = "查看crm分公司管理详情")
    @GetMapping(value = "/getDetailById")
    public R<TCrmBranchVO> getDetailById(@RequestParam String id) {
        TCrmBranch crmBranch = crmBranchService.getById(id);
        TCrmBranchVO crmBranchVO = new TCrmBranchVO();
        BeanUtils.copyProperties(crmBranch, crmBranchVO);
        // 查询负责区域
        List<TCrmBranchArea> crmBranchAreas = crmBranchAreaService.list(Wrappers.lambdaQuery(TCrmBranchArea.class)
                .eq(TCrmBranchArea::getAreaType, 1)
                .eq(TCrmBranchArea::getBranchId, id));
        crmBranchVO.setCrmBranchAreas(crmBranchAreas);
        // 查询管辖区域
        List<TCrmBranchArea> jurisdictionBranchAreas = crmBranchAreaService.list(Wrappers.lambdaQuery(TCrmBranchArea.class)
                .eq(TCrmBranchArea::getAreaType, 2)
                .eq(TCrmBranchArea::getBranchId, id));
        crmBranchVO.setJurisdictionBranchAreas(jurisdictionBranchAreas);
        // 职位薪资
        List<TCrmPosition> crmPositions = crmPositionService.list();
        List<TCrmBranchSalary> crmBranchSalaries = crmBranchSalaryService.list(Wrappers.lambdaQuery(TCrmBranchSalary.class).eq(TCrmBranchSalary::getBranchId, id));
        for (TCrmBranchSalary crmBranchSalary : crmBranchSalaries) {
            crmPositions.stream().filter(crmPosition -> Objects.equals(crmPosition.getId(), crmBranchSalary.getPositionId())).findFirst().ifPresent(crmPosition -> crmBranchSalary.setPositionName(crmPosition.getPositionName()));
        }
        crmBranchVO.setCrmBranchSalaries(crmBranchSalaries);
        return R.ok(crmBranchVO);
    }
 
    /**
     * 查看crm分公司管理详情
     */
    @ApiOperation(value = "查看crm分公司解绑详情")
    @GetMapping(value = "/getDetailUnbindById")
    public R<TCrmBranchLiftVO> getDetailUnbindById(@RequestParam String id) {
 
        TCrmBranchLift crmBranchLift = crmBranchLiftService.getById(id);
 
        if(Objects.isNull(crmBranchLift)){
            return R.fail("未找到该解绑信息");
        }
 
        TCrmBranchLiftVO crmBranchLiftVO = new TCrmBranchLiftVO();
        BeanUtils.copyProperties(crmBranchLift, crmBranchLiftVO);
 
        TCrmBranch crmBranch = crmBranchService.getById(crmBranchLift.getBranchId());
        TCrmBranchVO crmBranchVO = new TCrmBranchVO();
        BeanUtils.copyProperties(crmBranch, crmBranchVO);
        // 查询负责区域
        List<TCrmBranchArea> crmBranchAreas = crmBranchAreaService.list(Wrappers.lambdaQuery(TCrmBranchArea.class)
                .eq(TCrmBranchArea::getAreaType, 1)
                .eq(TCrmBranchArea::getBranchId, crmBranchLift.getBranchId()));
        crmBranchVO.setCrmBranchAreas(crmBranchAreas);
        // 查询管辖区域
        List<TCrmBranchArea> jurisdictionBranchAreas = crmBranchAreaService.list(Wrappers.lambdaQuery(TCrmBranchArea.class)
                .eq(TCrmBranchArea::getAreaType, 2)
                .eq(TCrmBranchArea::getBranchId, crmBranchLift.getBranchId()));
        crmBranchVO.setJurisdictionBranchAreas(jurisdictionBranchAreas);
        // 职位薪资
        List<TCrmPosition> crmPositions = crmPositionService.list();
        List<TCrmBranchSalary> crmBranchSalaries = crmBranchSalaryService.list(Wrappers.lambdaQuery(TCrmBranchSalary.class).eq(TCrmBranchSalary::getBranchId, id));
        for (TCrmBranchSalary crmBranchSalary : crmBranchSalaries) {
            crmPositions.stream().filter(crmPosition -> Objects.equals(crmPosition.getId(), crmBranchSalary.getPositionId())).findFirst().ifPresent(crmPosition -> crmBranchSalary.setPositionName(crmPosition.getPositionName()));
        }
        crmBranchVO.setCrmBranchSalaries(crmBranchSalaries);
 
        crmBranchLiftVO.setCrmBranchVO(crmBranchVO);
 
        return R.ok(crmBranchLiftVO);
    }
 
    /**
     * 删除crm分公司管理
     */
    @Log(title = "crm分公司管理信息-删除crm分公司管理", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除crm分公司管理")
    @DeleteMapping(value = "/deleteById")
    public R<Boolean> deleteById(@RequestParam String id) {
        // 删除区域
        crmBranchAreaService.remove(Wrappers.lambdaQuery(TCrmBranchArea.class).eq(TCrmBranchArea::getBranchId, id));
        // 删除职位薪资
        crmBranchSalaryService.remove(Wrappers.lambdaQuery(TCrmBranchSalary.class).eq(TCrmBranchSalary::getBranchId, id));
        // 删除账号
        TCrmBranch crmBranch = crmBranchService.getById(id);
        sysUserService.deleteUserById(crmBranch.getUserId());
        return R.ok(crmBranchService.removeById(id));
    }
 
    /**
     * 批量删除crm分公司管理
     */
    @Log(title = "crm分公司管理信息-删除crm分公司管理", businessType = BusinessType.DELETE)
    @ApiOperation(value = "批量删除crm分公司管理")
    @DeleteMapping(value = "/deleteByIds")
    public R<Boolean> deleteByIds(@RequestBody List<String> ids) {
        // 删除区域
        crmBranchAreaService.remove(Wrappers.lambdaQuery(TCrmBranchArea.class).in(TCrmBranchArea::getBranchId, ids));
        // 删除职位薪资
        crmBranchSalaryService.remove(Wrappers.lambdaQuery(TCrmBranchSalary.class).in(TCrmBranchSalary::getBranchId, ids));
        // 删除账号
        List<TCrmBranch> crmBranchList = crmBranchService.list(Wrappers.lambdaQuery(TCrmBranch.class).in(TCrmBranch::getId, ids));
        List<Long> userIds = crmBranchList.stream().map(TCrmBranch::getUserId).collect(Collectors.toList());
        sysUserService.deleteUserByIds(userIds);
        return R.ok(crmBranchService.removeByIds(ids));
    }
 
    /**
     * 批量删除crm分公司管理
     */
    @Log(title = "crm分公司管理信息-分公司管理解冻冻结", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "分公司管理解冻冻结",notes = "状态 1=使用中 2=冻结")
    @PutMapping(value = "/thawOrFreeze")
    public R<Boolean> thawOrFreeze(@RequestParam(value = "id")String id,
                                   @RequestParam(value = "status")Integer status) {
        TCrmBranch crmBranch = crmBranchService.getById(id);
        crmBranch.setStatus(status);
        crmBranchService.updateById(crmBranch);
        // 查询用户
        SysUser sysUser = sysUserService.selectUserById(crmBranch.getUserId());
        // 查询业务员
        List<TCrmSalesperson> crmSalespersons = crmSalespersonService.list(Wrappers.lambdaQuery(TCrmSalesperson.class)
                .eq(TCrmSalesperson::getBranchId, id));
        switch (status){
            case 1:
                // 解冻
                sysUser.setStatus("0");
                sysUserService.updateUser(sysUser);
                if(!CollectionUtils.isEmpty(crmSalespersons)){
                    List<Long> userIds = crmSalespersons.stream().map(TCrmSalesperson::getUserId).collect(Collectors.toList());
                    sysUserService.updateUserStatusByUserIds(userIds, "0");
                }
                break;
            case 2:
                // 冻结
                sysUser.setStatus("1");
                sysUserService.updateUser(sysUser);
                // 查询业务员
                if(!CollectionUtils.isEmpty(crmSalespersons)){
                    List<Long> userIds = crmSalespersons.stream().map(TCrmSalesperson::getUserId).collect(Collectors.toList());
                    sysUserService.updateUserStatusByUserIds(userIds, "1");
                }
                break;
        }
        return R.ok();
    }
 
    /**
     * 批量删除crm分公司管理
     */
    @Log(title = "crm分公司管理信息-分公司管理修改积分", businessType = BusinessType.DELETE)
    @ApiOperation(value = "分公司管理修改积分")
    @PutMapping(value = "/changePoints")
    public R<Boolean> changePoints(@RequestBody TCrmChangePoints changePoints) {
        // 查询分公司信息
        TCrmBranch crmBranch = crmBranchService.getById(changePoints.getBranchSalespersonId());
        if (Objects.isNull(crmBranch)) {
            return R.fail("未查询到该分公司");
        }
        switch (changePoints.getChangeType()){
            case 1:
                // 增加积分
                crmBranch.setUserPoints(crmBranch.getUserPoints() + changePoints.getChangeValue());
                break;
            case 2:
                // 减少积分
                if (crmBranch.getUserPoints() < changePoints.getChangeValue()) {
                    return R.fail("操作失败,剩余积分数不足");
                }
                crmBranch.setUserPoints(crmBranch.getUserPoints() - changePoints.getChangeValue());
                break;
        }
        crmBranchService.updateById(crmBranch);
        changePoints.setUserType(1);
        changePoints.setChangeReason(3);
        crmChangePointsService.save(changePoints);
        return R.ok();
    }
 
    @Log(title = "crm分公司管理信息-分公司管理信息导出", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "分公司管理信息导出")
    @PostMapping("/exportList")
    public void exportList(@RequestBody TCrmBranchQuery query){
        Integer roleType = tokenService.getLoginUser().getUser().getRoleType();
        query.setRoleType(roleType);
        List<TCrmBranchExport> crmBranchExports = crmBranchService.exportList(query);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), TCrmBranchExport.class, crmBranchExports);
        HttpServletResponse response = WebUtils.response();
        assert response != null;
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream outputStream = null;
        try {
            String fileName = URLEncoder.encode("分公司管理信息.xls", "utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    @Log(title = "crm分公司管理信息-分公司审核信息导出", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "分公司审核信息导出")
    @PostMapping("/exportAuditList")
    public void exportAuditList(@RequestBody TCrmBranchAuditQuery query){
        List<TCrmBranchAuditExport> crmBranchAuditExports = crmBranchService.exportAuditList(query);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), TCrmBranchAuditExport.class, crmBranchAuditExports);
        HttpServletResponse response = WebUtils.response();
        assert response != null;
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream outputStream = null;
        try {
            String fileName = URLEncoder.encode("分公司审核信息.xls", "utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 解除绑定
     */
    @Log(title = "crm分公司管理信息-解除绑定", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "crm分公司管理信息-解除绑定")
    @PostMapping(value = "/unbind")
    public R<String> unbind(@RequestBody UnbindDTO dto) {
        Long userId = tokenService.getLoginUser().getUserId();
        TCrmBranch crmBranch = crmBranchService.getOne(Wrappers.lambdaQuery(TCrmBranch.class)
                .eq(TCrmBranch::getUserId, userId)
                .last("LIMIT 1"));
        if(crmBranch.getPersonType() != 1){
            return R.fail("仅负责人可操作解除绑定");
        }
 
        TCrmBranchLift crmBranchLift = new TCrmBranchLift();
        crmBranchLift.setBranchId(dto.getBranchId());
        crmBranchLift.setChargePhone(dto.getChargePhone());
        crmBranchLift.setLiftReason(dto.getLiftReason());
        crmBranchLiftService.save(crmBranchLift);
 
        return R.ok();
    }
 
    /**
     * 分公司审核
     */
    @Log(title = "crm分公司管理信息-分公司审核", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "crm分公司管理信息-分公司审核")
    @PostMapping(value = "/branchAudit")
    public R<String> branchAudit(@RequestBody BranchAuditDTO dto) {
        TCrmBranch crmBranch = crmBranchService.getById(dto.getId());
        crmBranch.setAuditStatus(dto.getAuditStatus());
        crmBranch.setAuditRemark(dto.getAuditRemark());
        crmBranch.setAuditTime(LocalDateTime.now());
        crmBranch.setMoneyCommission(dto.getMoneyCommission());
        crmBranch.setPointsCommission(dto.getPointsCommission());
        crmBranchService.updateById(crmBranch);
        return R.ok();
    }
 
    /**
     * 解绑处理
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Log(title = "crm分公司管理信息-解绑处理", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "crm分公司管理信息-解绑处理")
    @PostMapping(value = "/unbindProcessing")
    public R<String> unbindProcessing(@RequestBody UnbindProcessingDTO dto) {
        // 查询解绑信息
        TCrmBranchLift crmBranchLift = crmBranchLiftService.getById(dto.getId());
        if (Objects.isNull(crmBranchLift)){
            return R.fail("未查询到该解绑信息");
        }
        crmBranchLift.setStatus(dto.getStatus());
        crmBranchLift.setRemarks(dto.getRemarks());
        crmBranchLiftService.updateById(crmBranchLift);
        TCrmBranch crmBranch = crmBranchService.getById(crmBranchLift.getBranchId());
        crmBranch.setPhone(crmBranchLift.getChargePhone());
        crmBranchService.updateById(crmBranch);
        // 查询分公司绑定的人员
        SysUser sysUser = sysUserService.selectUserById(crmBranch.getUserId());
        sysUser.setPhonenumber(crmBranchLift.getChargePhone());
        sysUser.setUserName(crmBranchLift.getChargePhone());
        sysUserService.updateUser(sysUser);
        return R.ok();
    }
 
    /**
     * 通过分公司上级id查询负责区域
     */
    @ApiOperation(value = "crm分公司管理信息-通过分公司上级id查询负责区域",notes = "branchId:分公司id")
    @GetMapping(value = "/getAreaByParentId")
    public R<Set<TRegion>> getAreaByParentId(@RequestParam String branchId) {
 
        List<TCrmBranchArea> list = crmBranchAreaService.list(Wrappers.lambdaQuery(TCrmBranchArea.class)
                .eq(TCrmBranchArea::getBranchId, branchId)
                .eq(TCrmBranchArea::getAreaType, 1));
 
        if(CollectionUtils.isEmpty(list)){
            return R.fail("未查询到负责区域");
        }
 
        List<TRegion> regionList = regionService.list();
 
        // 匹配到省份
        Set<TRegion> regions = new HashSet<>();
        for (TCrmBranchArea tCrmBranchArea : list) {
            List<TRegion> parent = regionList.stream().filter(a -> a.getCode().equals(tCrmBranchArea.getProvinceCode())).collect(Collectors.toList());
            regions.add(parent.get(0));
        }
 
        // 匹配市区和区县
        for (TRegion region : regions) {
            List<String> cityCodes = list.stream().filter(a -> a.getProvinceCode().equals(region.getCode()))
                    .map(TCrmBranchArea::getCityCode)
                    .collect(Collectors.toList());
 
            List<TRegion> tRegionList = regionList.stream().filter(a -> a.getParentId().equals(region.getId())
                    && cityCodes.contains(a.getCode())).collect(Collectors.toList());
 
            for (TRegion child : tRegionList) {
                List<TRegion> children1 = regionList.stream().filter(a -> a.getParentId().equals(child.getId())).collect(Collectors.toList());
                child.setChildren(children1);
            }
            region.setChildren(tRegionList);
 
        }
 
        return R.ok(regions);
    }
 
}