xuhy
2026-03-12 6df6d2e08dc7beeb72acecf1b01b6c546b153d3a
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
package com.xiaopeng.operation.controller;
 
 
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.core.util.PhoneUtil;
import com.xiaopeng.api.model.account.SysUser;
import com.xiaopeng.api.model.operation.XpWhitelist;
import com.xiaopeng.api.model.operation.XpWhitelistOperlog;
import com.xiaopeng.common.core.domain.R;
import com.xiaopeng.common.core.exception.ServiceException;
import com.xiaopeng.common.core.utils.WebUtils;
import com.xiaopeng.common.core.utils.bean.BeanUtils;
import com.xiaopeng.common.core.utils.ip.IpUtils;
import com.xiaopeng.common.core.web.domain.AjaxResult;
import com.xiaopeng.common.core.web.page.PageInfo;
import com.xiaopeng.common.log.annotation.Log;
import com.xiaopeng.common.log.enums.BusinessType;
import com.xiaopeng.common.security.service.TokenService;
import com.xiaopeng.operation.dto.WhitelistAddDto;
import com.xiaopeng.operation.dto.WhitelistEditDto;
import com.xiaopeng.operation.exportExcle.XpWhitelistExportExcel;
import com.xiaopeng.operation.importExcel.WhitelistImportExcel;
import com.xiaopeng.operation.query.WhitelistPageListQuery;
import com.xiaopeng.operation.service.IXpWhitelistOperlogService;
import com.xiaopeng.operation.service.IXpWhitelistService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 白名单管理 前端控制器
 * </p>
 *
 * @author mitao
 * @since 2026-02-03
 */
@RequestMapping("")
@RestController
@Api(tags = "白名单管理")
@Slf4j
public class XpWhitelistController {
    @Resource
    private IXpWhitelistService xpWhitelistService;
    @Resource
    private IXpWhitelistOperlogService xpWhitelistOperlogService;
    @Resource
    private TokenService tokenService;
 
 
 
    /**
     * 获取所有白名单手机号
     * @return
     */
    @PostMapping("/api/v1/whitelist/inner/getAllWhiteList")
    public R<List<String>> getAllWhiteList(){
        return R.ok(xpWhitelistService.getAllWhiteList());
    }
 
    @ApiOperation(value = "白名单管理分页列表", response = XpWhitelist.class)
    @PostMapping("/api/v1/whitelist/pageList")
    public R<PageInfo<XpWhitelist>> pageList(@RequestBody WhitelistPageListQuery query) {
        PageInfo<XpWhitelist> pageList = xpWhitelistService.pageList(query);
        return R.ok(pageList);
    }
 
    /**
     * 新增白名单
     */
    @PostMapping("/api/v1/whitelist/add")
    @ResponseBody
    @ApiOperation(value = "新增白名单")
    public R add(@Validated @RequestBody WhitelistAddDto dto) {
        if (!StringUtils.hasLength(dto.getAccount())) {
            return R.fail("请输入账号");
        }
 
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        return xpWhitelistService.addWhitelist(dto, sysUser);
    }
 
    /**
     * 编辑白名单
     */
    @PostMapping("/api/v1/whitelist/edit")
    @ResponseBody
    @ApiOperation(value = "编辑白名单")
    @Transactional
    public R edit(@Validated @RequestBody WhitelistEditDto dto) {
        if (!StringUtils.hasLength(dto.getAccount())) {
            return R.fail("请输入账号");
        }
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        XpWhitelist xpWhitelist = new XpWhitelist();
        BeanUtils.copyProperties(dto, xpWhitelist);
        xpWhitelist.setUpdateBy(tokenService.getLoginUser().getSysUser().getNickName());
 
        return xpWhitelistService.editWhitelist(xpWhitelist, sysUser);
    }
 
    /**
     * 冻结解冻
     */
    @GetMapping("/api/v1/whitelist/freezeUnfreeze")
    @ResponseBody
    @ApiOperation(value = "冻结解冻")
    @Transactional
    public R freezeUnfreeze(@RequestParam("id") Long id) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
 
        return xpWhitelistService.freezeUnfreeze(id, sysUser);
    }
 
    /**
     * 批量删除
     */
    @GetMapping("/api/v1/whitelist/deleteByIds")
    @ResponseBody
    @ApiOperation(value = "批量删除")
    public R deleteByIds(String ids) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        List<Long> whiteIds = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return xpWhitelistService.deleteByIds(whiteIds, sysUser);
    }
 
    /**
     * 批量冻结
     */
    @GetMapping("/api/v1/whitelist/freezeByIds")
    @ResponseBody
    @ApiOperation(value = "批量冻结")
    public R freezeByIds(String ids) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        List<Long> whiteIds = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return xpWhitelistService.freezeByIds(whiteIds, sysUser);
    }
 
    @ApiOperation(value = "白名单导入模板下载")
    @GetMapping("/api/v1/whitelist/import-template")
    public void importTemplate() {
        List<WhitelistImportExcel> whitelistImportExcels = new ArrayList<>();
        WhitelistImportExcel whitelistImportExcel = new WhitelistImportExcel();
        whitelistImportExcels.add(whitelistImportExcel);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), WhitelistImportExcel.class, whitelistImportExcels);
        HttpServletResponse response = WebUtils.response();
        ServletOutputStream outputStream = null;
        try {
            String fileName = URLEncoder.encode("白名单导入模板.xls", "utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("content-Type", "application/vnd.ms-excel");
            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();
            }
        }
    }
 
 
 
    @Transactional
    @ShardingSphereTransactionType(TransactionType.BASE)
    @Log(title = "白名单导入", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "白名单导入")
    @PostMapping("/base/v1/whitelist/importExcel")
    public AjaxResult<String> importExcel(@RequestParam("file") MultipartFile file) {
 
        ImportParams params = new ImportParams();
//        params.setTitleRows(1); // 标题行数
        params.setHeadRows(1); //表头行数
        List<WhitelistImportExcel> whitelistImportExcels;
        try {
            try (InputStream inputStream = file.getInputStream()) {
                whitelistImportExcels = ExcelImportUtil.importExcel(inputStream,
                        WhitelistImportExcel.class, params);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("白名单导入失败:{}", e.getMessage());
            throw new ServiceException("白名单导入失败!");
        }
        if (CollectionUtils.isEmpty(whitelistImportExcels)) {
            throw new ServiceException("白名单数据为空!");
        }
 
        int sampleLimitPerReason = 20;
        int totalCount = whitelistImportExcels.size();
        Map<String, Long> reasonCountMap = new HashMap<>();
        Map<String, LinkedHashSet<String>> reasonSampleMap = new HashMap<>();
 
        // 先做基础校验 + 文件内去重(允许部分成功)
        Set<String> seenAccounts = new HashSet<>();
        List<WhitelistImportExcel> candidates = new ArrayList<>();
        for (int i = 0; i < whitelistImportExcels.size(); i++) {
            WhitelistImportExcel row = whitelistImportExcels.get(i);
            String account = trimToNull(row.getAccount());
            String nickName = trimToNull(row.getNickName());
            row.setAccount(account);
            row.setNickName(nickName);
 
            int excelRowNumber = i + params.getHeadRows() + 1;
            if (!StringUtils.hasLength(account)) {
                recordFail(reasonCountMap, reasonSampleMap, "账号为空", "第" + excelRowNumber + "行", sampleLimitPerReason);
                continue;
            }
            if (!PhoneUtil.isMobile(account)) {
                recordFail(reasonCountMap, reasonSampleMap, "账号格式不正确", account, sampleLimitPerReason);
                continue;
            }
            if (!seenAccounts.add(account)) {
                recordFail(reasonCountMap, reasonSampleMap, "文件内账号重复", account, sampleLimitPerReason);
                continue;
            }
            candidates.add(row);
        }
 
        // 批量查询数据库已存在账号(避免全表扫描)
        Set<String> existsAccounts = Collections.emptySet();
        if (!CollectionUtils.isEmpty(candidates)) {
            Set<String> candidateAccounts = candidates.stream()
                    .map(WhitelistImportExcel::getAccount)
                    .filter(StringUtils::hasLength)
                    .collect(Collectors.toSet());
            if (!CollectionUtils.isEmpty(candidateAccounts)) {
                existsAccounts = xpWhitelistService.lambdaQuery()
                        .select(XpWhitelist::getAccount)
                        .in(XpWhitelist::getAccount, candidateAccounts)
                        .list()
                        .stream()
                        .map(XpWhitelist::getAccount)
                        .filter(StringUtils::hasLength)
                        .collect(Collectors.toSet());
            }
        }
 
        List<XpWhitelist> addList = new ArrayList<>();
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        for (WhitelistImportExcel whitelistImportExcel : candidates) {
            if (existsAccounts.contains(whitelistImportExcel.getAccount())) {
                recordFail(reasonCountMap, reasonSampleMap, "账号已存在", whitelistImportExcel.getAccount(), sampleLimitPerReason);
                continue;
            }
            XpWhitelist xpWhitelist = new XpWhitelist();
            xpWhitelist.setNickName(whitelistImportExcel.getNickName());
            xpWhitelist.setAccount(whitelistImportExcel.getAccount());
            xpWhitelist.setStatus(true);
            xpWhitelist.setIsPriorityDispatch(true);
            xpWhitelist.setWhitelistSource(1);
            xpWhitelist.setCreateBy(sysUser.getNickName());
            addList.add(xpWhitelist);
        }
 
        int successCount = addList.size();
        int failCount = totalCount - successCount;
 
        String message;
        if (failCount == 0) {
            message = "成功添加" + successCount + "条白名单记录";
        } else if (successCount == 0) {
            message = "所有帐号添加失败,请检查格式或唯一性";
        } else {
            String reasonDetail = buildReasonDetail(reasonCountMap, reasonSampleMap);
            message = "成功添加" + successCount + "条," + failCount + "条添加失败:原因" + reasonDetail;
        }
 
        if (successCount == 0) {
            return AjaxResult.error(message, message);
        }
 
        xpWhitelistService.saveBatch(addList);
        StringBuilder operationContent = new StringBuilder("白名单导入:成功添加")
                .append(successCount).append("条,失败").append(failCount).append("条");
        if (failCount > 0) {
            operationContent.append(";原因").append(buildReasonSummary(reasonCountMap));
        }
        String opContent = truncate(operationContent.toString(), 200);
        XpWhitelistOperlog xpWhitelistOperlog = new XpWhitelistOperlog();
        xpWhitelistOperlog.setOperationName(sysUser.getNickName());
        xpWhitelistOperlog.setOperationAccount(sysUser.getPhoneNumber());
        xpWhitelistOperlog.setOperationType(4);
        xpWhitelistOperlog.setOperationIp(IpUtils.getIpAddr());
        xpWhitelistOperlog.setOperationAccountId(sysUser.getId());
        xpWhitelistOperlog.setOperationContent(opContent);
        xpWhitelistOperlog.setCreateBy(sysUser.getNickName());
        xpWhitelistOperlogService.save(xpWhitelistOperlog);
 
        return AjaxResult.success(opContent, opContent);
    }
 
    private static String trimToNull(String value) {
        if (!StringUtils.hasLength(value)) {
            return null;
        }
        String trimmed = value.trim();
        return StringUtils.hasLength(trimmed) ? trimmed : null;
    }
 
    private static void incReason(Map<String, Long> reasonCountMap, String reason) {
        reasonCountMap.merge(reason, 1L, Long::sum);
    }
 
    private static void recordFail(Map<String, Long> reasonCountMap,
                                   Map<String, LinkedHashSet<String>> reasonSampleMap,
                                   String reason,
                                   String sample,
                                   int sampleLimitPerReason) {
        incReason(reasonCountMap, reason);
        if (!StringUtils.hasLength(sample) || sampleLimitPerReason <= 0) {
            return;
        }
        LinkedHashSet<String> samples = reasonSampleMap.computeIfAbsent(reason, k -> new LinkedHashSet<>());
        if (samples.size() >= sampleLimitPerReason) {
            return;
        }
        samples.add(sample);
    }
 
    private static String buildReasonSummary(Map<String, Long> reasonCountMap) {
        if (reasonCountMap == null || reasonCountMap.isEmpty()) {
            return "请检查格式或唯一性";
        }
        return reasonCountMap.entrySet().stream()
                .sorted(Comparator.<Map.Entry<String, Long>>comparingLong(e -> e.getValue() == null ? 0L : e.getValue())
                        .reversed()
                        .thenComparing(Map.Entry::getKey))
                .map(e -> e.getKey() + "(" + (e.getValue() == null ? 0L : e.getValue()) + ")")
                .collect(Collectors.joining(","));
    }
 
    private static String buildReasonDetail(Map<String, Long> reasonCountMap,
                                           Map<String, LinkedHashSet<String>> reasonSampleMap) {
        if (reasonCountMap == null || reasonCountMap.isEmpty()) {
            return "请检查格式或唯一性";
        }
        Map<String, LinkedHashSet<String>> safeSamples = reasonSampleMap == null ? Collections.emptyMap() : reasonSampleMap;
        return reasonCountMap.entrySet().stream()
                .sorted(Comparator.<Map.Entry<String, Long>>comparingLong(e -> e.getValue() == null ? 0L : e.getValue())
                        .reversed()
                        .thenComparing(Map.Entry::getKey))
                .map(entry -> {
                    String reason = entry.getKey();
                    long count = entry.getValue() == null ? 0L : entry.getValue();
                    LinkedHashSet<String> samples = safeSamples.getOrDefault(reason, new LinkedHashSet<>());
                    String samplePart = "";
                    if (!samples.isEmpty()) {
                        long remaining = count - samples.size();
                        String suffix = remaining > 0 ? "等" + remaining + "个" : "";
                        samplePart = "[" + String.join(",", samples) + (StringUtils.hasLength(suffix) ? ("," + suffix) : "") + "]";
                    }
                    return reason + "(" + count + ")" + samplePart;
                })
                .collect(Collectors.joining(";"));
    }
 
    private static String truncate(String value, int maxLength) {
        if (value == null || maxLength <= 0) {
            return value;
        }
        if (value.length() <= maxLength) {
            return value;
        }
        return value.substring(0, maxLength);
    }
 
    @ApiOperation(value = "白名单导出")
    @PostMapping(value = "/api/v1/whitelist/exportExcels")
    public void exportExcels(@RequestBody WhitelistPageListQuery query) {
        List<XpWhitelist> exportList = xpWhitelistService.exportList(query);
        List<XpWhitelistExportExcel> xpWhitelistExportExcels = new ArrayList<>();
        long sequence = 1L;
        for (XpWhitelist xpWhitelist : exportList) {
            XpWhitelistExportExcel xpWhitelistExportExcel = new XpWhitelistExportExcel();
            xpWhitelistExportExcel.setId(sequence++);
            xpWhitelistExportExcel.setAccount(xpWhitelist.getAccount());
            xpWhitelistExportExcel.setNickName(xpWhitelist.getNickName());
            xpWhitelistExportExcel.setStatus(xpWhitelist.getStatus());
            xpWhitelistExportExcel.setIsPriorityDispatch(xpWhitelist.getIsPriorityDispatch());
            xpWhitelistExportExcel.setCreateBy(xpWhitelist.getCreateBy());
            LocalDateTime createTime = xpWhitelist.getCreateTime();
            // 将LocalDateTime转化为yyyy-MM-dd HH:mm:ss格式字符串
            xpWhitelistExportExcel.setCreateTime(createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            xpWhitelistExportExcels.add(xpWhitelistExportExcel);
        }
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        StringBuilder operationContent = new StringBuilder("共计导出"+exportList.size()+"条数据");
        XpWhitelistOperlog xpWhitelistOperlog = new XpWhitelistOperlog();
        xpWhitelistOperlog.setOperationName(sysUser.getNickName());
        xpWhitelistOperlog.setOperationAccount(sysUser.getPhoneNumber());
        xpWhitelistOperlog.setOperationType(5);
        xpWhitelistOperlog.setOperationIp(IpUtils.getIpAddr());
        xpWhitelistOperlog.setOperationAccountId(sysUser.getId());
        xpWhitelistOperlog.setOperationContent(operationContent.toString());
        xpWhitelistOperlogService.save(xpWhitelistOperlog);
        //1.获取excel模板
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), XpWhitelistExportExcel.class, xpWhitelistExportExcels);
        HttpServletResponse response = WebUtils.response();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream outputStream = null;
        try {
            String fileName = URLEncoder.encode("白名单列表.xls", "utf-8");
            response.setHeader("Content-dispodition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
 
}