WXController.java 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412
  1. package com.xcgl.weixin;
  2. import cn.com.lzt.car.alarm.CarAlarmEntity;
  3. import cn.com.lzt.common.entity.TSysFileEntity;
  4. import cn.com.lzt.common.service.TSysFileServiceI;
  5. import cn.com.lzt.common.util.CustomerConstant;
  6. import cn.com.lzt.common.util.DictUtil;
  7. import cn.com.lzt.common.util.UserUtil;
  8. import cn.com.lzt.contract.entity.ContractEntity;
  9. import cn.com.lzt.maintainbill.entity.MaintainBillEntity;
  10. import cn.com.lzt.maintainplan.entity.MaintainPlanEntity;
  11. import cn.com.lzt.message.personal.entity.MPersonalMessageEntity;
  12. import cn.com.lzt.message.personal.service.MPersonalMessageServiceI;
  13. import cn.com.lzt.message.reply.entity.MMessageReplyEntity;
  14. import cn.com.lzt.message.reply.service.MMessageReplyServiceI;
  15. import cn.com.lzt.message.send.entity.MMessageEntity;
  16. import cn.com.lzt.message.send.service.MMessageServiceI;
  17. import com.aliyun.oss.OSSClient;
  18. import com.aliyun.oss.model.ObjectMetadata;
  19. import com.aliyuncs.DefaultAcsClient;
  20. import com.aliyuncs.IAcsClient;
  21. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
  22. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
  23. import com.aliyuncs.exceptions.ClientException;
  24. import com.aliyuncs.exceptions.ServerException;
  25. import com.aliyuncs.http.MethodType;
  26. import com.aliyuncs.profile.DefaultProfile;
  27. import com.aliyuncs.profile.IClientProfile;
  28. import com.xcgl.dataview.service.DataviewServiceI;
  29. import com.xcgl.projecttask.entity.ProjecttaskEntity;
  30. import com.xcgl.reports.dao.XcglRptDao;
  31. import com.xcgl.taskresult.entity.TaskResultEntity;
  32. import com.xcgl.utils.UUID;
  33. import com.xcgl.utils.XcglConstant;
  34. import com.xcgl.utils.XcglDateUtils;
  35. import com.xcgl.weeklyMeeting.entity.WeeklyMeetingEntity;
  36. import com.xcgl.weixin.base.ApiException;
  37. import com.xcgl.weixin.dao.WXDao;
  38. import com.xcgl.weixin.entity.*;
  39. import com.xcgl.weixin.service.WXServiceI;
  40. import com.xcgl.weixin.service.WxTokenService;
  41. import com.xcgl.weixin.utils.WXUtils;
  42. import org.activiti.engine.HistoryService;
  43. import org.activiti.engine.RepositoryService;
  44. import org.activiti.engine.RuntimeService;
  45. import org.activiti.engine.TaskService;
  46. import org.activiti.engine.history.HistoricProcessInstance;
  47. import org.activiti.engine.history.HistoricProcessInstanceQuery;
  48. import org.activiti.engine.impl.persistence.entity.TaskEntity;
  49. import org.activiti.engine.repository.ProcessDefinition;
  50. import org.activiti.engine.runtime.ProcessInstance;
  51. import org.activiti.engine.task.NativeTaskQuery;
  52. import org.activiti.engine.task.Task;
  53. import org.activiti.engine.task.TaskQuery;
  54. import org.apache.commons.lang.xwork.StringUtils;
  55. import org.apache.commons.lang3.time.DateFormatUtils;
  56. import org.apache.log4j.Logger;
  57. import org.hibernate.Query;
  58. import org.jeecgframework.core.common.exception.BusinessException;
  59. import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
  60. import org.jeecgframework.core.common.model.json.DataGrid;
  61. import org.jeecgframework.core.common.model.json.DataGridReturn;
  62. import org.jeecgframework.core.util.*;
  63. import org.jeecgframework.minidao.pojo.MiniDaoPage;
  64. import org.jeecgframework.minidao.util.MiniDaoUtil;
  65. import org.jeecgframework.tag.vo.datatable.SortDirection;
  66. import org.jeecgframework.web.system.pojo.base.TSBaseUser;
  67. import org.jeecgframework.web.system.pojo.base.TSDepart;
  68. import org.jeecgframework.web.system.pojo.base.TSType;
  69. import org.jeecgframework.web.system.pojo.base.TSUser;
  70. import org.jeecgframework.web.system.service.SystemService;
  71. import org.jeecgframework.workflow.common.WorkFlowGlobals;
  72. import org.jeecgframework.workflow.dao.IActivitiCommonDao;
  73. import org.jeecgframework.workflow.pojo.activiti.ActHiTaskinst;
  74. import org.jeecgframework.workflow.pojo.activiti.ActHiVarinst;
  75. import org.jeecgframework.workflow.pojo.base.TPProcess;
  76. import org.jeecgframework.workflow.service.ActivitiService;
  77. import org.springframework.beans.factory.annotation.Autowired;
  78. import org.springframework.stereotype.Controller;
  79. import org.springframework.web.bind.annotation.RequestMapping;
  80. import org.springframework.web.bind.annotation.RequestMethod;
  81. import org.springframework.web.bind.annotation.RequestParam;
  82. import org.springframework.web.bind.annotation.ResponseBody;
  83. import org.springframework.web.context.request.RequestContextHolder;
  84. import org.springframework.web.context.request.ServletRequestAttributes;
  85. import org.springframework.web.multipart.MultipartFile;
  86. import javax.servlet.http.HttpServletRequest;
  87. import javax.servlet.http.HttpServletResponse;
  88. import java.io.*;
  89. import java.net.HttpURLConnection;
  90. import java.net.SocketTimeoutException;
  91. import java.net.URL;
  92. import java.net.URLEncoder;
  93. import java.text.SimpleDateFormat;
  94. import java.util.*;
  95. import java.util.Map.Entry;
  96. @Controller
  97. @RequestMapping(value = "/api/wxdispatch")
  98. public class WXController {
  99. private static final Logger logger = Logger.getLogger(WXController.class);
  100. @Autowired
  101. SystemService systemService;
  102. @Autowired
  103. WXDao wxdao;
  104. @Autowired
  105. private DataviewServiceI dvservice;
  106. @Autowired
  107. private TSysFileServiceI tSysFileService;
  108. @Autowired
  109. private ActivitiService activitiService;
  110. @Autowired
  111. private HistoryService historyService;
  112. @Autowired
  113. protected RepositoryService repositoryService;
  114. @Autowired
  115. private WxTokenService wxTokenService;
  116. @Autowired
  117. private XcglRptDao rptDao;
  118. @Autowired
  119. private RuntimeService runtimeService;
  120. @Autowired
  121. private IActivitiCommonDao activitiCommonDao;
  122. @Autowired
  123. protected TaskService taskService;
  124. @Autowired
  125. private MMessageServiceI mMessageService;
  126. @Autowired
  127. private MPersonalMessageServiceI mPersonalMessageService;
  128. @Autowired
  129. private MMessageReplyServiceI mMessageReplyService;
  130. /**
  131. * 访问地址:http://localhost:8080/xcgl/api/wx
  132. *
  133. * @return
  134. */
  135. @RequestMapping(method = RequestMethod.GET)
  136. @ResponseBody
  137. public WXAjaxJson checkNet() {
  138. WXAjaxJson json = new WXAjaxJson();
  139. // String key = "userAccessory/03fbd2d1-5d97-4aed-9a33-91a7849b8d62.jpg";
  140. // HashMap<String, String> mediaurl = new HashMap<String, String>();
  141. // try {
  142. // URL url = getAliyunImgByurl(key);
  143. // mediaurl.put("url", url.toString());
  144. // } catch (Exception e) {
  145. // // TODO Auto-generated catch block
  146. // e.printStackTrace();
  147. // }
  148. // json.setData(mediaurl);
  149. return json;
  150. }
  151. @RequestMapping(value = "user/get_user_info")
  152. @ResponseBody
  153. public WXAjaxJson getUserInfo(HttpServletRequest request) {
  154. WXAjaxJson json = new WXAjaxJson();
  155. String openid = request.getParameter("openid");
  156. if (!StringUtils.isNotBlank(openid)) {
  157. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  158. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  159. return json;
  160. }
  161. UserDto data = wxdao.getUser(openid);
  162. if (data == null) {
  163. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  164. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  165. return json;
  166. }
  167. // 设置组织机构
  168. String orgId = data.getProjectid();
  169. String[] project = getParentProject(orgId);
  170. data.setProjectid(project[0]);
  171. data.setProjectname(project[1]);
  172. if (StringUtils.isNotEmpty(data.getJgprojectids())) {
  173. ArrayList<String> ids = new ArrayList<String>();
  174. ArrayList<String> names = new ArrayList<String>();
  175. String[] jzproject = data.getJgprojectids().split(",");
  176. for (String pid : jzproject) {
  177. String[] jzpro = getParentProject(pid);
  178. ids.add(jzpro[0]);
  179. names.add(jzpro[1]);
  180. }
  181. data.setJgprojectids(StringUtils.join(ids, ","));
  182. data.setJgprojectnames(StringUtils.join(names, ","));
  183. }
  184. //设置项目未完成工作数量
  185. // Map projectcount = getUserProjectNotFinashTaskCount(data.getUserid());
  186. // data.setProjectTaskCount(projectcount);
  187. //是否项目人员
  188. boolean isProjectUser = UserUtil.isProjectUser(data.getUserid());
  189. json.setData(data);
  190. ;
  191. return json;
  192. }
  193. private String[] getParentProject(String projectid) {
  194. String[] temp = new String[2];
  195. if (!StringUtils.isNotEmpty(projectid)) {
  196. return temp;
  197. }
  198. StringBuffer hql = new StringBuffer("from TSDepart where id = :pid");
  199. List<TSDepart> tsList = systemService.getSession().createQuery(hql.toString()).setParameter("pid", projectid).list();
  200. if (!tsList.isEmpty()) {
  201. TSDepart tsDepart = tsList.get(0);
  202. //直属项目、区域项目、公司类型
  203. if ("3".equals(tsDepart.getOrgType()) || "5".equals(tsDepart.getOrgType()) || "1".equals(tsDepart.getOrgType())
  204. || ("2".equals(tsDepart.getOrgType()) && ("1".equals(tsDepart.getTSPDepart().getOrgType())))) {
  205. temp[0] = tsDepart.getId();
  206. temp[1] = tsDepart.getDescription();
  207. } else if ("2".equals(tsDepart.getOrgType()) && ("1".equals(tsDepart.getTSPDepart().getOrgType())
  208. || "3".equals(tsDepart.getTSPDepart().getOrgType()) || "5".equals(tsDepart.getTSPDepart().getOrgType()))) {
  209. temp[0] = tsDepart.getTSPDepart().getId();
  210. temp[1] = tsDepart.getTSPDepart().getDescription();
  211. }
  212. }
  213. return temp;
  214. }
  215. @RequestMapping(value = "user/getProjectList4Mine")
  216. @ResponseBody
  217. public WXAjaxJson getProjectList4Mine(HttpServletRequest request) {
  218. WXAjaxJson json = new WXAjaxJson();
  219. String openid = request.getParameter("openid");
  220. if (!StringUtils.isNotBlank(openid)) {
  221. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  222. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  223. return json;
  224. }
  225. UserDto userdata = wxdao.getUser(openid);
  226. if (userdata == null) {
  227. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  228. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  229. return json;
  230. }
  231. // 设置组织机构
  232. Map<String, String> projectAndNameMap = new HashMap<String, String>();
  233. String orgId = userdata.getProjectid();
  234. String[] project = getParentProject(orgId);
  235. projectAndNameMap.put(project[0], project[1]);
  236. if (StringUtils.isNotEmpty(userdata.getJgprojectids())) {
  237. String[] jzproject = userdata.getJgprojectids().split(",");
  238. for (String pid : jzproject) {
  239. String[] jzpro = getParentProject(pid);
  240. projectAndNameMap.put(jzpro[0], jzpro[1]);
  241. }
  242. }
  243. //设置项目未完成工作数量
  244. List<Map<String, Object>> projectcount = getUserProjectNotFinashTaskCount(userdata.getUserid());
  245. for (Map<String, Object> pcountMap : projectcount) {
  246. if (projectAndNameMap.containsKey(pcountMap.get("id"))) {
  247. projectAndNameMap.remove(pcountMap.get("id"));
  248. }
  249. }
  250. for (Entry<String, String> projectIDName : projectAndNameMap.entrySet()) {
  251. Map<String, Object> oneProjectMap = new HashMap<String, Object>();
  252. oneProjectMap.put("id", projectIDName.getKey());
  253. oneProjectMap.put("name", projectIDName.getValue());
  254. oneProjectMap.put("count", "0");
  255. projectcount.add(oneProjectMap);
  256. }
  257. json.setData(projectcount);
  258. ;
  259. return json;
  260. }
  261. private List<Map<String, Object>> getUserProjectNotFinashTaskCount(String userid) {
  262. String taskCountSql = "select cast(count(1) as char) count , task.projectid id,project.description name from p_projecttask task \n" +
  263. "left join t_s_depart project on task.projectid = project.id\n" +
  264. "where owner =? and taskstatus in ('0','1') and left(task.planendtime,10)<=? group by task.projectid";
  265. List<Map<String, Object>> lsCount = systemService.findForJdbc(taskCountSql, userid, DateUtils.date_sdf.format(new Date()));
  266. return lsCount;
  267. }
  268. @RequestMapping(value = "user/getProjectList")
  269. @ResponseBody
  270. public WXAjaxJson getProjectList(HttpServletRequest request) {
  271. WXAjaxJson json = new WXAjaxJson();
  272. String openid = request.getParameter("openid");
  273. if (!StringUtils.isNotBlank(openid)) {
  274. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  275. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  276. return json;
  277. }
  278. UserDto userdata = wxdao.getUser(openid);
  279. if (userdata == null) {
  280. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  281. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  282. return json;
  283. }
  284. // 设置组织机构
  285. Map<String, String> projectAndNameMap = new HashMap<String, String>();
  286. String orgId = userdata.getProjectid();
  287. String[] project = getParentProject(orgId);
  288. projectAndNameMap.put(project[0], project[1]);
  289. if (StringUtils.isNotEmpty(userdata.getJgprojectids())) {
  290. String[] jzproject = userdata.getJgprojectids().split(",");
  291. for (String pid : jzproject) {
  292. String[] jzpro = getParentProject(pid);
  293. projectAndNameMap.put(jzpro[0], jzpro[1]);
  294. }
  295. }
  296. //设置项目未完成工作数量
  297. List<Map<String, Object>> projectcount = getProjectNotFinashTaskCount("'" + StringUtils.join(projectAndNameMap.keySet(), "','") + "'");
  298. for (Map<String, Object> pcountMap : projectcount) {
  299. if (projectAndNameMap.containsKey(pcountMap.get("id"))) {
  300. projectAndNameMap.remove(pcountMap.get("id"));
  301. }
  302. }
  303. for (Entry<String, String> projectIDName : projectAndNameMap.entrySet()) {
  304. Map<String, Object> oneProjectMap = new HashMap<String, Object>();
  305. oneProjectMap.put("id", projectIDName.getKey());
  306. oneProjectMap.put("name", projectIDName.getValue());
  307. oneProjectMap.put("count", "0");
  308. projectcount.add(oneProjectMap);
  309. }
  310. json.setData(projectcount);
  311. ;
  312. return json;
  313. }
  314. private List<Map<String, Object>> getProjectNotFinashTaskCount(String projectids) {
  315. String taskCountSql = "select cast(count(1) as char) count , task.projectid id,project.description name from p_projecttask task \n" +
  316. "left join t_s_depart project on task.projectid = project.id\n" +
  317. "where task.projectid in (" + projectids + ") and taskstatus in ('0','1') group by task.projectid";
  318. List<Map<String, Object>> lsCount = systemService.findForJdbc(taskCountSql);
  319. return lsCount;
  320. }
  321. /**
  322. * 微信绑定手机号
  323. */
  324. @RequestMapping(value = "user/bindTel")
  325. @ResponseBody
  326. public WXAjaxJson bindTel(HttpServletRequest request) {
  327. WXAjaxJson json = new WXAjaxJson();
  328. String openid = request.getParameter("openid");
  329. String phonenum = request.getParameter("phonenum");
  330. String timestamp = request.getParameter("timestamp");
  331. if (!StringUtils.isNotBlank(openid)) {
  332. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  333. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  334. return json;
  335. } else if (!StringUtils.isNotBlank(phonenum)) {
  336. json.setCode(XcglConstant.RETCODE_PHONE_NOTFOUND);
  337. json.setMsg(XcglConstant.RETMSG_PHONE_NOTFOUND);
  338. return json;
  339. } else if (!StringUtils.isNotBlank(timestamp)) {
  340. json.setCode(XcglConstant.RETCODE_TIMEOUT);
  341. json.setMsg(XcglConstant.RETMSG_TIMEOUT);
  342. return json;
  343. }
  344. //只有【已入职】、【已转正】状态的员工才可以注册
  345. String uptOpenidSql = " update t_s_user set openid =? where mobilePhone =? and "
  346. + "id in (select userid from t_bus_user_personnel where position_status in ('1','2'))";
  347. Integer count = systemService.executeSql(uptOpenidSql, openid, phonenum);
  348. if (count == 0) {
  349. json.setCode(XcglConstant.RETCODE_PHONE_NOTFOUND);
  350. json.setMsg(XcglConstant.RETMSG_PHONE_NOTFOUND);
  351. }
  352. return json;
  353. }
  354. /**
  355. * 下载图片
  356. */
  357. @RequestMapping(value = "user/download_wx_media")
  358. @ResponseBody
  359. public WXAjaxJson downloadWXMedia(HttpServletRequest request) {
  360. WXAjaxJson json = new WXAjaxJson();
  361. Map map = new HashMap<String, String>();
  362. json.setAttributes(map);
  363. return json;
  364. }
  365. /**
  366. * 上传附件
  367. */
  368. @RequestMapping(value = "user/uploadAttachment")
  369. @ResponseBody
  370. public WXAjaxJson uploadAttachment(HttpServletRequest request) {
  371. WXAjaxJson json = new WXAjaxJson();
  372. String userid = oConvertUtils.getString(request.getParameter("userid"));
  373. String upFlag = oConvertUtils.getString(request.getParameter("isup"));
  374. String delFlag = oConvertUtils.getString(request.getParameter("isdel"));
  375. String mediaid = oConvertUtils.getString(request.getParameter("picture0id")) +
  376. oConvertUtils.getString(request.getParameter("picture1id")) +
  377. oConvertUtils.getString(request.getParameter("picture2id")) +
  378. oConvertUtils.getString(request.getParameter("picture3id")) +
  379. oConvertUtils.getString(request.getParameter("picture4id")) +
  380. oConvertUtils.getString(request.getParameter("picture5id")) +
  381. oConvertUtils.getString(request.getParameter("picture6id"));
  382. // String token = oConvertUtils.getString(request.getParameter("accessToken"));
  383. String token = wxTokenService.getSkey();
  384. try {
  385. //如果是上传操作
  386. if ("1".equals(upFlag)) {
  387. HashMap<String, String> mediaurl = new HashMap<String, String>();
  388. String busiId = com.xcgl.utils.UUID.randomUUID().toString();
  389. String fileName = null;
  390. TSBaseUser baseUser = systemService.get(TSBaseUser.class, userid);
  391. //附件类型名,例如:*户口本本人页
  392. String accessoryName = null;
  393. //附件类型枚举 例如:hukoubenbenrenye4
  394. String accessoryType = null;
  395. String bizType = "userAccessory";//request.getParameter("bizType");//上传业务名称
  396. if (oConvertUtils.getString(request.getParameter("picture0id")).length() > 0) {
  397. accessoryName = "*身份证复印件";
  398. accessoryType = "shenfenzhengfuyinjian2";
  399. } else if (oConvertUtils.getString(request.getParameter("picture1id")).length() > 0) {
  400. accessoryName = "*政审材料第一页";
  401. accessoryType = "zhengshencailiao5";
  402. } else if (oConvertUtils.getString(request.getParameter("picture2id")).length() > 0) {
  403. accessoryName = "*政审材料第二页";
  404. accessoryType = "zhengshencailiao6";
  405. } else if (oConvertUtils.getString(request.getParameter("picture3id")).length() > 0) {
  406. accessoryName = "*体检表第一页";
  407. accessoryType = "tijianbiao1";
  408. } else if (oConvertUtils.getString(request.getParameter("picture4id")).length() > 0) {
  409. accessoryName = "*体检表第二页";
  410. accessoryType = "tijianbiao7";
  411. } else if (oConvertUtils.getString(request.getParameter("picture5id")).length() > 0) {
  412. accessoryName = "*户口本首页";
  413. accessoryType = "hukoubenshouye3";
  414. } else if (oConvertUtils.getString(request.getParameter("picture6id")).length() > 0) {
  415. accessoryName = "*户口本本人页";
  416. accessoryType = "hukoubenbenrenye4";
  417. } else if (oConvertUtils.getString(request.getParameter("picture7id")).length() > 0) {
  418. accessoryName = "*离职报告";
  419. accessoryType = "lizhibaogao8";
  420. }
  421. String extName = "jpg";//FileUtils.getExtend(fileName);
  422. fileName = baseUser.getRealName() + accessoryName.substring(1) + "." + extName;
  423. List<String> keyAndUrl = getWXfileToOSS(extName, bizType, token, mediaid);
  424. // List<String> keyAndUrl = getWXfileToOSSTest(extName, "test", token, mediaid, request);
  425. if (keyAndUrl.size() == 2) {
  426. mediaurl.put("url", keyAndUrl.get(1));
  427. String busiTable = "t_bus_accessory";// request.getParameter("busiTable");
  428. TSysFileEntity tSysFileEntity = new TSysFileEntity();
  429. tSysFileEntity.setBusiId(busiId);// 业务id
  430. tSysFileEntity.setFileUrl(keyAndUrl.get(0));// 文件访问路径
  431. tSysFileEntity.setFileName(fileName);// 文件名称
  432. tSysFileEntity.setTagetType(bizType);// 文件类型
  433. tSysFileEntity.setBusiTable(oConvertUtils.getString(busiTable));
  434. tSysFileService.save(tSysFileEntity);
  435. // 保存业务表
  436. String accessorySql = "INSERT INTO t_bus_accessory(id, accessory_name, userid, isfixed, gatet_type, delete_flag) "
  437. + "VALUES (?, ?, ?, '1', ?, '0')";
  438. systemService.executeSql(accessorySql, busiId, accessoryName, userid, accessoryType);
  439. // }
  440. json.setData(mediaurl);
  441. }
  442. } else if ("1".equals(delFlag)) {//如果是删除操作
  443. // TODO 删除业务表数据,再删除oss,t_sys_file数据
  444. Map<String, String[]> params = request.getParameterMap();
  445. String ossKey = deleteAccSysfile(params, userid);
  446. if (!deleteOssfile(ossKey)) {
  447. String msg = MutiLangUtil.getMutiLangInstance().getLang("file.warn.filelost");
  448. // 不存在前台也给他删除
  449. json.setMsg(msg);
  450. }
  451. } else {
  452. throw new BusinessException("没有传参指定上传还是删除操作!");
  453. }
  454. } catch (IOException e) {
  455. json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
  456. json.setMsg(e.getMessage());
  457. logger.error(e.getMessage());
  458. } catch (BusinessException b) {
  459. json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
  460. json.setMsg(b.getMessage());
  461. logger.error(b.getMessage());
  462. } catch (Exception e) {
  463. json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
  464. json.setMsg(e.getMessage());
  465. logger.error(e.getMessage());
  466. }
  467. return json;
  468. }
  469. /**
  470. * 从微信获取临时素材,存入到oss中
  471. */
  472. private List<String> getWXfileToOSSTest(String extName, String bizType, String wxtoken, String mediaid, HttpServletRequest request) throws IOException {
  473. List<String> keyAndUrl = new ArrayList<String>();
  474. InputStream input = null;
  475. int fileLength = 0;
  476. String realpath = request.getSession().getServletContext().getRealPath("").replaceAll("\\\\", "/") + "/images/";
  477. String getURL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + wxtoken + "&media_id=" + mediaid;
  478. FileInputStream is = null;
  479. FileOutputStream fileOutputStream = null;
  480. OSSClient ossClient = null;
  481. HttpURLConnection conn = null;
  482. try {
  483. URL url = new URL(getURL);
  484. logger.error("start: get image from weixin " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  485. conn = (HttpURLConnection) url.openConnection();
  486. conn.setDoInput(true);
  487. conn.setRequestMethod("GET");
  488. conn.connect();
  489. logger.error("end: get image from weixin " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  490. fileLength = conn.getContentLength();
  491. input = conn.getInputStream();
  492. logger.error("get inputSteam from weixin connection,over " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  493. String uuid = com.xcgl.utils.UUID.randomUUID().toString();
  494. fileOutputStream = new FileOutputStream(realpath + uuid + ".jpg");
  495. int len = 0;
  496. byte[] data = new byte[1024];
  497. while ((len = input.read(data)) != -1) {
  498. fileOutputStream.write(data, 0, len);
  499. }
  500. fileOutputStream.close();
  501. logger.error("image save local over " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  502. is = new FileInputStream(realpath + uuid + ".jpg");
  503. int i = is.available(); // 得到文件大小
  504. byte dataUp[] = new byte[i];
  505. is.read(dataUp);
  506. logger.error("image read over " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  507. // 创建上传Object的Metadata
  508. ObjectMetadata meta = new ObjectMetadata();
  509. // 设置contenttype否则上传图片在oss上预览时不显示图片
  510. meta.setContentType("image/jpeg");
  511. // 必须设置ContentLength
  512. meta.setContentLength(fileLength);
  513. // 创建OSSClient实例
  514. logger.error("start : OSS " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  515. ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  516. logger.error("new OSS client over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  517. String key = String.format(bizType + "/%s", uuid + "." + extName);
  518. ossClient.putObject(CustomerConstant.BUCKETNAME, key, new ByteArrayInputStream(dataUp), meta);
  519. logger.error("pus object to OSS over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  520. // 设置URL过期时间为1小时
  521. Date expiration = new Date(new Date().getTime() + 3600 * 1000);
  522. URL fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
  523. logger.error("get OSS object URL over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  524. logger.error("end OSS work: " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  525. keyAndUrl.add(key);
  526. keyAndUrl.add(fileUrl.toString());
  527. // 关闭client
  528. // ossClient.shutdown();
  529. // conn.disconnect();
  530. } catch (SocketTimeoutException e) {
  531. logger.error("获取微信图片请求出错: " + e);
  532. } catch (Exception ex) {
  533. ex.printStackTrace();
  534. logger.error("获取微信图片请求出错: " + ex);
  535. } finally {
  536. if (ossClient != null)
  537. ossClient.shutdown();
  538. if (conn != null)
  539. conn.disconnect();
  540. if (is != null)
  541. is.close();
  542. }
  543. return keyAndUrl;
  544. }
  545. /**
  546. * 从微信获取临时素材,存入到oss中
  547. */
  548. private List<String> getWXfileToOSS(String extName, String bizType, String wxtoken, String mediaid) throws IOException {
  549. List<String> keyAndUrl = new ArrayList<String>();
  550. try {
  551. OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  552. keyAndUrl = savefileToOSS(ossClient, extName, bizType, wxtoken, mediaid);
  553. // 关闭client
  554. ossClient.shutdown();
  555. } catch (SocketTimeoutException e) {
  556. logger.error("获取微信图片请求出错: " + e);
  557. } catch (Exception ex) {
  558. ex.printStackTrace();
  559. logger.error("获取微信图片请求出错: " + ex);
  560. }
  561. return keyAndUrl;
  562. }
  563. /**
  564. * 从微信获取临时素材,存入到oss中
  565. */
  566. private List<String> savefileToOSS(OSSClient ossClient, String extName, String bizType, String wxtoken, String mediaid) throws IOException {
  567. logger.error("********** toOSS start **********");
  568. logger.error("accessToken:" + wxtoken);
  569. logger.error("mediaid:" + mediaid);
  570. logger.error("*********** toOSS end *********");
  571. List<String> keyAndUrl = new ArrayList<String>();
  572. InputStream input = null;
  573. int fileLength = 0;
  574. String getURL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + wxtoken + "&media_id=" + mediaid;
  575. try {
  576. URL url = new URL(getURL);
  577. logger.error("start: get image from weixin " + getURL);
  578. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  579. conn.setDoInput(true);
  580. conn.setRequestMethod("GET");
  581. conn.connect();
  582. logger.error("end: get image from weixin ");
  583. fileLength = conn.getContentLength();
  584. input = conn.getInputStream();
  585. String uuid = com.xcgl.utils.UUID.randomUUID().toString();
  586. // 创建上传Object的Metadata
  587. ObjectMetadata meta = new ObjectMetadata();
  588. // 设置contenttype否则上传图片在oss上预览时不显示图片
  589. meta.setContentType("image/jpeg");
  590. // 必须设置ContentLength
  591. meta.setContentLength(fileLength);
  592. // 创建OSSClient实例
  593. String date = DateUtils.formatDate(new Date(), "yyyyMM");
  594. logger.error("start : OSS " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  595. logger.error("new OSS client over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  596. String key = String.format(bizType + "/%s/%s", date, uuid + "." + extName);
  597. ossClient.putObject(CustomerConstant.BUCKETNAME, key, input, meta);
  598. logger.error("pus object to OSS over");
  599. // 设置URL过期时间为1小时
  600. Date expiration = new Date(new Date().getTime() + 3600 * 1000);
  601. URL fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
  602. logger.error("get OSS object URL over");
  603. logger.error("end OSS work: " + fileUrl);
  604. keyAndUrl.add(key);
  605. keyAndUrl.add(fileUrl.toString());
  606. conn.disconnect();
  607. } catch (SocketTimeoutException e) {
  608. logger.error("获取微信图片请求出错: " + e);
  609. } catch (Exception ex) {
  610. ex.printStackTrace();
  611. logger.error("获取微信图片请求出错: " + ex);
  612. }
  613. return keyAndUrl;
  614. }
  615. private List<String> saveVideoToOSS(OSSClient ossClient, MultipartFile video, String bizType) {
  616. List<String> keyAndUrl = new ArrayList<String>();
  617. try {
  618. ObjectMetadata meta = new ObjectMetadata();
  619. // 设置contenttype否则上传图片在oss上预览时不显示图片
  620. meta.setContentType(video.getContentType());
  621. // 必须设置ContentLength
  622. meta.setContentLength(video.getSize());
  623. String fileName = video.getOriginalFilename();
  624. String uuid = UUID.randomUUID().toString();
  625. String key = String.format(bizType + "/video/%s", uuid + "." + FileUtils.getExtend(fileName));
  626. ossClient.putObject(CustomerConstant.BUCKETNAME, key, video.getInputStream(), meta);
  627. logger.error("pus object to OSS over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  628. // 设置URL过期时间为1小时
  629. Date expiration = new Date(new Date().getTime() + 3600 * 1000);
  630. URL fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
  631. logger.error("get OSS object URL over :" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));
  632. logger.error("end OSS work: " + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss SSS") + fileUrl.toString());
  633. keyAndUrl.add(key);
  634. keyAndUrl.add(fileUrl.toString());
  635. } catch (Exception ex) {
  636. ex.printStackTrace();
  637. logger.error("请求出错: " + ex);
  638. }
  639. return keyAndUrl;
  640. }
  641. private String saveToOSS(String extName, String bizType, InputStream fileStream, int fileLength, URL fileUrl) throws IOException {
  642. String uuid = com.xcgl.utils.UUID.randomUUID().toString();
  643. // 创建上传Object的Metadata
  644. ObjectMetadata meta = new ObjectMetadata();
  645. // 设置contenttype否则上传图片在oss上预览时不显示图片
  646. meta.setContentType("image/jpeg");
  647. // 必须设置ContentLength
  648. meta.setContentLength(fileLength);
  649. // 创建OSSClient实例
  650. OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  651. String key = String.format(bizType + "/%s", uuid + "." + extName);
  652. ossClient.putObject(CustomerConstant.BUCKETNAME, key, fileStream, meta);
  653. // 设置URL过期时间为1小时
  654. Date expiration = new Date(new Date().getTime() + 3600 * 1000);
  655. fileUrl = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, key, expiration);
  656. // 关闭client
  657. ossClient.shutdown();
  658. return key;
  659. }
  660. private boolean deleteOssfile(String path) {
  661. // 创建OSSClient实例
  662. OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  663. // Object是否存在
  664. boolean found = ossClient.doesObjectExist(CustomerConstant.BUCKETNAME, path);
  665. if (found) {
  666. ossClient.deleteObject(CustomerConstant.BUCKETNAME, path);
  667. ossClient.shutdown();
  668. return true;
  669. }
  670. return false;
  671. }
  672. /**
  673. * 1、删除系统数据库中记录的文件信息
  674. *
  675. * @return ossKey
  676. */
  677. private String deleteAccSysfile(Map<String, String[]> params, String userid) {
  678. String accessoryType = "";
  679. if (params.containsKey("picture0id")) {
  680. accessoryType = "shenfenzhengfuyinjian2";
  681. } else if (params.containsKey("picture1id")) {
  682. accessoryType = "zhengshencailiao5";
  683. } else if (params.containsKey("picture2id")) {
  684. accessoryType = "zhengshencailiao6";
  685. } else if (params.containsKey("picture3id")) {
  686. accessoryType = "tijianbiao1";
  687. } else if (params.containsKey("picture4id")) {
  688. accessoryType = "tijianbiao7";
  689. } else if (params.containsKey("picture5id")) {
  690. accessoryType = "hukoubenshouye3";
  691. } else if (params.containsKey("picture6id")) {
  692. accessoryType = "hukoubenbenrenye4";
  693. }
  694. if (accessoryType.length() == 0)
  695. return "";
  696. String qrySysFileSql = "select file_url from t_sys_file where busi_table = 't_bus_accessory' " +
  697. "and busi_id in (select id from t_bus_accessory where userid =? and gatet_type = ? ) ";
  698. List<Map<String, Object>> ret = systemService.findForJdbc(qrySysFileSql, userid, accessoryType);
  699. if (ret.size() == 0)
  700. return "";
  701. String ossKey = ret.get(0).get("file_url").toString();
  702. //删除系统文件库数据
  703. String delSysFileSql = "delete from t_sys_file where busi_table = 't_bus_accessory' " +
  704. "and busi_id in (select id from t_bus_accessory where userid =? and gatet_type = ? ) ";
  705. systemService.executeSql(delSysFileSql, userid, accessoryType);
  706. return ossKey;
  707. }
  708. /**
  709. * 从服务器获取用户功能权限
  710. */
  711. @RequestMapping(value = "user/qryAuth")
  712. @ResponseBody
  713. public WXAjaxJson qryAuth(HttpServletRequest request) {
  714. String openid = oConvertUtils.getString(request.getParameter("openid"));
  715. WXAjaxJson json = new WXAjaxJson();
  716. List<AuthorityDto> data = wxdao.getAuthByOpenid(openid);
  717. for (AuthorityDto auth : data) {
  718. auth.setAlert("0");
  719. //查询设备是否有异常,如果有异常,则前台界面小红点提示
  720. if (auth.getOptName().equals("设备监测")) {
  721. String alertSql = "select count(*) total from p_sensor_abnormal abn\n" +
  722. "left join p_sensor_monitor_point point on abn.monitor_point_id = point.id\n" +
  723. "where left(abn.create_date,10) = '2018-09-09'\n" +
  724. "and point.projectid in (select org_id from t_s_user_org uorg "
  725. + "left join t_s_user user on user.id = uorg.user_id where ifpluralism = '0' and openid = ?)";
  726. List<Map<String, Object>> ret = systemService.findForJdbc(alertSql, openid);
  727. if (ret.size() > 0 && Integer.parseInt(ret.get(0).get("total").toString()) > 0) {
  728. auth.setAlert("1");
  729. }
  730. }
  731. if (!auth.getEnable().equals("0"))
  732. auth.setEnable("1");
  733. }
  734. json.setData(data);
  735. return json;
  736. }
  737. /**
  738. * 变更工作状态
  739. */
  740. @RequestMapping(value = "task/changeWorkStatus")
  741. @ResponseBody
  742. public WXAjaxJson changeWorkStatus(HttpServletRequest request) {
  743. WXAjaxJson json = new WXAjaxJson();
  744. String openid = oConvertUtils.getString(request.getParameter("openid"));
  745. String userid = oConvertUtils.getString(request.getParameter("userid"));
  746. String taskid = oConvertUtils.getString(request.getParameter("taskid"));
  747. String oldStatus = oConvertUtils.getString(request.getParameter("oldStatus"));
  748. String newStatus = oConvertUtils.getString(request.getParameter("newStatus"));
  749. String closeReason = oConvertUtils.getString(request.getParameter("closeReason"));
  750. ProjecttaskEntity task = systemService.get(ProjecttaskEntity.class, taskid);
  751. if (task == null || !task.getTaskstatus().equals(oldStatus)) {
  752. json.setCode(XcglConstant.RETCODE_TASK_ERROR);
  753. json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
  754. return json;
  755. }
  756. String changeSql = "";
  757. switch (newStatus) {
  758. case XcglConstant.TASKSTATUS_EXEING:
  759. changeSql = "update p_projecttask set taskstatus =? ,executer = ? ,exestarttime=? where id = ? ";
  760. systemService.executeSql(changeSql, newStatus, userid, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), taskid);
  761. break;
  762. case XcglConstant.TASKSTATUS_CLOSED:
  763. changeSql = "update p_projecttask set taskstatus =? ,executer = ? ,closemsg=? where id = ? ";
  764. systemService.executeSql(changeSql, newStatus, userid, closeReason, taskid);
  765. break;
  766. case XcglConstant.TASKSTATUS_DONE:
  767. changeSql = "update p_projecttask set taskstatus =? ,exeendtime =? where id = ? ";
  768. systemService.executeSql(changeSql, newStatus, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), taskid);
  769. break;
  770. }
  771. return json;
  772. }
  773. /**
  774. * 提交工作执行结果
  775. */
  776. @RequestMapping(value = "task/sendWorkResult")
  777. @ResponseBody
  778. public WXAjaxJson sendWorkResult(
  779. @RequestParam(value = "video", required = false) MultipartFile video, HttpServletRequest request) {
  780. WXAjaxJson json = new WXAjaxJson();
  781. String openid = oConvertUtils.getString(request.getParameter("openid"));
  782. int progress = oConvertUtils.getInt(request.getParameter("progress"), 100);
  783. String pictureids = oConvertUtils.getString(request.getParameter("pictureids"));
  784. String taskid = oConvertUtils.getString(request.getParameter("taskid"));
  785. String texts = oConvertUtils.getString(request.getParameter("texts"));
  786. // String token = oConvertUtils.getString(request.getParameter("accessToken"));
  787. String token = wxTokenService.getSkey();
  788. int isTemp = oConvertUtils.getInt(request.getParameter("isTemp"), 0);
  789. ProjecttaskEntity task = systemService.get(ProjecttaskEntity.class, taskid);
  790. Map<String, String[]> params = request.getParameterMap();
  791. // logger.error("********** params start **********");
  792. // for(Entry<String, String[]> entity : params.entrySet()) {
  793. // logger.error(entity.getKey());
  794. // logger.error(entity.getValue().length>0?entity.getValue()[0]:"");
  795. // }
  796. // logger.error("*********** params end *********");
  797. // logger.error("accessToken:"+token);
  798. // logger.error(openid);
  799. // logger.error(pictureids);
  800. // logger.error(taskid);
  801. // logger.error(texts);
  802. if (task == null) {
  803. json.setCode(XcglConstant.RETCODE_TASK_ERROR);
  804. json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
  805. return json;
  806. }
  807. TaskResultEntity resultEntity = null;
  808. List<TaskResultEntity> list = systemService.findByProperty(TaskResultEntity.class, "taskid", taskid);
  809. if(list != null && list.size() > 0) {
  810. resultEntity = list.get(0);
  811. } else {
  812. resultEntity = new TaskResultEntity();
  813. }
  814. resultEntity.setTaskid(taskid);
  815. resultEntity.setMemo(texts);
  816. Integer qualityScore = oConvertUtils.getInt(request.getParameter("qualityScore"));//服务质量
  817. Integer efficiencyScore = oConvertUtils.getInt(request.getParameter("efficiencyScore"));//服务时效
  818. Integer attitudeScore = oConvertUtils.getInt(request.getParameter("attitudeScore"));//服务态度
  819. Integer skillsScore = oConvertUtils.getInt(request.getParameter("skillsScore"));//技术能力
  820. Integer taskObjectScore = oConvertUtils.getInt(request.getParameter("taskObjectScore"));//总分
  821. resultEntity.setEfficiencyScore(efficiencyScore);
  822. resultEntity.setQualityScore(qualityScore);
  823. resultEntity.setSkillsScore(skillsScore);
  824. resultEntity.setReviewScore(0);
  825. resultEntity.setTaskObjectScore(taskObjectScore);
  826. resultEntity.setAttitudeScore(attitudeScore);
  827. resultEntity.setCreateDate(new Date());
  828. resultEntity.setCreateBy("system");
  829. //最多10个图片
  830. String[] keys = new String[10];
  831. OSSClient ossClient = null;
  832. try {
  833. if (pictureids.length() > 0 || (video != null && !video.isEmpty())) {
  834. ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  835. }
  836. if (pictureids.length() > 0) {
  837. String[] picList = pictureids.split(",");
  838. //存储到oss
  839. String extName = "jpg";//FileUtils.getExtend(fileName);
  840. int index = 0;
  841. for (String mediaid : picList) {
  842. String bizType = "projecttask";
  843. if(mediaid.startsWith(bizType)) {
  844. keys[index] = mediaid;
  845. } else {
  846. List<String> keyAndUrl = savefileToOSS(ossClient, extName, bizType, token, mediaid);
  847. if (keyAndUrl.size() == 2) {
  848. keys[index] = keyAndUrl.get(0);
  849. }
  850. }
  851. index++;
  852. }
  853. }
  854. if (video != null && !video.isEmpty()) {
  855. List<String> keyAndUrl = saveVideoToOSS(ossClient, video, "project");
  856. resultEntity.setVideo(keyAndUrl.get(0));
  857. }
  858. if(ossClient != null) {
  859. ossClient.shutdown();
  860. }
  861. } catch (Exception e) {
  862. json.setCode(XcglConstant.RETCODE_PICTURE_ERROR);
  863. json.setMsg(XcglConstant.RETMSG_PICTURE_ERROR);
  864. return json;
  865. } finally {
  866. if (ossClient != null)
  867. ossClient.shutdown();
  868. }
  869. // String workRsultSql = " INSERT INTO p_taskresult(id, taskid, picture1, picture2, picture3, picture4, picture5, picture6, picture7, picture8, picture9, picture10, memo) "
  870. // + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
  871. resultEntity.setProgress(progress);
  872. resultEntity.setPicture1(keys[0]);
  873. resultEntity.setPicture2(keys[1]);
  874. resultEntity.setPicture3(keys[2]);
  875. resultEntity.setPicture4(keys[3]);
  876. resultEntity.setPicture5(keys[4]);
  877. resultEntity.setPicture6(keys[5]);
  878. resultEntity.setPicture7(keys[6]);
  879. resultEntity.setPicture8(keys[7]);
  880. resultEntity.setPicture9(keys[8]);
  881. resultEntity.setPicture10(keys[9]);
  882. systemService.save(resultEntity);
  883. // systemService.executeSql(workRsultSql, UUID.randomUUID().toString(),taskid,keys[0],keys[1],keys[2],keys[3],keys[4],keys[5],keys[6],keys[7],keys[8],keys[9],texts);
  884. if(isTemp != 1 && progress == 100) {
  885. String changeSql = "update p_projecttask set taskstatus =? ,exeendtime =? where id = ? ";
  886. systemService.executeSql(changeSql, XcglConstant.TASKSTATUS_DONE, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), taskid);
  887. if(org.apache.commons.lang3.StringUtils.equals(task.getSourcetype(), "caralarm")){
  888. CarAlarmEntity entity = systemService.get(CarAlarmEntity.class, task.getSourceid());
  889. entity.setExecuteDesc(resultEntity.getMemo());
  890. entity.setStatus(1);
  891. systemService.save(entity);
  892. }
  893. }
  894. if(isTemp!=1){
  895. task.setTemp(0);
  896. }
  897. task.setCompletePer(String.valueOf(progress));
  898. systemService.updateEntitie(task);
  899. json.setData(keys);
  900. return json;
  901. }
  902. @RequestMapping(value = "task/qryWorkResult")
  903. @ResponseBody
  904. public WXAjaxJson qryWorkResult(HttpServletRequest request) {
  905. WXAjaxJson json = new WXAjaxJson();
  906. String openid = oConvertUtils.getString(request.getParameter("openid"));
  907. String taskid = oConvertUtils.getString(request.getParameter("taskid"));
  908. List<TaskResultEntity> entitys = systemService.findByProperty(TaskResultEntity.class, "taskid", taskid);
  909. Map<String, Object> retMap = new HashMap<String, Object>();
  910. List<String> picURL = new ArrayList<String>();
  911. if (entitys != null && entitys.size() > 0) {
  912. TaskResultEntity entity = entitys.get(0);
  913. picURL = setTaskPicURL(entity);
  914. List<String> taskPictures = getTaskPictures(entity);
  915. String videoURL = setTaskVideoURL(entity);
  916. if (org.jeecgframework.p3.core.utils.common.StringUtils.isEmpty(entity.getMemo())
  917. && picURL.size() == 0) {
  918. retMap.put("taskid", entity.getId());
  919. retMap.put("text", "");
  920. retMap.put("pictures", picURL);
  921. } else {
  922. List<Map<String, Object>> pictures = new ArrayList<>();
  923. for (int i=0; i < taskPictures.size(); i++) {
  924. Map<String, Object> picItem = new HashMap<String, Object>();
  925. picItem.put("src", picURL.get(i));
  926. picItem.put("mediaid", taskPictures.get(i));
  927. pictures.add(picItem);
  928. }
  929. retMap.put("taskid", entity.getId());
  930. retMap.put("text", entity.getMemo());
  931. retMap.put("pictures", pictures);
  932. }
  933. retMap.put("video", videoURL);
  934. retMap.put("progress", entity.getProgress());
  935. json.setData(retMap);
  936. return json;
  937. } else {
  938. retMap.put("taskid", taskid);
  939. retMap.put("text", "");
  940. retMap.put("pictures", picURL);
  941. retMap.put("video", null);
  942. json.setData(retMap);
  943. }
  944. return json;
  945. }
  946. /**
  947. * 上报或分配工作
  948. */
  949. @RequestMapping(value = "task/dispatchWork")
  950. @ResponseBody
  951. public WXAjaxJson dispatchWork(HttpServletRequest request) {
  952. WXAjaxJson json = new WXAjaxJson();
  953. String openid = oConvertUtils.getString(request.getParameter("openid"));
  954. String taskid = oConvertUtils.getString(request.getParameter("taskid"));
  955. //指派类型: '0':上报 '1':分配下级
  956. String dispatchType = oConvertUtils.getString(request.getParameter("dispatchType"));
  957. String newOwner = oConvertUtils.getString(request.getParameter("newOwner"));
  958. ProjecttaskEntity task = systemService.get(ProjecttaskEntity.class, taskid);
  959. if (task == null) {
  960. json.setCode(XcglConstant.RETCODE_TASK_ERROR);
  961. json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
  962. logger.error("找不到项目信息");
  963. return json;
  964. }
  965. if (dispatchType.equals("0")) {//上报
  966. //查询项目负责人
  967. String projectManager = "";
  968. String qryManagerSql = "select distinct suser.id manager from t_s_user_org userorg\n" +
  969. "left join t_s_user suser on suser.id = userorg.user_id\n" +
  970. "left join t_s_role_user ruser on suser.id = ruser.userid\n" +
  971. "left join t_s_role role on ruser.roleid = role.id\n" +
  972. "where role.rolecode = 'P_XMJL' and userorg.org_id = ?";
  973. List<Map<String, Object>> ret = systemService.findForJdbc(qryManagerSql, task.getProjectid());
  974. if (ret.size() == 0) {
  975. json.setCode(XcglConstant.RETCODE_TASK_ERROR);
  976. json.setMsg(XcglConstant.RETMSG_TASK_ERROR);
  977. logger.error("task/dispatchWork,找不到项目负责人");
  978. return json;
  979. }
  980. projectManager = ret.get(0).get("manager").toString();
  981. String updTaskSql = "update p_projecttask set submittime = ? ,owner=? where id = ? ";
  982. systemService.executeSql(updTaskSql, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH-mm-ss"), projectManager, taskid);
  983. } else if (dispatchType.equals("1")) {//分配下级
  984. String updTaskSql = "update p_projecttask set dispatchtime = ? ,owner=? where id = ? ";
  985. systemService.executeSql(updTaskSql, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH-mm-ss"), newOwner, taskid);
  986. }
  987. return json;
  988. }
  989. /**
  990. * 查询用户工作
  991. * | openid | true | string | 用户openid |
  992. * | qrydate | false | string | 查询条件:日期,dateformater: yyyy-MM-dd hh:mm:ss ,参数中有taskid时,此参数可空|
  993. * | taskid | false | string | 工作id。进入任务详情时使用此参数,其他场景可空 |
  994. */
  995. @RequestMapping(value = "task/qryUserTasks")
  996. @ResponseBody
  997. public WXAjaxJson qryUserTasks(HttpServletRequest request) {
  998. WXAjaxJson json = new WXAjaxJson();
  999. String openid = oConvertUtils.getString(request.getParameter("openid"));
  1000. String taskid = oConvertUtils.getString(request.getParameter("taskid"));
  1001. String qrydate = oConvertUtils.getString(request.getParameter("qrydate"));
  1002. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1003. if (StringUtils.isNotEmpty(taskid)) {
  1004. openid = null;
  1005. }
  1006. //默认为今天
  1007. qrydate = taskid.length() > 0 ? null : (qrydate.length() == 0 ? DateUtils.formatDate(new Date(), "yyyy-MM-dd") : qrydate);
  1008. String status = oConvertUtils.getString(request.getParameter("status"));
  1009. List<ProjecttaskEntity> data = null;
  1010. switch (status) {
  1011. case ""://全部
  1012. data = wxdao.getTaskListAll(openid, qrydate, projectid, taskid);
  1013. break;
  1014. case "0"://未完成
  1015. data = wxdao.getTaskListNotDone(openid, qrydate, projectid, taskid, null);
  1016. break;
  1017. case "20"://已完成
  1018. data = wxdao.getTaskListDone(openid, qrydate, projectid, taskid);
  1019. break;
  1020. case "30"://逾期
  1021. data = wxdao.getTaskListNotDone(openid, qrydate, projectid, taskid, "1");
  1022. break;
  1023. }
  1024. Map<String, Object> retdata = new HashMap<String, Object>();
  1025. retdata.put("list", data);
  1026. retdata.put("hasmore", 0);
  1027. if(data!=null&&!data.isEmpty()){
  1028. ProjecttaskEntity projecttaskEntity = data.get(0);
  1029. if(StringUtils.equals(projecttaskEntity.getId(),taskid)){
  1030. String sourceType = projecttaskEntity.getSourcetype();
  1031. if(StringUtils.equals(projecttaskEntity.getSourcetype(),"maintainbill")){
  1032. String hql = "from MaintainBillEntity where taskId=? ";
  1033. List<MaintainBillEntity> billList = systemService.findHql(hql,taskid);
  1034. if(!billList.isEmpty()){
  1035. MaintainBillEntity billEntity = billList.get(0);
  1036. Map<String,Object> maintainBill = new HashMap<>();
  1037. maintainBill.put("projectName", billEntity.getProjectname());//项目名称
  1038. maintainBill.put("name", billEntity.getName());//计划名称
  1039. String serviceType = DictUtil.formatToTypeName(billEntity.getServicetypedetail(),"servicetypedetail");
  1040. maintainBill.put("serviceType", serviceType);//服务类型
  1041. maintainBill.put("pojectServiceName", billEntity.getProjectservicename());//服务明细
  1042. maintainBill.put("planDateStart", billEntity.getPlandatestart());//开始时间
  1043. maintainBill.put("planDateEnd", billEntity.getPlandateend());//结束时间
  1044. maintainBill.put("contractName", billEntity.getContractname());//合同名称
  1045. maintainBill.put("relatedUnitName", billEntity.getRelatedunitname());//供应商名称
  1046. String planId = billEntity.getMaintainPlanId();
  1047. MaintainPlanEntity planEntity = systemService.get(MaintainPlanEntity.class,planId);
  1048. maintainBill.put("remark", planEntity.getRemark());//备注
  1049. String contractId = billEntity.getContractid();
  1050. ContractEntity contractEntity = systemService.get(ContractEntity.class,contractId);
  1051. maintainBill.put("contractStartDate", contractEntity.getStartdate());//合同开始时间
  1052. maintainBill.put("contractEndDate", contractEntity.getEnddate());//合同结束时间
  1053. retdata.put("maintainBill",maintainBill);
  1054. }else if(StringUtils.equals(sourceType,"weeklymeeting")){
  1055. hql = "from WeeklyMeetingEntity where projectTaskId=? ";
  1056. List<WeeklyMeetingEntity> list = systemService.findHql(hql,taskid);
  1057. if(!list.isEmpty()){
  1058. WeeklyMeetingEntity entity = list.get(0);
  1059. retdata.put("weeklymeeting",entity);
  1060. }
  1061. }
  1062. }
  1063. }
  1064. }
  1065. json.setData(retdata);
  1066. return json;
  1067. }
  1068. /**
  1069. * 查询用户工作
  1070. * | openid | true | string | 用户openid |
  1071. * | taskid | false | string | 工作id。进入任务详情时使用此参数,其他场景可空 |
  1072. */
  1073. @RequestMapping(value = "task/qryTaskResult")
  1074. @ResponseBody
  1075. public WXAjaxJson qryTaskResult(HttpServletRequest request) {
  1076. WXAjaxJson json = new WXAjaxJson();
  1077. String openid = oConvertUtils.getString(request.getParameter("openid"));
  1078. String taskid = oConvertUtils.getString(request.getParameter("taskid"));
  1079. List<TaskResultEntity> entitys = systemService.findByProperty(TaskResultEntity.class, "taskid", taskid);
  1080. Map<String, Object> retMap = new HashMap<String, Object>();
  1081. List<String> picURL = new ArrayList<String>();
  1082. if (entitys != null && entitys.size() > 0) {
  1083. TaskResultEntity entity = entitys.get(0);
  1084. picURL = setTaskPicURL(entity);
  1085. String videoURL = setTaskVideoURL(entity);
  1086. if (org.jeecgframework.p3.core.utils.common.StringUtils.isEmpty(entity.getMemo())
  1087. && picURL.size() == 0) {
  1088. retMap.put("taskid", entity.getId());
  1089. retMap.put("text", "工作已完成(描述:无,图片:无)");
  1090. retMap.put("pictures", picURL);
  1091. } else {
  1092. retMap.put("taskid", entity.getId());
  1093. retMap.put("text", entity.getMemo());
  1094. retMap.put("pictures", picURL);
  1095. }
  1096. retMap.put("video", videoURL);
  1097. retMap.put("progress", entity.getProgress());
  1098. json.setData(retMap);
  1099. return json;
  1100. } else {
  1101. retMap.put("taskid", taskid);
  1102. retMap.put("text", "工作已完成(描述:无,图片:无)");
  1103. retMap.put("pictures", picURL);
  1104. retMap.put("video", null);
  1105. json.setData(retMap);
  1106. }
  1107. return json;
  1108. }
  1109. private String setTaskVideoURL(TaskResultEntity taskResult) {
  1110. if(StringUtil.isEmpty(taskResult.getVideo())) return null;
  1111. OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  1112. Date expiration = new Date(new Date().getTime() + 3600 * 1000);
  1113. String url = ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getVideo(), expiration).toString();
  1114. ossClient.shutdown();
  1115. return url;
  1116. }
  1117. private List<String> getTaskPictures(TaskResultEntity taskResult) {
  1118. List<String> picURL = new ArrayList<String>();
  1119. if (taskResult.getPicture1() != null && taskResult.getPicture1().trim().length() > 0) {
  1120. picURL.add(taskResult.getPicture1());
  1121. }
  1122. if (taskResult.getPicture2() != null && taskResult.getPicture2().trim().length() > 0) {
  1123. picURL.add(taskResult.getPicture2());
  1124. }
  1125. if (taskResult.getPicture3() != null && taskResult.getPicture3().trim().length() > 0) {
  1126. picURL.add(taskResult.getPicture3());
  1127. }
  1128. if (taskResult.getPicture4() != null && taskResult.getPicture4().trim().length() > 0) {
  1129. picURL.add(taskResult.getPicture4());
  1130. }
  1131. if (taskResult.getPicture5() != null && taskResult.getPicture5().trim().length() > 0) {
  1132. picURL.add(taskResult.getPicture5());
  1133. }
  1134. if (taskResult.getPicture6() != null && taskResult.getPicture6().trim().length() > 0) {
  1135. picURL.add(taskResult.getPicture6());
  1136. }
  1137. if (taskResult.getPicture7() != null && taskResult.getPicture7().trim().length() > 0) {
  1138. picURL.add(taskResult.getPicture7());
  1139. }
  1140. if (taskResult.getPicture8() != null && taskResult.getPicture8().trim().length() > 0) {
  1141. picURL.add(taskResult.getPicture8());
  1142. }
  1143. if (taskResult.getPicture9() != null && taskResult.getPicture9().trim().length() > 0) {
  1144. picURL.add(taskResult.getPicture9());
  1145. }
  1146. if (taskResult.getPicture10() != null && taskResult.getPicture10().trim().length() > 0) {
  1147. picURL.add(taskResult.getPicture10());
  1148. }
  1149. return picURL;
  1150. }
  1151. private List<String> setTaskPicURL(TaskResultEntity taskResult) {
  1152. List<String> picURL = new ArrayList<String>();
  1153. // 创建OSSClient实例
  1154. OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  1155. // 设置URL过期时间为1小时
  1156. Date expiration = new Date(new Date().getTime() + 3600 * 1000);
  1157. if (taskResult.getPicture1() != null && taskResult.getPicture1().trim().length() > 0) {
  1158. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture1(), expiration).toString());
  1159. }
  1160. if (taskResult.getPicture2() != null && taskResult.getPicture2().trim().length() > 0) {
  1161. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture2(), expiration).toString());
  1162. }
  1163. if (taskResult.getPicture3() != null && taskResult.getPicture3().trim().length() > 0) {
  1164. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture3(), expiration).toString());
  1165. }
  1166. if (taskResult.getPicture4() != null && taskResult.getPicture4().trim().length() > 0) {
  1167. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture4(), expiration).toString());
  1168. }
  1169. if (taskResult.getPicture5() != null && taskResult.getPicture5().trim().length() > 0) {
  1170. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture5(), expiration).toString());
  1171. }
  1172. if (taskResult.getPicture6() != null && taskResult.getPicture6().trim().length() > 0) {
  1173. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture6(), expiration).toString());
  1174. }
  1175. if (taskResult.getPicture7() != null && taskResult.getPicture7().trim().length() > 0) {
  1176. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture7(), expiration).toString());
  1177. }
  1178. if (taskResult.getPicture8() != null && taskResult.getPicture8().trim().length() > 0) {
  1179. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture8(), expiration).toString());
  1180. }
  1181. if (taskResult.getPicture9() != null && taskResult.getPicture9().trim().length() > 0) {
  1182. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture9(), expiration).toString());
  1183. }
  1184. if (taskResult.getPicture10() != null && taskResult.getPicture10().trim().length() > 0) {
  1185. picURL.add(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, taskResult.getPicture10(), expiration).toString());
  1186. }
  1187. // 关闭client
  1188. ossClient.shutdown();
  1189. return picURL;
  1190. }
  1191. /**
  1192. * 查询项目工作
  1193. * | projectid | true | string | 项目id |
  1194. * | openid | true | string | 用户openid |
  1195. * | qrydate | true | string | 查询条件:日期,dateformater: yyyy-MM-dd hh:mm:ss |
  1196. * | taskid | false | string | 工作id。进入任务详情时使用此参数,其他场景可空 |
  1197. */
  1198. @RequestMapping(value = "task/qryProjectTasks")
  1199. @ResponseBody
  1200. public WXAjaxJson qryProjectTasks(HttpServletRequest request) {
  1201. WXAjaxJson json = new WXAjaxJson();
  1202. String taskid = oConvertUtils.getString(request.getParameter("taskid"));
  1203. String qrydate = oConvertUtils.getString(request.getParameter("qrydate"));
  1204. //默认为今天
  1205. qrydate = taskid.length() > 0 ? null : (qrydate.length() == 0 ? DateUtils.formatDate(new Date(), "yyyy-MM-dd") : qrydate);
  1206. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1207. String status = oConvertUtils.getString(request.getParameter("status"));
  1208. List<ProjecttaskEntity> data = null;
  1209. switch (status) {
  1210. case ""://全部
  1211. data = wxdao.getTaskListAll(null, qrydate, projectid, taskid);
  1212. break;
  1213. case "0"://未完成
  1214. data = wxdao.getTaskListNotDone(null, qrydate, projectid, taskid, null);
  1215. break;
  1216. case "20"://已完成
  1217. data = wxdao.getTaskListDone(null, qrydate, projectid, taskid);
  1218. break;
  1219. case "30"://逾期
  1220. data = wxdao.getTaskListNotDone(null, qrydate, projectid, taskid, "1");
  1221. break;
  1222. }
  1223. Map<String, Object> retdata = new HashMap<String, Object>();
  1224. retdata.put("list", data);
  1225. retdata.put("hasmore", 0);
  1226. json.setData(retdata);
  1227. return json;
  1228. }
  1229. /**
  1230. * 查询项目本日工作完成率
  1231. * | projectid | true | string | 项目id |
  1232. */
  1233. @RequestMapping(value = "task/qryTodayWorkStati")
  1234. @ResponseBody
  1235. public WXAjaxJson qryTodayWorkStati(HttpServletRequest request) {
  1236. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1237. WXAjaxJson json = new WXAjaxJson();
  1238. List<Map<String, Object>> list = null;
  1239. try {
  1240. SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
  1241. String date = dateformat.format(new Date());
  1242. list = wxdao.getTodayWorkStati(projectid, date);
  1243. } catch (Exception e) {
  1244. logger.error(e.getMessage());
  1245. }
  1246. // if(list == null || list.isEmpty()) {
  1247. // return null;
  1248. // }
  1249. // Option option = new Option();
  1250. //
  1251. // List<Object> seriesdata = new ArrayList<Object>();
  1252. // List<Axis> xaxisList = new ArrayList<Axis>();
  1253. // List<Object> xaxisdata = new ArrayList<Object>();
  1254. //
  1255. // CategoryAxis axis = new CategoryAxis();
  1256. //
  1257. // xaxisList.add(axis);
  1258. // for(Map<String,Object> oneRec : list) {
  1259. // seriesdata.add(oneRec.get("rate"));
  1260. // xaxisdata.add(oneRec.get("name"));
  1261. // }
  1262. // axis.setData(xaxisdata);
  1263. // Bar bar = new Bar();
  1264. // bar.setData(seriesdata);
  1265. // option.xAxis(xaxisList);
  1266. // option.series(bar);
  1267. json.setData(list);
  1268. return json;
  1269. }
  1270. /**
  1271. * 查询项目七日内工作完成率
  1272. * | projectid | true | string | 项目id |
  1273. */
  1274. @RequestMapping(value = "task/qryWeekWorkStati")
  1275. @ResponseBody
  1276. public WXAjaxJson qryWeekWorkStati(HttpServletRequest request) {
  1277. WXAjaxJson json = new WXAjaxJson();
  1278. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1279. SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
  1280. String today = dateformat.format(new Date());
  1281. String lastWeekDay = XcglDateUtils.addDateDay(today, -7, dateformat);
  1282. List<Map<String, Object>> list = null;
  1283. try {
  1284. list = wxdao.getWeekWorkStati(projectid, today, lastWeekDay);
  1285. } catch (Exception e) {
  1286. logger.error(e.getMessage());
  1287. }
  1288. // if(list == null || list.isEmpty()) {
  1289. // return null;
  1290. // }
  1291. // Option option = new Option();
  1292. //
  1293. // List<Object> seriesdata = new ArrayList<Object>();
  1294. // List<Axis> xaxisList = new ArrayList<Axis>();
  1295. // List<Object> xaxisdata = new ArrayList<Object>();
  1296. //
  1297. // CategoryAxis axis = new CategoryAxis();
  1298. //
  1299. // xaxisList.add(axis);
  1300. // for(Map<String,Object> oneRec : list) {
  1301. // if(oneRec.get("date").toString().length() == 10) {
  1302. // seriesdata.add(oneRec.get("rate"));
  1303. // xaxisdata.add(oneRec.get("date").toString().substring(5));
  1304. // }
  1305. // }
  1306. // axis.setData(xaxisdata);
  1307. // Bar bar = new Bar();
  1308. // bar.setData(seriesdata);
  1309. // option.xAxis(xaxisList);
  1310. // option.series(bar);
  1311. json.setData(list);
  1312. return json;
  1313. }
  1314. /**
  1315. * 查询项目设备状态统计
  1316. * | projectid | true | string | 项目id |
  1317. */
  1318. @RequestMapping(value = "device/qryDeviceStatusSumData")
  1319. @ResponseBody
  1320. public WXAjaxJson qryDeviceStatusSumData(HttpServletRequest request) {
  1321. WXAjaxJson json = new WXAjaxJson();
  1322. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1323. if (!StringUtils.isNotBlank(projectid)) {
  1324. return json;
  1325. }
  1326. SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
  1327. String today = dateformat.format(new Date());
  1328. List<Map<String, Object>> list = null;
  1329. try {
  1330. list = wxdao.getDeviceStatusSumData(projectid, today);
  1331. } catch (Exception e) {
  1332. logger.error(e.getMessage());
  1333. }
  1334. json.setData(list);
  1335. return json;
  1336. }
  1337. /**
  1338. * 查询项目设备监测数据
  1339. * | projectid | true | string | 项目id |
  1340. * | openid | true | string | 用户openid |
  1341. */
  1342. @RequestMapping(value = "device/qryProjectDevicesData")
  1343. @ResponseBody
  1344. public WXAjaxJson qryProjectDevicesData(HttpServletRequest request) {
  1345. WXAjaxJson json = new WXAjaxJson();
  1346. String qrydate = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
  1347. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1348. List<SensorLiveDto> data = wxdao.getSensorLiveData(qrydate, projectid);
  1349. json.setData(data);
  1350. return json;
  1351. }
  1352. /**
  1353. * 查询项目设备本日能耗
  1354. */
  1355. @RequestMapping(value = "device/getNenghao")
  1356. @ResponseBody
  1357. public WXAjaxJson getNenghao(HttpServletRequest request) {
  1358. WXAjaxJson json = new WXAjaxJson();
  1359. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1360. Map map = dvservice.getNenghaoSumDataByProject(false, projectid);
  1361. json.setData(map);
  1362. return json;
  1363. }
  1364. /**
  1365. * 查询项目人员信息
  1366. * | projectid | true | string | 项目id |
  1367. * | openid | true | string | 用户openid |
  1368. */
  1369. @RequestMapping(value = "employee/qryProjectEmployee")
  1370. @ResponseBody
  1371. public WXAjaxJson qryProjectEmployee(HttpServletRequest request) {
  1372. WXAjaxJson json = new WXAjaxJson();
  1373. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1374. if (!StringUtils.isNotEmpty(projectid)) {
  1375. json.setCode(XcglConstant.RETCODE_SERVICE_ERROR);
  1376. json.setMsg(XcglConstant.RETMSG_SERVICEERROR);
  1377. return json;
  1378. }
  1379. List<UserDto> data = wxdao.getProjectUsers(projectid);
  1380. // 设置组织机构
  1381. for (UserDto user : data) {
  1382. user.setProjectid(null);
  1383. user.setProjectname(null);
  1384. user.setProjectTaskCount(null);
  1385. user.setJgprojectids(null);
  1386. user.setJgprojectnames(null);
  1387. /*
  1388. String orgId = user.getProjectid();
  1389. String[] project = getParentProject(orgId);
  1390. user.setProjectid(project[0]);
  1391. user.setProjectname(project[1]);
  1392. if(StringUtils.isNotEmpty(user.getJgprojectids())) {
  1393. ArrayList<String> ids = new ArrayList<String>();
  1394. ArrayList<String> names = new ArrayList<String>();
  1395. String[] jzproject = user.getJgprojectids().split(",");
  1396. for(String pid : jzproject) {
  1397. String[] jzpro = getParentProject(pid);
  1398. ids.add(jzpro[0]);
  1399. names.add(jzpro[1]);
  1400. }
  1401. user.setJgprojectids(StringUtils.join(ids,","));
  1402. user.setJgprojectnames(StringUtils.join(names,","));
  1403. }
  1404. */
  1405. }
  1406. json.setData(data);
  1407. return json;
  1408. }
  1409. /**
  1410. * 查询员工附件信息
  1411. * | openid | true | String | openid |
  1412. * | userid | true | String | 员工id |
  1413. */
  1414. @RequestMapping(value = "employee/qryEmployeeAttc")
  1415. @ResponseBody
  1416. public WXAjaxJson qryEmployeeAttc(HttpServletRequest request) {
  1417. WXAjaxJson json = new WXAjaxJson();
  1418. String openid = oConvertUtils.getString(request.getParameter("openid"));
  1419. String userid = oConvertUtils.getString(request.getParameter("userid"));
  1420. List<UserAccessoryDto> dtolist = wxdao.getUserAccessory(userid);
  1421. if (dtolist.size() == 0) {
  1422. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  1423. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  1424. return json;
  1425. }
  1426. json.setData(setURL(dtolist.get(0)));
  1427. return json;
  1428. }
  1429. private UserAccessoryDto setURL(UserAccessoryDto userAcc) {
  1430. // 创建OSSClient实例
  1431. OSSClient ossClient = new OSSClient(XcglConstant.ENDPOINT_INTERNET, CustomerConstant.ACCESSKEY_ID, CustomerConstant.ACCESSKEY_SECRET);
  1432. // 设置URL过期时间为1小时
  1433. Date expiration = new Date(new Date().getTime() + 3600 * 1000);
  1434. if (userAcc.getPicture0id() != null && userAcc.getPicture0id().trim().length() > 0) {
  1435. userAcc.setPicture0id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture0id(), expiration).toString());
  1436. }
  1437. if (userAcc.getPicture1id() != null && userAcc.getPicture1id().trim().length() > 0) {
  1438. userAcc.setPicture1id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture1id(), expiration).toString());
  1439. }
  1440. if (userAcc.getPicture2id() != null && userAcc.getPicture2id().trim().length() > 0) {
  1441. userAcc.setPicture2id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture2id(), expiration).toString());
  1442. }
  1443. if (userAcc.getPicture3id() != null && userAcc.getPicture3id().trim().length() > 0) {
  1444. userAcc.setPicture3id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture3id(), expiration).toString());
  1445. }
  1446. if (userAcc.getPicture4id() != null && userAcc.getPicture4id().trim().length() > 0) {
  1447. userAcc.setPicture4id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture5id(), expiration).toString());
  1448. }
  1449. if (userAcc.getPicture5id() != null && userAcc.getPicture5id().trim().length() > 0) {
  1450. userAcc.setPicture5id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture5id(), expiration).toString());
  1451. }
  1452. if (userAcc.getPicture6id() != null && userAcc.getPicture6id().trim().length() > 0) {
  1453. userAcc.setPicture6id(ossClient.generatePresignedUrl(CustomerConstant.BUCKETNAME, userAcc.getPicture6id(), expiration).toString());
  1454. }
  1455. // 关闭client
  1456. ossClient.shutdown();
  1457. return userAcc;
  1458. }
  1459. /**
  1460. * 发送验证码
  1461. * | phoneno | true | String | 手机号
  1462. * | openid | true | String | openid
  1463. *
  1464. * @throws ClientException
  1465. * @throws ServerException
  1466. */
  1467. @RequestMapping(value = "employee/sendSms")
  1468. @ResponseBody
  1469. public WXAjaxJson sendSms(HttpServletRequest req) throws ServerException, ClientException {
  1470. WXAjaxJson json = new WXAjaxJson();
  1471. String phoneno = req.getParameter("phoneno");
  1472. if (!StringUtils.isNotBlank(phoneno)) {
  1473. json.setCode(XcglConstant.RETCODE_UNKNOW_USER);
  1474. json.setMsg(XcglConstant.RETMSG_UNKNOW_USER);
  1475. return json;
  1476. }
  1477. //设置超时时间-可自行调整
  1478. System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
  1479. System.setProperty("sun.net.client.defaultReadTimeout", "10000");
  1480. //初始化ascClient需要的几个参数
  1481. final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
  1482. final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
  1483. //替换成你的AK
  1484. final String accessKeyId = "LTAImsMOGNQTqWvX";//你的accessKeyId,参考本文档步骤2
  1485. final String accessKeySecret = "zdf5cux8RzTl531tQQ1rIlESTBBiBe";//你的accessKeySecret,参考本文档步骤2
  1486. //初始化ascClient,暂时不支持多region(请勿修改)
  1487. IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
  1488. accessKeySecret);
  1489. DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
  1490. IAcsClient acsClient = new DefaultAcsClient(profile);
  1491. //组装请求对象
  1492. SendSmsRequest request = new SendSmsRequest();
  1493. //使用post提交
  1494. request.setMethod(MethodType.POST);
  1495. //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
  1496. request.setPhoneNumbers(phoneno);
  1497. //必填:短信签名-可在短信控制台中找到
  1498. request.setSignName("美都环卫物业");
  1499. //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
  1500. request.setTemplateCode("SMS_144450234");
  1501. //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
  1502. //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
  1503. String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
  1504. request.setTemplateParam("{\"code\":\"" + code + "\"}");
  1505. //可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
  1506. //request.setSmsUpExtendCode("90997");
  1507. //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
  1508. // request.setOutId("yourOutId");
  1509. //请求失败这里会抛ClientException异常
  1510. SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
  1511. if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
  1512. //请求成功
  1513. String logSql = "INSERT INTO p_usersms(`id`, `phoneno`, `sendtime`, `validtime`, `code`) "
  1514. + "VALUES (?, ?, ?, ?, ?)";
  1515. systemService.executeSql(logSql, com.xcgl.utils.UUID.randomUUID().toString(), phoneno, DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
  1516. XcglDateUtils.addDateMinut(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), 5), code);
  1517. }
  1518. json.setData(code);
  1519. return json;
  1520. }
  1521. @RequestMapping(value = "task/qryTaskStati")
  1522. @ResponseBody
  1523. public WXAjaxJson qryTaskStati(HttpServletRequest request) throws ServerException, ClientException {
  1524. WXAjaxJson json = new WXAjaxJson();
  1525. Map<String, String> retMap = new HashMap<String, String>();
  1526. retMap.put("today", "0/0");
  1527. retMap.put("week", "0/0");
  1528. retMap.put("month", "0/0");
  1529. String openid = oConvertUtils.getString(request.getParameter("openid"));
  1530. String projectid = oConvertUtils.getString(request.getParameter("projectid"));
  1531. String weekStart = DateUtils.date_sdf.format(XcglDateUtils.getTimesWeekmorning());
  1532. String weekend = DateUtils.date_sdf.format(XcglDateUtils.getTimesWeeknight());
  1533. String monthStart = DateUtils.date_sdf.format(XcglDateUtils.getTimesMonthmorning());
  1534. String monthend = DateUtils.date_sdf.format(XcglDateUtils.getTimesMonthnight());
  1535. String today = DateUtils.date_sdf.format(new Date());
  1536. List<Map<String, String>> retList = wxdao.getTaskStati(openid, projectid, today, weekStart, weekend, monthStart, monthend);
  1537. if (retList.size() > 0) {
  1538. retMap = retList.get(0);
  1539. }
  1540. json.setData(retMap);
  1541. return json;
  1542. }
  1543. // public void weixinLogin(HttpServletRequest request,HttpServletResponse response) throws Exception {
  1544. // Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
  1545. // String[] codes = params.get("code");//拿到的code的值
  1546. // String code = codes[0];//code
  1547. // String APPID = "";
  1548. // String AppSecret = "";
  1549. // /*
  1550. // * 拼写微信api请求地址并通过微信的appId和微信公众号的AppSecret
  1551. // * 以及授权回调的code获取用户的openid和access_token
  1552. // */
  1553. // String requestUrl = " https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID"
  1554. // + "&redirect_uri=APPSECRET&response_type=code&scope=snsapi_userinfo&state=STATE"
  1555. // .replace("APPID",APPID).replace("APPSECRET", AppSecret).replace("CODE", code);
  1556. // String requestResult = doGet(requestUrl);
  1557. // com.alibaba.fastjson.JSONObject jsons = com.alibaba.fastjson.JSON.parseObject(requestResult);//结果转换成JSON对象
  1558. // if(jsons == null || jsons.getInteger("errcode") != null || jsons.getString("openid") == null) {
  1559. // throw new NoResultException();//自定义异常类
  1560. // }
  1561. // String openid = jsons.getString("openid");
  1562. // //注意:公众号通用的access_token和登录用户的access_token是有区别的
  1563. // //微信公众号的通用access_token每天只能取2000次 每次token有效期是7200S
  1564. // requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"
  1565. // + "?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code"
  1566. // .replace("APPID", APPID).replace("APPSECRET", AppSecret);
  1567. // requestResult = doGet(requestUrl);
  1568. // JSONObject weixinToken = JSON.parseObject(requestResult);
  1569. // if(weixinToken == null){
  1570. // throw new NoResultException();//自定义异常类,获取我们公众号token失败
  1571. // }
  1572. // String wxgzhToken = weixinToken.getString("access_token");
  1573. // requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN"
  1574. // + "&openid=OPENID&lang=zh_CN".replace("ACCESS_TOKEN", wxgzhToken).replace("OPENID", openid);
  1575. // requestResult = doGet(requestUrl);
  1576. // JSONObject user = JSON.parseObject(requestResult);
  1577. // if(user == null || user.getInteger("errcode") != null ) {
  1578. // throw new NoResultException();//自定义异常类
  1579. // }
  1580. // //把这些信息存在我们的数据库中然后跳转到我们前台页面
  1581. // }
  1582. // /**
  1583. // * get方式
  1584. // * @param url
  1585. // * @author blog.yoodb.com
  1586. // * @return
  1587. // */
  1588. // public static String doGet(String url) {
  1589. // String responseMsg = "";
  1590. // HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
  1591. // GetMethod getMethod = new GetMethod(url);
  1592. // getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER
  1593. // ,new DefaultHttpMethodRetryHandler());
  1594. // try {
  1595. // httpClient.executeMethod(getMethod);
  1596. // ByteArrayOutputStream out = new ByteArrayOutputStream();
  1597. // InputStream in = getMethod.getResponseBodyAsStream();
  1598. // int len = 0;
  1599. // byte[] buf = new byte[1024];
  1600. // while((len=in.read(buf))!=-1){
  1601. // out.write(buf, 0, len);
  1602. // }
  1603. // responseMsg = out.toString("UTF-8");
  1604. // } catch (org.apache.commons.httpclient.HttpException e) {
  1605. // e.printStackTrace();
  1606. // } catch (IOException e) {
  1607. // e.printStackTrace();
  1608. // } finally {
  1609. // //释放连接
  1610. // getMethod.releaseConnection();
  1611. // }
  1612. // return responseMsg;
  1613. // }
  1614. /**
  1615. * 按照微信消息模板keyword要求,组织消息,然后调用美都环卫微信平台服务发送消息
  1616. */
  1617. @RequestMapping(value = "test/msg")
  1618. @ResponseBody
  1619. public WXAjaxJson testMsg(HttpServletRequest request) {
  1620. WXAjaxJson json = new WXAjaxJson();
  1621. WXServiceI service = ApplicationContextUtil.getContext().getBean(WXServiceI.class);
  1622. try {
  1623. service.sendMsgToWXInMorning();
  1624. } catch (Exception e) {
  1625. json.setMsg(e.getMessage());
  1626. e.printStackTrace();
  1627. }
  1628. return json;
  1629. }
  1630. @RequestMapping(value = "interaction/textaction")
  1631. @ResponseBody
  1632. public WXAjaxJson textAction(HttpServletRequest request) throws ServerException, ClientException {
  1633. WXAjaxJson json = new WXAjaxJson();
  1634. String openid = oConvertUtils.getString(request.getParameter("openid"));
  1635. String text = "";
  1636. try {
  1637. text = new String(request.getParameter("text").getBytes("iso-8859-1"), "utf-8");
  1638. } catch (UnsupportedEncodingException e) {
  1639. logger.error(e);
  1640. e.printStackTrace();
  1641. }
  1642. //查询是否为总经理微信
  1643. List<Map<String, Object>> ret = systemService.findForJdbc("select * from t_s_user where openid =? and usernum = '0001'", openid);
  1644. if (ret == null || ret.size() == 0)
  1645. json.setData("<a href=\"http://hgl.shenqin.work/hgl\" target=\"_blank\">美都环卫物业</a>:勤思、勤学、勤劳、勤勉");
  1646. if (text.indexOf("下周") > -1)
  1647. json.setData("<a href=\"http://hgl.shenqin.work/hgl\" target=\"_blank\">点击</a>查看下周工作计划\r\n \r\n★温馨提示:智能工作助理正在设计、开发中,敬请期待后续功能");
  1648. else
  1649. json.setData("美都环卫物业:勤思、勤学、勤劳、勤勉");
  1650. return json;
  1651. }
  1652. /**
  1653. * 新版首页数据 ,以后可能会拆分
  1654. * 2019年12月7日
  1655. *
  1656. * @param request
  1657. * @return
  1658. */
  1659. @RequestMapping(value = "/indexData")
  1660. @ResponseBody
  1661. public WXAjaxJson indexData(HttpServletRequest request) {
  1662. WXAjaxJson json = new WXAjaxJson();
  1663. String openid = oConvertUtils.getString(request.getParameter("openid"));
  1664. if (StringUtils.isBlank(openid)) {
  1665. return json;
  1666. }
  1667. // 待我审批数量
  1668. List<TSUser> userList = systemService.findByProperty(TSUser.class, "openid", openid);
  1669. if (userList.size() == 0) {
  1670. return json;
  1671. }
  1672. TSUser user = userList.get(0);
  1673. String userName = user.getUserName();
  1674. Map<String, Object> data = new HashMap<String, Object>();
  1675. Long activitiToDoSize = this.activitiService.countPriTodaoTask(userName, request);
  1676. data.put("activitiToDoSize", activitiToDoSize);
  1677. //我发起的未审批完成的数量
  1678. Long activitiStartSize = historyService.createHistoricProcessInstanceQuery().startedBy(userName).unfinished().count();
  1679. data.put("activitiStartSize", activitiStartSize);
  1680. //部门签报未完成
  1681. List<Map<String, Object>> activitiStatsOrgUnFinishedData = rptDao.activitiStatsOrgUnFinishedData(5);
  1682. data.put("activitiStatsOrgUnFinishedData", activitiStatsOrgUnFinishedData);
  1683. //人员签报未完成
  1684. List<?> activitiStatsUserUnFinishedData = rptDao.activitiStatsUserUnFinishedData(5);
  1685. data.put("activitiStatsUserUnFinishedData", activitiStatsUserUnFinishedData);
  1686. //部门工作
  1687. List<?> taskStatsOrgUnFinishedData = rptDao.taskStatsOrgUnFinishedData(5);
  1688. data.put("taskStatsOrgUnFinishedData", taskStatsOrgUnFinishedData);
  1689. //人员工作未完成
  1690. List<?> taskStatsOrgUserUnFinishedData = rptDao.taskStatsOrgUserUnFinishedData(5);
  1691. data.put("taskStatsOrgUserUnFinishedData", taskStatsOrgUserUnFinishedData);
  1692. json.setData(data);
  1693. return json;
  1694. }
  1695. /**
  1696. * 上传附件
  1697. */
  1698. @RequestMapping(value = "user/uploadPersonalImage")
  1699. @ResponseBody
  1700. public WXAjaxJson uploadPersonalImage(HttpServletRequest request) {
  1701. WXAjaxJson json = new WXAjaxJson();
  1702. String userid = oConvertUtils.getString(request.getParameter("userid"));
  1703. String upFlag = oConvertUtils.getString(request.getParameter("isup"));
  1704. String delFlag = oConvertUtils.getString(request.getParameter("isdel"));
  1705. String mediaid = oConvertUtils.getString(request.getParameter("pictureid"));
  1706. // String token = oConvertUtils.getString(request.getParameter("accessToken"));
  1707. String token = wxTokenService.getSkey();
  1708. try {
  1709. //如果是上传操作
  1710. if ("1".equals(upFlag)) {
  1711. HashMap<String, String> mediaurl = new HashMap<String, String>();
  1712. String busiId = com.xcgl.utils.UUID.randomUUID().toString();
  1713. String fileName = null;
  1714. //附件类型名,例如:*户口本本人页
  1715. String accessoryName = null;
  1716. //附件类型枚举 例如:hukoubenbenrenye4
  1717. String accessoryType = null;
  1718. // String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
  1719. String now = DateUtils.yyyymmddhhmmss.format(new Date());
  1720. String bizType = "personalImage/" + userid;//request.getParameter("bizType");//上传业务名称
  1721. if (oConvertUtils.getString(request.getParameter("pictureid")).length() > 0) {
  1722. accessoryName = "wxupload-" + now;
  1723. accessoryType = "personalImage";
  1724. }
  1725. String extName = "jpg";//FileUtils.getExtend(fileName);
  1726. fileName = accessoryName + "." + extName;
  1727. List<String> keyAndUrl = getWXfileToOSS(extName, bizType, token, mediaid);
  1728. // List<String> keyAndUrl = getWXfileToOSSTest(extName, "test", token, mediaid, request);
  1729. if (keyAndUrl.size() == 2) {
  1730. mediaurl.put("url", keyAndUrl.get(1));
  1731. String busiTable = "t_b_personalImage";// request.getParameter("busiTable");
  1732. TSysFileEntity tSysFileEntity = new TSysFileEntity();
  1733. tSysFileEntity.setBusiId(busiId);// 业务id
  1734. tSysFileEntity.setFileUrl(keyAndUrl.get(0));// 文件访问路径
  1735. tSysFileEntity.setFileName(fileName);// 文件名称
  1736. tSysFileEntity.setTagetType(bizType);// 文件类型
  1737. tSysFileEntity.setBusiTable(oConvertUtils.getString(busiTable));
  1738. tSysFileService.save(tSysFileEntity);
  1739. // 保存业务表
  1740. String accessorySql = "INSERT INTO t_b_personalImage(id, accessory_name, userid, isfixed, gatet_type, delete_flag,createtime,accUrl,ossKey) "
  1741. + "VALUES (?, ?, ?, '1', ?, '0',?,?,?)";
  1742. systemService.executeSql(accessorySql, busiId, accessoryName, userid, accessoryType, now, "", keyAndUrl.get(0));
  1743. // }
  1744. json.setData(mediaurl);
  1745. }
  1746. } else if ("1".equals(delFlag)) {//如果是删除操作
  1747. // TODO 删除业务表数据,再删除oss,t_sys_file数据
  1748. Map<String, String[]> params = request.getParameterMap();
  1749. String ossKey = deleteAccSysfile(params, userid);
  1750. if (!deleteOssfile(ossKey)) {
  1751. String msg = MutiLangUtil.getMutiLangInstance().getLang("file.warn.filelost");
  1752. // 不存在前台也给他删除
  1753. json.setMsg(msg);
  1754. }
  1755. } else {
  1756. throw new BusinessException("没有传参指定上传还是删除操作!");
  1757. }
  1758. } catch (IOException e) {
  1759. json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
  1760. json.setMsg(e.getMessage());
  1761. logger.error(e.getMessage());
  1762. } catch (BusinessException b) {
  1763. json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
  1764. json.setMsg(b.getMessage());
  1765. logger.error(b.getMessage());
  1766. } catch (Exception e) {
  1767. json.setCode(XcglConstant.RETCODE_UPLOAD_FAILT);
  1768. json.setMsg(e.getMessage());
  1769. logger.error(e.getMessage());
  1770. }
  1771. return json;
  1772. }
  1773. /**
  1774. * 校验用户授权
  1775. *
  1776. * @param forceLogin 是否强制用户登录
  1777. * @return
  1778. */
  1779. protected TSUser verifyUser(boolean forceLogin) {
  1780. try {
  1781. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
  1782. .getRequestAttributes())
  1783. .getRequest();
  1784. String openid = oConvertUtils.getString(request.getParameter("openid"));
  1785. if (StringUtils.isBlank(openid)) {
  1786. throw new ApiException(300, "openid required");
  1787. }
  1788. List<TSUser> userList = systemService.findByProperty(TSUser.class, "openid", openid);
  1789. if (userList.size() == 0) {
  1790. throw new ApiException(301, "用户未找到");
  1791. }
  1792. TSUser user = userList.get(0);
  1793. return user;
  1794. } catch (ApiException e) {
  1795. if (forceLogin) throw e;
  1796. }
  1797. return null;
  1798. }
  1799. /**
  1800. * 待我审批
  1801. *
  1802. * @param request
  1803. * @return
  1804. */
  1805. @RequestMapping(value = "/workflow/taskList")
  1806. @ResponseBody
  1807. public WXAjaxJson workflow_taskList(HttpServletRequest request) {
  1808. TSUser user = verifyUser(true);
  1809. int rows = Integer.parseInt(request.getParameter("rows"));
  1810. WXAjaxJson json = new WXAjaxJson();
  1811. String userName = user.getUserName();
  1812. Map<String, Object> data = new HashMap<String, Object>();
  1813. List taskList = this.findBaseTodoTasks(true,user.getUserName(), request);
  1814. String fields = "id,bpmBizTitle,Process_processDefinition_id,Process_processDefinition_name," +
  1815. "Process_task_processInstanceId,userRealName,assigneeName," +
  1816. "Process_task_createTime,Process_task_dueTime,TSPrjstatus_description," +
  1817. "Process_task_name,Process_task_id,Process_task_taskDefinitionKey";
  1818. List<Map> datalist = WXUtils.copyRecordListFields(taskList, fields);
  1819. data.put("list", datalist);
  1820. data.put("hasmore", datalist.size() >= rows ? 1 : 0);
  1821. json.setData(data);
  1822. return json;
  1823. }
  1824. /*
  1825. * 从activitiService中移植过来的,为了改变部分查询过程
  1826. * 1、与activitiService比,改变了排序为正序,即最先产生的任务排在上面
  1827. * */
  1828. private List findBaseTodoTasks(boolean isPri, String id, HttpServletRequest request) {
  1829. List results = new ArrayList();
  1830. List<Task> tasks = new ArrayList();
  1831. Integer page = Integer.parseInt(request.getParameter("page"));
  1832. Integer rows = Integer.parseInt(request.getParameter("rows"));
  1833. Integer start = (page - 1) * rows;
  1834. Integer end = page * rows - 1;
  1835. String typeid;
  1836. String inUserNameStr;
  1837. try {
  1838. List<Task> tempList = new ArrayList();
  1839. if (!isPri) {
  1840. } else {
  1841. String userName = request.getParameter("userName");
  1842. typeid = oConvertUtils.getString(request.getParameter("typeid"));
  1843. StringBuilder userNamesb = new StringBuilder("");
  1844. if (StringUtils.isNotEmpty(userName)) {
  1845. List<ProcessInstance> processInstanceList = this.runtimeService.createProcessInstanceQuery()
  1846. .variableValueEquals("applyUserId", userName).list();
  1847. if (processInstanceList != null && processInstanceList.size() > 0) {
  1848. for (int i = 0; i < processInstanceList.size(); ++i) {
  1849. if (i == 0) {
  1850. userNamesb.append("'"
  1851. + ((ProcessInstance) processInstanceList.get(i)).getProcessInstanceId() + "'");
  1852. } else {
  1853. userNamesb.append(",'"
  1854. + ((ProcessInstance) processInstanceList.get(i)).getProcessInstanceId() + "'");
  1855. }
  1856. }
  1857. }
  1858. }
  1859. inUserNameStr = userNamesb.toString();
  1860. String procDefId = request.getParameter("Process.processDefinition.id");
  1861. StringBuilder sb = new StringBuilder("");
  1862. sb.append("select * ").append("from (");
  1863. sb.append("(select distinct RES.* ");
  1864. sb.append(" from ACT_RU_TASK RES inner join ACT_RU_IDENTITYLINK I on I.TASK_ID_ = RES.ID_ ");
  1865. sb.append(" \tLEFT JOIN t_p_process tpp on tpp.processkey = LEFT(RES.PROC_DEF_ID_ ,20) ");
  1866. sb.append("WHERE RES.ASSIGNEE_ is null and I.TYPE_ = 'candidate' ");
  1867. if (oConvertUtils.isNotEmpty(typeid)) {
  1868. sb.append(" and tpp.typeid = #{typeid}");
  1869. }
  1870. sb.append(
  1871. "\tand ( I.USER_ID_ = #{userid} or I.GROUP_ID_ IN ( select g.GROUP_ID_ from ACT_ID_MEMBERSHIP g where g.USER_ID_ = #{userid} ) ");
  1872. sb.append(" ) ").append(" and RES.SUSPENSION_STATE_ = 1 ");
  1873. if (StringUtils.isNotEmpty(procDefId)) {
  1874. sb.append(" AND RES.PROC_DEF_ID_ LIKE #{procDefId} ");
  1875. }
  1876. if (StringUtils.isNotEmpty(userName)) {
  1877. if (StringUtils.isNotEmpty(inUserNameStr)) {
  1878. sb.append(" AND RES.PROC_INST_ID_ in (" + inUserNameStr + ") ");
  1879. } else {
  1880. sb.append(" AND RES.PROC_INST_ID_ in ('-1') ");
  1881. }
  1882. }
  1883. sb.append(") union ");
  1884. sb.append("(select distinct RES.* ");
  1885. sb.append(" from ACT_RU_TASK RES ");
  1886. sb.append("WHERE RES.ASSIGNEE_ = #{userid} ");
  1887. if (StringUtils.isNotEmpty(procDefId)) {
  1888. sb.append(" AND RES.PROC_DEF_ID_ LIKE #{procDefId} ");
  1889. }
  1890. if (StringUtils.isNotEmpty(userName)) {
  1891. if (StringUtils.isNotEmpty(inUserNameStr)) {
  1892. sb.append(" AND RES.PROC_INST_ID_ in (" + inUserNameStr + ") ");
  1893. } else {
  1894. sb.append(" AND RES.PROC_INST_ID_ in ('-1') ");
  1895. }
  1896. }
  1897. sb.append(" )) v ");
  1898. sb.append(" order by v.CREATE_TIME_ asc, v.PRIORITY_ desc ");
  1899. String dbType = DBTypeUtil.getDBType();
  1900. String sql = MiniDaoUtil.createPageSql(dbType, sb.toString(), page, rows);
  1901. NativeTaskQuery query = (NativeTaskQuery) ((NativeTaskQuery) this.taskService.createNativeTaskQuery()
  1902. .sql(sql)).parameter("userid", id);
  1903. if (StringUtils.isNotEmpty(typeid)) {
  1904. query.parameter("typeid", typeid);
  1905. }
  1906. if (StringUtils.isNotEmpty(procDefId)) {
  1907. query.parameter("procDefId", "%" + procDefId + "%");
  1908. }
  1909. List<Task> pretasks = query.list();
  1910. tempList.addAll(pretasks);
  1911. TaskQuery tq = (TaskQuery) ((TaskQuery) this.taskService.createTaskQuery()
  1912. .taskCandidateGroupIn(Arrays.asList(id.split(","))).orderByTaskCreateTime().desc())
  1913. .orderByTaskPriority().desc();
  1914. tq = this.installQueryParam(tq, request);
  1915. List<Task> unsignedTasks = tq.listPage(start, end);
  1916. tempList.addAll(unsignedTasks);
  1917. }
  1918. tasks.addAll(tempList);
  1919. } catch (Exception var32) {
  1920. var32.printStackTrace();
  1921. }
  1922. Iterator var35 = tasks.iterator();
  1923. while (var35.hasNext()) {
  1924. Task task = (Task) var35.next();
  1925. typeid = task.getProcessInstanceId();
  1926. ProcessInstance processInstance = (ProcessInstance) this.runtimeService.createProcessInstanceQuery()
  1927. .processInstanceId(typeid).singleResult();
  1928. inUserNameStr = this.getBusinessKeyByTask(task);
  1929. Class entityClass = MyClassLoader.getClassByScn("org.jeecgframework.workflow.pojo.base.TSBaseBusQuery");
  1930. Object entityObj = systemService.getEntity(entityClass, inUserNameStr);
  1931. Object obj = null;
  1932. try {
  1933. obj = entityClass.newInstance();
  1934. MyBeanUtils.copyBeanNotNull2Bean(entityObj, obj);
  1935. } catch (Exception var31) {
  1936. ;
  1937. }
  1938. if (obj != null) {
  1939. ReflectHelper reflectHelper = new ReflectHelper(obj);
  1940. org.jeecgframework.workflow.model.activiti.Process process = new org.jeecgframework.workflow.model.activiti.Process();
  1941. process.setTask(task);
  1942. process.setProcessInstance(processInstance);
  1943. process.setProcessDefinition(this.getProcessDefinition(processInstance.getProcessDefinitionId()));
  1944. reflectHelper.setMethodValue("Process", process);
  1945. String userid = (String) reflectHelper.getMethodValue("userid");
  1946. if (userid != null) {
  1947. TSBaseUser baseUser = (TSBaseUser) this.activitiCommonDao.findUniqueByProperty(TSBaseUser.class,
  1948. "userName", userid);
  1949. if (baseUser != null) {
  1950. reflectHelper.setMethodValue("userRealName", baseUser.getRealName());
  1951. }
  1952. }
  1953. String assigneeUserId = task.getAssignee();
  1954. if (assigneeUserId != null) {
  1955. TSBaseUser baseUser = (TSBaseUser) this.activitiCommonDao.findUniqueByProperty(TSBaseUser.class,
  1956. "userName", assigneeUserId);
  1957. if (baseUser != null) {
  1958. reflectHelper.setMethodValue("assigneeName", baseUser.getRealName());
  1959. }
  1960. }
  1961. String bpmBizTitle = (String) this.taskService.getVariable(task.getId(), WorkFlowGlobals.BPM_BIZ_TITLE);
  1962. if (bpmBizTitle != null) {
  1963. reflectHelper.setMethodValue("bpmBizTitle", bpmBizTitle);
  1964. }
  1965. String processnodecode = task.getTaskDefinitionKey();
  1966. String processDefinitionId = task.getProcessDefinitionId();
  1967. String sql = "select node.NODE_TIMEOUT from T_P_PROCESSNODE node where node.PROCESSID = (select tpp.ID from T_P_PROCESS tpp where tpp.PROCESSKEY = ";
  1968. sql = sql + "(select arp.KEY_ from ACT_RE_PROCDEF arp where arp.ID_ = ?)) and node.PROCESSNODECODE = ?";
  1969. List<Map<String, Object>> list = this.systemService.findForJdbc(sql,
  1970. new Object[] { processDefinitionId, processnodecode });
  1971. if (list != null && list.size() > 0) {
  1972. Map<String, Object> map = (Map) list.get(0);
  1973. Integer nodeTimeout = (Integer) map.get("NODE_TIMEOUT");
  1974. if (this.checkTimeOut(task.getCreateTime(), nodeTimeout)) {
  1975. reflectHelper.setMethodValue("timeoutRemaid", true);
  1976. } else {
  1977. reflectHelper.setMethodValue("timeoutRemaid", false);
  1978. }
  1979. }
  1980. if (oConvertUtils.getString(processDefinitionId).length() > 20) {
  1981. String processDefinkey = processDefinitionId.substring(0, 20);
  1982. TPProcess tpProcess = (TPProcess) systemService.findUniqueByProperty(TPProcess.class, "processkey",
  1983. processDefinkey);
  1984. if (tpProcess != null) {
  1985. reflectHelper.setMethodValue("typeid", tpProcess.getTypeid());
  1986. }
  1987. }
  1988. results.add(obj);
  1989. }
  1990. }
  1991. return results;
  1992. }
  1993. private TaskQuery installQueryParam(TaskQuery tq, HttpServletRequest request) {
  1994. String procDefId = request.getParameter("Process.processDefinition.id");
  1995. String procName = request.getParameter("Process.processDefinition.name");
  1996. if (StringUtils.isNotEmpty(procDefId)) {
  1997. tq = tq.processDefinitionId(procDefId);
  1998. }
  1999. if (StringUtils.isNotEmpty(procName)) {
  2000. tq = tq.processDefinitionName(procName);
  2001. }
  2002. return tq;
  2003. }
  2004. private boolean checkTimeOut(Date startTime, Integer timeout) {
  2005. boolean flag = false;
  2006. try {
  2007. if (timeout == null || startTime == null) {
  2008. return flag;
  2009. }
  2010. Calendar calSrc = Calendar.getInstance();
  2011. Calendar calDes = Calendar.getInstance();
  2012. calDes.setTime(startTime);
  2013. int diff = DateUtils.dateDiff('h', calSrc, calDes);
  2014. if (diff >= timeout) {
  2015. flag = true;
  2016. }
  2017. } catch (Exception var7) {
  2018. ;
  2019. }
  2020. return flag;
  2021. }
  2022. private ProcessDefinition getProcessDefinition(String processDefinitionId) {
  2023. return (ProcessDefinition) this.repositoryService.createProcessDefinitionQuery()
  2024. .processDefinitionId(processDefinitionId).singleResult();
  2025. }
  2026. private String getBusinessKeyByTask(Task task) {
  2027. String businessKey = "";
  2028. TaskEntity taskEntity = (TaskEntity) this.taskService.createTaskQuery().taskId(task.getId()).singleResult();
  2029. HistoricProcessInstance hiproins = (HistoricProcessInstance) this.historyService
  2030. .createHistoricProcessInstanceQuery().processInstanceId(taskEntity.getProcessInstanceId())
  2031. .singleResult();
  2032. if (hiproins != null) {
  2033. if (hiproins.getSuperProcessInstanceId() != null && hiproins.getBusinessKey() == null) {
  2034. hiproins = (HistoricProcessInstance) this.historyService.createHistoricProcessInstanceQuery()
  2035. .processInstanceId(hiproins.getSuperProcessInstanceId()).singleResult();
  2036. businessKey = hiproins.getBusinessKey();
  2037. } else {
  2038. businessKey = hiproins.getBusinessKey();
  2039. }
  2040. }
  2041. return businessKey;
  2042. }
  2043. //审批历史
  2044. @RequestMapping(value = "/workflow/myAuditHistoryList")
  2045. @ResponseBody
  2046. public WXAjaxJson workflow_myAuditHistoryList(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
  2047. TSUser user = verifyUser(true);
  2048. WXAjaxJson json = new WXAjaxJson();
  2049. int rows = Integer.parseInt(request.getParameter("rows"));
  2050. List taskList = findHistoryTasks(user.getUserName(), request);
  2051. Long taskSize = this.activitiService.countHistoryTasks(user.getUserName(), request);
  2052. Map<String, Object> data = new HashMap<>();
  2053. String fields = "id,bpmBizTitle,prodef_name,proInsl_procInstId,name,proInsl_startUserId,assignee,startTime,endTime,durationStr";
  2054. List<Map> datalist = WXUtils.copyRecordListFields(taskList, fields);
  2055. data.put("list", datalist);
  2056. data.put("hasmore", datalist.size() >= rows ? 1 : 0);
  2057. json.setData(data);
  2058. return json;
  2059. }
  2060. private List findHistoryTasks(String userName, HttpServletRequest request) {
  2061. Integer page = Integer.parseInt(request.getParameter("page"));
  2062. Integer rows = Integer.parseInt(request.getParameter("rows"));
  2063. Integer start = (page - 1) * rows;
  2064. Query query = systemService.getSession().createQuery(this
  2065. .installQueryParamH("from ActHiTaskinst o where o.duration>0 and o.assignee =? and o.deleteReason <>? ", request));
  2066. query.setFirstResult(start);
  2067. query.setMaxResults(rows);
  2068. query.setString(0, userName);
  2069. query.setString(1,"发起人流程追回");
  2070. this.installQueryParamHV(query, request, 1);
  2071. List result = query.list();
  2072. for (int i = 0; i < result.size(); ++i) {
  2073. ActHiTaskinst hi = (ActHiTaskinst) result.get(i);
  2074. hi.setBpmBizTitle(this.getHiVariable(hi.getProcInstId(), WorkFlowGlobals.BPM_BIZ_TITLE));
  2075. }
  2076. return result;
  2077. }
  2078. private String installQueryParamH(String sql, HttpServletRequest request) {
  2079. String procDefId = request.getParameter("procDefId");
  2080. String procName = request.getParameter("prodef.name");
  2081. StringBuilder s = new StringBuilder(sql);
  2082. if (StringUtils.isNotEmpty(procDefId)) {
  2083. s.append(" and o.procDefId =? ");
  2084. }
  2085. if (StringUtils.isNotEmpty(procName)) {
  2086. s.append(" and o.prodef.name like CONCAT('%',CONCAT(?,'%')) ");
  2087. }
  2088. s.append(" order by o.endTime desc ");
  2089. return s.toString();
  2090. }
  2091. private void installQueryParamHV(Query query, HttpServletRequest request, int index) {
  2092. String procDefId = request.getParameter("procDefId");
  2093. String procName = request.getParameter("prodef.name");
  2094. if (StringUtils.isNotEmpty(procDefId)) {
  2095. query.setParameter(index, procDefId);
  2096. ++index;
  2097. }
  2098. if (StringUtils.isNotEmpty(procName)) {
  2099. query.setParameter(index, procName);
  2100. }
  2101. }
  2102. private String getHiVariable(String taskId, String variableName) {
  2103. StringBuilder sb = new StringBuilder("");
  2104. sb.append("from ActHiVarinst VAR where VAR.procInstId =? and VAR.name = ?");
  2105. Query query = this.activitiService.getSession().createQuery(sb.toString());
  2106. query.setString(0, taskId);
  2107. query.setString(1, variableName);
  2108. ActHiVarinst obj = (ActHiVarinst) query.uniqueResult();
  2109. return obj == null ? "" : obj.getText();
  2110. }
  2111. //我发起的
  2112. @RequestMapping(value = "/workflow/myLaunchTaskList")
  2113. @ResponseBody
  2114. public WXAjaxJson workflow_myLaunchTaskList(HttpServletRequest request, HttpServletResponse response) {
  2115. TSUser user = verifyUser(true);
  2116. WXAjaxJson json = new WXAjaxJson();
  2117. Map<String, Object> data = new HashMap<>();
  2118. String currentUserName = user.getUserName();
  2119. String realName = user.getRealName();
  2120. int page = Integer.parseInt(request.getParameter("page"));
  2121. int rows = Integer.parseInt(request.getParameter("rows"));
  2122. HistoricProcessInstanceQuery historicProcessInstanceQuery = this.historyService
  2123. .createHistoricProcessInstanceQuery().startedBy(currentUserName);
  2124. List<HistoricProcessInstance> list = ((HistoricProcessInstanceQuery) historicProcessInstanceQuery
  2125. .orderByProcessInstanceStartTime().desc()).listPage((page - 1) * rows, rows);
  2126. Iterator var9 = list.iterator();
  2127. List<Map> datalist = new ArrayList<>();
  2128. while (var9.hasNext()) {
  2129. HistoricProcessInstance hi = (HistoricProcessInstance) var9.next();
  2130. String starttime = DateFormatUtils.format(hi.getStartTime(), "yyyy-MM-dd HH:mm:ss");
  2131. String endtime = hi.getEndTime() == null ? "" : DateFormatUtils.format(hi.getEndTime(), "yyyy-MM-dd HH:mm:ss");
  2132. long totalTimes = hi.getEndTime() == null
  2133. ? Calendar.getInstance().getTimeInMillis() - hi.getStartTime().getTime()
  2134. : hi.getEndTime().getTime() - hi.getStartTime().getTime();
  2135. long dayCount = totalTimes / 86400000L;
  2136. long restTimes = totalTimes % 86400000L;
  2137. long hourCount = restTimes / 3600000L;
  2138. restTimes %= 3600000L;
  2139. long minuteCount = restTimes / 60000L;
  2140. String spendTimes = dayCount + "天" + hourCount + "小时" + minuteCount + "分";
  2141. ProcessDefinition processDefinition = (ProcessDefinition) this.repositoryService
  2142. .createProcessDefinitionQuery()
  2143. .processDefinitionId(hi.getProcessDefinitionId())
  2144. .singleResult();
  2145. String bpmBizTitle = this.getHiVariable(hi.getId(), WorkFlowGlobals.BPM_BIZ_TITLE);
  2146. Map<String, Object> item = new HashMap<>();
  2147. item.put("id", hi.getId());
  2148. item.put("prcocessDefinitionName", StringUtils.trimToEmpty(processDefinition.getName()));
  2149. item.put("startUserId", hi.getStartUserId());
  2150. item.put("startUserName", realName);
  2151. item.put("starttime", starttime);
  2152. item.put("endtime", endtime);
  2153. item.put("spendTimes", spendTimes);
  2154. item.put("processDefinitionId", hi.getProcessDefinitionId());
  2155. item.put("processInstanceId", hi.getId());
  2156. item.put("bpmBizTitle", bpmBizTitle);
  2157. datalist.add(item);
  2158. }
  2159. data.put("list", datalist);
  2160. data.put("hasmore", datalist.size() >= rows ? 1 : 0);
  2161. json.setData(data);
  2162. return json;
  2163. }
  2164. /**
  2165. * 我的消息列表
  2166. * @param request
  2167. * @param response
  2168. * @param noticeType 通知类型
  2169. * @param isRead 是否已读 0未读 1已读
  2170. * @return
  2171. */
  2172. @RequestMapping(value = "/message/myList")
  2173. @ResponseBody
  2174. public WXAjaxJson messeg_myList(
  2175. @RequestParam(value = "noticeType",required = false) String noticeType
  2176. ,@RequestParam(value = "isRead",required = false) Integer isRead
  2177. ,@RequestParam(value = "page",required = false,defaultValue = "1") Integer page
  2178. ,@RequestParam(value = "rows",required = false,defaultValue = "10") Integer rows
  2179. ,HttpServletRequest request, HttpServletResponse response) {
  2180. TSUser user = verifyUser(true);
  2181. WXAjaxJson json = new WXAjaxJson();
  2182. Map<String, Object> data = new HashMap<>();
  2183. MiniDaoPage<MPersonalMessageEntity> pageList = mPersonalMessageService.getUserMessage(user.getId(),noticeType,isRead,page,rows);
  2184. List<TSType> types = systemService.getTypesByGroupcodeFromCache("message_notice_type");
  2185. List<Map<String,String>> noticeTypeList = new ArrayList<>(types.size());
  2186. for(TSType type:types){
  2187. Map<String,String> map = new HashMap<>();
  2188. map.put("code",type.getTypecode());
  2189. map.put("name",type.getTypename());
  2190. noticeTypeList.add(map);
  2191. }
  2192. data.put("list",pageList.getResults());
  2193. data.put("noticeTypeList",noticeTypeList);
  2194. data.put("hasmore", pageList.getPages() > page ? 1 : 0);
  2195. json.setData(data);
  2196. return json;
  2197. }
  2198. /**
  2199. * 消息详情
  2200. * @param messageId 消息id
  2201. * @param request
  2202. * @param response
  2203. * @return
  2204. */
  2205. @RequestMapping(value = "/message/detail")
  2206. @ResponseBody
  2207. public WXAjaxJson messeg_detail(
  2208. @RequestParam(value = "messageId") String messageId
  2209. ,HttpServletRequest request
  2210. , HttpServletResponse response) {
  2211. TSUser user = verifyUser(true);
  2212. WXAjaxJson json = new WXAjaxJson();
  2213. Map<String, Object> data = new HashMap<>();
  2214. MMessageEntity entity = mMessageService.userPreview(user.getId(),messageId);
  2215. Map<String,Object> obj = new HashMap<>();
  2216. obj.put("title",entity.getTitle());
  2217. obj.put("text",entity.getSendText());
  2218. obj.put("id",messageId);
  2219. data.put("entity",obj);
  2220. //消息附件
  2221. CriteriaQuery cq = new CriteriaQuery(TSysFileEntity.class);
  2222. try{
  2223. cq.eq("busiTable","m_message");
  2224. cq.eq("tagetType","mmessage");
  2225. cq.addOrder("createDate",SortDirection.asc);
  2226. cq.eq("busiId",messageId);
  2227. }catch (Exception e) {
  2228. throw new BusinessException(e.getMessage());
  2229. }
  2230. cq.add();
  2231. cq.setDataGrid(new DataGrid());
  2232. DataGridReturn dataGridReturn = systemService.getDataGridReturn(cq, false);
  2233. String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
  2234. List<TSysFileEntity> fileEntityList = dataGridReturn.getRows();
  2235. List<Map<String,String>> fileList = new ArrayList<>();
  2236. for(TSysFileEntity fileEntity:fileEntityList){
  2237. Map<String,String> map = new HashMap<>();
  2238. map.put("fileName",fileEntity.getFileName());
  2239. try {
  2240. map.put("fileUrl",showAndDownUrl+fileEntity.getFileUrl()+"&down=1&userName="+URLEncoder.encode(user.getUserName(),"UTF-8"));
  2241. } catch (UnsupportedEncodingException e) {
  2242. e.printStackTrace();
  2243. }
  2244. fileList.add(map);
  2245. }
  2246. data.put("fileList",fileList);
  2247. json.setData(data);
  2248. return json;
  2249. }
  2250. /**
  2251. * 我的回复列表
  2252. * @param messageId 消息id
  2253. * @return
  2254. */
  2255. @RequestMapping(value = "/message/myreply")
  2256. @ResponseBody
  2257. public WXAjaxJson messeg_myreply(@RequestParam(value = "messageId") String messageId
  2258. , HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
  2259. TSUser user = verifyUser(true);
  2260. WXAjaxJson json = new WXAjaxJson();
  2261. Map<String, Object> data = new HashMap<>();
  2262. CriteriaQuery cq = new CriteriaQuery(MMessageReplyEntity.class, dataGrid);
  2263. //查询条件组装器
  2264. try{
  2265. cq.eq("userId",user.getId());
  2266. cq.eq("messageId",messageId);
  2267. //自定义追加查询条件
  2268. }catch (Exception e) {
  2269. throw new BusinessException(e.getMessage());
  2270. }
  2271. cq.add();
  2272. systemService.getDataGridReturn(cq, true);
  2273. data.put("list",dataGrid.getResults());
  2274. json.setData(data);
  2275. return json;
  2276. }
  2277. /**
  2278. * 回复消息
  2279. * @param messageId 消息id
  2280. * @param reply 回复内容
  2281. * @return
  2282. */
  2283. @RequestMapping(value = "/message/doreply")
  2284. @ResponseBody
  2285. public WXAjaxJson messeg_doreply(@RequestParam(value = "messageId") String messageId
  2286. , @RequestParam(value = "reply") String reply
  2287. , HttpServletRequest request, HttpServletResponse response) {
  2288. TSUser user = verifyUser(true);
  2289. WXAjaxJson json = new WXAjaxJson();
  2290. Map<String, Object> data = new HashMap<>();
  2291. mMessageReplyService.reply(user.getId(),messageId,reply);
  2292. data.put("success",true);
  2293. json.setData(data);
  2294. return json;
  2295. }
  2296. }