TAppOrderController.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. package com.yys.scsp.controller.app;
  2. import com.alibaba.druid.support.json.JSONUtils;
  3. import com.yys.scsp.config.jwt.JwtIgnore;
  4. import com.yys.scsp.entity.*;
  5. import com.yys.scsp.entityVo.TOrderInfoVo;
  6. import com.yys.scsp.mapper.TPowerRecordMapper;
  7. import com.yys.scsp.service.*;
  8. import com.yys.scsp.service.device.MessageService;
  9. import com.yys.scsp.utils.*;
  10. import com.yys.scsp.websocket.WebSocketServer;
  11. import org.apache.commons.lang.StringUtils;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.stereotype.Controller;
  16. import org.springframework.transaction.annotation.Transactional;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RequestParam;
  19. import org.springframework.web.bind.annotation.ResponseBody;
  20. import java.math.BigDecimal;
  21. import java.text.DateFormat;
  22. import java.text.SimpleDateFormat;
  23. import java.util.*;
  24. /**
  25. * User: yangkaiyong
  26. * Date: 2019/8/28
  27. * Remake:
  28. */
  29. @Controller
  30. @RequestMapping("app/order")
  31. @SuppressWarnings("unchecked")
  32. public class TAppOrderController {
  33. static Logger logger = LoggerFactory.getLogger(TAppOrderController.class);
  34. @Autowired
  35. private TAppUserService userService;
  36. @Autowired
  37. private TDeviceService deviceService;
  38. @Autowired
  39. private TNetworkDotService networkDotService;
  40. @Autowired
  41. private TOrderInfoService tOrderInfoService;
  42. @Autowired
  43. public MessageService messageService;
  44. @Autowired
  45. public TPowerRecordMapper powerRecordMapper;
  46. @Autowired
  47. private TMonthlyService tMonthlyService;
  48. @Autowired
  49. private TAnnualService annualService;
  50. @Autowired
  51. private SharingConfigService configService;
  52. /**
  53. * 录入订单
  54. * @param userId 用户ID
  55. * @param deviceCode 设备号
  56. * @param totalPrice 总价
  57. * @param devicePort 设备端口
  58. * @param orderType 充电类型 0刷卡充电 1 扫码充电 2免费充电 3包月充电
  59. * @param hour 充电时长,单位:分钟
  60. * @param type 收费类型 0时间 1电量 2功率
  61. * @param isFullStop 是否充满自停,默认充满自停
  62. * @param
  63. * @param
  64. * @return
  65. */
  66. @RequestMapping("saveOrder")
  67. @JwtIgnore // 加此注解, 请求不做token验证
  68. @ResponseBody
  69. @Transactional
  70. public ResultUtil saveOrder(@RequestParam(value = "userId") Integer userId,
  71. @RequestParam(value = "deviceCode") String deviceCode,
  72. @RequestParam(value = "totalPrice") Double totalPrice,
  73. @RequestParam(value = "devicePort") Integer devicePort,
  74. @RequestParam(value = "orderType") Integer orderType,
  75. @RequestParam(value = "hour") Integer hour,
  76. @RequestParam(value = "type") String type,
  77. @RequestParam(value = "isFullStop", required = false, defaultValue = "1") Integer isFullStop,
  78. @RequestParam(value = "insuranceFee", required = false, defaultValue = "0") Double insuranceFee
  79. ) {
  80. if (Objects.isNull(userId) || StringUtils.isBlank(deviceCode)
  81. || Objects.isNull(totalPrice) || Objects.isNull(devicePort)
  82. || Objects.isNull(orderType) || Objects.isNull(hour)) {
  83. return ResultUtil.error("参数不合格");
  84. }
  85. // 所有订单充电时长不得超过12小时
  86. if (hour > 12 * 60)
  87. hour = 12 * 60;
  88. TAppUser appUser = userService.findAppUserById(userId);
  89. if (Objects.isNull(appUser)) {
  90. return ResultUtil.error("用户不存在");
  91. }
  92. Map device = deviceService.findDeviceInfoByDeviceCode(deviceCode);
  93. if (Objects.isNull(device)) {
  94. return ResultUtil.error("设备未录入");
  95. }
  96. Integer portStatus = (Integer) device.get("port" + devicePort);
  97. if (portStatus == 1) {
  98. return ResultUtil.error("端口" + portStatus + "正在使用状态");
  99. }
  100. // 判断是否存在未响应的订单,是则取消下单
  101. Map orderMap = new HashMap();
  102. orderMap.put("orderStatus", 0);
  103. orderMap.put("page", 0);
  104. orderMap.put("limit", 1);
  105. orderMap.put("deviceCode", deviceCode);
  106. orderMap.put("port", devicePort);
  107. List<TOrderInfoVo> orderList = tOrderInfoService.findAppOrderList(orderMap);
  108. if (orderList.size() > 0)
  109. return ResultUtil.error("已提交订单,请勿重复提交");
  110. // //是否抽单
  111. // int isDraw = 0;
  112. boolean canUseAnnual;
  113. boolean canUseMonthly = false;
  114. //1.判断是不是包年用户
  115. Map<String, Object> annualMap = canUseAnnual(userId, device, hour);
  116. canUseAnnual = (Boolean) annualMap.get("canUseAnnual");
  117. if (canUseAnnual) {
  118. logger.info("用户{}使用包年充电{}分钟", userId, hour);
  119. orderType = 4;
  120. type = "00";
  121. hour = (Integer) annualMap.get("hour");
  122. } else {
  123. //2.判断是不是包月用户
  124. Map<String, Object> monthlyMap = canUseMonthly(userId, device, hour);
  125. canUseMonthly = (Boolean) monthlyMap.get("canUseMonthly");
  126. if (canUseMonthly) {
  127. logger.info("用户{}使用包月充电{}分钟", userId, hour);
  128. orderType = 3;
  129. type = "00";
  130. hour = (Integer) monthlyMap.get("hour");
  131. } else {
  132. if (!"03".equals(type)) {
  133. if (BigDecimal.valueOf(appUser.getCash()).compareTo(BigDecimal.valueOf(totalPrice)) < 0) {
  134. return ResultUtil.error("订单金额不能大于余额,请充值");
  135. }
  136. // 正运行订单总金额
  137. double appOrderSumPrice = tOrderInfoService.findAppOrderSumPrice(userId);
  138. BigDecimal remain = BigDecimal.valueOf(appUser.getCash()).subtract(new BigDecimal(appOrderSumPrice));
  139. if (remain.doubleValue() < totalPrice) {
  140. return ResultUtil.error("当前已有订单在充电,余额不足开启其他端口,请充值");
  141. }
  142. } else {// 电费+服务费收费
  143. // 判断余额是否大于或等于开启充电最低余额,小于不能充电
  144. String minBalance = configService.getGlobalConfig(SharingConfig.CHARGING_START_BALANCE);
  145. if (appUser.getCash().compareTo(Double.valueOf(minBalance)) < 0) {
  146. return ResultUtil.error("余额小于启动充电最低余额" + minBalance + "元,请充值");
  147. }
  148. }
  149. // 根据订单总数判断判断是否抽单
  150. // int orderCount = tOrderInfoService.getOrderCountByDeviceCode(deviceCode);
  151. // NetworkDot networkDot = networkDotService.findNetworkDotInfoById(StringISNULLUtil.mapToInteger(device.get("networkDotId")));
  152. // Integer drawOrderNumber = networkDot.getDrawNumber();
  153. // if (drawOrderNumber == null)
  154. // drawOrderNumber = Integer.valueOf(configService.getGlobalConfig(SharingConfig.DRAW_ORDER_NUMBER));
  155. // if ((orderCount + 1) % drawOrderNumber == 0)
  156. // isDraw = 1;
  157. }
  158. }
  159. // String nonceStr = (UUID.randomUUID()).toString().replaceAll("-", "");
  160. DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  161. Calendar calendar = Calendar.getInstance();
  162. String dateName = df.format(calendar.getTime());
  163. int v = (int) ((Math.random() * 9 + 1) * 1000000);
  164. //设置订单号
  165. String outTradeNo = dateName + v;
  166. OrderInfo orderInfoMy = new OrderInfo();
  167. orderInfoMy.setOrderCode(outTradeNo);
  168. orderInfoMy.setUserId(appUser.getId());
  169. orderInfoMy.setDeviceId(StringISNULLUtil.mapToInteger(device.get("id")));
  170. orderInfoMy.setTotalPrice(BigDecimal.valueOf(totalPrice));
  171. orderInfoMy.setDeviceCode(deviceCode);
  172. orderInfoMy.setDevicePort(devicePort);
  173. orderInfoMy.setOrderType(orderType);
  174. orderInfoMy.setOrderStatus(0);
  175. orderInfoMy.setPayStatus(1);
  176. // 包月、包年和电费+服务费模式订单设置为已续充
  177. if (orderType == 3 || orderType == 4 || "03".equals(type)) {
  178. orderInfoMy.setIsContinued(1);
  179. } else {
  180. orderInfoMy.setIsContinued(0);
  181. }
  182. orderInfoMy.setIsDraw(0);
  183. orderInfoMy.setInsuranceFee(insuranceFee);// 保险费用
  184. orderInfoMy.setPriceType(Integer.parseInt(type));
  185. Calendar ca = Calendar.getInstance();
  186. orderInfoMy.setCreateTime(ca.getTime());
  187. orderInfoMy.setStartTime(ca.getTime());
  188. if (!(canUseAnnual || canUseMonthly)) {
  189. switch (type) {
  190. case "00":
  191. break;
  192. case "01":// 电量
  193. hour = hour * 100;
  194. break;
  195. case "02":// 功率
  196. type = "00";
  197. hour = 25;
  198. break;
  199. case "03":// 电费+服务费
  200. type = "00";
  201. }
  202. }
  203. ca.add(Calendar.MINUTE, hour);
  204. Date end = ca.getTime();
  205. orderInfoMy.setEndTime(end);
  206. orderInfoMy.setHour(hour + "");
  207. tOrderInfoService.addOrderInfo(orderInfoMy);
  208. Integer port = devicePort;
  209. if (isFullStop == 0)
  210. port = devicePort | (1 << 8 - 1);
  211. String ports = String.format("%02x", port);
  212. String cmc = "2A0AAE" + ports + type + String.format("%04x", hour);
  213. //将十六进制字符串转数组
  214. byte[] bytes = HexUtils.hexStringToBytes(cmc);
  215. String crc = CrcTest.getCRC(bytes);
  216. System.out.println("CRC:" + crc);
  217. String s = HexUtils.HighAndLowSwap(crc);
  218. String cmd = cmc + s + "23";
  219. messageService.sendMqttMessage("/down/" + deviceCode, 1, HexUtils.hexStringToBytes(cmd));
  220. Map map = new HashMap();
  221. Map data = new HashMap();
  222. data.put("messageType", 1);
  223. map.put("deviceCode", deviceCode);
  224. map.put("devicePort", devicePort);
  225. map.put("type", 1);
  226. map.put("commandContent", cmd);
  227. map.put("createTime", new Date());
  228. map.put("commandRemarks", "启动" + devicePort + "端口");
  229. data.put("messageData", map);
  230. WebSocketServer.sendMsg(deviceCode, JSONUtils.toJSONString(data));
  231. return ResultUtil.success("执行成功!");
  232. }
  233. /**
  234. * 查询订单
  235. *
  236. * @param deviceCode
  237. * @param port
  238. * @param page
  239. * @param limit
  240. * @param userId
  241. * @param orderStatus
  242. * @return
  243. */
  244. @RequestMapping("getOrderList")
  245. @JwtIgnore // 加此注解, 请求不做token验证
  246. @ResponseBody
  247. public ResultUtil getOrderList(@RequestParam("deviceCode") String deviceCode,
  248. @RequestParam("port") Integer port,
  249. @RequestParam("page") Integer page,
  250. @RequestParam("limit") Integer limit,
  251. @RequestParam("userId") Integer userId,
  252. @RequestParam("orderStatus") Integer orderStatus) {
  253. if (StringUtils.isBlank(deviceCode) || Objects.isNull(userId) || Objects.isNull(port) || Objects.isNull(page) || Objects.isNull(limit) || Objects.isNull(orderStatus)) {
  254. return ResultUtil.error("参数不合格");
  255. }
  256. try {
  257. Map maps = new HashMap();
  258. maps.put("deviceCode", deviceCode);
  259. maps.put("port", port);
  260. maps.put("orderStatus", orderStatus);
  261. maps.put("page", (page - 1) * 10);
  262. maps.put("limit", limit);
  263. maps.put("userId", userId);
  264. List<TOrderInfoVo> appOrderList = tOrderInfoService.findAppOrderList(maps);
  265. return ResultUtil.success(appOrderList);
  266. } catch (Exception e) {
  267. return ResultUtil.error("查询设备信息失败");
  268. }
  269. }
  270. /**
  271. * 充电结束后查看弹出订单详情
  272. *
  273. * @param orderCode 订单号
  274. * @return
  275. */
  276. @RequestMapping("getOrderListByOrderCode")
  277. @JwtIgnore // 加此注解, 请求不做token验证
  278. @ResponseBody
  279. public ResultUtil getOrderListByOrderCode(@RequestParam("orderCode") String orderCode) {
  280. if (Objects.isNull(orderCode)) {
  281. return ResultUtil.error("参数不合格");
  282. }
  283. try {
  284. Map maps = new HashMap();
  285. maps.put("orderCode", orderCode);
  286. TOrderInfoVo order = tOrderInfoService.findAppOrderByOrderCode(maps);
  287. // String power = order.getChargingPower();
  288. // if (StringUtils.isEmpty(power)) {
  289. // power = order.getPower();
  290. // }
  291. // 收费标准
  292. // if (StringUtils.isNotEmpty(power)) {
  293. // Device device = deviceService.findDeviceByDeviceCode(order.getDeviceCode());
  294. // for (PriceContent priceContent : device.getPriceContentList()) {
  295. // if (Double.parseDouble(power) >= Double.parseDouble(priceContent.getPowerSectionBefore())
  296. // && ( StringUtils.isEmpty(priceContent.getPowerSectionAfter())
  297. // || Double.parseDouble(power) <= Double.parseDouble(priceContent.getPowerSectionAfter()) )) {
  298. // order.setPriceContent(priceContent);
  299. // break;
  300. // }
  301. // }
  302. // }
  303. return ResultUtil.success(order);
  304. } catch (Exception e) {
  305. return ResultUtil.error("查询订单详情失败");
  306. }
  307. }
  308. /**
  309. * 查询订单列表
  310. *
  311. * @param page 页码
  312. * @param limit 每页数
  313. * @param userId 用户id
  314. * @param orderStatus 订单状态
  315. * @return
  316. */
  317. @RequestMapping("getAppOrderListTable")
  318. @JwtIgnore // 加此注解, 请求不做token验证
  319. @ResponseBody
  320. public ResultUtil findAppOrderListTable(
  321. @RequestParam("page") Integer page,
  322. @RequestParam("limit") Integer limit,
  323. @RequestParam("userId") Integer userId,
  324. @RequestParam("orderStatus") Integer orderStatus
  325. ) {
  326. if (Objects.isNull(page) || Objects.isNull(limit) || Objects.isNull(orderStatus)) {
  327. return ResultUtil.error("参数不合格");
  328. }
  329. try {
  330. Map maps = new HashMap();
  331. maps.put("orderStatus", orderStatus);
  332. maps.put("page", (page - 1) * limit);
  333. maps.put("limit", limit);
  334. maps.put("userId", userId);
  335. List<TOrderInfoVo> appOrderList = tOrderInfoService.findAppOrderListTable(maps);
  336. return ResultUtil.success(appOrderList);
  337. } catch (Exception e) {
  338. return ResultUtil.error("查询订单列表失败");
  339. }
  340. }
  341. /**
  342. * 取消订单
  343. *
  344. * @param orderCode
  345. * @return
  346. */
  347. @RequestMapping("closeOrder")
  348. @JwtIgnore // 加此注解, 请求不做token验证
  349. @ResponseBody
  350. public ResultUtil closeOrder(@RequestParam("orderCode") String orderCode,@RequestParam(value="deviceCat",defaultValue="0") Integer deviceCat) {
  351. if (StringUtils.isBlank(orderCode)) {
  352. return ResultUtil.error("参数不合格");
  353. }
  354. try {
  355. Map maps = new HashMap();
  356. maps.put("orderCode", orderCode);
  357. TOrderInfoVo appOrderList = tOrderInfoService.findAppOrderByOrderCode(maps);
  358. if (appOrderList.getOrderStatus() != 1) {
  359. return ResultUtil.error("订单不可结束");
  360. }
  361. // 更新下发停止订单类型为用户停止
  362. tOrderInfoService.updateStopType(appOrderList.getId(), 9, "");
  363. String ports = String.format("%02x", appOrderList.getDevicePort());
  364. String cmc = "2A07AF" + ports;
  365. //将十六进制字符串转数组
  366. byte[] bytes = HexUtils.hexStringToBytes(cmc);
  367. String crc = CrcTest.getCRC(bytes);
  368. String s = HexUtils.HighAndLowSwap(crc);
  369. String cmd = cmc + s + "23";
  370. logger.info("用户结束充电,订单号:{},关闭端口报文:{}", orderCode, cmd);
  371. messageService.sendMqttMessage("/down/" + appOrderList.getDeviceCode(), 1, HexUtils.hexStringToBytes(cmd));
  372. Map map = new HashMap();
  373. map.put("deviceCode", appOrderList.getDeviceCode());
  374. map.put("type", 1);
  375. map.put("commandContent", cmd);
  376. map.put("commandRemarks", "关闭订单" + ports + "端口");
  377. //deviceService.addDeviceCommandDetails(map);
  378. WebSocketServer.sendMsg(appOrderList.getDeviceCode(), JSONUtils.toJSONString(map));
  379. return ResultUtil.success();
  380. } catch (Exception e) {
  381. return ResultUtil.error("取消订单失败");
  382. }
  383. }
  384. /**
  385. * 查询用户当天订单已充电分钟
  386. * @param userId
  387. * @param orderType
  388. * @return
  389. */
  390. @RequestMapping("getOrderSumHourByTime")
  391. @JwtIgnore // 加此注解, 请求不做token验证
  392. @ResponseBody
  393. public ResultUtil getOrderSumHourByTime(
  394. @RequestParam("userId") Integer userId,
  395. @RequestParam("orderType") Integer orderType
  396. ) {
  397. if (Objects.isNull(userId) || Objects.isNull(orderType)) {
  398. return ResultUtil.error("参数不合格");
  399. }
  400. try {
  401. return ResultUtil.success(getUsedMinute(userId, orderType));
  402. } catch (Exception e) {
  403. return ResultUtil.error("查询订单已充电分钟失败");
  404. }
  405. }
  406. /**
  407. * 查询用户当天订单已充电度数
  408. * @param userId
  409. * @param orderType
  410. * @return
  411. */
  412. @RequestMapping("getOrderUsedDegree")
  413. @JwtIgnore // 加此注解, 请求不做token验证
  414. @ResponseBody
  415. public ResultUtil getOrderUsedDegree(
  416. @RequestParam("userId") Integer userId,
  417. @RequestParam("orderType") Integer orderType
  418. ) {
  419. if (Objects.isNull(userId) || Objects.isNull(orderType)) {
  420. return ResultUtil.error("参数不合格");
  421. }
  422. try {
  423. return ResultUtil.success(getUsedDegree(userId, orderType));
  424. } catch (Exception e) {
  425. return ResultUtil.error("查询订单已充电分钟失败");
  426. }
  427. }
  428. /**
  429. * 用户是否可以使用包月
  430. * @param userId 用户ID
  431. * @param device 设备
  432. * @param hour 充电时长
  433. * @return 返回是否可以使用包月和充电时长
  434. */
  435. private Map<String, Object> canUseMonthly(Integer userId, Map<String, Object> device, int hour) {
  436. Map<String, Object> result = new HashMap<>();
  437. boolean canUseMonthly = false;
  438. TAppUser user = userService.findAppUserById(userId);
  439. TMonthly monthly = tMonthlyService.getMonthlyByUserId(userId);
  440. if (Objects.nonNull(monthly)) { //用户包月记录是否存在
  441. Boolean hasMonthCard = false;
  442. if (Integer.valueOf(device.get("hasMonthCard").toString())==1) {
  443. hasMonthCard = true;
  444. }
  445. logger.info("设备是否开启包月:{},用户包月是否有效:{}", hasMonthCard, monthly.isAvailable());
  446. //判断包月是否可用依据有3个,分别是设备是否开启包月、包月是否有效、购买包月站点是否和设备站点一致
  447. canUseMonthly = hasMonthCard && monthly.isAvailable()
  448. && monthly.getNetworkDotId().equals(Integer.valueOf(device.get("networkDotId").toString()));
  449. if (canUseMonthly) {
  450. // 用户包月剩余时长
  451. long remainMinute = monthly.getTime() - monthly.getUsedTime();
  452. logger.info("用户{}包月剩余{}分钟,当前订单充电{}分钟", userId, remainMinute, hour);
  453. // 判断包月是否设置每日限免时长,是的话获取当日已使用包月限免分钟
  454. if (remainMinute <= 0) {
  455. canUseMonthly = false;
  456. } else if (user.getChargingPower() != null && monthly.getPowerUpper() != null
  457. && user.getChargingPower().compareTo(monthly.getPowerUpper()) > 0) {
  458. canUseMonthly = false;// 用户充电功率超出包月功率限制
  459. } else {
  460. if (Objects.isNull(monthly.getDailyTime())) {
  461. if (remainMinute < hour)
  462. hour = (int) remainMinute;
  463. } else {
  464. // 当日已使用包月时长
  465. long usedMinute = getUsedMinute(userId, 3);
  466. // 计算当日剩余充电限制时长
  467. int toDayCanUseTime = (int) (monthly.getDailyTime() - usedMinute);
  468. logger.info("用户{}包月每日限免时长:{},今日已使用包月时长:{}", userId, monthly.getDailyTime(), usedMinute);
  469. // 当日剩余限制时长
  470. if (toDayCanUseTime <= 0) {
  471. logger.info("用户{}包月每日限免时长已用完", userId);
  472. canUseMonthly = false;
  473. } else {
  474. // 每日限免时长与总限免时长比较,用较小的
  475. int chargeMinute = Math.min(toDayCanUseTime, (int) remainMinute);
  476. if (chargeMinute < hour)
  477. hour = chargeMinute;
  478. }
  479. }
  480. }
  481. }
  482. }
  483. result.put("canUseMonthly", canUseMonthly);
  484. result.put("hour", hour);
  485. return result;
  486. }
  487. /**
  488. * 用户是否可以使用包年
  489. * @param userId 用户ID
  490. * @param device 设备
  491. * @param hour 充电时长
  492. * @return 返回是否可以使用包年和充电时长
  493. */
  494. private Map<String, Object> canUseAnnual(Integer userId, Map<String, Object> device, int hour) {
  495. Map<String, Object> result = new HashMap<>();
  496. boolean canUseAnnual = false;
  497. TAnnualUser annualUser = annualService.getAnnualUserByUserId(userId);
  498. if (Objects.nonNull(annualUser)) {
  499. Boolean hasAnnualCard = false;
  500. if (Integer.valueOf(device.get("hasAnnualCard").toString())==1) {
  501. hasAnnualCard = true;
  502. }
  503. logger.info("设备是否开启包年:{},用户包年是否有效:{}", hasAnnualCard, annualUser.isAvailable());
  504. //判断包年是否可用依据有3个,分别是设备是否开启包年、包年是否有效、购买包年站点是否和设备站点一致
  505. canUseAnnual = hasAnnualCard && annualUser.isAvailable()
  506. && annualUser.getNetworkDotId().equals(Integer.valueOf(device.get("networkDotId").toString()));
  507. if (canUseAnnual) {
  508. // 用户包月剩余时长
  509. long remainMinute = annualUser.getTotalMinute() - annualUser.getUsedMinute();
  510. logger.info("用户{}包年剩余{}分钟,当前订单充电{}分钟", userId, remainMinute, hour);
  511. // 判断包月是否设置每日限免时长,是的话获取当日已使用包月限免分钟
  512. if (remainMinute <= 0) {
  513. canUseAnnual = false;
  514. } else {
  515. if (Objects.isNull(annualUser.getDailyMinute())) {
  516. if (remainMinute < hour)
  517. hour = (int) remainMinute;
  518. } else {
  519. // 当日已使用包月时长
  520. long usedMinute = getUsedMinute(userId, 4);
  521. // 计算当日剩余充电限制时长
  522. int todayCanUseMinute = (int) (annualUser.getDailyMinute() - usedMinute);
  523. logger.info("用户{}包年每日限免时长:{},当天已使用时长:{}", userId, annualUser.getDailyMinute(), usedMinute);
  524. // 当日剩余限制时长
  525. if (todayCanUseMinute <= 0) {
  526. logger.info("用户{}包年每日限免时长已用完", userId);
  527. canUseAnnual = false;
  528. } else {
  529. // 每日限免时长与总限免时长比较,用较小的
  530. int chargeMinute = Math.min(todayCanUseMinute, (int) remainMinute);
  531. if (chargeMinute < hour)
  532. hour = chargeMinute;
  533. }
  534. }
  535. }
  536. }
  537. }
  538. result.put("canUseAnnual", canUseAnnual);
  539. result.put("hour", hour);
  540. return result;
  541. }
  542. private long getUsedMinute(Integer userId, Integer orderType) {
  543. Calendar calendar = Calendar.getInstance();
  544. calendar.set(Calendar.HOUR_OF_DAY, 0);
  545. calendar.set(Calendar.MINUTE, 0);
  546. calendar.set(Calendar.SECOND, 0);
  547. calendar.set(Calendar.MILLISECOND, 0);
  548. // 当天最开始时间
  549. Date startTime = calendar.getTime();
  550. calendar.add(Calendar.DATE, 1);
  551. // 第二天
  552. Date endTime = calendar.getTime();
  553. return tOrderInfoService.getOrderSumHourByTime(userId, orderType,
  554. startTime, endTime);
  555. }
  556. private double getUsedDegree(Integer userId, Integer orderType) {
  557. Calendar calendar = Calendar.getInstance();
  558. calendar.set(Calendar.HOUR_OF_DAY, 0);
  559. calendar.set(Calendar.MINUTE, 0);
  560. calendar.set(Calendar.SECOND, 0);
  561. calendar.set(Calendar.MILLISECOND, 0);
  562. // 当天最开始时间
  563. Date startTime = calendar.getTime();
  564. calendar.add(Calendar.DATE, 1);
  565. // 第二天
  566. Date endTime = calendar.getTime();
  567. return tOrderInfoService.getOrderTotalPowerByTime(userId, orderType,
  568. startTime, endTime);
  569. }
  570. }