guyue
1 天以前 91735f6452dca94bcc8782b4a7551a64b1e465e6
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
package com.linghu.controller;
 
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linghu.listener.PlatformExcelListener;
import com.linghu.listener.TypeDropdownWriteHandler;
import com.linghu.mapper.ReferenceMapper;
import com.linghu.model.common.ResponseResult;
import com.linghu.model.entity.Platform;
import com.linghu.model.entity.Reference;
import com.linghu.model.entity.Type;
import com.linghu.model.excel.ExcelDataWithRow;
import com.linghu.model.excel.PlatformExcel;
import com.linghu.model.page.CustomPage;
import com.linghu.service.PlatformService;
import com.linghu.service.TypeService;
 
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
 
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
 
@RestController
@RequestMapping("/platform")
@Api(value = "平台相关接口", tags = "设置-平台")
@Slf4j
public class PlatformController {
 
 
    @Autowired
    private PlatformService platformService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private ReferenceMapper referenceMapper;
 
    @PostMapping
    @ApiOperation(value = "添加平台")
    public ResponseResult<Platform> add(@RequestBody Platform platform) {
        // 校验平台名称和域名不能为空
        if (!StringUtils.hasText(platform.getPlatform_name())) {
            return ResponseResult.error("平台名称不能为空");
        }
        if (!StringUtils.hasText(platform.getDomain())) {
            return ResponseResult.error("平台域名不能为空");
        }
 
        boolean success = platformService.save(platform);
        if (success) {
            return ResponseResult.success(platform);
        }
        return ResponseResult.error("添加平台失败");
    }
 
    @DeleteMapping("/{platformId}")
    @ApiOperation(value = "删除平台")
    public ResponseResult<Void> delete(@PathVariable Integer platformId) {
        //平台被引用了没
        Integer count = referenceMapper.selectCount(new LambdaQueryWrapper<Reference>().eq(Reference::getPlatform_id, platformId));
        if (count > 0) {
            return ResponseResult.error("该平台被引用中,不能删除");
        }
        boolean success = platformService.removeById(platformId);
        if (success) {
            return ResponseResult.success();
        }
        return ResponseResult.error("删除平台失败");
    }
 
    @PutMapping
    @ApiOperation(value = "更新平台")
    public ResponseResult<Void> update(@RequestBody Platform platform) {
        // 校验平台名称和域名不能为空
        if (!StringUtils.hasText(platform.getPlatform_name())) {
            return ResponseResult.error("平台名称不能为空");
        }
        if (!StringUtils.hasText(platform.getDomain())) {
            return ResponseResult.error("平台域名不能为空");
        }
 
        platformService.updateById(platform);
 
        return ResponseResult.success();
    }
 
    @GetMapping("/{platformId}")
    @ApiOperation("根据id获取平台")
    public ResponseResult<Platform> getById(@PathVariable Integer platformId) {
        Platform platform = platformService.getById(platformId);
        if (platform != null) {
            return ResponseResult.success(platform);
        }
        return ResponseResult.error("平台不存在");
    }
 
    @GetMapping("/list")
    @ApiOperation("查询平台列表,不传页数和大小就查全部")
    public ResponseResult<CustomPage<Platform>> list(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize) {
        // 构建查询条件并添加排序(按创建时间倒序)
        LambdaQueryWrapper<Platform> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Platform::getCreate_time); // 新增的排序条件
 
        if (page != null && pageSize != null) {
            Page<Platform> pageInfo = new Page<>(page, pageSize);
            Page<Platform> result = platformService.page(pageInfo, queryWrapper);
            return ResponseResult.success(new CustomPage<>(result));
        } else {
            List<Platform> list = platformService.list(queryWrapper);
            CustomPage<Platform> customPage = new CustomPage<>(new Page<>());
            customPage.setRecords(list);
            customPage.setTotal(list.size());
            return ResponseResult.success(customPage);
        }
    }
 
    @GetMapping("/download")
    @ApiOperation("下载平台模板")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {
        // 获取所有类型名称
        List<Type> typeList = typeService.list();
        List<String> typeNames = typeList.stream()
                .map(Type::getType_name)
                .collect(Collectors.toList());
 
        ByteArrayOutputStream out = new ByteArrayOutputStream();
 
        // 注册下拉框拦截器
        EasyExcel.write(out, PlatformExcel.class)
                .registerWriteHandler(new TypeDropdownWriteHandler(typeNames))
                .sheet("平台模板")
                .doWrite(new ArrayList<>());
 
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=platform_template.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(out.toByteArray());
    }
 
    @PostMapping("/import")
    @ApiOperation("导入平台数据")
    public ResponseResult<String> importPlatforms(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseResult.error("上传文件不能为空");
            }
 
            // 使用自定义监听器读取数据(包含行号)
            PlatformExcelListener listener = new PlatformExcelListener();
            EasyExcel.read(file.getInputStream())
                    .head(PlatformExcel.class)
                    .sheet()
                    .registerReadListener(listener)
                    .doRead();
 
            List<ExcelDataWithRow<PlatformExcel>> excelList = listener.getDataList();
            List<Platform> platforms = new ArrayList<>();
            List<String> errorMessages = new ArrayList<>();
 
            // 遍历数据并验证(逻辑同方案一)
            for (ExcelDataWithRow<PlatformExcel> excelData : excelList) {
                int rowNum = excelData.getRowNumber();
                PlatformExcel excel = excelData.getData();
                List<String> rowErrors = new ArrayList<>();
                // 验证逻辑
                if (!StringUtils.hasText(excel.getPlatform_name())) {
                    rowErrors.add("平台名称不能为空");
                }
                if (!StringUtils.hasText(excel.getDomain())) {
                    rowErrors.add("平台域名不能为空");
                }
                // ... 其他验证
                // 查找类型(仅当类型名称不为空时检查,避免空指针)
                Integer typeId = null;
                if (StringUtils.hasText(excel.getType_name())) {
                    Type typeByName = typeService.getTypeByName(excel.getType_name());
                    if (typeByName == null) {
                        rowErrors.add("未知的平台类型: " + excel.getType_name());
                    }
                    typeId = typeByName.getType_id();
 
                }else {
                    rowErrors.add("平台类型不能为空");
                }
                if (!rowErrors.isEmpty()) {
                    errorMessages.add(String.format("第%d行错误: %s", rowNum, String.join(";", rowErrors)));
                } else {
                    // 构建Platform对象...
                    Platform platform = new Platform();
                    platform.setPlatform_name(excel.getPlatform_name());
                    platform.setDomain(excel.getDomain());
                    platform.setType_id(typeId);
                    platform.setCreate_time(LocalDateTime.now());
                    platforms.add(platform);
                }
            }
 
            // 错误处理和导入逻辑(同方案一)
            if (!errorMessages.isEmpty()) {
                // 构建清晰的错误信息
                StringBuilder errorMsg = new StringBuilder();
                errorMsg.append("导入失败,共").append(errorMessages.size()).append("条数据存在错误:\n");
                errorMessages.forEach(msg -> errorMsg.append(msg).append("\n"));
 
                return ResponseResult.error(400, errorMsg.toString());
            }
 
            // 无错误时导入...
            return ResponseResult.success("导入成功,共" + platforms.size() + "条数据");
 
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.error("文件解析失败:" + e.getMessage());
        }
    }
}