WxxcxIndexController.java 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. package com.wxxcx.index;
  2. import java.io.*;
  3. import java.math.BigDecimal;
  4. import java.security.MessageDigest;
  5. import java.sql.Timestamp;
  6. import java.sql.Types;
  7. import java.time.LocalDate;
  8. import java.time.format.DateTimeFormatter;
  9. import java.util.*;
  10. import java.util.stream.Collectors;
  11. import javax.annotation.Resource;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import com.admin.alarm_event.AlarmEvent;
  15. import com.admin.alarm_event.StayTime;
  16. import com.alibaba.excel.EasyExcel;
  17. import com.fasterxml.jackson.databind.JsonNode;
  18. import com.fasterxml.jackson.databind.ObjectMapper;
  19. import com.fasterxml.jackson.databind.node.ObjectNode;
  20. import io.swagger.annotations.Api;
  21. import io.swagger.annotations.ApiOperation;
  22. import org.apache.commons.lang.StringUtils;
  23. import org.springframework.beans.factory.annotation.Autowired;
  24. import org.springframework.dao.DataAccessException;
  25. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  26. import org.springframework.jdbc.core.JdbcTemplate;
  27. import org.springframework.util.CollectionUtils;
  28. import org.springframework.web.bind.annotation.GetMapping;
  29. import org.springframework.web.bind.annotation.PostMapping;
  30. import org.springframework.web.bind.annotation.RequestBody;
  31. import org.springframework.web.bind.annotation.RequestMapping;
  32. import org.springframework.web.bind.annotation.RequestParam;
  33. import org.springframework.web.bind.annotation.RestController;
  34. import org.springframework.web.multipart.MultipartFile;
  35. import com.admin.dev.DevVO;
  36. import com.admin.floorPlan.FloorPlanVO;
  37. import com.admin.group.GroupProVO;
  38. import com.admin.group.GroupVO;
  39. import com.admin.groupShare.GroupShareVO;
  40. import com.admin.lbt.LbtVO;
  41. import com.admin.map.GroupDevMapVO;
  42. import com.admin.sbgj.SbgjVO;
  43. import com.admin.areaBase.Base;
  44. import com.wxxcx.room.DevRoomVO;
  45. import com.wxxcx.room.RoomVO;
  46. import com.wxxcx.share.ShareVO;
  47. import com.wxxcx.targets.TargetVO;
  48. import com.wxxcx.user.MiniUserVO;
  49. import com.wxxcx.user.WxRelatiion;
  50. import com.alibaba.fastjson.JSON;
  51. import com.alibaba.fastjson.JSONArray;
  52. import com.alibaba.fastjson.JSONObject;
  53. import com.pub.constant.Constants;
  54. import com.pub.env.Environment;
  55. import com.pub.jdbc.BaseDAO;
  56. import com.pub.log.Log;
  57. import com.pub.page.PageRecord;
  58. import com.pub.util.HttpUtil;
  59. import com.pub.util.JSONUtil;
  60. import com.pub.util.MqttUtil;
  61. import com.pub.util.MsgUtil;
  62. import com.pub.util.PageUtil;
  63. import com.pub.util.R;
  64. import com.pub.upload.FileUploadController;
  65. import com.pub.util.ImageUtil;
  66. @RequestMapping("/s/wxxcx/index")
  67. @Api(tags = "小程序接口")
  68. @RestController
  69. public class WxxcxIndexController<AesException extends Throwable> {
  70. @Resource
  71. private JdbcTemplate jdbcTemplate;
  72. @Autowired
  73. private BaseDAO baseDAO;
  74. @GetMapping("/login")
  75. @ApiOperation(value = "登录接口")
  76. public R login(String code) {
  77. R r = JSONUtil.getSuccessMsg(null);
  78. String res = HttpUtil.request(
  79. "https://api.weixin.qq.com/sns/jscode2session?appid=" + Constants.WXXCXAPPID + "&secret="
  80. + Constants.WXXCXAPPSECRET + "&js_code=" + code + "&grant_type=authorization_code",
  81. null, false, null, null);
  82. JSONObject obj = JSONObject.parseObject(res);
  83. r.data.put("openid", obj.getString("openid"));
  84. r.data.put("unionid", obj.getString("unionid"));
  85. // 查询是否存在该 openid
  86. List<WxRelatiion> list = baseDAO.getJdbcTemplate().query(
  87. "SELECT * FROM wx_relation WHERE openid = ?",
  88. new Object[]{obj.getString("openid")},
  89. new BeanPropertyRowMapper<>(WxRelatiion.class)
  90. );
  91. if (list.size() <= 0) {
  92. String insertSql = "INSERT INTO wx_relation (openid, unionid,fwhopenid) VALUES (?, ?,?)";
  93. baseDAO.getJdbcTemplate().update(insertSql, obj.getString("openid"), obj.getString("unionid"), null);
  94. }
  95. return r;
  96. }
  97. /**
  98. * 小程序用户登录
  99. *
  100. * @param phonef
  101. * @param password
  102. * @return
  103. * @author wy
  104. */
  105. @GetMapping("/checkUser")
  106. @ApiOperation(value = "手机号登录")
  107. public R checkUser(String phone, String password, String openid) {
  108. R r = JSONUtil.getSuccessMsg(null);
  109. // 查询用户信息
  110. Object[] args = new Object[]{phone, password};
  111. List<MiniUserVO> users = baseDAO.getJdbcTemplate().query(
  112. "SELECT * FROM user_info WHERE IFNULL(delete_tag, 0) = 0 AND phone = ? AND password = ?", args,
  113. new BeanPropertyRowMapper<>(MiniUserVO.class));
  114. if (users.size() > 0) {
  115. MiniUserVO user = users.get(0);
  116. if (StringUtils.isEmpty(user.getOpenid())) {
  117. String updateSql = "UPDATE user_info SET openid = ? WHERE phone = ?";
  118. baseDAO.getJdbcTemplate().update(updateSql, openid, phone);
  119. user.setOpenid(openid);
  120. }
  121. r.data.put("user", user);
  122. } else {
  123. r = JSONUtil.getErrorMsg("手机号码或密码错误");
  124. }
  125. return r;
  126. }
  127. /**
  128. * 查找手机号
  129. *
  130. * @param phone
  131. * @return
  132. * @author wy
  133. */
  134. @GetMapping("/checkPhone")
  135. @ApiOperation(value = "查找手机号")
  136. public R checkPhone(String phone, String openid) {
  137. R r = JSONUtil.getSuccessMsg(null);
  138. Object[] args = new Object[]{phone};
  139. List<MiniUserVO> users = baseDAO.getJdbcTemplate().query(
  140. "SELECT * FROM user_info WHERE IFNULL(delete_tag, 0) = 0 AND phone = ?", args,
  141. new BeanPropertyRowMapper<>(MiniUserVO.class));
  142. if (users.size() > 0) {
  143. MiniUserVO user = users.get(0);
  144. if (StringUtils.isEmpty(user.getOpenid()) && StringUtils.isNotEmpty(openid)) {
  145. String updateSql = "UPDATE user_info SET openid = ? WHERE phone = ?";
  146. baseDAO.getJdbcTemplate().update(updateSql, openid, phone);
  147. user.setOpenid(openid);
  148. }
  149. r.data.put("user", user);
  150. } else {
  151. r = JSONUtil.getErrorMsg("该号码未注册");
  152. }
  153. return r;
  154. }
  155. /**
  156. * 记住用户
  157. *
  158. * @param openid
  159. * @return
  160. * @author wy
  161. */
  162. @GetMapping("/checkOpenid")
  163. @ApiOperation(value = "查询是否为新用户")
  164. public R checkOpenid(String openid) {
  165. if (StringUtils.isEmpty(openid)) {
  166. return JSONUtil.getErrorMsg("openid为空");
  167. }
  168. R r = JSONUtil.getSuccessMsg(null);
  169. Object[] args = new Object[]{openid};
  170. List<MiniUserVO> users = baseDAO.getJdbcTemplate().query(
  171. "select * from user_info where IFNULL(delete_tag,0)=0 and openid =?", args,
  172. new BeanPropertyRowMapper<>(MiniUserVO.class));
  173. if (!users.isEmpty()) {
  174. r.data.put("user", users.get(0));
  175. } else {
  176. r = JSONUtil.getErrorMsg("无信息");
  177. }
  178. return r;
  179. }
  180. /**
  181. * 发送登录验证码
  182. *
  183. * @param tel
  184. * @return
  185. * @throws IOException
  186. */
  187. @GetMapping("/sendLoginCaptcha")
  188. @ApiOperation(value = "发送登录验证码")
  189. public R sendLoginCaptcha(String tel) throws IOException {
  190. R r = JSONUtil.getSuccessMsg(null);
  191. int captcha = (int) ((Math.random() * 9 + 1) * 1000);
  192. MsgUtil.sendLoginMsg(tel, String.valueOf(captcha));
  193. r.data.put("captcha", captcha);
  194. return r;
  195. }
  196. /**
  197. * 发送注册验证码
  198. *
  199. * @param tel
  200. * @return
  201. * @throws IOException
  202. */
  203. @GetMapping("/sendRegisterCaptcha")
  204. @ApiOperation(value = "发送注册验证码")
  205. public R sendRegisterCaptcha(String tel) throws IOException {
  206. R r = JSONUtil.getSuccessMsg(null);
  207. int captcha = (int) ((Math.random() * 9 + 1) * 1000);
  208. MsgUtil.sendRegisterMsg(tel, String.valueOf(captcha));
  209. r.data.put("captcha", captcha);
  210. return r;
  211. }
  212. /**
  213. * 发送跌倒提示
  214. *
  215. * @param tel
  216. * @return
  217. * @throws IOException
  218. */
  219. @GetMapping("/sendFallMsg")
  220. @ApiOperation(value = "发送跌倒提示")
  221. public R sendFallMsg(String tel, String dev_name) throws IOException {
  222. R r = JSONUtil.getSuccessMsg(null);
  223. MsgUtil.sendNotifyMsg(tel, dev_name);
  224. return r;
  225. }
  226. public String getAccessToken() {
  227. String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.WXXCXAPPID + "&secret=" + Constants.WXXCXAPPSECRET;
  228. String response = HttpUtil.request(url, null, false, null, null);
  229. JSONObject jsonResponse = JSONObject.parseObject(response);
  230. return jsonResponse.getString("access_token");
  231. }
  232. @GetMapping("/getPhoneNumber")
  233. @ApiOperation(value = "一键获取手机号")
  234. public R getPhoneNumber(String code) {
  235. R r = JSONUtil.getSuccessMsg(null);
  236. if (StringUtils.isNotEmpty(code)) {
  237. String phoneNumber = "";
  238. // 获取 access_token
  239. String accessToken = getAccessToken();
  240. // 检查 access_token 是否有效
  241. if (StringUtils.isEmpty(accessToken)) {
  242. return JSONUtil.getErrorMsg("获取 access_token 失败,请检查配置");
  243. }
  244. // 请求参数
  245. JSONObject param = new JSONObject();
  246. param.put("code", code);
  247. // 请求获取手机号的接口
  248. String res = HttpUtil.request("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, param.toJSONString(), false, null, null);
  249. // 处理返回的结果
  250. if (StringUtils.isNotEmpty(res)) {
  251. try {
  252. JSONObject resJson = JSONObject.parseObject(res);
  253. if (resJson.containsKey("phone_info") && resJson.getJSONObject("phone_info").containsKey("phoneNumber")) {
  254. phoneNumber = resJson.getJSONObject("phone_info").getString("phoneNumber");
  255. } else {
  256. phoneNumber = "未返回手机号";
  257. }
  258. } catch (Exception e) {
  259. phoneNumber = "解析失败,异常:" + e.getMessage();
  260. }
  261. } else {
  262. phoneNumber = "接口调用失败,未获取到手机号";
  263. }
  264. // 将获取到的手机号放入返回数据中
  265. r.data.put("phoneNumber", phoneNumber);
  266. } else {
  267. r.data.put("phoneNumber", "无效的 code 参数");
  268. }
  269. return r;
  270. }
  271. @GetMapping("/loginByPhone")
  272. @ApiOperation(value = "一键获取手机号登录")
  273. public R loginByPhone(String code, String openId, String unionId) {
  274. R r = JSONUtil.getSuccessMsg(null);
  275. if (StringUtils.isNotEmpty(code)) {
  276. String phoneNumber = "";
  277. // 获取 access_token
  278. String accessToken = getAccessToken();
  279. // 检查 access_token 是否有效
  280. if (StringUtils.isEmpty(accessToken)) {
  281. return JSONUtil.getErrorMsg("获取 access_token 失败,请检查配置");
  282. }
  283. // 请求参数
  284. JSONObject param = new JSONObject();
  285. param.put("code", code);
  286. // 请求获取手机号的接口
  287. String res = HttpUtil.request("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, param.toJSONString(), false, null, null);
  288. // 处理返回的结果
  289. if (StringUtils.isNotEmpty(res)) {
  290. try {
  291. JSONObject resJson = JSONObject.parseObject(res);
  292. if (resJson.containsKey("phone_info") && resJson.getJSONObject("phone_info").containsKey("phoneNumber")) {
  293. phoneNumber = resJson.getJSONObject("phone_info").getString("phoneNumber");
  294. MiniUserVO user = new MiniUserVO();
  295. List<MiniUserVO> users = baseDAO.queryAllByCondition(MiniUserVO.class, " and phone='" + phoneNumber + "' ", null);
  296. if (users.size() == 0) {
  297. user.setOpenid(openId);
  298. user.setPhone(phoneNumber);
  299. user.setDelete_tag(0);
  300. baseDAO.insertAll(user);
  301. // 查询是否存在该 openid
  302. List<WxRelatiion> list = baseDAO.getJdbcTemplate().query(
  303. "SELECT * FROM wx_relation WHERE openid = ?",
  304. new Object[]{openId},
  305. new BeanPropertyRowMapper<>(WxRelatiion.class)
  306. );
  307. if (list.size() <= 0) {
  308. String insertSql = "INSERT INTO wx_relation (openid, unionid,fwhopenid) VALUES (?, ?,?)";
  309. baseDAO.getJdbcTemplate().update(insertSql, openId, unionId, null);
  310. }
  311. } else {
  312. r = JSONUtil.getErrorMsg("该号码已注册");
  313. }
  314. } else {
  315. phoneNumber = "未返回手机号";
  316. }
  317. } catch (Exception e) {
  318. phoneNumber = "解析失败,异常:" + e.getMessage();
  319. }
  320. } else {
  321. phoneNumber = "接口调用失败,未获取到手机号";
  322. }
  323. // 将获取到的手机号放入返回数据中
  324. r.data.put("phoneNumber", phoneNumber);
  325. } else {
  326. r.data.put("phoneNumber", "无效的 code 参数");
  327. }
  328. return r;
  329. }
  330. /**
  331. * 检测用户是否拥有设备
  332. *
  333. * @param openid
  334. * @param dev_id
  335. * @return
  336. */
  337. @GetMapping("/checkDev")
  338. @ApiOperation(value = "检测用户是否拥有设备")
  339. public R checkDev(String openid, String dev_id) {
  340. R r = JSONUtil.getSuccessMsg(null);
  341. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and ((user_openid ='" + openid + "' and dev_id='" + dev_id + "') or '"
  342. + dev_id + "' in (select dev_id from dev_share where delete_tag =0 and shared ='" + openid + "' and state =1))", null);
  343. if (devs != null && devs.size() > 0) {
  344. r = JSONUtil.getErrorMsg("");
  345. }
  346. return r;
  347. }
  348. /**
  349. * 小程序用户注册
  350. *
  351. * @param user
  352. * @return
  353. * @throws IOException
  354. * @author wy
  355. */
  356. @GetMapping("/userReg")
  357. @ApiOperation(value = "小程序用户注册")
  358. public R userReg(MiniUserVO user) throws IOException {
  359. R r = JSONUtil.getSuccessMsg(null);
  360. List<MiniUserVO> users = baseDAO.queryAllByCondition(MiniUserVO.class, " and phone='" + user.getPhone() + "' ", null);
  361. if (users.size() == 0) {
  362. user.setDelete_tag(0);
  363. baseDAO.insertAll(user);
  364. } else {
  365. r = JSONUtil.getErrorMsg("该号码已注册");
  366. }
  367. return r;
  368. }
  369. /**
  370. * 首页加载
  371. *
  372. * @param user_openid
  373. * @return
  374. * @throws IOException
  375. * @author wy
  376. */
  377. @GetMapping("/home")
  378. @ApiOperation(value = "获取个人首页信息")
  379. public R home(String user_openid) throws IOException {
  380. R r = JSONUtil.getSuccessMsg(null);
  381. List<LbtVO> lbts = baseDAO.queryByCondition(LbtVO.class, null, " create_time desc ");
  382. for (LbtVO v : lbts) {
  383. v.setLbt(Constants.DOMAIN + Environment.COMMON_FILE_UPLOAD_PATH + v.getLbt());
  384. }
  385. r.data.put("lbts", lbts);
  386. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and (user_openid='" + user_openid + "' or " +
  387. "dev_id in (select dev_id from dev_share where delete_tag =0 and shared ='" + user_openid + "' and state =1))", null);
  388. r.data.put("qb", devs.size());
  389. int bj = 0;
  390. for (DevVO v : devs) {
  391. if (v.getDev_warn() != null && v.getDev_warn() == 1) {
  392. bj++;
  393. }
  394. }
  395. r.data.put("bj", bj);
  396. // 群组数
  397. List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and (user_openid='" + user_openid + "' or group_uuid in (select group_uuid"
  398. + " from group_share where delete_tag =0 and shared='" + user_openid + "' and state =1))", null);
  399. int qz = groups.size();
  400. r.data.put("qz", qz);
  401. // 待确认分享数
  402. Integer fxqr = baseDAO.getJdbcTemplate().queryForObject(
  403. "select count(dev_id) from dev_share where delete_tag=0 and shared='" + user_openid + "' and (state is null or state =0)", Integer.class);
  404. if (fxqr == null) {
  405. fxqr = 0;
  406. }
  407. r.data.put("fxqr", fxqr);
  408. return r;
  409. }
  410. /**
  411. * 修改密码
  412. *
  413. * @param user_openid
  414. * @param newPassword
  415. * @param oldPassword
  416. * @param phone
  417. * @return
  418. * @throws IOException
  419. */
  420. @GetMapping("/xgmm")
  421. @ApiOperation(value = "修改密码")
  422. public R xgmm(String user_openid, String newPassword, String oldPassword, String phone) throws IOException {
  423. R r = JSONUtil.getSuccessMsg(null);
  424. try {
  425. if (StringUtils.isNotEmpty(phone)) {
  426. MiniUserVO user = baseDAO.queryByKey(MiniUserVO.class, "openid", user_openid);
  427. if (!user.getPhone().equals(phone)) {
  428. throw new Exception("手机号码错误");
  429. }
  430. baseDAO.updateSQL("update user_info set password='" + newPassword + "',update_time ='"
  431. + new Timestamp(System.currentTimeMillis()) + "' where openid='" + user_openid + "'");
  432. } else {
  433. MiniUserVO user = baseDAO.queryByKey(MiniUserVO.class, "openid", user_openid);
  434. if (!user.getPassword().equals(oldPassword)) {
  435. throw new Exception("旧密码错误");
  436. }
  437. baseDAO.updateSQL("update user_info set password='" + newPassword + "',update_time ='"
  438. + new Timestamp(System.currentTimeMillis()) + "' where openid='" + user_openid + "'");
  439. }
  440. } catch (Exception e) {
  441. r = JSONUtil.getErrorMsg(e);
  442. }
  443. return r;
  444. }
  445. /**
  446. * 设备列表
  447. *
  448. * @param user_openid
  449. * @param keyword
  450. * @param zt
  451. * @return
  452. * @throws IOException
  453. */
  454. @GetMapping("/devList")
  455. @ApiOperation(value = "查询设备列表")
  456. public R devList(String user_openid, String keyword, Integer zt) throws IOException {
  457. R r = JSONUtil.getSuccessMsg(null);
  458. String con = "";
  459. if (StringUtils.isNotEmpty(keyword)) {
  460. con = con + " and (dev_name like '%" + keyword + "%' or dev_id like '%" + keyword + "%') ";
  461. }
  462. if (zt != null) {
  463. if (zt == 2) {
  464. con = con + " and online=0 ";
  465. }
  466. if (zt == 3) {
  467. con = con + " and online=1 ";
  468. }
  469. if (zt == 4) {
  470. con = con + " and dev_warn is not null and dev_warn =1";
  471. }
  472. }
  473. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and (user_openid='" + user_openid + "' or " +
  474. "dev_id in (select dev_id from dev_share where delete_tag =0 and shared ='" + user_openid + "' and state =1)) " + con, null);
  475. r.data.put("devs", devs);
  476. return r;
  477. }
  478. /**
  479. * 设备列表
  480. *
  481. * @param user_openid
  482. * @param keyword
  483. * @param zt
  484. * @return
  485. * @throws IOException
  486. */
  487. @GetMapping("/devListWithTimes")
  488. @ApiOperation(value = "查询设备列表")
  489. public R devListWithTimes(String user_openid, String keyword, Integer zt, String time) throws IOException {
  490. R r = JSONUtil.getSuccessMsg(null);
  491. String con = "";
  492. if (StringUtils.isNotEmpty(keyword)) {
  493. con = con + " and (dev_name like '%" + keyword + "%' or dev_id like '%" + keyword + "%') ";
  494. }
  495. if (zt != null) {
  496. if (zt == 2) {
  497. con = con + " and online=0 ";
  498. }
  499. if (zt == 3) {
  500. con = con + " and online=1 ";
  501. }
  502. if (zt == 4) {
  503. con = con + " and dev_warn is not null and dev_warn =1";
  504. }
  505. }
  506. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and (user_openid='" + user_openid + "' or " +
  507. "dev_id in (select dev_id from dev_share where delete_tag =0 and shared ='" + user_openid + "' and state =1)) " + con, null);
  508. List<Map> res = new ArrayList<>();
  509. if (devs != null && devs.size() > 0) {
  510. ObjectMapper objectMapper = new ObjectMapper();
  511. for (DevVO dev : devs) {
  512. Map beanMap = objectMapper.convertValue(dev, Map.class);
  513. LocalDate inputDate = LocalDate.now();
  514. if (StringUtils.isNotEmpty(time)) {
  515. inputDate = LocalDate.parse(time);
  516. }
  517. String inputDateStr = inputDate.toString();
  518. // 判断查询结果并返回
  519. List<StayTime> stayTimes = null;
  520. try {
  521. stayTimes = jdbcTemplate.query(
  522. "SELECT * FROM stay_time WHERE dev_id = ? AND DATE(leave_time) = ? and type = 0 order by leave_time",
  523. new Object[]{dev.getDev_id(), inputDateStr},
  524. new BeanPropertyRowMapper<>(StayTime.class)
  525. );
  526. } catch (Exception e) {
  527. e.printStackTrace();
  528. }
  529. if (Objects.nonNull(stayTimes) && stayTimes.size() > 0) {
  530. beanMap.put("stayTimes", stayTimes);
  531. beanMap.put("count", stayTimes.size());
  532. } else {
  533. beanMap.put("stayTimes", null);
  534. beanMap.put("count", 0);
  535. }
  536. res.add(beanMap);
  537. }
  538. }
  539. r.data.put("devs", res);
  540. return r;
  541. }
  542. /**
  543. * 设备解绑
  544. *
  545. * @param dev_id
  546. * @param user_openid
  547. * @return
  548. * @throws IOException
  549. */
  550. @GetMapping("/sbjb")
  551. @ApiOperation(value = "解绑设备")
  552. public R sbjb(String dev_id, String user_openid) throws IOException {
  553. R r = JSONUtil.getSuccessMsg(null);
  554. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and dev_id='" + dev_id + "' and user_openid= '" + user_openid + "'", null);
  555. try {
  556. if (devs.size() > 0) {
  557. // 绑定人解绑
  558. baseDAO.updateSQL("update dev_info set user_openid=null where dev_id='" + dev_id + "'");
  559. baseDAO.updateSQL("update dev_share set state =0,delete_tag =1 where dev_id='" + dev_id + "'");
  560. } else {
  561. // 被分享者解绑
  562. baseDAO.updateSQL("update dev_share set state =0,delete_tag =1 where dev_id='" + dev_id + "' and shared ='" + user_openid + "' ");
  563. }
  564. } catch (DataAccessException e) {
  565. // 捕获数据库相关的异常,并记录日志
  566. Log.error("数据库操作失败: ", e);
  567. r = JSONUtil.getErrorMsg("数据库操作失败,请稍后再试");
  568. } catch (Exception e) {
  569. // 捕获其他未知的异常,并记录日志
  570. Log.error("解绑设备失败: ", e);
  571. r = JSONUtil.getErrorMsg("解绑设备失败,请稍后再试");
  572. }
  573. return r;
  574. }
  575. /**
  576. * 设备绑定
  577. *
  578. * @param dev
  579. * @return
  580. * @throws IOException
  581. */
  582. @GetMapping("/sbbd")
  583. @ApiOperation(value = "绑定设备")
  584. public R sbbd(DevVO dev) throws IOException {
  585. R r = JSONUtil.getSuccessMsg(null);
  586. try {
  587. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and dev_id='" + dev.getDev_id() + "' ", null);
  588. if (devs.size() == 0) {
  589. throw new Exception("设备ID错误");
  590. }
  591. if (StringUtils.isNotEmpty(devs.get(0).getUser_openid())) {
  592. throw new Exception("设备已被绑定");
  593. }
  594. dev.setUpdate_time(new Timestamp(System.currentTimeMillis()));
  595. baseDAO.updateSQL("update dev_info set user_openid='" + dev.getUser_openid() + "',dev_name ='" + dev.getDev_name() + "',length ="
  596. + dev.getLength() + ",width=" + dev.getWidth() + ",height=" + dev.getHeight() + ",update_time ='" + dev.getUpdate_time() + "',north_angle=" +
  597. dev.getNorth_angle() + ",online =1 where dev_id='" + dev.getDev_id() + "'");
  598. } catch (Exception e) {
  599. r = JSONUtil.getErrorMsg(e);
  600. }
  601. return r;
  602. }
  603. /**
  604. * 设备详情
  605. *
  606. * @param dev_id
  607. * @return
  608. * @throws IOException
  609. */
  610. @GetMapping("/sbxq")
  611. @ApiOperation(value = "设备详情")
  612. public R sbxq(String dev_id) throws IOException {
  613. R r = JSONUtil.getSuccessMsg(null);
  614. List<DevVO> devs = baseDAO.queryAllByCondition(DevVO.class, " and dev_id ='" + dev_id + "' ", null);
  615. if (devs.size() != 0) {
  616. r.data.put("dev", devs.get(0));
  617. }
  618. return r;
  619. }
  620. @GetMapping("/sbgj")
  621. @ApiOperation(value = "设备关系")
  622. public R sbgj(String sb_id, String s_date, String e_date) throws IOException {
  623. R r = JSONUtil.getSuccessMsg(null);
  624. List<SbgjVO> sbgjs = baseDAO.queryByCondition(SbgjVO.class, " and sb_id='" + sb_id + "' and create_time>='" + s_date + "' and create_time<='" + e_date + "' ", " create_time desc ");
  625. r.data.put("sbgjs", sbgjs);
  626. return r;
  627. }
  628. /**
  629. * 设备事件
  630. *
  631. * @param dev_id
  632. * @param s_date
  633. * @param e_date
  634. * @param req
  635. * @return
  636. * @throws IOException
  637. */
  638. @GetMapping("/sbsj")
  639. @ApiOperation(value = "设备事件")
  640. public R sbsj(String dev_id, String s_date, String e_date, HttpServletRequest req) throws IOException {
  641. R r = JSONUtil.getSuccessMsg(null);
  642. String con = "";
  643. if (StringUtils.isNotEmpty(s_date)) {
  644. con = con + " and create_time>='" + s_date + "' ";
  645. }
  646. if (StringUtils.isNotEmpty(e_date)) {
  647. con = con + " and create_time<='" + e_date + "' ";
  648. }
  649. PageRecord<TargetVO> targets = baseDAO.queryAllPaginateByCondition(TargetVO.class, " and dev_id='" + dev_id + "' and event=3 " + con, PageUtil.getPageSize(req), PageUtil.getPageNum(req), " create_time desc ");
  650. r.data.put("targets", targets);
  651. return r;
  652. }
  653. @GetMapping("/sbsjV2")
  654. @ApiOperation(value = "设备事件")
  655. public R sbsjV2(String dev_id, String s_date, String e_date, HttpServletRequest req) throws IOException {
  656. StringBuilder sql = new StringBuilder("SELECT * FROM event_list WHERE dev_id = ? AND event = 3");
  657. List<Object> params = new ArrayList<>();
  658. params.add(dev_id);
  659. // 根据传入的日期条件,动态拼接 SQL
  660. if (StringUtils.isNotEmpty(s_date)) {
  661. sql.append(" AND create_time >= ?");
  662. params.add(s_date);
  663. }
  664. if (StringUtils.isNotEmpty(e_date)) {
  665. sql.append(" AND create_time <= ?");
  666. params.add(e_date);
  667. }
  668. // 分页参数
  669. int pageSize = PageUtil.getPageSize(req);
  670. int pageNum = PageUtil.getPageNum(req);
  671. int offset = (pageNum - 1) * pageSize;
  672. sql.append(" ORDER BY create_time DESC LIMIT ? OFFSET ?");
  673. params.add(pageSize);
  674. params.add(offset);
  675. // 执行查询
  676. List<TargetVO> targets = jdbcTemplate.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper<>(TargetVO.class));
  677. // 查询总数,重新初始化参数以避免分页参数干扰
  678. List<Object> countParams = new ArrayList<>();
  679. countParams.add(dev_id);
  680. if (StringUtils.isNotEmpty(s_date)) {
  681. countParams.add(s_date);
  682. }
  683. if (StringUtils.isNotEmpty(e_date)) {
  684. countParams.add(e_date);
  685. }
  686. String countSql = "SELECT COUNT(*) FROM event_list WHERE dev_id = ? AND event = 3";
  687. if (StringUtils.isNotEmpty(s_date)) {
  688. countSql += " AND create_time >= ?";
  689. }
  690. if (StringUtils.isNotEmpty(e_date)) {
  691. countSql += " AND create_time <= ?";
  692. }
  693. int total = jdbcTemplate.queryForObject(countSql, countParams.toArray(), Integer.class);
  694. // 封装分页数据
  695. PageRecord<TargetVO> pageRecord = new PageRecord<>();
  696. pageRecord.setRows(targets);
  697. pageRecord.setTotal((long) total);
  698. pageRecord.setPageSize(pageSize);
  699. pageRecord.setPageNum(pageNum);
  700. // 返回结果
  701. R r = new R();
  702. r.data.put("targets", pageRecord);
  703. return r;
  704. }
  705. /**
  706. * 处理设备事件
  707. *
  708. * @param id
  709. * @return
  710. * @throws IOException
  711. */
  712. @GetMapping("/handleMessage")
  713. @ApiOperation(value = "处理设备事件")
  714. public R handleMessage(int id) throws IOException {
  715. R r = JSONUtil.getSuccessMsg(null);
  716. try {
  717. String sql = "UPDATE event_list SET is_handle = 1 WHERE id = " + id;
  718. baseDAO.updateSQL(sql);
  719. } catch (Exception e) {
  720. r = JSONUtil.getErrorMsg(e);
  721. }
  722. return r;
  723. }
  724. /**
  725. * 设备修改保存
  726. *
  727. * @param vo
  728. * @return
  729. */
  730. @GetMapping("/devSave")
  731. @ApiOperation(value = "设备信息修改保存")
  732. public R devSave(DevVO vo) {
  733. R r = JSONUtil.getSuccessMsg(null);
  734. // 数据库更新
  735. baseDAO.updateSQL("update dev_info set dev_name ='" + vo.getDev_name() + "',north_angle=" + vo.getNorth_angle() + ",start_x=" + vo.getStart_x() + ",stop_x=" + vo.getStop_x() + ",start_y=" + vo.getStart_y() + ",stop_y=" + vo.getStop_y() + ",height=" + vo.getHeight() + ",start_z=" + vo.getStart_z() + ",stop_z=" + vo.getStop_z() + ",status_light=" + vo.getStatus_light() + " where dev_id ='" + vo.getDev_id() + "' ");
  736. DevVO devInfoVO = baseDAO.queryByKey(DevVO.class, "dev_id", vo.getDev_id());
  737. String software = devInfoVO.getSoftware();
  738. String result = "";
  739. if (software != null) {
  740. String[] parts = software.split("\\.");
  741. result = parts[0] + "." + parts[1];
  742. } else {
  743. result = "2.0";
  744. }
  745. if (Double.parseDouble(result) >= 2.0) {
  746. String topic = "/dev/" + devInfoVO.getDev_id() + "/set_device_param";
  747. Map<String, BigDecimal> base = new HashMap<>();
  748. Map<String, Map<String, BigDecimal>> baseParent = new HashMap<>();
  749. base.put("x_cm_start", vo.getStart_x());
  750. base.put("x_cm_stop", vo.getStop_x());
  751. base.put("y_cm_start", vo.getStart_y());
  752. base.put("y_cm_stop", vo.getStop_y());
  753. base.put("z_cm_start", vo.getStart_z());
  754. base.put("z_cm_stop", vo.getStop_z());
  755. baseParent.put("base", base);
  756. Map<String, BigDecimal> z_cm = new HashMap<>();
  757. z_cm.put("z_cm", vo.getHeight());
  758. JSONObject jsonObject = new JSONObject();
  759. jsonObject.put("sensor_location", z_cm);
  760. jsonObject.put("ext_region", baseParent);
  761. int indicator_led = 0;
  762. if (vo.getStatus_light() == 0) {
  763. indicator_led = 1;
  764. }
  765. if (vo.getStatus_light() == 1) {
  766. indicator_led = 0;
  767. }
  768. jsonObject.put("indicator_led", indicator_led);
  769. try {
  770. MqttUtil.pub(topic, jsonObject.toJSONString());
  771. } catch (Exception e) {
  772. // TODO: handle exception
  773. // r = JSONUtil.getErrorMsg(e);
  774. }
  775. } else {
  776. String topic = "/mps/set_device_param";
  777. JSONObject msg = new JSONObject();
  778. msg.put("dev_id", vo.getDev_id());
  779. msg.put("mounting_plain", vo.getMount_plain());
  780. msg.put("height", vo.getHeight());
  781. JSONObject area = new JSONObject();
  782. area.put("start_x", vo.getStart_x());
  783. area.put("stop_x", vo.getStop_x());
  784. area.put("start_y", vo.getStart_y());
  785. area.put("stop_y", vo.getStop_y());
  786. area.put("start_z", vo.getStart_z());
  787. area.put("stop_z", vo.getStop_z());
  788. msg.put("area", area);
  789. try {
  790. MqttUtil.pub(topic, msg.toJSONString());
  791. } catch (Exception e) {
  792. // TODO: handle exception
  793. r = JSONUtil.getErrorMsg(e);
  794. }
  795. }
  796. return r;
  797. }
  798. /**
  799. * 房间布局读取
  800. *
  801. * @param openid
  802. * @param dev_id
  803. * @return
  804. */
  805. @GetMapping("/readRoom")
  806. @ApiOperation(value = "读取房间信息")
  807. public R readRoom(String openid, String dev_id) {
  808. R r = JSONUtil.getSuccessMsg(null);
  809. DevRoomVO devRoomVO = baseDAO.queryByKey(DevRoomVO.class, "dev_id", dev_id);
  810. if (devRoomVO == null) {
  811. r = JSONUtil.getErrorMsg("房间信息不存在");
  812. return r;
  813. }
  814. JSONArray res = new JSONArray();
  815. if (devRoomVO.getFurnitures() != null && devRoomVO.getFurnitures().length() > 0) {
  816. res.addAll(JSON.parseArray(devRoomVO.getFurnitures()));
  817. }
  818. if (devRoomVO.getSub_regions() != null && devRoomVO.getSub_regions().length() > 0) {
  819. res.addAll(JSON.parseArray(devRoomVO.getSub_regions()));
  820. }
  821. // 向前端发送数据
  822. r.data.put("data", res);
  823. return r;
  824. }
  825. /**
  826. * 房间布局保存
  827. *
  828. * @param vo
  829. * @return
  830. */
  831. @PostMapping("/saveRoom")
  832. @ApiOperation(value = "房间布局保存")
  833. public R saveRoom(@RequestBody RoomVO vo) {
  834. R r = JSONUtil.getSuccessMsg(null);
  835. String dev_id = vo.getDev_id();
  836. try {
  837. String jsonString = JSON.toJSONString(vo);
  838. // 写入数据库
  839. JSONObject obj = JSONObject.parseObject(jsonString);
  840. JSONArray roomParams = obj.getJSONArray("roomParams");
  841. DevRoomVO devRoomVO = baseDAO.queryByKey(DevRoomVO.class, "dev_id", dev_id);
  842. if (devRoomVO == null) {
  843. DevRoomVO room = new DevRoomVO();
  844. room.setDelete_tag(0);
  845. room.setDev_id(dev_id);
  846. baseDAO.insertAll(room);
  847. }
  848. // StringBuffer sql = new StringBuffer("update dev_room set room_params= JSON_OBJECT(");
  849. StringBuffer sql = new StringBuffer("update dev_room set ");
  850. // sql.append("'openid','" + obj.getString("openid") + "',");
  851. // sql.append("'dev_id','" + obj.getString("dev_id") + "',");
  852. // sql.append("'start_x','" + obj.getString("start_x") + "',");
  853. // sql.append("'stop_x','" + obj.getString("stop_x") + "',");
  854. // sql.append("'start_y','" + obj.getString("start_y") + "',");
  855. // sql.append("'stop_y','" + obj.getString("stop_y") + "',");
  856. // sql.append("'roomParams'," + "JSON_ARRAY(");
  857. // 子区域插入sql
  858. StringBuffer subBuffer = new StringBuffer("sub_regions= JSON_ARRAY(");
  859. // 家具插入sql
  860. StringBuffer furBuffer = new StringBuffer("furnitures= JSON_ARRAY(");
  861. if (roomParams.size() > 0) {
  862. boolean hasSub = false;
  863. boolean hasFur = false;
  864. for (int i = 0; i < roomParams.size(); i++) {
  865. JSONObject itemObj = roomParams.getJSONObject(i);
  866. // sql.append("JSON_OBJECT('name','" + itemObj.getString("name") + "',");
  867. // sql.append("'type','" + itemObj.getString("type") + "',");
  868. // sql.append("'width'," + itemObj.getString("width") + ",");
  869. // sql.append("'height'," + itemObj.getString("height") + ",");
  870. // sql.append("'heightToM'," + itemObj.getString("heightToM") + ",");
  871. // sql.append("'left'," + itemObj.getString("left") + ",");
  872. // sql.append("'rotate'," + itemObj.getString("rotate") + ",");
  873. // sql.append("'top'," + itemObj.getString("top") + ",");
  874. // sql.append("'widthToM'," + itemObj.getString("widthToM") + ",");
  875. // sql.append("'x'," + itemObj.getString("x") + ",");
  876. // sql.append("'y'," + itemObj.getString("y") + ",");
  877. // sql.append("'yuanX'," + itemObj.getString("yuanX") + ",");
  878. // sql.append("'yuanY'," + itemObj.getString("yuanY") + "),");
  879. String type = itemObj.getString("type");
  880. if (type.contains("area") || type.contains("otherArea")) {
  881. // 子区域
  882. subBuffer.append("JSON_OBJECT('name','" + itemObj.getString("name") + "',");
  883. subBuffer.append("'type','" + itemObj.getString("type") + "',");
  884. subBuffer.append("'width'," + itemObj.getString("width") + ",");
  885. subBuffer.append("'height'," + itemObj.getString("height") + ",");
  886. // subBuffer.append("'heightToM'," + itemObj.getString("heightToM") + ",");
  887. subBuffer.append("'left'," + itemObj.getString("left") + ",");
  888. subBuffer.append("'rotate'," + itemObj.getString("rotate") + ",");
  889. subBuffer.append("'top'," + itemObj.getString("top") + ",");
  890. // subBuffer.append("'widthToM'," + itemObj.getString("widthToM") + ",");
  891. subBuffer.append("'x'," + itemObj.getString("x") + ",");
  892. subBuffer.append("'y'," + itemObj.getString("y") + ",");
  893. subBuffer.append("'yuanX'," + itemObj.getString("yuanX") + ",");
  894. subBuffer.append("'yuanY'," + itemObj.getString("yuanY") + "),");
  895. hasSub = true;
  896. } else {
  897. // 家具
  898. furBuffer.append("JSON_OBJECT('name','" + itemObj.getString("name") + "',");
  899. furBuffer.append("'type','" + itemObj.getString("type") + "',");
  900. furBuffer.append("'width'," + itemObj.getString("width") + ",");
  901. furBuffer.append("'height'," + itemObj.getString("height") + ",");
  902. // furBuffer.append("'heightToM'," + itemObj.getString("heightToM") + ",");
  903. furBuffer.append("'left'," + itemObj.getString("left") + ",");
  904. furBuffer.append("'rotate'," + itemObj.getString("rotate") + ",");
  905. furBuffer.append("'top'," + itemObj.getString("top") + ",");
  906. // furBuffer.append("'widthToM'," + itemObj.getString("widthToM") + ",");
  907. furBuffer.append("'x'," + itemObj.getString("x") + ",");
  908. furBuffer.append("'y'," + itemObj.getString("y") + ",");
  909. furBuffer.append("'yuanX'," + itemObj.getString("yuanX") + ",");
  910. furBuffer.append("'yuanY'," + itemObj.getString("yuanY") + "),");
  911. hasFur = true;
  912. }
  913. }
  914. // sql.setLength(sql.length() - 1);
  915. // sql.append("))" );
  916. if (hasSub) {
  917. subBuffer.setLength(subBuffer.length() - 1);
  918. sql.append(subBuffer).append(")");
  919. } else {
  920. sql.append(" sub_regions=null ");
  921. }
  922. sql.append(",");
  923. if (hasFur) {
  924. furBuffer.setLength(furBuffer.length() - 1);
  925. sql.append(furBuffer).append(")");
  926. } else {
  927. sql.append(" furnitures=null ");
  928. }
  929. sql.append(" where dev_id ='" + dev_id + "' ");
  930. System.out.println(sql.toString());
  931. // update dev_room set room_params= JSON_OBJECT('openid','oioMm7VtkWkvHFYBlzCR6couIENQ','dev_id','8CBFEA0B75D8','start_x','-200.0','stop_x','200.0','start_y','-200.0','stop_y','200.0',JSON_OBJECT('name','门','type','other','width',20,'height',80,'heightToM',80.0,'left',303,'rotate',false,'top',191,'widthToM',20.0,'x',-196.97,'y',198.09,'yuanX',0,'yuanY',0)) where dev_id ='8CBFEA0B75D8'
  932. baseDAO.updateSQL(sql.toString());
  933. //发送屏蔽区域的数据到服务器
  934. // 创建 ObjectMapper 实例
  935. ObjectMapper objectMapper = new ObjectMapper();
  936. // 将 JSON 字符串转换成 JsonNode 对象
  937. JsonNode rootNode = objectMapper.readTree(jsonString);
  938. // 获取 roomParams 数组
  939. JsonNode roomParamsNode = rootNode.path("roomParams");
  940. // 创建一个新的 List 用来存储 type 包含 "area" 的元素
  941. List<Base> ext_sub_regions = new ArrayList<>();
  942. for (JsonNode room : roomParamsNode) {
  943. // 遍历 roomParamsNode 数组
  944. String type = room.path("type").asText();
  945. if (type.contains("area") || type.contains("otherArea")) {
  946. Base base = new Base(0, 100, 0, 50, 1, 1);
  947. int x = room.path("x").asInt();
  948. int y = room.path("y").asInt();
  949. int width = room.path("width").asInt();
  950. int height = room.path("height").asInt();
  951. // 设置 base 对象的字段值
  952. base.setX_cm_start(x);
  953. base.setX_cm_stop(x + width);
  954. base.setY_cm_start(y);
  955. base.setY_cm_stop(y - height);
  956. // 设置固定值
  957. base.setTrack_presence(1);
  958. base.setExclude_falling(1);
  959. ext_sub_regions.add(base);
  960. }
  961. }
  962. ObjectMapper objectMapperOne = new ObjectMapper();
  963. List<ObjectNode> transformedList = new ArrayList<>();
  964. if (ext_sub_regions.size() > 0) {
  965. for (Base baseOne : ext_sub_regions) {
  966. ObjectNode newObject = objectMapperOne.createObjectNode();
  967. ObjectNode baseNode = objectMapperOne.createObjectNode();
  968. baseNode.put("x_cm_start", baseOne.getX_cm_start());
  969. baseNode.put("x_cm_stop", baseOne.getX_cm_stop());
  970. baseNode.put("y_cm_start", baseOne.getY_cm_start());
  971. baseNode.put("y_cm_stop", baseOne.getY_cm_stop());
  972. baseNode.put("presence_enter_duration", 0);
  973. baseNode.put("presence_exit_duration", 0);
  974. baseNode.put("track_presence", baseOne.getTrack_presence());
  975. baseNode.put("exclude_falling", baseOne.getExclude_falling());
  976. newObject.set("base", baseNode);
  977. newObject.put("z_cm_start", 0); // 固定为 0
  978. newObject.put("z_cm_stop", 0); // 固定为 0
  979. newObject.put("is_low_snr", 0); // 固定为 0
  980. newObject.put("is_door", 0); // 固定为 0
  981. transformedList.add(newObject);
  982. }
  983. ObjectNode resultNode = objectMapper.createObjectNode();
  984. resultNode.set("ext_sub_regions", objectMapper.valueToTree(transformedList));
  985. String jsonStringTwo = objectMapper.writeValueAsString(resultNode);
  986. try {
  987. StringBuffer getTopic = new StringBuffer("/dev/" + dev_id + "/set_device_param");
  988. MqttUtil.pub(getTopic.toString(), jsonStringTwo);
  989. } catch (Exception e) {
  990. r = JSONUtil.getErrorMsg(e);
  991. }
  992. } else {
  993. ObjectNode resultNode = objectMapper.createObjectNode();
  994. resultNode.set("ext_sub_regions", objectMapper.valueToTree(transformedList));
  995. String jsonStringTwo = objectMapper.writeValueAsString(resultNode);
  996. try {
  997. StringBuffer getTopic = new StringBuffer("/dev/" + dev_id + "/set_device_param");
  998. MqttUtil.pub(getTopic.toString(), jsonStringTwo);
  999. } catch (Exception e) {
  1000. r = JSONUtil.getErrorMsg(e);
  1001. }
  1002. }
  1003. } else {
  1004. sql.append(" sub_regions=null , furnitures=null ");
  1005. sql.append(" where dev_id ='" + dev_id + "' ");
  1006. baseDAO.updateSQL(sql.toString());
  1007. JSONObject jsonObject = new JSONObject();
  1008. JSONArray extRegion = new JSONArray();
  1009. jsonObject.put("ext_sub_regions", extRegion);
  1010. try {
  1011. StringBuffer getTopic = new StringBuffer("/dev/" + dev_id + "/set_device_param");
  1012. MqttUtil.pub(getTopic.toString(), jsonObject.toJSONString());
  1013. } catch (Exception e) {
  1014. r = JSONUtil.getErrorMsg(e);
  1015. }
  1016. }
  1017. } catch (IOException e) {
  1018. e.printStackTrace();
  1019. r = JSONUtil.getErrorMsg(e);
  1020. }
  1021. return r;
  1022. }
  1023. /**
  1024. * 设备(修改)保存
  1025. *
  1026. * @param dev
  1027. * @return
  1028. * @throws IOException
  1029. */
  1030. @GetMapping("/sbbc")
  1031. @ApiOperation(value = "设备修改保存(第一次绑定)")
  1032. public R sbbc(DevVO vo) throws IOException {
  1033. R r = JSONUtil.getSuccessMsg(null);
  1034. double length = vo.getLength().doubleValue();
  1035. double width = vo.getWidth().doubleValue();
  1036. BigDecimal start_x = new BigDecimal(-length / 2);
  1037. BigDecimal stop_x = new BigDecimal(length / 2);
  1038. BigDecimal start_y = new BigDecimal(-width / 2);
  1039. BigDecimal stop_y = new BigDecimal(width / 2);
  1040. vo.setStart_x(start_x);
  1041. vo.setStop_x(stop_x);
  1042. vo.setStart_y(start_y);
  1043. vo.setStop_y(stop_y);
  1044. // 数据库更新
  1045. baseDAO.updateSQL("update dev_info set dev_name ='" + vo.getDev_name() + "',mount_plain='" + vo.getMount_plain() + "',length=" + vo.getLength() + ",width="
  1046. + vo.getWidth() + ",height=" + vo.getHeight() + ",start_x =" + vo.getStart_x() + ",stop_x =" + vo.getStop_x() + ",start_y =" + vo.getStart_y() + ",stop_y ="
  1047. + vo.getStop_y() + ",start_z =" + vo.getStart_z() + ",stop_z =" + vo.getStop_z() + " where dev_id ='" + vo.getDev_id() + "' ");
  1048. String topic = "/mps/set_device_param";
  1049. JSONObject msg = new JSONObject();
  1050. msg.put("dev_id", vo.getDev_id());
  1051. msg.put("mounting_plain", vo.getMount_plain());
  1052. msg.put("height", vo.getHeight());
  1053. JSONObject area = new JSONObject();
  1054. area.put("start_x", vo.getStart_x());
  1055. area.put("stop_x", vo.getStop_x());
  1056. area.put("start_y", vo.getStart_y());
  1057. area.put("stop_y", vo.getStop_y());
  1058. area.put("start_z", vo.getStart_z());
  1059. area.put("stop_z", vo.getStop_z());
  1060. msg.put("area", area);
  1061. try {
  1062. MqttUtil.pub(topic, msg.toJSONString());
  1063. } catch (Exception e) {
  1064. // TODO: handle exception
  1065. r = JSONUtil.getErrorMsg(e);
  1066. }
  1067. return r;
  1068. }
  1069. // 雷达位置更新
  1070. @GetMapping("/devPosUpdate")
  1071. @ApiOperation(value = "更新雷达位置")
  1072. public R devSave(String dev_id, float x, float y) {
  1073. R r = JSONUtil.getSuccessMsg(null);
  1074. DevVO vo = baseDAO.queryByKey(DevVO.class, "dev_id", dev_id);
  1075. if (vo == null) {
  1076. return JSONUtil.getErrorMsg("未查询到该设备,请退出重试");
  1077. }
  1078. baseDAO.updateSQL("update dev_info set x=" + x + ",y=" + y + " where dev_id ='" + dev_id + "' and delete_tag=0");
  1079. return r;
  1080. }
  1081. /**
  1082. * 设备分享
  1083. *
  1084. * @param share
  1085. * @return
  1086. * @throws IOException
  1087. */
  1088. @GetMapping("/sbfx")
  1089. @ApiOperation(value = "个人分享设备")
  1090. public R sbfx(ShareVO share) throws IOException {
  1091. R r = JSONUtil.getSuccessMsg(null);
  1092. List<MiniUserVO> users = baseDAO.queryAllByCondition(MiniUserVO.class, " and phone='" + share.getShared_phone() + "' ", null);
  1093. // 被分享者已注册
  1094. if (users.size() > 0) {
  1095. MiniUserVO user = users.get(0);
  1096. share.setShared(user.getOpenid());
  1097. share.setState(0);
  1098. // 检查当前设备是否存在未处理邀请
  1099. List<ShareVO> shares = baseDAO.queryAllByCondition(ShareVO.class, " and sharer='" + share.getSharer() + "' and shared='" + share.getShared() +
  1100. "' and dev_id='" + share.getDev_id() + "' and state=0", null);
  1101. // 已发送邀请未处理
  1102. if (shares.size() > 0) {
  1103. r = JSONUtil.getErrorMsg("请勿重复发送邀请");
  1104. }
  1105. // 未发送邀请
  1106. else {
  1107. baseDAO.insertAll(share);
  1108. }
  1109. } else {
  1110. r = JSONUtil.getErrorMsg("手机号码未注册");
  1111. }
  1112. return r;
  1113. }
  1114. /**
  1115. * 通过链接分享设备
  1116. *
  1117. * @return
  1118. */
  1119. @GetMapping("/sbfxByUrl")
  1120. @ApiOperation(value = "通过链接分享设备")
  1121. public R sbfxByUrl(ShareVO share) {
  1122. R r = JSONUtil.getSuccessMsg(null);
  1123. // 分享人手机号为空(链接分享)
  1124. if (share.getSharer_phone() == null || share.getSharer_phone().isEmpty()) {
  1125. List<MiniUserVO> sharers = baseDAO.queryAllByCondition(MiniUserVO.class, " and openid='" + share.getSharer() + "' ", null);
  1126. if (sharers.size() > 0) {
  1127. MiniUserVO userVO = sharers.get(0);
  1128. share.setSharer_phone(userVO.getPhone());
  1129. }
  1130. }
  1131. share.setState(1);
  1132. List<ShareVO> shares = baseDAO.queryAllByCondition(ShareVO.class, " and sharer='" + share.getSharer() + "' and shared='" + share.getShared() + "' "
  1133. + "and dev_id='" + share.getDev_id() + "' and state=0", null);
  1134. // 已发送邀请未处理
  1135. if (shares != null && shares.size() > 0) {
  1136. r = JSONUtil.getErrorMsg("存在未处理的邀请,请回主页查看");
  1137. }
  1138. // 未发送邀请
  1139. else {
  1140. baseDAO.insertAll(share);
  1141. }
  1142. Log.info("分享结果:" + r.getResult());
  1143. return r;
  1144. }
  1145. /**
  1146. * 设备分享记录
  1147. *
  1148. * @param user_openid
  1149. * @return
  1150. * @throws IOException
  1151. */
  1152. @GetMapping("/sbfxjl")
  1153. @ApiOperation(value = "查看设备分享记录")
  1154. public R sbfxjl(String user_openid) throws IOException {
  1155. R r = JSONUtil.getSuccessMsg(null);
  1156. List<ShareVO> shares = baseDAO.queryAllByCondition(ShareVO.class, " and shared='" + user_openid + "' ", null);
  1157. // ForeignKeyUtil.processForeignKey(fxjls, "tbl_sb", "sb_id", new String[] {"mc","bh"}, new String[] {"mc","bh"});
  1158. // ForeignKeyUtil.processForeignKey(fxjls, "tbl_hy", "fxr", new String[] {"sjhm"}, new String[] {"sjhm"});
  1159. r.data.put("shares", shares);
  1160. return r;
  1161. }
  1162. /**
  1163. * 设备分享确认
  1164. *
  1165. * @param dev_id
  1166. * @param state
  1167. * @return
  1168. * @throws IOException
  1169. */
  1170. @GetMapping("/sbfxqr")
  1171. @ApiOperation(value = "设备分享确认")
  1172. public R sbfx(String dev_id, Integer state, String user_openid) throws IOException {
  1173. R r = JSONUtil.getSuccessMsg(null);
  1174. baseDAO.updateSQL("update dev_share set state=" + state + " where dev_id='" + dev_id + "' and shared ='" +
  1175. user_openid + "' ");
  1176. return r;
  1177. }
  1178. /**
  1179. * 检查更新/获取版本
  1180. *
  1181. * @return
  1182. * @throws IOException
  1183. */
  1184. @GetMapping("/getVersion")
  1185. @ApiOperation(value = "获取设备新版本")
  1186. public R getVersion(String dev_id) throws IOException {
  1187. R r = JSONUtil.getSuccessMsg(null);
  1188. StringBuffer getTopic = new StringBuffer("/mps/" + dev_id + "/get_device_info ");
  1189. try {
  1190. JSONObject msg = new JSONObject();
  1191. msg.put("dev_id", dev_id);
  1192. MqttUtil.pub(getTopic.toString(), msg.toJSONString());
  1193. } catch (Exception e) {
  1194. // TODO: handle exception
  1195. r = JSONUtil.getErrorMsg(e);
  1196. }
  1197. return r;
  1198. }
  1199. /**
  1200. * 设备软重启
  1201. *
  1202. * @param dev_id
  1203. * @return
  1204. */
  1205. @GetMapping("/reboot")
  1206. @ApiOperation(value = "设备软重启")
  1207. public R reboot(String dev_id) {
  1208. R r = JSONUtil.getSuccessMsg(null);
  1209. StringBuffer topic = new StringBuffer("/dev/" + dev_id + "/reboot");
  1210. try {
  1211. MqttUtil.pub(topic.toString(), "1");
  1212. } catch (Exception e) {
  1213. // TODO: handle exception
  1214. r = JSONUtil.getErrorMsg(e);
  1215. }
  1216. return r;
  1217. }
  1218. /**
  1219. * OTA升级
  1220. *
  1221. * @param dev_id
  1222. * @return
  1223. */
  1224. @GetMapping("/updateOTA")
  1225. @ApiOperation(value = "OTA升级")
  1226. public R updateOTA(String dev_id) {
  1227. R r = JSONUtil.getSuccessMsg(null);
  1228. StringBuffer topic = new StringBuffer("/dev/" + dev_id + "/update_firmware");
  1229. try {
  1230. MqttUtil.pub(topic.toString(), "1");
  1231. } catch (Exception e) {
  1232. // TODO: handle exception
  1233. r = JSONUtil.getErrorMsg(e);
  1234. }
  1235. return r;
  1236. }
  1237. // 0:站 1:坐 2:躺 3:跌倒
  1238. @GetMapping("/startPoseFix")
  1239. @ApiOperation(value = "姿态修正")
  1240. public R startPoseFix(int poseIndex, String dev_id) {
  1241. R r = JSONUtil.getSuccessMsg(null);
  1242. Short pose;
  1243. switch (poseIndex) {
  1244. case 0:
  1245. pose = 4;
  1246. break;
  1247. case 1:
  1248. pose = 5;
  1249. break;
  1250. case 2:
  1251. pose = 0;
  1252. break;
  1253. case 3:
  1254. pose = 7;
  1255. break;
  1256. default:
  1257. pose = -1;
  1258. break;
  1259. }
  1260. MqttUtil.setMap(pose, dev_id);
  1261. return r;
  1262. }
  1263. @GetMapping("/stopPoseFix")
  1264. @ApiOperation(value = "停止姿态修正")
  1265. public R stopPoseFix(String dev_id) {
  1266. R r = JSONUtil.getSuccessMsg(null);
  1267. MqttUtil.deleteMap(dev_id);
  1268. return r;
  1269. }
  1270. @GetMapping("/getDeviceInfo")
  1271. @ApiOperation(value = "获取设备信息")
  1272. public R getDeviceInfo(String dev_id) {
  1273. R r = JSONUtil.getSuccessMsg(null);
  1274. String topic = "/mps/get_device_info";
  1275. JSONObject msg = new JSONObject();
  1276. msg.put("dev_id", dev_id);
  1277. try {
  1278. MqttUtil.pub(topic, msg.toJSONString());
  1279. } catch (Exception e) {
  1280. // TODO: handle exception
  1281. r = JSONUtil.getErrorMsg(e);
  1282. }
  1283. return r;
  1284. }
  1285. @GetMapping("/getDeviceParam")
  1286. @ApiOperation(value = "获取设备参数")
  1287. public R getDeviceParam(String dev_id) {
  1288. R r = JSONUtil.getSuccessMsg(null);
  1289. String topic = "/mps/get_device_param";
  1290. JSONObject msg = new JSONObject();
  1291. msg.put("dev_id", dev_id);
  1292. try {
  1293. MqttUtil.pub(topic, msg.toJSONString());
  1294. } catch (Exception e) {
  1295. // TODO: handle exception
  1296. r = JSONUtil.getErrorMsg(e);
  1297. }
  1298. return r;
  1299. }
  1300. // 添加群组
  1301. @GetMapping("/addGroup")
  1302. @ApiOperation(value = "添加群组")
  1303. public R addGroup(GroupVO vo) {
  1304. R r = JSONUtil.getSuccessMsg(null);
  1305. vo.setGroup_uuid((UUID.randomUUID()).toString());
  1306. vo.setDelete_tag(0);
  1307. baseDAO.insertAll(vo);
  1308. // MQTT
  1309. String topic = "/mps/add_group";
  1310. JSONObject msg = new JSONObject();
  1311. msg.put("group_uuid", vo.getGroup_uuid());
  1312. msg.put("north_angle", vo.getNorth_angle());
  1313. try {
  1314. MqttUtil.pub(topic, msg.toJSONString());
  1315. } catch (Exception e) {
  1316. Log.info("添加群组:MQTT消息发送失败");
  1317. }
  1318. return r;
  1319. }
  1320. // 删除群组
  1321. @GetMapping("/deleteGroup")
  1322. @ApiOperation(value = "删除群组")
  1323. public R deleteGroup(String group_uuid) {
  1324. R r = JSONUtil.getSuccessMsg(null);
  1325. baseDAO.updateSQL("update dev_group set delete_tag =1 where group_uuid ='" + group_uuid + "' ");
  1326. // MQTT
  1327. String topic = "/mps/del_group";
  1328. JSONObject msg = new JSONObject();
  1329. msg.put("group_uuid", group_uuid);
  1330. try {
  1331. MqttUtil.pub(topic, msg.toJSONString());
  1332. } catch (Exception e) {
  1333. Log.info("删除群组:MQTT消息发送失败");
  1334. }
  1335. return r;
  1336. }
  1337. // 更新群组
  1338. @GetMapping("/updateGroup")
  1339. @ApiOperation(value = "更新群组")
  1340. public R updateGroup(GroupVO vo) {
  1341. R r = JSONUtil.getSuccessMsg(null);
  1342. baseDAO.updateSQL("update dev_group set group_name ='" + vo.getGroup_name() + "',length=" + vo.getLength()
  1343. + ",width=" + vo.getWidth() + ",north_angle=" + vo.getNorth_angle() + " where group_uuid ='" + vo.getGroup_uuid() + "' ");
  1344. // MQTT
  1345. String topic = "/mps/update_group";
  1346. JSONObject msg = new JSONObject();
  1347. msg.put("group_uuid", vo.getGroup_uuid());
  1348. msg.put("north_angle", vo.getNorth_angle());
  1349. try {
  1350. MqttUtil.pub(topic, msg.toJSONString());
  1351. } catch (Exception e) {
  1352. Log.info("更新群组:MQTT消息发送失败");
  1353. }
  1354. return r;
  1355. }
  1356. // 群组列表
  1357. // @GetMapping("/groupList")
  1358. // public R groupList(String openid) {
  1359. // R r =JSONUtil.getSuccessMsg(null);
  1360. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and (user_openid='" + openid + "' or group_uuid in (select group_uuid"
  1361. // + " from group_share where delete_tag =0 and shared='"+openid+"' and state =1))", null);
  1362. // List<GroupProVO> groupsPro =new ArrayList<>();
  1363. // for(int i=0;i<groups.size();i++) {
  1364. // GroupVO vo = groups.get(i);
  1365. // GroupProVO voPro =new GroupProVO();
  1366. // voPro.setGroup(vo);
  1367. // int total =0;
  1368. // int online =0;
  1369. // int warn =0;
  1370. // JSONArray devListArray =JSONArray.parseArray(vo.getDev_list());
  1371. // if(devListArray!=null && devListArray.size()>0) {
  1372. // total =devListArray.size();
  1373. // for(int j=0;j<devListArray.size();j++) {
  1374. // DevVO devVO =baseDAO.queryByKey(DevVO.class, "dev_id", devListArray.getString(j));
  1375. // if(devVO.getOnline() == 1) {
  1376. // online++;
  1377. // }
  1378. // if(devVO.getDev_warn()!=null && devVO.getDev_warn() ==1) {
  1379. // warn++;
  1380. // }
  1381. // }
  1382. // }
  1383. // voPro.setTotal(total);
  1384. // voPro.setOnline(online);
  1385. // voPro.setWarn(warn);
  1386. // groupsPro.add(voPro);
  1387. // }
  1388. // r.data.put("groups", groupsPro);
  1389. // return r;
  1390. // }
  1391. // 群组设备列表
  1392. // @GetMapping("/groupDevList")
  1393. // public R groupDevList(String group_uuid) {
  1394. // R r =JSONUtil.getSuccessMsg(null);
  1395. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and group_uuid ='"+group_uuid+"' ", null);
  1396. // if(groups.size()>0) {
  1397. // GroupVO vo =groups.get(0);
  1398. // JSONArray devListArray =JSONArray.parseArray(vo.getDev_list());
  1399. // List<DevVO> dev_list =new ArrayList<>();
  1400. // if(devListArray!=null && devListArray.size()>0) {
  1401. // for(int i=0;i<devListArray.size();i++) {
  1402. // DevVO devVO =baseDAO.queryByKey(DevVO.class, "dev_id", devListArray.getString(i));
  1403. // dev_list.add(devVO);
  1404. // }
  1405. // }
  1406. // r.data.put("dev_list", dev_list);
  1407. // }
  1408. // return r;
  1409. // }
  1410. // 添加群组设备
  1411. // @GetMapping("/addGroupDev")
  1412. // public R addGroupDev(String dev_id,String group_uuid) {
  1413. // R r =JSONUtil.getSuccessMsg(null);
  1414. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and group_uuid ='"+group_uuid+"' ", null);
  1415. // if(groups.size()>0) {
  1416. // GroupVO vo =groups.get(0);
  1417. // String jsonStr =vo.getDev_list();
  1418. // if(StringUtils.isEmpty(jsonStr)) {
  1419. // StringBuffer sql = new StringBuffer("update dev_group set dev_list =JSON_ARRAY('"+dev_id+"') where delete_tag =0 and group_uuid='"+group_uuid+"'");
  1420. // baseDAO.updateSQL(sql.toString());
  1421. // }
  1422. // else {
  1423. // JSONArray jsonArray =JSONArray.parseArray(jsonStr);
  1424. // jsonArray.add(dev_id);
  1425. // StringBuffer sql = new StringBuffer("update dev_group set dev_list =JSON_ARRAY(");
  1426. // for(int i=0;i<jsonArray.size();i++) {
  1427. // sql.append("'"+jsonArray.getString(i)+"',");
  1428. // }
  1429. // sql.setLength(sql.length() - 1);
  1430. // sql.append(") where delete_tag =0 and group_uuid='"+group_uuid+"' ");
  1431. // baseDAO.updateSQL(sql.toString());
  1432. // }
  1433. // }
  1434. // return r;
  1435. // }
  1436. // 删除群组设备
  1437. // @GetMapping("/removeGroupDev")
  1438. // public R removeGroupDev(String dev_id,String group_uuid) {
  1439. // R r =JSONUtil.getSuccessMsg(null);
  1440. // List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and group_uuid ='"+group_uuid+"' ", null);
  1441. // if(groups.size()>0) {
  1442. // GroupVO vo =groups.get(0);
  1443. // String jsonStr =vo.getDev_list();
  1444. // // 原数组
  1445. // JSONArray jsonArray =JSONArray.parseArray(jsonStr);
  1446. // // 删除指定元素后的列表
  1447. // JSONArray updatedArray = new JSONArray();
  1448. // for(int i=0;i<jsonArray.size();i++) {
  1449. // if (!jsonArray.getString(i).equals(dev_id)) {
  1450. // updatedArray.add(jsonArray.getString(i));
  1451. // }
  1452. // }
  1453. // StringBuffer sql = new StringBuffer("update dev_group set dev_list =JSON_ARRAY(");
  1454. //
  1455. // // 列表不为空
  1456. // if(updatedArray.size()>0) {
  1457. // for(int i=0;i<updatedArray.size();i++) {
  1458. // sql.append("'"+updatedArray.getString(i)+"',");
  1459. // }
  1460. // sql.setLength(sql.length() - 1);
  1461. // }
  1462. // sql.append(") where delete_tag =0 and group_uuid='"+group_uuid+"' ");
  1463. // baseDAO.updateSQL(sql.toString());
  1464. // }
  1465. // return r;
  1466. // }
  1467. // 群组列表
  1468. @GetMapping("/groupList")
  1469. @ApiOperation(value = "群组列表")
  1470. public R groupList(String openid) {
  1471. R r = JSONUtil.getSuccessMsg(null);
  1472. List<GroupVO> groups = baseDAO.queryAllByCondition(GroupVO.class, " and (user_openid='" + openid + "' or group_uuid in (select group_uuid"
  1473. + " from group_share where delete_tag =0 and shared='" + openid + "' and state =1))", null);
  1474. List<GroupProVO> groupsPro = new ArrayList<>();
  1475. for (int i = 0; i < groups.size(); i++) {
  1476. GroupVO vo = groups.get(i);
  1477. GroupProVO voPro = new GroupProVO();
  1478. voPro.setGroup(vo);
  1479. int total = 0;
  1480. int online = 0;
  1481. int warn = 0;
  1482. List<GroupDevMapVO> maps = baseDAO.queryAllByCondition(GroupDevMapVO.class, " and group_uuid ='" + vo.getGroup_uuid() + "' and delete_tag =0 ", null);
  1483. for (int j = 0; j < maps.size(); j++) {
  1484. GroupDevMapVO mapVO = maps.get(j);
  1485. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", mapVO.getDev_id());
  1486. // 设备存在且未删除
  1487. if (devVO != null && devVO.getDelete_tag() == 0) {
  1488. total++;
  1489. if (devVO.getOnline() == 1) {
  1490. online++;
  1491. }
  1492. if (devVO.getDev_warn() != null && devVO.getDev_warn() == 1) {
  1493. warn++;
  1494. }
  1495. }
  1496. }
  1497. voPro.setTotal(total);
  1498. voPro.setOnline(online);
  1499. voPro.setWarn(warn);
  1500. groupsPro.add(voPro);
  1501. }
  1502. r.data.put("groups", groupsPro);
  1503. return r;
  1504. }
  1505. // 群组设备列表
  1506. @GetMapping("/groupDevList")
  1507. @ApiOperation(value = "群组设备列表")
  1508. public R groupDevList(String group_uuid) {
  1509. R r = JSONUtil.getSuccessMsg(null);
  1510. List<GroupDevMapVO> maps = baseDAO.queryAllByCondition(GroupDevMapVO.class, " and group_uuid ='" + group_uuid + "' and delete_tag =0 ", null);
  1511. // 获取群组设备列表
  1512. List<DevVO> dev_list = new ArrayList<>();
  1513. for (int i = 0; i < maps.size(); i++) {
  1514. GroupDevMapVO mapVO = maps.get(i);
  1515. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", mapVO.getDev_id());
  1516. // 设备存在且未删除
  1517. if (devVO != null && devVO.getDelete_tag() == 0) {
  1518. dev_list.add(devVO);
  1519. }
  1520. }
  1521. // 获取群组基本信息
  1522. GroupVO group = baseDAO.queryByKey(GroupVO.class, "group_uuid", group_uuid);
  1523. r.data.put("dev_list", dev_list);
  1524. r.data.put("group", group);
  1525. return r;
  1526. }
  1527. // 添加群组设备
  1528. @GetMapping("/addGroupDev")
  1529. @ApiOperation(value = "添加群组设备")
  1530. public R addGroupDev(String dev_id, String group_uuid) {
  1531. R r = JSONUtil.getSuccessMsg(null);
  1532. GroupVO groupVO = baseDAO.queryByKey(GroupVO.class, "group_uuid", group_uuid);
  1533. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", dev_id);
  1534. if (groupVO != null && devVO != null) {
  1535. List<GroupDevMapVO> maps = baseDAO.queryAllByConditionNocare(GroupDevMapVO.class, " and dev_id='" + dev_id + "' and group_uuid ='" + group_uuid + "' ", null);
  1536. Log.info(String.valueOf(maps.size()));
  1537. if (maps.size() > 0) {
  1538. GroupDevMapVO vo = maps.get(0);
  1539. if (vo.getDelete_tag() == 1) {
  1540. baseDAO.updateSQL("update group_dev_map set delete_tag =0 where dev_id='" + dev_id + "' and group_uuid ='" + group_uuid + "' ");
  1541. return r;
  1542. }
  1543. r = JSONUtil.getErrorMsg("请勿重复添加同一设备");
  1544. return r;
  1545. }
  1546. GroupDevMapVO mapVO = new GroupDevMapVO();
  1547. mapVO.setDev_group_index(groupVO.getId());
  1548. mapVO.setGroup_uuid(group_uuid);
  1549. mapVO.setDev_info_index(devVO.getId());
  1550. mapVO.setDev_id(dev_id);
  1551. mapVO.setDelete_tag(0);
  1552. baseDAO.insertAll(mapVO);
  1553. } else {
  1554. r = JSONUtil.getErrorMsg("数据出现错误,请重新进入小程序");
  1555. }
  1556. return r;
  1557. }
  1558. // 删除群组设备
  1559. @GetMapping("/removeGroupDev")
  1560. @ApiOperation(value = "删除群组设备")
  1561. public R removeGroupDev(String dev_id, String group_uuid) {
  1562. R r = JSONUtil.getSuccessMsg(null);
  1563. List<GroupDevMapVO> maps = baseDAO.queryAllByCondition(GroupDevMapVO.class, " and group_uuid ='" + group_uuid + "' and dev_id ='" + dev_id + "' and "
  1564. + "delete_tag =0", null);
  1565. if (maps.size() > 0) {
  1566. baseDAO.updateSQL("update group_dev_map set delete_tag =1 where group_uuid ='" + group_uuid + "' and dev_id ='" + dev_id + "' ");
  1567. } else {
  1568. r = JSONUtil.getErrorMsg("删除群组设备失败,请重新进入小程序");
  1569. }
  1570. return r;
  1571. }
  1572. /**
  1573. * 通过链接分享群组
  1574. *
  1575. * @param vo
  1576. * @return
  1577. */
  1578. @GetMapping("/groupShare")
  1579. @ApiOperation(value = "通过链接分享群组")
  1580. public R groupShare(GroupShareVO groupShare) {
  1581. R r = JSONUtil.getSuccessMsg(null);
  1582. baseDAO.insertAll(groupShare);
  1583. return r;
  1584. }
  1585. /**
  1586. * 群组分享信息确认
  1587. *
  1588. * @param uuid
  1589. * @return
  1590. */
  1591. @GetMapping("/groupShareConfirm")
  1592. @ApiOperation(value = "群组分享信息确认")
  1593. public R groupShareConfirm(String uuid, String shared, String shared_phone) {
  1594. R r = JSONUtil.getSuccessMsg(null);
  1595. GroupShareVO vo = baseDAO.queryByKey(GroupShareVO.class, "uuid", uuid);
  1596. if (vo != null) {
  1597. if (vo.getState() == 0) {
  1598. vo.setState(3);
  1599. baseDAO.updateSQL("update group_share set state =3,shared='" + shared + "',shared_phone='" + shared_phone + "' where uuid='" + uuid + "' and delete_tag =0 ");
  1600. }
  1601. r.data.put("groupShare", vo);
  1602. } else {
  1603. r = JSONUtil.getErrorMsg("分享已过期");
  1604. }
  1605. return r;
  1606. }
  1607. /**
  1608. * 群组分享事件处理
  1609. *
  1610. * @param uuid
  1611. * @return
  1612. */
  1613. @GetMapping("/groupSharePro")
  1614. @ApiOperation(value = "群组分享事件处理")
  1615. public R groupSharePro(String uuid, int state) {
  1616. R r = JSONUtil.getSuccessMsg(null);
  1617. GroupShareVO vo = baseDAO.queryByKey(GroupShareVO.class, "uuid", uuid);
  1618. if (vo != null) {
  1619. vo.setState(state);
  1620. baseDAO.updateSQL("update group_share set state =" + state + " where uuid='" + uuid + "' and delete_tag =0 ");
  1621. r.data.put("groupShare", vo);
  1622. }
  1623. return r;
  1624. }
  1625. /**
  1626. * 生成uuid
  1627. *
  1628. * @return
  1629. */
  1630. @GetMapping("/generateUUID")
  1631. @ApiOperation(value = "生成uuid")
  1632. public R generateUUID() {
  1633. R r = JSONUtil.getSuccessMsg(null);
  1634. String uuid = UUID.randomUUID().toString();
  1635. r.data.put("uuid", uuid);
  1636. return r;
  1637. }
  1638. /**
  1639. * 用户注销
  1640. *
  1641. * @param openid
  1642. * @return
  1643. */
  1644. @GetMapping("userLogout")
  1645. @ApiOperation(value = "用户注销")
  1646. public R userLogout(String openid) {
  1647. R r = JSONUtil.getSuccessMsg(null);
  1648. // user_info
  1649. baseDAO.updateSQL("update user_info set delete_tag =1 where openid ='" + openid + "' ");
  1650. // dev_share
  1651. baseDAO.updateSQL("update dev_share set delete_tag =1 where sharer ='" + openid + "' or shared ='" + openid + "' ");
  1652. // dev_info
  1653. baseDAO.updateSQL("update dev_info set delete_tag =1 where user_openid ='" + openid + "' ");
  1654. // dev_group
  1655. baseDAO.updateSQL("update dev_group set delete_tag =1 where user_openid ='" + openid + "' ");
  1656. // group_share
  1657. baseDAO.updateSQL("update group_share set delete_tag =1 where sharer ='" + openid + "' or shared ='" + openid + "' ");
  1658. return r;
  1659. }
  1660. // 获取设备所属群组
  1661. @GetMapping("getDevGroup")
  1662. @ApiOperation(value = "获取设备所属群组")
  1663. public R getDevGroup(String dev_id) {
  1664. R r = JSONUtil.getSuccessMsg(null);
  1665. baseDAO.queryBySQL("");
  1666. return r;
  1667. }
  1668. // 上传户型图
  1669. @PostMapping("/uploadMap")
  1670. @ApiOperation(value = "上传户型图")
  1671. public R uploadMap(@RequestParam("file") MultipartFile file,
  1672. @RequestParam String group_uuid) throws IllegalStateException,
  1673. IOException {
  1674. // 校验文件非空
  1675. if (file.isEmpty()) {
  1676. return JSONUtil.getErrorMsg("文件为空");
  1677. }
  1678. // 校验文件类型
  1679. String contentType = file.getContentType();
  1680. if (contentType == null || (!contentType.equalsIgnoreCase("image/png") && !contentType.equalsIgnoreCase("image/jpeg"))) {
  1681. return JSONUtil.getErrorMsg("仅支持PNG或JPG 格式");
  1682. }
  1683. // 校验文件头
  1684. byte[] fileHeader = new byte[8];
  1685. try (InputStream is = file.getInputStream()) {
  1686. int readBytes = is.read(fileHeader);
  1687. if (readBytes < 8) {
  1688. return JSONUtil.getErrorMsg("文件格式不完整");
  1689. }
  1690. }
  1691. boolean isPng = ImageUtil.checkPngMagicNumber(fileHeader);
  1692. boolean isJpeg = ImageUtil.checkJpegMagicNumber(fileHeader);
  1693. if (!isPng && !isJpeg) {
  1694. return JSONUtil.getErrorMsg("文件实际格式与声明不符,仅支持 PNG/JPG");
  1695. }
  1696. // 生成安全路径
  1697. String dirPath = FileUploadController.getFilePath() + "map/" + group_uuid + "/";
  1698. File dir = new File(dirPath);
  1699. if (!dir.exists() && !dir.mkdirs()) {
  1700. Log.error("目录创建失败: " + dirPath);
  1701. return JSONUtil.getErrorMsg("服务器错误");
  1702. }
  1703. // 删除旧文件
  1704. File[] existingFiles = dir.listFiles();
  1705. if (existingFiles != null) {
  1706. for (File existingFile : existingFiles) {
  1707. if (existingFile.isFile()) {
  1708. if (!existingFile.delete()) {
  1709. Log.error("旧文件无法删除,上传中断");
  1710. return JSONUtil.getErrorMsg("旧文件无法删除,上传中断");
  1711. }
  1712. }
  1713. }
  1714. }
  1715. // 根据文件类型生成正确扩展名
  1716. String extension = isPng ? ".png" : ".jpg";
  1717. String fileName = System.currentTimeMillis() + extension;
  1718. // 上传服务器
  1719. file.transferTo(new File(dirPath, fileName));
  1720. Log.info("上传成功");
  1721. // 查询
  1722. FloorPlanVO vo = baseDAO.queryByKey(FloorPlanVO.class, "group_uuid", group_uuid);
  1723. // 上传数据库
  1724. String floorplan_addr = "map/" + group_uuid + "/" + fileName;
  1725. if (vo != null) {
  1726. StringBuffer buffer = new StringBuffer("update group_floorplan set ");
  1727. if (vo.getDelete_tag() == 1) {
  1728. buffer.append("delete_tag =0,");
  1729. }
  1730. buffer.append("floorplan_addr ='" + floorplan_addr + "',update_time ='" + new Timestamp(System.currentTimeMillis())
  1731. + "' where group_uuid ='" + group_uuid + "' ");
  1732. baseDAO.updateSQL(buffer.toString());
  1733. } else {
  1734. vo = new FloorPlanVO();
  1735. vo.setCreate_time(new Timestamp(System.currentTimeMillis()));
  1736. vo.setDelete_tag(0);
  1737. vo.setGroup_uuid(group_uuid);
  1738. vo.setFloorplan_addr(floorplan_addr);
  1739. baseDAO.insertAll(vo);
  1740. }
  1741. return JSONUtil.getSuccessMsg(null);
  1742. }
  1743. // 获取户型图(URL地址)
  1744. @GetMapping("/getFloorPlan")
  1745. @ApiOperation(value = "获取户型图")
  1746. public R getFloorPlan(String group_uuid) {
  1747. String dirPath = FileUploadController.getFilePath() + "map/" + group_uuid + "/";
  1748. File dir = new File(dirPath);
  1749. File[] existingFiles = dir.listFiles();
  1750. if (existingFiles != null) {
  1751. if (existingFiles.length > 1) {
  1752. // 存在多张户型图
  1753. return JSONUtil.getErrorMsg("存在多张户型图");
  1754. } else if (existingFiles.length == 1) {
  1755. // 存在且只有一张户型图
  1756. File existingFile = existingFiles[0];
  1757. // URL拼接
  1758. FloorPlanVO vo = baseDAO.queryByKey(FloorPlanVO.class, "group_uuid", group_uuid);
  1759. StringBuffer fileURL = new StringBuffer(Environment.COMMON_FILE_UPLOAD_PATH);
  1760. if (vo != null && vo.getDelete_tag() == 0) {
  1761. fileURL.append(vo.getFloorplan_addr());
  1762. } else {
  1763. fileURL.append("map/" + group_uuid + "/" + existingFile.getName());
  1764. }
  1765. // 返回成功信息,包含户型图的URL
  1766. R r = JSONUtil.getSuccessMsg("户型图获取成功");
  1767. r.customData.put("url", fileURL.toString());
  1768. return r;
  1769. }
  1770. }
  1771. // 无户型图
  1772. return JSONUtil.getErrorMsg("户型图未配置");
  1773. }
  1774. private final static String TOKEN = "lnServer";
  1775. /**
  1776. * 查询前一天上厕所的次数
  1777. *
  1778. * @param time
  1779. * @param dev_id
  1780. * @return
  1781. */
  1782. @GetMapping("/getWcTimes")
  1783. @ApiOperation(value = "查询前一天用卫生间的次数")
  1784. public R getWcTimes(String dev_id, String time) {
  1785. R r = JSONUtil.getSuccessMsg(null);
  1786. LocalDate inputDate = LocalDate.parse(time);
  1787. String previousDateStr = inputDate.toString();
  1788. // 判断查询结果并返回
  1789. List<StayTime> stayTimes = null;
  1790. try {
  1791. stayTimes = jdbcTemplate.query(
  1792. "SELECT * FROM stay_time WHERE dev_id = ? AND DATE(leave_time) = ? and type = 0 order by leave_time",
  1793. new Object[]{dev_id, previousDateStr},
  1794. new BeanPropertyRowMapper<>(StayTime.class)
  1795. );
  1796. } catch (Exception e) {
  1797. e.printStackTrace();
  1798. }
  1799. if (Objects.nonNull(stayTimes) && stayTimes.size() > 0) {
  1800. r.data.put("stayTimes", stayTimes);
  1801. r.data.put("count", stayTimes.size());
  1802. } else {
  1803. r.data.put("stayTimes", null);
  1804. r.data.put("count", 0);
  1805. }
  1806. return r;
  1807. }
  1808. /**
  1809. * 查询当天上卫生间的次数,以及用马桶的次数
  1810. *
  1811. * @param time
  1812. * @param dev_id
  1813. * @return
  1814. */
  1815. @GetMapping("/getWcInfo")
  1816. @ApiOperation(value = "查询当天上卫生间的次数,以及用马桶的次数")
  1817. public R getWcInfo(String dev_id, String time) {
  1818. R r = JSONUtil.getSuccessMsg(null);
  1819. LocalDate inputDate = LocalDate.parse(time);
  1820. String inputDateStr = inputDate.toString();
  1821. // 判断查询结果并返回
  1822. List<StayTime> stayTimes = null;
  1823. try {
  1824. stayTimes = jdbcTemplate.query(
  1825. "SELECT * FROM stay_time WHERE dev_id = ? AND DATE(leave_time) = ? order by leave_time ",
  1826. new Object[]{dev_id, inputDateStr},
  1827. new BeanPropertyRowMapper<>(StayTime.class)
  1828. );
  1829. } catch (Exception e) {
  1830. e.printStackTrace();
  1831. }
  1832. if (Objects.nonNull(stayTimes) && stayTimes.size() > 0) {
  1833. List<StayTime> roomList = stayTimes.stream().filter(stayTime -> 0 == (stayTime.getType())).collect(Collectors.toList());
  1834. List<StayTime> toiletList = stayTimes.stream().filter(stayTime -> 1 == stayTime.getType()).collect(Collectors.toList());
  1835. if (!CollectionUtils.isEmpty(roomList)) {
  1836. for (StayTime stayTime : roomList) {
  1837. if (!CollectionUtils.isEmpty(toiletList)) {
  1838. stayTime.setToiletList(toiletList.stream().filter(
  1839. toilet ->
  1840. toilet.getEnter_time().compareTo(stayTime.getEnter_time())>=0 && toilet.getLeave_time().compareTo(stayTime.getLeave_time())<=0
  1841. ).collect(Collectors.toList()));
  1842. }
  1843. }
  1844. r.data.put("stayTimes", roomList);
  1845. r.data.put("count", roomList.size());
  1846. return r;
  1847. }
  1848. }
  1849. r.data.put("stayTimes", null);
  1850. r.data.put("count", 0);
  1851. return r;
  1852. }
  1853. //公众号模块
  1854. @GetMapping("/getAccessTokenTwo")
  1855. @ApiOperation(value = "获取公众号token")
  1856. public R getAccessTokenTwo() {
  1857. R r = JSONUtil.getSuccessMsg(null);
  1858. // 发送模板消息
  1859. wxSendMessage.queryAccessToken("devId", "测试设备", "17356519496", "oWlo-6iXL0pQeYWZxEpwB8knv6D8", "test");
  1860. return r;
  1861. }
  1862. @GetMapping("/serverCheck")
  1863. @ApiOperation(value = "公众号发信息接口")
  1864. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
  1865. String signature = request.getParameter("signature");
  1866. String timestamp = request.getParameter("timestamp");
  1867. String nonce = request.getParameter("nonce");
  1868. String echostr = request.getParameter("echostr");
  1869. String signatureCheck = getSHA1(TOKEN, timestamp, nonce);
  1870. if (signatureCheck != null && signatureCheck.equals(signature)) {
  1871. PrintWriter out = response.getWriter();
  1872. out.print(echostr);
  1873. out.flush();
  1874. out.close();
  1875. }
  1876. }
  1877. @PostMapping("/addOneDevice")
  1878. @ApiOperation(value = "单个添加设备")
  1879. public R addOneDevice(String dev_id, String dev_type, String software){
  1880. //校验判断 1.存在且未软删除
  1881. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", dev_id);
  1882. if (devVO != null && devVO.getDelete_tag() == 0) {
  1883. return JSONUtil.getErrorMsg("设备已存在");
  1884. }
  1885. //检验判断 2.存在且已软删除 实现逻辑删除恢复
  1886. if (devVO != null && devVO.getDelete_tag() == 1){
  1887. String updateSql = "UPDATE dev_info SET dev_type = ?, software = ?, delete_tag = 0, update_time = ? WHERE dev_id = ?";
  1888. baseDAO.getJdbcTemplate().update(updateSql,
  1889. dev_type,
  1890. software,
  1891. new Timestamp(System.currentTimeMillis()),
  1892. dev_id
  1893. );
  1894. return JSONUtil.getSuccessMsg("设备恢复成功");
  1895. }
  1896. //3.新设备添加
  1897. DevVO deviceVO = new DevVO();
  1898. deviceVO.setDev_id(dev_id);
  1899. deviceVO.setDev_type(dev_type);
  1900. deviceVO.setSoftware(software);
  1901. deviceVO.setStatus_light(1);
  1902. deviceVO.setOnline(0);
  1903. deviceVO.setDelete_tag(0);
  1904. baseDAO.insertAll(deviceVO);
  1905. return JSONUtil.getSuccessMsg("添加成功");
  1906. }
  1907. @PostMapping("/deleteDevice")
  1908. @ApiOperation(value = "删除设备")
  1909. public R deleteDevice(String dev_id) {
  1910. //1.参数校验
  1911. if (StringUtils.isBlank(dev_id)){
  1912. return JSONUtil.getErrorMsg("设备ID不能为空");
  1913. }
  1914. //2.查询设备
  1915. DevVO devVO = baseDAO.queryByKey(DevVO.class, "dev_id", dev_id);
  1916. if (devVO != null) {
  1917. String updateSql = "UPDATE dev_info SET delete_tag = 1 WHERE dev_id = ?";
  1918. baseDAO.getJdbcTemplate().update(updateSql, dev_id);
  1919. return JSONUtil.getSuccessMsg("设备删除成功");
  1920. } else {
  1921. return JSONUtil.getErrorMsg("设备不存在");
  1922. }
  1923. }
  1924. public String getSHA1(String token, String timestamp, String nonce) {
  1925. try {
  1926. String[] array = new String[]{token, timestamp, nonce};
  1927. Arrays.sort(array);
  1928. StringBuilder sb = new StringBuilder();
  1929. for (String s : array) {
  1930. sb.append(s);
  1931. }
  1932. MessageDigest md = MessageDigest.getInstance("SHA-1");
  1933. md.update(sb.toString().getBytes());
  1934. byte[] digest = md.digest();
  1935. StringBuilder hexstr = new StringBuilder();
  1936. for (byte b : digest) {
  1937. String shaHex = Integer.toHexString(b & 0xFF);
  1938. if (shaHex.length() < 2) {
  1939. hexstr.append(0);
  1940. }
  1941. hexstr.append(shaHex);
  1942. }
  1943. return hexstr.toString();
  1944. } catch (Exception e) {
  1945. e.printStackTrace();
  1946. return null;
  1947. }
  1948. }
  1949. // 上传导入表
  1950. @PostMapping("/uploadDevInfo")
  1951. @ApiOperation(value = "上传导入表")
  1952. public R uploadDevInfo(@RequestParam("file") MultipartFile file) throws IllegalStateException,
  1953. IOException {
  1954. // 校验文件非空
  1955. if (file.isEmpty()) {
  1956. return JSONUtil.getErrorMsg("文件为空");
  1957. }
  1958. System.out.println("start time :" + System.currentTimeMillis());
  1959. List<DevInfoImportVo> devInfoImportVoList = EasyExcel.read(file.getInputStream(), DevInfoImportVo.class, null).sheet(0).doReadSync();
  1960. System.out.println("parse time :" + System.currentTimeMillis());
  1961. if (CollectionUtils.isEmpty(devInfoImportVoList)) {
  1962. return JSONUtil.getErrorMsg("数据为空");
  1963. }
  1964. R r = JSONUtil.getSuccessMsg(null);
  1965. String sql2 = "SELECT * FROM dev_info WHERE dev_id IN (" +
  1966. devInfoImportVoList.stream()
  1967. .map(DevInfoImportVo::getDev_id)
  1968. .distinct()
  1969. .map(id -> "?")
  1970. .collect(Collectors.joining(", ")) +
  1971. ")";
  1972. List<String> params2 = devInfoImportVoList.stream()
  1973. .map(DevInfoImportVo::getDev_id)
  1974. .distinct()
  1975. .collect(Collectors.toList());
  1976. List<DevVO> newlist2 = baseDAO.getJdbcTemplate().query(sql2, params2.toArray(), new BeanPropertyRowMapper<>(DevVO.class));
  1977. if (!CollectionUtils.isEmpty(newlist2)) {
  1978. List<String> dupDevIds = newlist2.stream().map(DevVO::getDev_id).collect(Collectors.toList());
  1979. r.data.put("dupIdList", dupDevIds);
  1980. devInfoImportVoList = devInfoImportVoList.stream().filter(item -> !dupDevIds.contains(item.getDev_id())).collect(Collectors.toList());
  1981. }
  1982. // 将数据分批插入数据库,每批100条,使用jdbcTemplate
  1983. // 将devInfoImportVoList按元素每一百个分成多个集合
  1984. int batchSize = 100;
  1985. int total = devInfoImportVoList.size();
  1986. for (int i = 0; i < total; i += batchSize) {
  1987. int end = Math.min(i + batchSize, total);
  1988. List<DevInfoImportVo> subList = devInfoImportVoList.subList(i, end);
  1989. // 使用jdbcTemplate批量插入数据
  1990. baseDAO.getJdbcTemplate().batchUpdate(
  1991. "INSERT INTO dev_info (dev_id, dev_type, software, status_light, online, delete_tag, create_time, update_time, x, y, north_angle) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
  1992. subList.stream().map(devVO -> new Object[]{
  1993. devVO.getDev_id(),
  1994. devVO.getDev_type(),
  1995. devVO.getSoftware(),
  1996. 1,
  1997. 0,
  1998. 0,
  1999. new Timestamp(System.currentTimeMillis()),
  2000. new Timestamp(System.currentTimeMillis()), 0, 0, 0
  2001. }).collect(Collectors.toList()),
  2002. new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.TIMESTAMP, Types.TIMESTAMP}
  2003. );
  2004. }
  2005. System.out.println("end time :" + System.currentTimeMillis());
  2006. return r;
  2007. }
  2008. // 查询列表
  2009. @PostMapping("/queryList")
  2010. @ApiOperation(value = "查询列表")
  2011. public R queryList(@RequestBody QueryListParam queryListParam) throws IllegalStateException,
  2012. IOException {
  2013. // 根据queryListParam查询条件是否为空,拼接 jdbc sql
  2014. StringBuilder sql = new StringBuilder("SELECT * FROM dev_info WHERE delete_tag = 0 ");
  2015. StringBuilder countSql = new StringBuilder("SELECT count(*) FROM dev_info WHERE delete_tag = 0 ");
  2016. if (!StringUtils.isEmpty(queryListParam.getDevId())) {
  2017. sql.append(" AND dev_id like '%" + queryListParam.getDevId() + "%'");
  2018. countSql.append(" AND dev_id like '%" + queryListParam.getDevId() + "%'");
  2019. }
  2020. if (!StringUtils.isEmpty(queryListParam.getDevType())) {
  2021. sql.append(" AND dev_type = '" + queryListParam.getDevType() + "'");
  2022. countSql.append(" AND dev_type = '" + queryListParam.getDevType() + "'");
  2023. }
  2024. if (!StringUtils.isEmpty(queryListParam.getSoftware())) {
  2025. sql.append(" AND software = '" + queryListParam.getSoftware() + "'");
  2026. countSql.append(" AND software = '" + queryListParam.getSoftware() + "'");
  2027. }
  2028. if (!StringUtils.isEmpty(queryListParam.getDevName())) {
  2029. sql.append(" AND dev_name like '%" + queryListParam.getDevName() + "%'");
  2030. countSql.append(" AND dev_name like '%" + queryListParam.getDevName() + "%'");
  2031. }
  2032. if (queryListParam.getOnline() != null) {
  2033. sql.append(" AND online = '" + queryListParam.getOnline() + "'");
  2034. countSql.append(" AND online = '" + queryListParam.getOnline() + "'");
  2035. }
  2036. // 添加创建时间的范围查询 数据库里的create_time字段为timestamp类型,查询条件里的createtimestart和createtimeend为string类型,需要转换成timestamp类型,yyyyMMdd
  2037. String queryStartTime = queryListParam.getCreateTimeStart();
  2038. if (!StringUtils.isEmpty(queryStartTime)) {
  2039. sql.append(" AND create_time >= STR_TO_DATE('" + queryStartTime + "', '%Y%m%d') ");
  2040. countSql.append(" AND create_time >= STR_TO_DATE('" + queryStartTime + "', '%Y%m%d') ");
  2041. }
  2042. String queryEndTime = queryListParam.getCreateTimeEnd();
  2043. if (!StringUtils.isEmpty(queryEndTime)) {
  2044. LocalDate endDate = LocalDate.parse(queryEndTime, DateTimeFormatter.ofPattern("yyyyMMdd"));
  2045. endDate = endDate.plusDays(1);
  2046. sql.append(" AND create_time < STR_TO_DATE('" + DateTimeFormatter.ofPattern("yyyyMMdd").format(endDate) + "', '%Y%m%d') ");
  2047. countSql.append(" AND create_time < STR_TO_DATE('" + DateTimeFormatter.ofPattern("yyyyMMdd").format(endDate) + "', '%Y%m%d') ");
  2048. }
  2049. // count
  2050. // 待确认分享数
  2051. Integer count = baseDAO.getJdbcTemplate().queryForObject(
  2052. countSql.toString(), Integer.class);
  2053. R r = JSONUtil.getSuccessMsg(null);
  2054. if (count == null || count == 0) {
  2055. r.data.put("count", 0);
  2056. return r;
  2057. } else {
  2058. r.data.put("count", count);
  2059. }
  2060. // 分页参数
  2061. int pageSize = queryListParam.getPageSize();
  2062. int pageNum = queryListParam.getPageNum();
  2063. int offset = (pageNum - 1) * pageSize;
  2064. sql.append(" ORDER BY create_time DESC LIMIT ").append("" + pageSize).append(" OFFSET ").append("" + offset);
  2065. List<DevVO> newlist2 = baseDAO.getJdbcTemplate().query(sql.toString(), new BeanPropertyRowMapper<>(DevVO.class));
  2066. System.out.println("end time :" + System.currentTimeMillis());
  2067. r.data.put("resList", newlist2);
  2068. return r;
  2069. }
  2070. }