#
Junjie
2024-10-17 d62c5c0eb2e28b7bf27d23de84a609b5a2e415e4
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
package com.zy.asrs.wcs.core.controller;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.asrs.framework.common.Cools;
import com.zy.asrs.framework.common.R;
import com.zy.asrs.wcs.common.annotation.OperationLog;
import com.zy.asrs.wcs.common.domain.BaseParam;
import com.zy.asrs.wcs.common.domain.KeyValVo;
import com.zy.asrs.wcs.common.domain.PageParam;
import com.zy.asrs.wcs.core.domain.param.ShuttleCommandParam;
import com.zy.asrs.wcs.core.domain.param.ShuttleCommandRollbackParam;
import com.zy.asrs.wcs.core.domain.param.ShuttleCommandUpdateCompleteParam;
import com.zy.asrs.wcs.core.entity.Motion;
import com.zy.asrs.wcs.core.entity.MotionLog;
import com.zy.asrs.wcs.core.entity.Task;
import com.zy.asrs.wcs.core.entity.TaskLog;
import com.zy.asrs.wcs.core.model.NavigateNode;
import com.zy.asrs.wcs.core.model.command.ShuttleAssignCommand;
import com.zy.asrs.wcs.core.model.command.ShuttleCommand;
import com.zy.asrs.wcs.core.model.command.ShuttleRedisCommand;
import com.zy.asrs.wcs.core.model.enums.ShuttleCommandModeType;
import com.zy.asrs.wcs.core.model.enums.TaskStsType;
import com.zy.asrs.wcs.core.service.MotionLogService;
import com.zy.asrs.wcs.core.service.MotionService;
import com.zy.asrs.wcs.core.service.TaskLogService;
import com.zy.asrs.wcs.core.service.TaskService;
import com.zy.asrs.wcs.core.utils.RedisUtil;
import com.zy.asrs.wcs.core.utils.Utils;
import com.zy.asrs.wcs.rcs.constant.DeviceRedisConstant;
import com.zy.asrs.wcs.system.controller.BaseController;
import com.zy.asrs.wcs.utils.ExcelUtil;
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.*;
 
@RestController
@RequestMapping("/api")
public class TaskController extends BaseController {
 
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskLogService taskLogService;
    @Autowired
    private MotionService motionService;
    @Autowired
    private MotionLogService motionLogService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ObjectMapper objectMapper;
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @PostMapping("/task/page")
    public R page(@RequestBody Map<String, Object> map) {
        BaseParam baseParam = buildParam(map, BaseParam.class);
        PageParam<Task, BaseParam> pageParam = new PageParam<>(baseParam, Task.class);
        return R.ok().add(taskService.page(pageParam, pageParam.buildWrapper(true)));
    }
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @PostMapping("/task/list")
    public R list(@RequestBody Map<String, Object> map) {
        return R.ok().add(taskService.list());
    }
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @GetMapping("/task/{id}")
    public R get(@PathVariable("id") Long id) {
        return R.ok().add(taskService.getById(id));
    }
 
    @PreAuthorize("hasAuthority('core:task:save')")
    @OperationLog("添加任务列表")
    @PostMapping("/task/save")
    public R save(@RequestBody Task task) {
        if (!taskService.save(task)) {
            return R.error("添加失败");
        }
        return R.ok("添加成功");
    }
 
    @PreAuthorize("hasAuthority('core:task:update')")
    @OperationLog("修改任务列表")
    @PostMapping("/task/update")
    public R update(@RequestBody Task task) {
        if (!taskService.updateById(task)) {
            return R.error("修改失败");
        }
        return R.ok("修改成功");
    }
 
    @PreAuthorize("hasAuthority('core:task:remove')")
    @OperationLog("删除任务列表")
    @PostMapping("/task/remove/{ids}")
    public R remove(@PathVariable Long[] ids) {
        if (!taskService.removeByIds(Arrays.asList(ids))) {
            return R.error("删除失败");
        }
        return R.ok("删除成功");
    }
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @PostMapping("/task/query")
    public R query(@RequestParam(required = false) String condition) {
        List<KeyValVo> vos = new ArrayList<>();
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        if (!Cools.isEmpty(condition)) {
            wrapper.like(Task::getTaskNo, condition);
        }
        taskService.page(new Page<>(1, 30), wrapper).getRecords().forEach(
                item -> vos.add(new KeyValVo(item.getId(), item.getTaskNo()))
        );
        return R.ok().add(vos);
    }
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @PostMapping("/task/export")
    public void export(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        ExcelUtil.build(ExcelUtil.create(taskService.list(), Task.class), response);
    }
 
    @PreAuthorize("hasAuthority('core:task:complete')")
    @OperationLog("手动完成任务")
    @PostMapping("/task/complete/{id}")
    @Transactional
    public synchronized R complete(@PathVariable Long id) {
        Task task = taskService.getById(id);
        if (task == null) {
            return R.error("任务不存在");
        }
        switch (TaskStsType.query(task.getTaskSts())) {
            case NEW_INBOUND:
            case ANALYZE_INBOUND:
            case EXECUTE_INBOUND:
                task.setTaskSts(TaskStsType.COMPLETE_INBOUND.sts);
                break;
            case NEW_OUTBOUND:
            case ANALYZE_OUTBOUND:
            case EXECUTE_OUTBOUND:
                task.setTaskSts(TaskStsType.COMPLETE_OUTBOUND.sts);
                break;
            case NEW_CHARGE:
            case ANALYZE_CHARGE:
            case EXECUTE_CHARGE:
                task.setTaskSts(TaskStsType.CHARGE_WORKING.sts);
                break;
            case NEW_MOVE:
            case ANALYZE_MOVE:
            case EXECUTE_MOVE:
                task.setTaskSts(TaskStsType.COMPLETE_MOVE.sts);
                break;
            case NEW_MANUAL:
            case ANALYZE_MANUAL:
            case EXECUTE_MANUAL:
                task.setTaskSts(TaskStsType.COMPLETE_MANUAL.sts);
                break;
            default:
                return R.error("当前状态不可被完成");
        }
        task.setUpdateTime(new Date());
        task.setUpdateBy(getLoginUserId());
        if (!taskService.updateById(task)) {
            return R.error("完成失败");
        }
        return R.ok("任务完成");
    }
 
    @PreAuthorize("hasAuthority('core:task:cancel')")
    @OperationLog("手动取消任务")
    @PostMapping("/task/cancel/{id}")
    @Transactional
    public synchronized R cancel(@PathVariable Long id) {
        Task task = taskService.getById(id);
        if (task == null) {
            return R.error("任务不存在");
        }
 
        //创建历史档
        TaskLog taskLog = new TaskLog();
        taskLog.sync(task);
        taskLog.setUpdateTime(new Date());
        taskLog.setUpdateBy(getLoginUserId());
        taskLog.setHostId(null);
        taskLogService.save(taskLog);
 
        List<Motion> motions = motionService.list(new LambdaQueryWrapper<Motion>().eq(Motion::getTaskNo, task.getTaskNo()).eq(Motion::getHostId, task.getHostId()));
        for (Motion motion : motions) {
            //创建动作历史档
            MotionLog motionLog = new MotionLog();
            motionLog.sync(motion);
            motionLog.setUpdateTime(new Date());
            motionLog.setHostId(null);
            motionLogService.save(motionLog);
        }
 
        //删除源任务
        taskService.removeById(task.getId());
        //删除动作
        motionService.remove(new LambdaQueryWrapper<Motion>().eq(Motion::getTaskNo, task.getTaskNo()).eq(Motion::getHostId, task.getHostId()));
 
        return R.ok("取消成功");
    }
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @PostMapping("/task/shuttleCommand")
    public R shuttleCommand(@RequestBody ShuttleCommandParam param) {
        Object object = redisUtil.get(DeviceRedisConstant.SHUTTLE_WORK_FLAG + param.getTaskNo());
        if (object == null) {
            return R.ok();
        }
 
        ShuttleRedisCommand redisCommand = null;
        try {
            redisCommand = objectMapper.readValue(String.valueOf(object), ShuttleRedisCommand.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
 
        if (redisCommand == null) {
            return R.ok();
        }
 
        HashMap<String, Object> hashMap = new HashMap<>();
        ShuttleAssignCommand assignCommand = redisCommand.getAssignCommand();
        List<ShuttleCommand> commands = assignCommand.getCommands();
        Integer commandStep = redisCommand.getCommandStep();//当前步序
 
        ArrayList<JSONObject> list = new ArrayList<>();
        int index = 0;
        for (ShuttleCommand command : commands) {
            JSONObject data = JSON.parseObject(JSON.toJSONString(command));
            data.put("index", index++);
            data.put("commandStep", commandStep);
 
            ShuttleCommandModeType type = ShuttleCommandModeType.get(command.getMode());
            if (type == null) {
                data.put("mode$", command.getMode());
            }else {
                data.put("mode$", type.desc);
            }
 
            if (command.getNodes() != null) {
                List<NavigateNode> nodes = command.getNodes();
                NavigateNode start = nodes.get(0);
                NavigateNode target = nodes.get(nodes.size() - 1);
                data.put("start", Utils.getLocNo(start.getX(), start.getY(), start.getZ()));
                data.put("target", Utils.getLocNo(target.getX(), target.getY(), target.getZ()));
            }
 
            list.add(data);
        }
 
 
        hashMap.put("total", commands.size());
        hashMap.put("records", list);
        hashMap.put("commandStep", commandStep);
        return R.ok().add(hashMap);
    }
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @PostMapping("/task/shuttleCommand/completeSwitch")
    public R shuttleCommandCompleteSwitch(@RequestBody ShuttleCommandUpdateCompleteParam param) {
        Object object = redisUtil.get(DeviceRedisConstant.SHUTTLE_WORK_FLAG + param.getTaskNo());
        if (object == null) {
            return R.error("指令不存在");
        }
 
        ShuttleRedisCommand redisCommand = null;
        try {
            redisCommand = objectMapper.readValue(String.valueOf(object), ShuttleRedisCommand.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
 
        if (redisCommand == null) {
            return R.error("指令不存在");
        }
 
        ShuttleAssignCommand assignCommand = redisCommand.getAssignCommand();
        List<ShuttleCommand> commands = assignCommand.getCommands();
        ShuttleCommand command = commands.get(param.getIndex());
        command.setComplete(param.getComplete());
 
        redisUtil.set(DeviceRedisConstant.SHUTTLE_WORK_FLAG + param.getTaskNo(), JSON.toJSONString(redisCommand, SerializerFeature.DisableCircularReferenceDetect));
        return R.ok();
    }
 
    @PreAuthorize("hasAuthority('core:task:list')")
    @PostMapping("/task/shuttleCommand/commandRollback")
    public R shuttleCommandRollback(@RequestBody ShuttleCommandRollbackParam param) {
        Object object = redisUtil.get(DeviceRedisConstant.SHUTTLE_WORK_FLAG + param.getTaskNo());
        if (object == null) {
            return R.error("指令不存在");
        }
 
        ShuttleRedisCommand redisCommand = null;
        try {
            redisCommand = objectMapper.readValue(String.valueOf(object), ShuttleRedisCommand.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
 
        if (redisCommand == null) {
            return R.error("指令不存在");
        }
 
        redisCommand.setCommandStep(param.getIndex());
        redisUtil.set(DeviceRedisConstant.SHUTTLE_WORK_FLAG + param.getTaskNo(), JSON.toJSONString(redisCommand, SerializerFeature.DisableCircularReferenceDetect));
        return R.ok();
    }
}