longz
2026-07-28 79f1a19bb3344de47dff029cf5498d787e223782
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
package com.ruoyi.account.service.impl;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.account.api.dto.AppUserWhitelistImportDTO;
import com.ruoyi.account.api.dto.AppUserWhitelistQueryDTO;
import com.ruoyi.account.api.dto.AppUserWhitelistSaveDTO;
import com.ruoyi.account.api.model.TAppUser;
import com.ruoyi.account.api.model.TAppUserWhitelist;
import com.ruoyi.account.api.model.TAppUserWhitelistSite;
import com.ruoyi.account.api.vo.AppUserWhitelistMatchVO;
import com.ruoyi.account.api.vo.AppUserWhitelistImportErrorVO;
import com.ruoyi.account.api.vo.AppUserWhitelistImportResultVO;
import com.ruoyi.account.mapper.TAppUserWhitelistMapper;
import com.ruoyi.account.service.TAppUserService;
import com.ruoyi.account.service.TAppUserWhitelistService;
import com.ruoyi.account.service.TAppUserWhitelistSiteService;
import com.ruoyi.chargingPile.api.domain.SiteMenu;
import com.ruoyi.chargingPile.api.feignClient.PartnerClient;
import com.ruoyi.chargingPile.api.feignClient.SiteClient;
import com.ruoyi.chargingPile.api.model.Partner;
import com.ruoyi.chargingPile.api.model.Site;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.domain.BasePojo;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.feignClient.SysUserClient;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * 白名单用户服务实现
 */
@Service
public class TAppUserWhitelistServiceImpl extends ServiceImpl<TAppUserWhitelistMapper, TAppUserWhitelist> implements TAppUserWhitelistService {
 
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1\\d{10}$");
    private static final String IMPORT_HEADER_PHONE = "用户手机号";
    private static final String IMPORT_HEADER_BENEFIT_TYPE = "享受权益";
    private static final String IMPORT_HEADER_WHITELIST_SITE = "白名单电站";
    private static final int BENEFIT_ALL_FREE = 1;
    private static final int BENEFIT_ELECTRIC_FREE = 2;
    private static final int BENEFIT_SERVICE_FREE = 3;
    private static final int SCOPE_ALL_SITE = 1;
    private static final int SCOPE_SELECTED_SITE = 2;
    private static final int SCOPE_PARTNER = 3;
    private static final int STATUS_ENABLED = 1;
 
    @Resource
    private TAppUserWhitelistSiteService whitelistSiteService;
    @Resource
    private TAppUserService appUserService;
    @Resource
    private SiteClient siteClient;
    @Resource
    private PartnerClient partnerClient;
    @Resource
    private TokenService tokenService;
    @Resource
    private SysUserClient sysUserClient;
    @Resource
    private PlatformTransactionManager transactionManager;
 
    @Override
    public Page<TAppUserWhitelist> pageList(AppUserWhitelistQueryDTO queryDTO) {
        if (queryDTO == null) {
            queryDTO = new AppUserWhitelistQueryDTO();
        }
        Integer currentPartnerId = getCurrentPartnerId();
        String username = getUsername();
        LambdaQueryChainWrapper<TAppUserWhitelist> query = this.lambdaQuery()
                .like(StringUtils.isNotBlank(queryDTO.getPhone()), TAppUserWhitelist::getPhone, queryDTO.getPhone())
                .eq(TAppUserWhitelist::getDelFlag, false);
        if (currentPartnerId != null) {
            if (StringUtils.isNotBlank(username)) {
                query.and(wrapper -> wrapper.eq(TAppUserWhitelist::getPartnerId, currentPartnerId)
                        .or()
                        .eq(TAppUserWhitelist::getCreateBy, username));
            } else {
                query.eq(TAppUserWhitelist::getPartnerId, currentPartnerId);
            }
        }
        Page<TAppUserWhitelist> page = query.orderByDesc(BasePojo::getCreateTime)
                .page(Page.of(queryDTO.getPageCurr(), queryDTO.getPageSize()));
        fillDisplay(page.getRecords());
        return page;
    }
 
    @Override
    public TAppUserWhitelist detail(Long id) {
        TAppUserWhitelist whitelist = this.getById(id);
        if (whitelist == null) {
            throw new ServiceException("白名单用户不存在");
        }
        assertPartnerVisible(whitelist);
        fillDisplay(Collections.singletonList(whitelist));
        return whitelist;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWhitelist(AppUserWhitelistSaveDTO saveDTO) {
        validateSaveDTO(saveDTO);
        if (saveDTO.getId() == null) {
            createWhitelist(saveDTO);
        } else {
            updateWhitelist(saveDTO);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            return;
        }
        for (String id : ids.split(",")) {
            if (StringUtils.isBlank(id)) {
                continue;
            }
            Long whitelistId = Long.valueOf(id);
            TAppUserWhitelist whitelist = this.getById(whitelistId);
            if (whitelist == null) {
                continue;
            }
            assertPartnerVisible(whitelist);
            this.removeById(whitelistId);
            whitelistSiteService.remove(Wrappers.lambdaQuery(TAppUserWhitelistSite.class)
                    .eq(TAppUserWhitelistSite::getWhitelistId, whitelistId));
        }
    }
 
    @Override
    public AppUserWhitelistImportResultVO importWhitelist(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("导入文件不能为空");
        }
        int titleNum = getImportTitleNum(file);
        ExcelUtil<AppUserWhitelistImportDTO> util = new ExcelUtil<>(AppUserWhitelistImportDTO.class);
        List<AppUserWhitelistImportDTO> rows = util.importExcel(file.getInputStream(), titleNum);
        if (rows == null || rows.isEmpty()) {
            throw new ServiceException("导入数据不能为空");
        }
 
        Map<String, Site> siteCodeMap = getSiteCodeMap();
        Map<String, AppUserWhitelistSaveDTO> validRows = new LinkedHashMap<>();
        Map<String, Integer> validRowNumbers = new HashMap<>();
        List<AppUserWhitelistImportErrorVO> errors = new ArrayList<>();
        Set<String> importPhones = new HashSet<>();
        for (int i = 0; i < rows.size(); i++) {
            AppUserWhitelistImportDTO row = rows.get(i);
            int rowNum = titleNum + i + 2;
            List<String> rowErrors = validateImportRow(row, siteCodeMap);
            if (!rowErrors.isEmpty()) {
                errors.add(new AppUserWhitelistImportErrorVO(rowNum, normalize(row.getPhone()), String.join(";", rowErrors)));
                continue;
            }
            AppUserWhitelistSaveDTO dto = buildSaveDTO(row, siteCodeMap);
            if (!importPhones.add(dto.getPhone())) {
                errors.add(new AppUserWhitelistImportErrorVO(rowNum, dto.getPhone(), "导入文件中手机号重复"));
                continue;
            }
            if (getByPhone(dto.getPhone()) != null) {
                errors.add(new AppUserWhitelistImportErrorVO(rowNum, dto.getPhone(), "该手机号已存在白名单配置"));
                continue;
            }
            validRows.put(dto.getPhone(), dto);
            validRowNumbers.put(dto.getPhone(), rowNum);
        }
 
        TransactionTemplate rowTransaction = new TransactionTemplate(transactionManager);
        rowTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        int successCount = 0;
        for (Map.Entry<String, AppUserWhitelistSaveDTO> entry : validRows.entrySet()) {
            try {
                rowTransaction.execute(status -> {
                    createWhitelist(entry.getValue());
                    return null;
                });
                successCount++;
            } catch (Exception exception) {
                errors.add(new AppUserWhitelistImportErrorVO(validRowNumbers.get(entry.getKey()), entry.getKey(),
                        getImportSaveErrorMessage(exception)));
            }
        }
 
        AppUserWhitelistImportResultVO result = new AppUserWhitelistImportResultVO();
        result.setTotalCount(rows.size());
        result.setErrorCount(errors.size());
        result.setSuccessCount(successCount);
        result.setErrorMessage(errors);
        return result;
    }
 
    private String getImportSaveErrorMessage(Exception exception) {
        Throwable current = exception;
        while (current != null) {
            if (current instanceof ServiceException && StringUtils.isNotBlank(current.getMessage())) {
                return current.getMessage();
            }
            current = current.getCause();
        }
        return "数据保存失败";
    }
 
    /**
     * 判断指定用户在指定站点是否命中启用状态的白名单规则
     *
     * @param appUserId APP用户ID
     * @param siteId 站点ID
     * @return 白名单命中结果
     */
    @Override
    public AppUserWhitelistMatchVO matchWhitelist(Long appUserId, Integer siteId) {
        AppUserWhitelistMatchVO emptyResult = new AppUserWhitelistMatchVO();
        if (appUserId == null || siteId == null) {
            return emptyResult;
        }
        TAppUser appUser = appUserService.getById(appUserId);
        if (appUser == null || StringUtils.isBlank(appUser.getPhone())) {
            return emptyResult;
        }
        TAppUserWhitelist whitelist = this.lambdaQuery()
                .eq(TAppUserWhitelist::getPhone, appUser.getPhone())
                .eq(TAppUserWhitelist::getStatus, STATUS_ENABLED)
                .eq(TAppUserWhitelist::getDelFlag, false)
                .last("LIMIT 1")
                .one();
        if (whitelist == null || !isWhitelistScopeMatched(whitelist, siteId)) {
            return emptyResult;
        }
        AppUserWhitelistMatchVO result = new AppUserWhitelistMatchVO();
        result.setMatched(true);
        result.setWhitelistId(whitelist.getId());
        result.setBenefitType(whitelist.getBenefitType());
        result.setScopeType(whitelist.getScopeType());
        result.setBenefitName(getBenefitName(whitelist.getBenefitType()));
        return result;
    }
 
    /**
     * 根据白名单范围类型判断当前站点是否在可用范围内
     *
     * @param whitelist 白名单配置
     * @param siteId 站点ID
     * @return true=命中范围
     */
    private boolean isWhitelistScopeMatched(TAppUserWhitelist whitelist, Integer siteId) {
        if (Objects.equals(whitelist.getScopeType(), SCOPE_ALL_SITE)) {
            return whitelist.getPartnerId() == null || isSiteBelongsToPartner(siteId, whitelist.getPartnerId());
        }
        if (Objects.equals(whitelist.getScopeType(), SCOPE_SELECTED_SITE)) {
            return whitelistSiteService.lambdaQuery()
                    .eq(TAppUserWhitelistSite::getWhitelistId, whitelist.getId())
                    .eq(TAppUserWhitelistSite::getSiteId, siteId)
                    .count() > 0;
        }
        if (Objects.equals(whitelist.getScopeType(), SCOPE_PARTNER)) {
            R<List<Site>> siteResult = siteClient.getSiteByIds(Collections.singletonList(siteId));
            List<Site> sites = siteResult == null || siteResult.getData() == null ? Collections.emptyList() : siteResult.getData();
            return !sites.isEmpty() && Objects.equals(sites.get(0).getPartnerId(), whitelist.getPartnerId());
        }
        return false;
    }
 
    private int getImportTitleNum(MultipartFile file) throws Exception {
        try (InputStream inputStream = file.getInputStream(); Workbook workbook = WorkbookFactory.create(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new ServiceException("导入文件sheet不存在");
            }
            int maxRow = Math.min(sheet.getLastRowNum(), 5);
            for (int i = 0; i <= maxRow; i++) {
                Row row = sheet.getRow(i);
                if (isImportHeaderRow(row)) {
                    return i;
                }
            }
        }
        throw new ServiceException("导入文件表头不正确,请下载最新模板后填写");
    }
 
    private boolean isImportHeaderRow(Row row) {
        if (row == null) {
            return false;
        }
        ExcelUtil<AppUserWhitelistImportDTO> util = new ExcelUtil<>(AppUserWhitelistImportDTO.class);
        return IMPORT_HEADER_PHONE.equals(normalize(String.valueOf(util.getCellValue(row, 0))))
                && IMPORT_HEADER_BENEFIT_TYPE.equals(normalize(String.valueOf(util.getCellValue(row, 1))))
                && IMPORT_HEADER_WHITELIST_SITE.equals(normalize(String.valueOf(util.getCellValue(row, 2))));
    }
 
    private void validateSaveDTO(AppUserWhitelistSaveDTO saveDTO) {
        if (saveDTO == null) {
            throw new ServiceException("请求参数不能为空");
        }
        saveDTO.setPhone(normalize(saveDTO.getPhone()));
        if (!isValidPhone(saveDTO.getPhone())) {
            throw new ServiceException("请输入正确的用户手机号");
        }
        if (!isValidBenefit(saveDTO.getBenefitType())) {
            throw new ServiceException("请选择正确的享受权益");
        }
        if (!isValidScope(saveDTO.getScopeType())) {
            throw new ServiceException("请选择正确的白名单电站范围");
        }
        if (Objects.equals(saveDTO.getScopeType(), SCOPE_SELECTED_SITE)
                && (saveDTO.getSiteIds() == null || saveDTO.getSiteIds().isEmpty())) {
            throw new ServiceException("请选择白名单电站");
        }
        if (Objects.equals(saveDTO.getScopeType(), SCOPE_PARTNER) && saveDTO.getPartnerId() == null) {
            throw new ServiceException("请选择加盟商");
        }
        validatePartnerDataScope(saveDTO);
        TAppUserWhitelist exists = getByPhone(saveDTO.getPhone());
        if (saveDTO.getId() == null && exists != null) {
            throw new ServiceException("该手机号已存在白名单配置");
        }
        if (saveDTO.getId() != null && exists != null && !Objects.equals(exists.getId(), saveDTO.getId())) {
            throw new ServiceException("该手机号已存在白名单配置");
        }
    }
 
    private void createWhitelist(AppUserWhitelistSaveDTO saveDTO) {
        if (getByPhone(saveDTO.getPhone()) != null) {
            throw new ServiceException("该手机号已存在白名单配置");
        }
        TAppUserWhitelist whitelist = new TAppUserWhitelist();
        TAppUser appUser = appUserService.lambdaQuery()
                .eq(TAppUser::getPhone, saveDTO.getPhone())
                .last("LIMIT 1")
                .one();
        whitelist.setCreateBy(getUsername());
        whitelist.setAppUserId(appUser == null ? null : appUser.getId());
        whitelist.setPhone(saveDTO.getPhone());
        whitelist.setBenefitType(saveDTO.getBenefitType());
        whitelist.setScopeType(saveDTO.getScopeType());
        whitelist.setPartnerId(resolveWhitelistPartnerId(saveDTO));
        whitelist.setStatus(STATUS_ENABLED);
        whitelist.setUpdateBy(getUsername());
        whitelist.setRemark(saveDTO.getRemark());
        whitelist.setDelFlag(false);
        if (whitelist.getId() == null) {
            this.save(whitelist);
        }
 
        whitelistSiteService.deleteByWhitelistId(whitelist.getId());
        if (Objects.equals(saveDTO.getScopeType(), SCOPE_SELECTED_SITE)) {
            Long whitelistId = whitelist.getId();
            List<TAppUserWhitelistSite> sites = saveDTO.getSiteIds().stream()
                    .filter(Objects::nonNull)
                    .distinct()
                    .map(siteId -> {
                        TAppUserWhitelistSite site = new TAppUserWhitelistSite();
                        site.setWhitelistId(whitelistId);
                        site.setSiteId(siteId);
                        site.setDelFlag(false);
                        return site;
                    }).collect(Collectors.toList());
            if (!sites.isEmpty()) {
                whitelistSiteService.saveBatch(sites);
            }
        }
    }
 
    private void updateWhitelist(AppUserWhitelistSaveDTO saveDTO) {
        TAppUserWhitelist whitelist = this.getById(saveDTO.getId());
        if (whitelist == null) {
            throw new ServiceException("白名单用户不存在");
        }
        assertPartnerVisible(whitelist);
        TAppUser appUser = appUserService.lambdaQuery()
                .eq(TAppUser::getPhone, saveDTO.getPhone())
                .last("LIMIT 1")
                .one();
        whitelist.setAppUserId(appUser == null ? null : appUser.getId());
        whitelist.setPhone(saveDTO.getPhone());
        whitelist.setBenefitType(saveDTO.getBenefitType());
        whitelist.setScopeType(saveDTO.getScopeType());
        whitelist.setPartnerId(resolveWhitelistPartnerId(saveDTO));
        whitelist.setStatus(STATUS_ENABLED);
        whitelist.setUpdateBy(getUsername());
        whitelist.setRemark(saveDTO.getRemark());
        whitelist.setDelFlag(false);
        this.baseMapper.updateByIdIgnoreLogic(whitelist);
 
        whitelistSiteService.deleteByWhitelistId(whitelist.getId());
        if (Objects.equals(saveDTO.getScopeType(), SCOPE_SELECTED_SITE)) {
            Long whitelistId = whitelist.getId();
            List<TAppUserWhitelistSite> sites = saveDTO.getSiteIds().stream()
                    .filter(Objects::nonNull)
                    .distinct()
                    .map(siteId -> {
                        TAppUserWhitelistSite site = new TAppUserWhitelistSite();
                        site.setWhitelistId(whitelistId);
                        site.setSiteId(siteId);
                        site.setDelFlag(false);
                        return site;
                    }).collect(Collectors.toList());
            if (!sites.isEmpty()) {
                whitelistSiteService.saveBatch(sites);
            }
        }
    }
 
    /**
     * 查询手机号对应的有效白名单配置,逻辑删除记录允许重新新增。
     *
     * @param phone 用户手机号
     * @return 有效白名单配置
     */
    private TAppUserWhitelist getByPhone(String phone) {
        return this.baseMapper.selectValidByPhone(phone);
    }
 
    private List<String> validateImportRow(AppUserWhitelistImportDTO row, Map<String, Site> siteCodeMap) {
        List<String> errors = new ArrayList<>();
        if (row == null) {
            errors.add("空行");
            return errors;
        }
        String phone = normalize(row.getPhone());
        if (!isValidPhone(phone)) {
            errors.add("用户手机号格式错误");
        }
        Integer benefitType = parseInteger(row.getBenefitType());
        if (!isValidBenefit(benefitType)) {
            errors.add("享受权益只能填写1、2、3");
        }
        String whitelistSite = normalize(row.getWhitelistSite());
        if (StringUtils.isBlank(whitelistSite)) {
            errors.add("白名单电站不能为空");
        } else if (!"all".equalsIgnoreCase(whitelistSite)) {
            for (String code : whitelistSite.split(",")) {
                String siteCode = normalize(code);
                if (StringUtils.isBlank(siteCode)) {
                    errors.add("白名单电站存在空编号");
                } else if (!siteCodeMap.containsKey(siteCode)) {
                    errors.add("站点编号不存在:" + siteCode);
                }
            }
        }
        return errors;
    }
 
    private AppUserWhitelistSaveDTO buildSaveDTO(AppUserWhitelistImportDTO row, Map<String, Site> siteCodeMap) {
        AppUserWhitelistSaveDTO dto = new AppUserWhitelistSaveDTO();
        dto.setPhone(normalize(row.getPhone()));
        dto.setBenefitType(parseInteger(row.getBenefitType()));
        String whitelistSite = normalize(row.getWhitelistSite());
        if ("all".equalsIgnoreCase(whitelistSite)) {
            dto.setScopeType(SCOPE_ALL_SITE);
            dto.setSiteIds(Collections.emptyList());
        } else {
            dto.setScopeType(SCOPE_SELECTED_SITE);
            List<Integer> siteIds = new ArrayList<>();
            for (String code : whitelistSite.split(",")) {
                Site site = siteCodeMap.get(normalize(code));
                if (site != null) {
                    siteIds.add(site.getId());
                }
            }
            dto.setSiteIds(siteIds.stream().distinct().collect(Collectors.toList()));
        }
        return dto;
    }
 
    private Map<String, Site> getSiteCodeMap() {
        List<Site> sites = getCurrentSelectableSites();
        Map<String, Site> siteCodeMap = new HashMap<>();
        for (Site site : sites) {
            if (site != null && StringUtils.isNotBlank(site.getCode())) {
                siteCodeMap.put(site.getCode(), site);
            }
        }
        return siteCodeMap;
    }
 
    private void fillDisplay(List<TAppUserWhitelist> records) {
        if (records == null || records.isEmpty()) {
            return;
        }
        Map<Integer, Site> siteMap = getSiteMap(records);
        Map<Integer, Partner> partnerMap = getPartnerMap(records, siteMap);
        for (TAppUserWhitelist record : records) {
            record.setUid(record.getId() == null ? null : record.getId().toString());
            record.setBenefitName(getBenefitName(record.getBenefitType()));
            record.setScopeName(getScopeName(record.getScopeType()));
            if (record.getPartnerId() != null) {
                Partner partner = partnerMap.get(record.getPartnerId());
                record.setPartnerName(partner == null ? null : partner.getName());
            }
            List<TAppUserWhitelistSite> sites = whitelistSiteService.lambdaQuery()
                    .eq(TAppUserWhitelistSite::getWhitelistId, record.getId())
                    .list();
            for (TAppUserWhitelistSite siteItem : sites) {
                Site site = siteMap.get(siteItem.getSiteId());
                if (site != null) {
                    siteItem.setSiteCode(site.getCode());
                    siteItem.setSiteName(site.getName());
                    siteItem.setSiteType(site.getSiteType());
                    siteItem.setBusinessCategory(site.getBusinessCategory());
                    siteItem.setStatus(site.getStatus());
                    Partner partner = partnerMap.get(site.getPartnerId());
                    siteItem.setPartnerName(partner == null ? null : partner.getName());
                }
            }
            record.setSiteList(sites);
            record.setSiteIds(sites.stream().map(TAppUserWhitelistSite::getSiteId).collect(Collectors.toList()));
        }
    }
 
    private Map<Integer, Site> getSiteMap(List<TAppUserWhitelist> records) {
        List<Long> whitelistIds = records.stream().map(TAppUserWhitelist::getId).collect(Collectors.toList());
        List<TAppUserWhitelistSite> siteLinks = whitelistSiteService.lambdaQuery()
                .in(TAppUserWhitelistSite::getWhitelistId, whitelistIds)
                .list();
        List<Integer> siteIds = siteLinks.stream().map(TAppUserWhitelistSite::getSiteId).distinct().collect(Collectors.toList());
        if (siteIds.isEmpty()) {
            return Collections.emptyMap();
        }
        R<List<Site>> siteResult = siteClient.getSiteByIds(siteIds);
        List<Site> sites = siteResult == null || siteResult.getData() == null ? Collections.emptyList() : siteResult.getData();
        return sites.stream().collect(Collectors.toMap(Site::getId, site -> site, (a, b) -> a));
    }
 
    private Map<Integer, Partner> getPartnerMap(List<TAppUserWhitelist> records, Map<Integer, Site> siteMap) {
        Map<Integer, Partner> partnerMap = new HashMap<>();
        Set<Integer> partnerIds = new HashSet<>();
        for (TAppUserWhitelist record : records) {
            if (record.getPartnerId() != null) {
                partnerIds.add(record.getPartnerId());
            }
        }
        if (siteMap != null) {
            for (Site site : siteMap.values()) {
                if (site != null && site.getPartnerId() != null) {
                    partnerIds.add(site.getPartnerId());
                }
            }
        }
        for (Integer partnerId : partnerIds) {
            R<Partner> partnerResult = partnerClient.getPartnerById(partnerId);
            if (partnerResult != null && partnerResult.getData() != null) {
                partnerMap.put(partnerId, partnerResult.getData());
            }
        }
        return partnerMap;
    }
 
    private void validatePartnerDataScope(AppUserWhitelistSaveDTO saveDTO) {
        Integer currentPartnerId = getCurrentPartnerId();
        if (currentPartnerId == null) {
            return;
        }
        if (Objects.equals(saveDTO.getScopeType(), SCOPE_PARTNER)
                && !Objects.equals(saveDTO.getPartnerId(), currentPartnerId)) {
            throw new ServiceException("合作商账号只能选择本合作商");
        }
        if (Objects.equals(saveDTO.getScopeType(), SCOPE_SELECTED_SITE)) {
            Set<Integer> authSiteIds = getCurrentPartnerSiteIds(currentPartnerId);
            if (authSiteIds.isEmpty()) {
                throw new ServiceException("当前合作商没有可用电站权限");
            }
            List<Integer> unauthorizedSiteIds = saveDTO.getSiteIds().stream()
                    .filter(Objects::nonNull)
                    .filter(siteId -> !authSiteIds.contains(siteId))
                    .collect(Collectors.toList());
            if (!unauthorizedSiteIds.isEmpty()) {
                throw new ServiceException("只能选择当前合作商负责的电站");
            }
        }
    }
 
    private void assertPartnerVisible(TAppUserWhitelist whitelist) {
        Integer currentPartnerId = getCurrentPartnerId();
        if (currentPartnerId == null || whitelist == null) {
            return;
        }
        if (Objects.equals(whitelist.getPartnerId(), currentPartnerId)) {
            return;
        }
        if (StringUtils.isNotBlank(whitelist.getCreateBy()) && Objects.equals(whitelist.getCreateBy(), getUsername())) {
            return;
        }
        throw new ServiceException("无权操作该白名单数据");
    }
 
    private Integer resolveWhitelistPartnerId(AppUserWhitelistSaveDTO saveDTO) {
        Integer currentPartnerId = getCurrentPartnerId();
        if (currentPartnerId != null) {
            return currentPartnerId;
        }
        return Objects.equals(saveDTO.getScopeType(), SCOPE_PARTNER) ? saveDTO.getPartnerId() : null;
    }
 
    private List<Site> getCurrentSelectableSites() {
        Integer currentPartnerId = getCurrentPartnerId();
        if (currentPartnerId == null) {
            R<List<Site>> siteResult = siteClient.getSiteAll();
            return siteResult == null || siteResult.getData() == null ? Collections.emptyList() : siteResult.getData();
        }
        Set<Integer> siteIds = getCurrentPartnerSiteIds(currentPartnerId);
        if (siteIds.isEmpty()) {
            return Collections.emptyList();
        }
        R<List<Site>> siteResult = siteClient.getSiteByIds(new ArrayList<>(siteIds));
        List<Site> sites = siteResult == null || siteResult.getData() == null ? Collections.emptyList() : siteResult.getData();
        return sites.stream()
                .filter(site -> site != null && Objects.equals(site.getPartnerId(), currentPartnerId))
                .collect(Collectors.toList());
    }
 
    private Set<Integer> getCurrentPartnerSiteIds(Integer partnerId) {
        R<Set<Integer>> siteResult = partnerClient.authSite(partnerId, SiteMenu.SITE_LIST.getValue());
        return siteResult == null || siteResult.getData() == null ? Collections.emptySet() : siteResult.getData();
    }
 
    private boolean isSiteBelongsToPartner(Integer siteId, Integer partnerId) {
        if (siteId == null || partnerId == null) {
            return false;
        }
        R<List<Site>> siteResult = siteClient.getSiteByIds(Collections.singletonList(siteId));
        List<Site> sites = siteResult == null || siteResult.getData() == null ? Collections.emptyList() : siteResult.getData();
        return !sites.isEmpty() && Objects.equals(sites.get(0).getPartnerId(), partnerId);
    }
 
    private Integer getCurrentPartnerId() {
        SysUser sysUser = getCurrentSysUser();
        if (sysUser == null || !Objects.equals(sysUser.getRoleType(), 2)) {
            return null;
        }
        return sysUser.getObjectId();
    }
 
    private SysUser getCurrentSysUser() {
        LoginUser loginUser = null;
        try {
            loginUser = tokenService.getLoginUser();
        } catch (Exception e) {
            // ignore and try security context fallback
        }
        if (loginUser == null) {
            try {
                loginUser = SecurityUtils.getLoginUser();
            } catch (Exception e) {
                // ignore and fall through to null
            }
        }
        if (loginUser == null) {
            return null;
        }
        if (loginUser.getSysUser() != null && loginUser.getSysUser().getRoleType() != null) {
            return loginUser.getSysUser();
        }
        if (loginUser.getUserid() == null) {
            return loginUser.getSysUser();
        }
        R<SysUser> userResult = sysUserClient.getSysUser(loginUser.getUserid());
        if (userResult != null && userResult.getData() != null) {
            return userResult.getData();
        }
        return loginUser.getSysUser();
    }
 
    private boolean isValidPhone(String phone) {
        return StringUtils.isNotBlank(phone) && PHONE_PATTERN.matcher(phone).matches();
    }
 
    private boolean isValidBenefit(Integer benefitType) {
        return Objects.equals(benefitType, BENEFIT_ALL_FREE)
                || Objects.equals(benefitType, BENEFIT_ELECTRIC_FREE)
                || Objects.equals(benefitType, BENEFIT_SERVICE_FREE);
    }
 
    private boolean isValidScope(Integer scopeType) {
        return Objects.equals(scopeType, SCOPE_ALL_SITE)
                || Objects.equals(scopeType, SCOPE_SELECTED_SITE)
                || Objects.equals(scopeType, SCOPE_PARTNER);
    }
 
    private Integer parseInteger(String value) {
        try {
            String normalizedValue = normalize(value);
            if (StringUtils.isBlank(normalizedValue)) {
                return null;
            }
            if (normalizedValue.matches("^\\d+\\.0+$")) {
                normalizedValue = normalizedValue.substring(0, normalizedValue.indexOf("."));
            }
            return Integer.valueOf(normalizedValue);
        } catch (Exception e) {
            return null;
        }
    }
 
    private String normalize(String value) {
        return value == null ? null : value.trim();
    }
 
    private String getBenefitName(Integer benefitType) {
        if (Objects.equals(benefitType, BENEFIT_ALL_FREE)) {
            return "全部免费";
        }
        if (Objects.equals(benefitType, BENEFIT_ELECTRIC_FREE)) {
            return "免电费";
        }
        if (Objects.equals(benefitType, BENEFIT_SERVICE_FREE)) {
            return "免服务费";
        }
        return "";
    }
 
    private String getScopeName(Integer scopeType) {
        if (Objects.equals(scopeType, SCOPE_ALL_SITE)) {
            return "全部电站";
        }
        if (Objects.equals(scopeType, SCOPE_SELECTED_SITE)) {
            return "部分电站";
        }
        if (Objects.equals(scopeType, SCOPE_PARTNER)) {
            return "指定合作商";
        }
        return "";
    }
 
    private String getUsername() {
        try {
            String username = SecurityUtils.getUsername();
            if (StringUtils.isNotBlank(username)) {
                return username;
            }
        } catch (Exception e) {
            // ignore and try token context fallback
        }
        try {
            LoginUser loginUser = tokenService.getLoginUser();
            if (loginUser != null) {
                if (StringUtils.isNotBlank(loginUser.getUsername())) {
                    return loginUser.getUsername();
                }
                if (loginUser.getSysUser() != null && StringUtils.isNotBlank(loginUser.getSysUser().getUserName())) {
                    return loginUser.getSysUser().getUserName();
                }
            }
        } catch (Exception e) {
            // ignore and fall through to null
        }
        return null;
    }
}