vincentlu
1 天以前 9480117a82283efc252063814391e2ab5e653e91
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
package com.zy.acs.manager.manager.controller;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.acs.common.utils.GsonUtils;
import com.zy.acs.common.utils.QrCodeCodecSupport;
import com.zy.acs.framework.common.Cools;
import com.zy.acs.framework.common.R;
import com.zy.acs.framework.exception.CoolException;
import com.zy.acs.manager.common.annotation.OperationLog;
import com.zy.acs.manager.common.domain.BaseParam;
import com.zy.acs.manager.common.domain.KeyValVo;
import com.zy.acs.manager.common.domain.PageParam;
import com.zy.acs.manager.common.utils.ExcelUtil;
import com.zy.acs.manager.manager.entity.Code;
import com.zy.acs.manager.manager.entity.CodeGap;
import com.zy.acs.manager.manager.entity.FuncSta;
import com.zy.acs.manager.manager.entity.Route;
import com.zy.acs.manager.manager.enums.StatusType;
import com.zy.acs.manager.manager.service.CodeGapService;
import com.zy.acs.manager.manager.service.CodeService;
import com.zy.acs.manager.manager.service.FuncStaService;
import com.zy.acs.manager.manager.service.RouteService;
import com.zy.acs.manager.system.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletResponse;
import java.util.*;
 
@Slf4j
@RestController
@RequestMapping("/api")
public class CodeController extends BaseController {
 
    @Autowired
    private CodeService codeService;
    @Autowired
    private CodeGapService codeGapService;
    @Autowired
    private RouteService routeService;
    @Autowired
    private FuncStaService funcStaService;
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping("/code/page")
    public R page(@RequestBody Map<String, Object> map) {
        BaseParam baseParam = buildParam(map, BaseParam.class);
        PageParam<Code, BaseParam> pageParam = new PageParam<>(baseParam, Code.class);
        return R.ok().add(codeService.page(pageParam, pageParam.buildWrapper(true)));
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping("/code/list")
    public R list(@RequestBody Map<String, Object> map) {
        return R.ok().add(codeService.list());
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping({"/code/many/{ids}", "/codes/many/{ids}"})
    public R many(@PathVariable Long[] ids) {
        return R.ok().add(codeService.listByIds(Arrays.asList(ids)));
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @GetMapping("/code/{id}")
    public R get(@PathVariable("id") Long id) {
        return R.ok().add(codeService.getCacheById(id));
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping("/code/info")
    public R info(@RequestParam(required = false) String codeData) {
        if (Cools.isEmpty(codeData)) {
            return R.error();
        }
        Code code = codeService.getCacheByData(codeData);
        if (code == null) {
            return R.error("Code Not Found");
        }
        return R.ok().add(code);
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping("/code/route/list")
    public R routeList(@RequestParam(required = false) String codeData) {
        if (Cools.isEmpty(codeData)) {
            return R.error();
        }
        Code code = codeService.getCacheByData(codeData);
        if (code == null) {
            return R.ok().add(Collections.emptyList());
        }
        List<Route> routeList = routeService.list(new LambdaQueryWrapper<Route>()
                .eq(Route::getStatus, StatusType.ENABLE.val)
                .and(wrapper -> wrapper.eq(Route::getStartCode, code.getId()).or().eq(Route::getEndCode, code.getId()))
                .orderByAsc(Route::getId));
        return R.ok().add(routeList);
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping("/code/funcSta/list")
    public R funcStaList(@RequestParam(required = false) String codeData) {
        if (Cools.isEmpty(codeData)) {
            return R.error();
        }
        Code code = codeService.getCacheByData(codeData);
        if (code == null) {
            return R.ok().add(Collections.emptyList());
        }
        List<FuncSta> funcStaList = funcStaService.list(new LambdaQueryWrapper<FuncSta>()
                .eq(FuncSta::getCode, code.getId())
                .eq(FuncSta::getStatus, StatusType.ENABLE.val)
                .orderByAsc(FuncSta::getId));
        return R.ok().add(funcStaList);
    }
 
    @PreAuthorize("hasAuthority('manager:code:save')")
    @OperationLog("Create Code")
    @PostMapping("/code/save")
    public R save(@RequestBody Code code) {
        code.setData(QrCodeCodecSupport.normalize(code.getData()));
        code.setUuid("code".concat(code.getData()));
        code.setCreateBy(getLoginUserId());
        code.setCreateTime(new Date());
        code.setUpdateBy(getLoginUserId());
        code.setUpdateTime(new Date());
        if (!codeService.save(code)) {
            return R.error("Save Fail");
        }
        codeService.refreshCacheById(code.getId());
        return R.ok("Save Success").add(code);
    }
 
    @PreAuthorize("hasAuthority('manager:code:update')")
    @OperationLog("Update Code")
    @PostMapping("/code/update")
    public R update(@RequestBody Code code) {
        Code origin = codeService.getById(code.getId());
        boolean cornerChanged = origin != null
                && code.getCorner() != null
                && !Objects.equals(origin.getCorner(), code.getCorner());
        code.setData(QrCodeCodecSupport.normalize(code.getData()));
        code.setUpdateBy(getLoginUserId());
        code.setUpdateTime(new Date());
        if (!codeService.updateById(code)) {
            return R.error("Update Fail");
        }
        List<Long> affectedCodeIds = new ArrayList<>(routeService.getAdjacencyNode(code.getId()));
        if (!cornerChanged) {
            affectedCodeIds.add(code.getId());
        }
        codeService.evictCacheById(code.getId(), origin == null ? null : origin.getData());
        codeService.refreshCacheById(code.getId());
        if (!affectedCodeIds.isEmpty()) {
            codeService.refreshCornerByCodeIds(affectedCodeIds);
        }
        return R.ok("Update Success").add(code);
    }
 
    @PreAuthorize("hasAuthority('manager:code:remove')")
    @OperationLog("Delete Code")
    @PostMapping("/code/remove/{ids}")
    @Transactional
    public R remove(@PathVariable Long[] ids) {
        List<Long> affectedCodeIds = new ArrayList<>();
        for (Long id : ids) {
            Code code = codeService.getById(id);
            if (null == code) {
                continue;
            }
            affectedCodeIds.addAll(routeService.getAdjacencyNode(code.getId()));
            codeGapService.remove(new LambdaQueryWrapper<CodeGap>().eq(CodeGap::getCode0, code.getId()).or().eq(CodeGap::getCode1, code.getId()));
            routeService.remove(new LambdaQueryWrapper<Route>().eq(Route::getStartCode, code.getId()).or().eq(Route::getEndCode, code.getId()));
            if (!codeService.removeById(id)) {
                throw new CoolException("failed to remove code");
            }
            codeService.evictCacheById(code.getId(), code.getData());
        }
        codeService.refreshCornerByCodeIds(affectedCodeIds);
        return R.ok("Delete Success").add(ids);
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping("/code/query")
    public R query(@RequestParam(required = false) String condition) {
        List<KeyValVo> vos = new ArrayList<>();
        LambdaQueryWrapper<Code> wrapper = new LambdaQueryWrapper<>();
        if (!Cools.isEmpty(condition)) {
            wrapper.like(Code::getUuid, condition);
        }
        codeService.page(new Page<>(1, 30), wrapper).getRecords().forEach(
                item -> vos.add(new KeyValVo(item.getId(), item.getUuid()))
        );
        return R.ok().add(vos);
    }
 
    @PreAuthorize("hasAuthority('manager:code:list')")
    @PostMapping("/code/export")
    public void export(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        // 1. 提取筛选条件(兼容前端 { filter: {...} } 格式)
        Map<String, Object> filter = map;
        if (map != null && map.containsKey("filter")) {
            Object filterObj = map.get("filter");
            if (filterObj instanceof Map) {
                filter = (Map<String, Object>) filterObj;
            }
        }
 
        // 2. 构建查询条件(MyBatis-Plus)
        QueryWrapper<Code> wrapper = new QueryWrapper<>();
        if (filter != null && !filter.isEmpty()) {
            // 根据前端可能传递的字段添加条件(字段名需与数据库列或实体属性对应)
            if (filter.containsKey("corner")) {
                wrapper.eq("corner", filter.get("corner"));
            }
            if (filter.containsKey("condition")) {
                String condition = (String) filter.get("condition");
                wrapper.and(w -> w.like("data", condition).or().like("uuid", condition));
            }
            if (filter.containsKey("timeStart")) {
                wrapper.ge("create_time", filter.get("timeStart"));
            }
            if (filter.containsKey("timeEnd")) {
                wrapper.le("create_time", filter.get("timeEnd"));
            }
            if (filter.containsKey("x")) {
                wrapper.eq("x", filter.get("x"));
            }
            if (filter.containsKey("y")) {
                wrapper.eq("y", filter.get("y"));
            }
            if (filter.containsKey("memo")) {
                wrapper.like("memo", filter.get("memo"));
            }
            if (filter.containsKey("status")) {
                wrapper.eq("status", filter.get("status"));
            }
            // 还可以添加其他字段如 data, uuid 等
        }
 
        // 3. 查询符合条件的数据
        List<Code> list = codeService.list(wrapper);
 
        // 4. 导出 Excel
        ExcelUtil.build(ExcelUtil.create(list, Code.class), response);
    }
 
    @PreAuthorize("hasAuthority('manager:code:save')")
    @PostMapping("/code/import")
    public R importBatch(@RequestBody List<Map<String, Object>> list) {
        Date now = new Date();  Long userId = getLoginUserId();
        for (Map<String, Object> map : list) {
            Code code = Cools.convert(map, Code.class);
            code.setData(QrCodeCodecSupport.normalize(code.getData()));
            if (null != codeService.getCacheByData(code.getData())) {
                continue;
            }
            code.setUuid("code".concat(code.getData()));
//            code.setCorner(0);
            code.setScale(GsonUtils.toJson(Cools.add("x", 1).add("y", 1)));
            code.setStatus(StatusType.ENABLE.val);
            code.setCreateBy(userId);
            code.setCreateTime(now);
            code.setUpdateBy(userId);
            code.setUpdateTime(now);
            if (!codeService.save(code)) {
                log.error("failed to save code {}", JSON.toJSONString(map));
            }
            codeService.refreshCacheById(code.getId());
        }
        return R.ok();
    }
 
}