hjl
2024-07-23 562699fa6d0c279fe0f4f81ce87c336a34a3fb91
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
package com.ruoyi.admin.controller;
 
 
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.admin.entity.MasterWorker;
import com.ruoyi.admin.entity.RecoveryServe;
import com.ruoyi.admin.entity.Site;
import com.ruoyi.admin.netty.NettyChannelMap;
import com.ruoyi.admin.netty.NettyWebSocketController;
import com.ruoyi.admin.service.MasterWorkerService;
import com.ruoyi.admin.service.OrderService;
import com.ruoyi.admin.service.RecoveryServeService;
import com.ruoyi.admin.service.SiteService;
import com.ruoyi.admin.vo.OrderDetailVO;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.SnowflakeIdWorker;
import com.ruoyi.common.security.annotation.Logical;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.order.api.entity.*;
import com.ruoyi.order.api.feignClient.ExchangeDispatchClient;
import com.ruoyi.order.api.feignClient.OrderClient;
import com.ruoyi.order.api.request.OrderCountDataRequest;
import com.ruoyi.system.api.model.LoginUser;
import io.netty.channel.ChannelHandlerContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 订单管理 前端控制器
 * </p>
 *
 * @author hjl
 * @since 2024-05-29
 */
@RestController
@RequestMapping("/order")
@Api(tags = {"后台-订单管理"})
public class OrderController {
 
    @Resource
    private OrderService orderService;
    @Resource
    private MasterWorkerService masterWorkerService;
    @Resource
    private RecoveryServeService recoveryServeService;
    @Resource
    private SiteService siteService;
    @Resource
    private OrderClient orderClient;
    @Resource
    private ExchangeDispatchClient dispatchClient;
    @Resource
    private TokenService tokenService;
 
    /**
     * 雪花算法类
     */
    private static final SnowflakeIdWorker SNOW_FLAKE_ID_WORKER = new SnowflakeIdWorker(5, 5);
 
 
    /**
     * 根据前台用户id查询所有订单信息
     *
     * @param phone 手机号
     */
    @ApiOperation(value = "查询用户所有订单", tags = {"后台-订单管理"})
    @GetMapping(value = "/queryList")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "手机号", name = "phone", dataType = "String", required = true)
    })
    public R<List<Order>> queryList(@RequestParam("phone") String phone) {
        return R.ok(orderClient.queryList(phone).getData());
    }
 
    /**
     * 订单列表-查询订单详情(包含服务信息、师傅信息、服务记录、订单评价)
     * 用户列表模块 点击订单记录点击详情 也是调用该接口
     * 订单评价管理 点击订单详情 也是调用该接口
     *
     * @param id 订单id
     */
    @RequiresPermissions(value = {"user_detail", "order_detail"}, logical = Logical.OR)
    @ApiOperation(value = "订单列表-查询订单详情(包含服务信息、师傅信息、服务记录、订单评价)", tags = {"后台-订单管理"})
    @GetMapping(value = "/orderDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单id", name = "id", dataType = "Integer", required = true)
    })
    public R<OrderDetailVO> orderDetail(@RequestParam String id) {
        // 独立orderService
        return R.ok(orderService.orderListDetail(id));
    }
 
    /**
     * 订单列表
     *
     * @param orderQueryRequest 订单列表查询参数
     */
    @RequiresPermissions("order_list")
    @ApiOperation(value = "订单列表-分页", tags = {"后台-订单管理"})
    @PostMapping(value = "/queryPage")
    public R<Page<Order>> queryPage(@RequestBody OrderQueryRequest orderQueryRequest) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (null == loginUser) {
            return R.loginExpire("登录失效!");
        }
        if (loginUser.getIsFranchisee()) {
            orderQueryRequest.setCityList(loginUser.getCityList());
        }
        Page<Order> data = orderClient.queryPage(orderQueryRequest).getData();
        if (null != data) {
            for (Order record : data.getRecords()) {
                // 回收服务信息
                Integer serverId = record.getServerId();
                MasterWorker masterWorker = masterWorkerService.lambdaQuery()
                        .eq(MasterWorker::getId, serverId)
                        .eq(MasterWorker::getIsDelete, 0).one();
                if (null != masterWorker) {
                    record.setServerName(masterWorker.getRealName());
                    record.setServerPhone(masterWorker.getPhone());
                }
            }
        }
        return R.ok(data);
    }
 
    /**
     * 订单列表
     */
    @RequiresPermissions("order_list")
    @ApiOperation(value = "订单列表-各订单数量统计", tags = {"后台-订单管理"})
    @PostMapping(value = "/orderPageCount")
    public R<OrderPageCountVO> orderPageCount(@RequestBody OrderQueryRequest orderQueryRequest) {
        return R.ok(orderClient.orderPageCount(orderQueryRequest).getData());
    }
 
    /**
     * 站点详情
     *
     * @param id 订单id
     */
    @RequiresPermissions("order_detail")
    @ApiOperation(value = "订单列表-订单详情", tags = {"后台-订单管理"})
    @GetMapping(value = "/detail")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单id", name = "id", dataType = "Integer", required = true)
    })
    public R<Order> detail(@RequestParam String id) {
        return R.ok(orderClient.detail(id).getData());
    }
 
    /**
     * 新增订单
     * 后台订单为指定订单,默认为待上门状态
     *
     * @param order 站点信息
     */
    @RequiresPermissions("order_save")
    @ApiOperation(value = "订单列表-新增订单", tags = {"后台-订单管理"})
    @PostMapping(value = "/save")
    public R<String> save(@RequestBody OrderRequest order) {
        // 站点信息
        Site site = siteService.lambdaQuery()
                .eq(Site::getId, order.getSiteId())
                .eq(Site::getIsDelete, 0).one();
        order.setSiteName(site.getSiteName());
        // 师傅信息
        if (null != order.getServerId()) {
            MasterWorker masterWorker = masterWorkerService.lambdaQuery()
                    .eq(MasterWorker::getId, order.getServerId())
                    .eq(MasterWorker::getIsDelete, 0).one();
            order.setServerName(masterWorker.getRealName());
            order.setServerPhone(masterWorker.getPhone());
            // 待上门
            order.setState(Constants.ONE);
        } else {
            // 待派单状态
            order.setState(Constants.ZERO);
        }
        // 后台订单
        order.setType(Constants.ONE);
        order.setSubsidy(BigDecimal.ZERO);
        order.setOrderNumber(String.valueOf(SNOW_FLAKE_ID_WORKER.nextId()));
        // 回收服务信息
        RecoveryServe recoveryServe = recoveryServeService.lambdaQuery()
                .eq(RecoveryServe::getId, order.getServeId())
                .eq(RecoveryServe::getIsDelete, 0).one();
        order.setServeName(recoveryServe.getServeName());
        order.setServePrice(recoveryServe.getDefaultPrice());
        order.setOrderMoney(recoveryServe.getDefaultPrice());
        Boolean data = orderClient.save(order).getData();
        if (null == data) {
            return R.fail(orderClient.save(order).getMsg());
        }
        System.out.println("服务人员id:" + order.getServerId());
        ChannelHandlerContext context = NettyChannelMap.getData(String.valueOf(order.getServerId()));
        System.out.println("socket连接信息:" + context);
        if (null != context) {
            System.out.println("服务端发送消息到: " + order.getServerId());
            NettyWebSocketController.sendMsgToClient(context, "您有一条新的订单,请注意查收!");
        }
        return data ? R.ok() : R.fail();
    }
 
    /**
     * 订单派单/改派
     *
     * @param type 1:订单派单;2:订单改派
     */
    @RequiresPermissions("order_reassignment")
    @ApiOperation(value = "订单列表-订单派单/改派", tags = {"后台-订单管理"})
    @GetMapping(value = "/reassignment")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "操作类型(1:订单派单;2:订单改派)", name = "type", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "订单id", name = "orderId", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "服务人员id", name = "workerId", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "改派原因", name = "applyReason", dataType = "String")
    })
    @Transactional(rollbackFor = Exception.class)
    public R<String> reassignment(@RequestParam Integer type, @RequestParam String orderId,
                                  @RequestParam Integer workerId, String applyReason) {
        MasterWorker masterWorker = masterWorkerService.lambdaQuery()
                .eq(MasterWorker::getId, workerId)
                .eq(MasterWorker::getIsDelete, 0).one();
        Order item = orderClient.detail(orderId).getData();
        Order order = orderClient.exchangeOrder(type, orderId, workerId,
                masterWorker.getRealName(), masterWorker.getPhone()).getData();
        // 订单派单
        boolean result = true;
        if (Constants.TWO.equals(type)) {
            if (order.getState().equals(Constants.SIX) || order.getState().equals(Constants.THREE)) {
                orderClient.updateState(order.getId(), Constants.ONE);
            }
            // 订单状态为 待完工时,需要更改状态 待上门且清空师傅到达预约点时间
            if (order.getState().equals(Constants.TWO)) {
                orderClient.updateStateAndArrivalTime(orderId, Constants.ONE);
            }
            // 生成改派信息
            ChangeDispatch changeDispatch = new ChangeDispatch();
            changeDispatch.setWorkerId(item.getServerId());
            changeDispatch.setWorkerName(item.getServerName());
            changeDispatch.setApplyReason(applyReason);
            changeDispatch.setApplyTime(new Date());
            changeDispatch.setState(Constants.ONE);
            changeDispatch.setOrderId(orderId);
            changeDispatch.setOrderNumber(item.getOrderNumber());
            if (null != item.getUserId()) {
                changeDispatch.setUserId(item.getUserId());
            }
            changeDispatch.setUserName(item.getReservationName());
            changeDispatch.setIsDelete(Constants.ZERO);
            result = dispatchClient.saveRecord(changeDispatch).getData();
        }
        ChannelHandlerContext context = NettyChannelMap.getData(String.valueOf(workerId));
        if (null != context) {
            NettyWebSocketController.sendMsgToClient(context, "您有一条新的订单,请注意查收!");
        }
//        try {
//            WebSocketServer.sendInfo("您有一条新的订单,请注意查收!", String.valueOf(workerId));
//        } catch (IOException e) {
//            return R.fail("订单推送失败!");
//        }
        return result ? R.ok() : R.fail();
    }
 
    /**
     * 根据id批量删除站点
     *
     * @param ids 站点多条id拼接
     */
    @RequiresPermissions("order_delete")
    @ApiOperation(value = "订单列表-批量删除订单", tags = {"后台-订单管理"})
    @GetMapping(value = "/batchDelete")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "多个id ',' 拼接", name = "ids", dataType = "String", required = true)
    })
    public R<Boolean> batchDelete(@RequestParam String ids) {
        return R.ok(orderClient.batchDelete(ids).getData());
    }
 
    /**
     * 订单列表-excel导出
     *
     * @param orderQueryRequest 筛选参数
     */
    @RequiresPermissions("order_export")
    @ApiOperation(value = "订单列表-excel导出", tags = {"后台-订单管理"})
    @PostMapping(value = "/excelExport")
    public R<String> excelExport(@RequestBody OrderQueryRequest orderQueryRequest, HttpServletResponse response) {
        R<List<Order>> result = orderClient.excelExport(orderQueryRequest);
        // 独立orderService
        return orderService.excelExport(result.getData(), response);
    }
 
    /**
     * 旧数据迁移
     *
     * @param index 权限
     */
    @ApiOperation(value = "旧数据迁移", tags = {"后台-首页"})
    @GetMapping(value = "/oldData")
    public R<String> oldData(@RequestParam Integer index, @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize) {
        return orderClient.oldData(index, pageNum, pageSize);
    }
 
    /**
     * 订单列表-excel导出
     *
     * @param name  师傅姓名
     * @param phone 师傅电话
     */
    @RequiresPermissions("order_count")
    @ApiOperation(value = "订单统计", tags = {"后台-订单管理"})
    @GetMapping(value = "/orderCount")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "师傅姓名", name = "name", dataType = "String"),
            @ApiImplicitParam(value = "师傅电话", name = "phone", dataType = "String"),
            @ApiImplicitParam(value = "页码", name = "pageNum", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "每页条数", name = "pageSize", dataType = "Integer", required = true)
    })
    public R<Page<OrderCountVO>> orderCount(String name, String phone,
                                            @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (null == loginUser) {
            return R.loginExpire("登录失效!");
        }
        List<String> cityList = new ArrayList<>();
        if (loginUser.getIsFranchisee()) {
            cityList = loginUser.getCityList();
        }
        // 查询参数
        OrderCountDataRequest orderCountDataRequest = new OrderCountDataRequest();
        orderCountDataRequest.setWorkerName(name);
        orderCountDataRequest.setWorkerPhone(phone);
        orderCountDataRequest.setCityList(cityList);
        orderCountDataRequest.setPageNum(pageNum);
        orderCountDataRequest.setPageSize(pageSize);
        // 远程调用
        Page<OrderCountVO> data = orderClient.orderCount(orderCountDataRequest).getData();
        List<Integer> idList = data.getRecords().stream().map(OrderCountVO::getWorkerId)
                .collect(Collectors.toList());
        List<MasterWorker> masterWorkerList;
        if (!idList.isEmpty()) {
            masterWorkerList = masterWorkerService.lambdaQuery()
                    .in(MasterWorker::getId, idList)
                    .eq(MasterWorker::getIsDelete, 0).list();
        } else {
            masterWorkerList = masterWorkerService.lambdaQuery()
                    .eq(MasterWorker::getIsDelete, 0).list();
        }
        // 师傅头像列表
        Map<Integer, String> profilePictureMap = masterWorkerList.stream().collect(Collectors.toMap(MasterWorker::getId,
                mw -> Optional.ofNullable(mw.getProfilePicture()).orElse("")));
        // 师傅姓名
        Map<Integer, String> realNameMap = masterWorkerList.stream().collect(Collectors.toMap(MasterWorker::getId,
                mw -> Optional.ofNullable(mw.getRealName()).orElse("")));
        for (OrderCountVO record : data.getRecords()) {
            Integer workerId = record.getWorkerId();
            record.setRealName(realNameMap.get(workerId));
            record.setProfilePicture(profilePictureMap.get(workerId));
        }
        return R.ok(data);
    }
 
}