AuthServiceImpl.java 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  1. package com.caimei.service.auth.impl;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.caimei.annotation.CurrentUser;
  6. import com.caimei.components.RedisService;
  7. import com.caimei.config.FastDfsClient;
  8. import com.caimei.mapper.cmMapper.AuthMapper;
  9. import com.caimei.mapper.cmMapper.AuthProductMapper;
  10. import com.caimei.mapper.ldmMapper.LdmMapper;
  11. import com.caimei.model.ResponseJson;
  12. import com.caimei.model.po.*;
  13. import com.caimei.model.vo.*;
  14. import com.caimei.service.auth.AuthProductService;
  15. import com.caimei.service.auth.AuthService;
  16. import com.caimei.service.auth.ShopService;
  17. import com.caimei.service.auth.UploadService;
  18. import com.caimei.utils.*;
  19. import com.github.pagehelper.PageHelper;
  20. import com.github.pagehelper.PageInfo;
  21. import lombok.extern.slf4j.Slf4j;
  22. import lombok.val;
  23. import org.apache.commons.lang3.ObjectUtils;
  24. import org.apache.commons.lang3.StringUtils;
  25. import org.apache.http.Consts;
  26. import org.apache.http.HttpEntity;
  27. import org.apache.http.NameValuePair;
  28. import org.apache.http.client.entity.UrlEncodedFormEntity;
  29. import org.apache.http.client.methods.CloseableHttpResponse;
  30. import org.apache.http.client.methods.HttpGet;
  31. import org.apache.http.client.methods.HttpPost;
  32. import org.apache.http.client.utils.URIBuilder;
  33. import org.apache.http.entity.ContentType;
  34. import org.apache.http.entity.StringEntity;
  35. import org.apache.http.entity.mime.MultipartEntityBuilder;
  36. import org.apache.http.impl.client.CloseableHttpClient;
  37. import org.apache.http.impl.client.HttpClients;
  38. import org.apache.http.message.BasicNameValuePair;
  39. import org.apache.http.util.EntityUtils;
  40. import org.apache.poi.ss.usermodel.*;
  41. import org.apache.poi.xssf.usermodel.*;
  42. import org.springframework.beans.factory.annotation.Autowired;
  43. import org.springframework.beans.factory.annotation.Value;
  44. import org.springframework.core.io.ClassPathResource;
  45. import org.springframework.stereotype.Service;
  46. import org.springframework.transaction.annotation.Transactional;
  47. import org.springframework.transaction.interceptor.TransactionAspectSupport;
  48. import org.springframework.util.Assert;
  49. import org.springframework.web.bind.annotation.*;
  50. import org.springframework.web.multipart.MultipartFile;
  51. import javax.annotation.Resource;
  52. import javax.imageio.ImageIO;
  53. import javax.servlet.ServletOutputStream;
  54. import javax.servlet.http.HttpServletRequest;
  55. import javax.servlet.http.HttpServletResponse;
  56. import javax.swing.*;
  57. import java.awt.*;
  58. import java.awt.Font;
  59. import java.io.*;
  60. import java.math.BigDecimal;
  61. import java.net.URISyntaxException;
  62. import java.net.URL;
  63. import java.nio.charset.StandardCharsets;
  64. import java.text.SimpleDateFormat;
  65. import java.util.*;
  66. import java.util.List;
  67. import java.util.regex.Matcher;
  68. import java.util.regex.Pattern;
  69. import java.util.stream.Collectors;
  70. import java.util.stream.Stream;
  71. /**
  72. * Description
  73. *
  74. * @author : Aslee
  75. * @date : 2021/5/11
  76. */
  77. @Slf4j
  78. @Service
  79. public class AuthServiceImpl implements AuthService {
  80. @Resource
  81. private AuthMapper authMapper;
  82. @Resource
  83. private LdmMapper ldmMapper;
  84. @Value("${caimei.zpapi}")
  85. private String zpServer;
  86. private AuthProductService authProductService;
  87. @Autowired
  88. public void setAuthProductService(AuthProductService authProductService) {
  89. this.authProductService = authProductService;
  90. }
  91. private ShopService shopService;
  92. @Autowired
  93. public void setShopService(ShopService shopService) {
  94. this.shopService = shopService;
  95. }
  96. private UploadService uploadService;
  97. @Autowired
  98. public void setUploadService(UploadService uploadService) {
  99. this.uploadService = uploadService;
  100. }
  101. @Value("${spring.profiles.active}")
  102. private String active;
  103. @Autowired
  104. private FastDfsClient client;
  105. @Value("${caimei.imageDomain}")
  106. private String imageDomain;
  107. @Resource
  108. private RedisService redisService;
  109. @Override
  110. public ResponseJson<PageInfo<AuthVo>> getAuthList(Integer listType, Integer authUserId, String authParty,
  111. String mobile, Integer status, Integer starFlag, Integer auditStatus,
  112. Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus,String authCode, Integer pageNum, Integer pageSize) {
  113. listType = null == listType ? 1 : listType;
  114. PageHelper.startPage(pageNum, pageSize);
  115. List<AuthVo> authList = authMapper.getAuthList(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus,authCode);
  116. PageInfo<AuthVo> pageData = new PageInfo<>(authList);
  117. return ResponseJson.success(pageData);
  118. }
  119. @Override
  120. public ResponseJson<PageInfo<AuthVo>> getAuthListAll(Integer listType, Integer authUserId, String authParty,
  121. String mobile, Integer status, Integer starFlag, Integer auditStatus,
  122. Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus, String name, String snCode, Integer pageNum, Integer pageSize) {
  123. listType = null == listType ? 1 : listType;
  124. PageHelper.startPage(pageNum, pageSize);
  125. List<AuthVo> authList = authMapper.getAuthListAll(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus, name, snCode);
  126. PageInfo<AuthVo> pageData = new PageInfo<>(authList);
  127. return ResponseJson.success(pageData);
  128. }
  129. @Override
  130. public ResponseJson updateAuthStatus(Integer authId, Integer status) {
  131. if (null == authId) {
  132. return ResponseJson.error("请输入授权id");
  133. }
  134. if (null == status) {
  135. return ResponseJson.error("请输入要更新的状态值");
  136. }
  137. authMapper.updateAuthStatusByAuthId(authId, status);
  138. if (0 == status) {
  139. return ResponseJson.success("下线品牌授权成功");
  140. } else {
  141. return ResponseJson.success("上线品牌授权成功");
  142. }
  143. }
  144. @Override
  145. public ResponseJson deleteAuth(Integer authId) {
  146. if (null == authId) {
  147. return ResponseJson.error("参数异常,请输入授权id");
  148. }
  149. // 删除品牌授权
  150. authMapper.deleteAuthByAuthId(authId);
  151. // 删除轮播图
  152. authMapper.deleteBanner(authId);
  153. // 删除商品及商品参数
  154. List<Integer> productIdList = authProductService.getProductIdsByAuthId(authId);
  155. productIdList.forEach(productId -> {
  156. if (null != productId) {
  157. authProductService.deleteProduct(productId);
  158. }
  159. });
  160. return ResponseJson.success("删除品牌授权成功");
  161. }
  162. @Override
  163. public ResponseJson<AuthFormVo> getAuthFormData(Integer authId) {
  164. if (null == authId) {
  165. return ResponseJson.error("参数异常,机构id不能为空", null);
  166. }
  167. AuthFormVo authFormVo = authMapper.getAuthFormById(authId);
  168. //该机构关联机构用集合形式返回便于前端赋值
  169. if (null != authFormVo.getRelationId() && !"".equals(authFormVo.getRelationId())) {
  170. String[] relationIdList = authFormVo.getRelationId().split(",");
  171. List<AuthFormVo> authIdList = authMapper.getAuthIdList(relationIdList);
  172. authFormVo.setReleationClubList(authIdList);
  173. }
  174. if (null != authFormVo.getLng()) {
  175. authFormVo.setLngAndLat(authFormVo.getLng() + "," + authFormVo.getLat());
  176. }
  177. List<String> bannerList = authMapper.getBannerList(authId);
  178. authFormVo.setBannerList(bannerList);
  179. return ResponseJson.success(authFormVo);
  180. }
  181. @Override
  182. public ResponseJson<List<AuthVo>> getAuthSelectList(Integer authUserId) {
  183. List<AuthVo> authList = authMapper.getAuthList(1, authUserId, null, null, null, null, null, null, null, null,null);
  184. return ResponseJson.success(authList);
  185. }
  186. @Override
  187. public ResponseJson importLdmImage(Integer authUserId) {
  188. List<LdmDataPo> ldmClubData = ldmMapper.getLdmClubData(null, 0);
  189. ldmClubData.forEach(ldmClub -> {
  190. String pic2 = ldmClub.getPic2();
  191. String pic3 = ldmClub.getPic3();
  192. String pic4 = ldmClub.getPic4();
  193. List<AuthVo> authList = authMapper.getAuthByNameAndAddress(ldmClub.getAuthParty(), ldmClub.getAddress());
  194. if (null != authList && authList.size() > 0) {
  195. if (authList.size() > 1) {
  196. log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:对应门店过多,门店名称:" + ldmClub.getAuthParty());
  197. } else {
  198. AuthVo auth = authList.get(0);
  199. Integer authId = auth.getAuthId();
  200. if (StringUtils.isNotEmpty(pic2) || StringUtils.isNotEmpty(pic3) || StringUtils.isNotEmpty(pic4)) {
  201. authMapper.deleteBanner(authId);
  202. insertBanner(pic2, authId);
  203. insertBanner(pic3, authId);
  204. insertBanner(pic4, authId);
  205. }
  206. if (StringUtils.isNotEmpty(ldmClub.getRemarks())) {
  207. authMapper.updateRemarks(authId, ldmClub.getRemarks());
  208. }
  209. }
  210. } else {
  211. log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:找不到对应门店,门店名称:" + ldmClub.getAuthParty());
  212. }
  213. });
  214. return ResponseJson.success();
  215. }
  216. @Override
  217. public ResponseJson checkAuth(Integer authId) {
  218. authMapper.checkAuth(authId);
  219. return ResponseJson.success();
  220. }
  221. @Override
  222. public ResponseJson starAuth(Integer authId, Integer starFlag, String starNum) {
  223. authMapper.starAuth(authId, starFlag, starNum);
  224. return ResponseJson.success();
  225. }
  226. private void insertBanner(String pic, Integer authId) {
  227. if (StringUtils.isNotEmpty(pic)) {
  228. String imagePath = "https://wangdian.skinovachina.com" + pic;
  229. String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
  230. try {
  231. String banner = uploadService.saveFileByUrl(imagePath, fileName);
  232. authMapper.insertBanner(authId, banner);
  233. } catch (Exception e) {
  234. e.printStackTrace();
  235. }
  236. }
  237. }
  238. @Override
  239. public ResponseJson saveAuth(CmBrandAuthPo auth, List<String> bannerList, boolean importFlag, Integer source) {
  240. Integer authId = auth.getId();
  241. boolean insertFlag = null == authId;
  242. AuthVo dbAuth = null;
  243. if (!insertFlag) {
  244. dbAuth = authMapper.getAuthById(authId);
  245. }
  246. String authParty = auth.getAuthParty();
  247. if (StringUtils.isBlank(authParty)) {
  248. return ResponseJson.error("参数异常,请输入授权机构名称");
  249. }
  250. if (null == auth.getFirstClubType()) {
  251. return ResponseJson.error("请勾选机构类型");
  252. }
  253. if ((1 == auth.getFirstClubType() || 2 == auth.getFirstClubType()) && null == auth.getSecondClubType()) {
  254. return ResponseJson.error("请勾选二级机构类型");
  255. }
  256. if (1 == auth.getFirstClubType() && StringUtils.isEmpty(auth.getMedicalLicenseImage())) {
  257. return ResponseJson.error("请上传医疗许可证");
  258. }
  259. if (null == auth.getEmpNum()) {
  260. return ResponseJson.error("请输入员工人数");
  261. }
  262. if (1 == source) {
  263. if (null == auth.getCreateBy()) {
  264. return ResponseJson.error("参数异常,请输入创建人id");
  265. }
  266. /*if (1 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImageLogo())) {
  267. return ResponseJson.error("授权牌logo不能为空");
  268. }*/
  269. if (2 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImage())) {
  270. return ResponseJson.error("授权牌不能为空");
  271. }
  272. } else {
  273. // 机构添加默认模板库生成
  274. auth.setAuthImageType(1);
  275. }
  276. if (!importFlag) {
  277. if (null == auth.getProvinceId() || null == auth.getCityId() || null == auth.getTownId() || StringUtils.isEmpty(auth.getAddress()) || null == auth.getLng() || null == auth.getLat()) {
  278. return ResponseJson.error("参数异常,地址信息异常");
  279. }
  280. if (StringUtils.isEmpty(auth.getLogo())) {
  281. return ResponseJson.error("参数异常,请上传机构logo");
  282. }
  283. if (null == bannerList || bannerList.size() <= 0) {
  284. return ResponseJson.error("参数异常,请上传轮播图");
  285. }
  286. }
  287. // 供应商保存,直接上线;机构保存,需要供应商审核通过后才上线
  288. if (null != dbAuth && 1 != dbAuth.getAuditStatus()) {
  289. // 被驳回的数据,编辑变为待审核状态
  290. auth.setStatus(2);
  291. auth.setAuditStatus(2);
  292. } else {
  293. auth.setStatus(1 == source ? 1 : 2);
  294. auth.setAuditStatus(1 == source ? 1 : 2);
  295. }
  296. Integer adminUserId = authMapper.getAdminUserId();
  297. auth.setAuditBy(adminUserId);
  298. auth.setAuditTime(new Date());
  299. if (1 == source) {
  300. auth.setShopAuditBy(auth.getCreateBy());
  301. auth.setShopAuditTime(new Date());
  302. }
  303. auth.setDelFlag(0);
  304. auth.setCheckFlag(0);
  305. auth.setShopAuditStatus(1 == source ? 1 : 2);
  306. /*
  307. 保存授权
  308. */
  309. if (insertFlag) {
  310. authMapper.insertAuth(auth);
  311. } else {
  312. //机构互关
  313. relaMech(auth);
  314. authMapper.updateAuthByAuthId(auth);
  315. // 删除原有的轮播图
  316. authMapper.deleteBanner(auth.getId());
  317. }
  318. // 保存之后生成授权牌和水印授权牌
  319. String authImage = null;
  320. if (1 == auth.getAuthImageType()) {
  321. // 模板库生成
  322. // 获取对应模板
  323. TemplateVo authTemplate = authMapper.getAuthTemplate(auth.getId(), null, 1);
  324. authImage = generateAuthImage(authTemplate, auth);
  325. auth.setAuthImage(authImage);
  326. }
  327. // 添加水印
  328. if (StringUtils.isNotEmpty(auth.getAuthImage())) {
  329. auth.setPcAuthImage(addWaterMark(auth.getAuthImage(), 1));
  330. auth.setAppletsAuthImage(addWaterMark(auth.getAuthImage(), 2));
  331. authMapper.updateAuthImage(auth);
  332. }
  333. // 保存轮播图
  334. if (null != bannerList) {
  335. bannerList.forEach(banner -> authMapper.insertBanner(auth.getId(), banner));
  336. }
  337. return ResponseJson.success("保存品牌授权成功", auth);
  338. }
  339. /**
  340. * 机构互关
  341. * @param auth
  342. */
  343. public void relaMech(CmBrandAuthPo auth){
  344. if(null!=auth&&StringUtils.isNotEmpty(auth.getRelationId())&&StringUtils.isNotEmpty(auth.getRelationName())){
  345. String[] relaIdArr = auth.getRelationId().split(",");
  346. for(int i=0;i<relaIdArr.length;i++){
  347. String relaId=auth.getId().toString();
  348. String relaName=auth.getAuthParty();
  349. Integer id = Integer.valueOf(relaIdArr[i]);
  350. //先获取该机构是否与其他机构关联,有则合并
  351. CmBrandAuthPo relationInfo = authMapper.getRelationInfo(id);
  352. if(null!=relationInfo&&StringUtils.isNotEmpty(relationInfo.getRelationId())&&StringUtils.isNotEmpty(relationInfo.getRelationName())){
  353. //避免保存一样的数据
  354. if(!relationInfo.getRelationId().contains(relaId)&&!relationInfo.getRelationName().contains(relaName)){
  355. relaId=relaId+","+relationInfo.getRelationId();
  356. relaName=relaName+","+relationInfo.getRelationName();
  357. authMapper.updateRelaByAuthId(id,relaId,relaName);
  358. }
  359. }else {
  360. authMapper.updateRelaByAuthId(id,relaId,relaName);
  361. }
  362. }
  363. }
  364. }
  365. @Override
  366. public String addWaterMark(String image, Integer type) {
  367. try {
  368. //type:1pc,2applets
  369. ClassPathResource classPathResource = new ClassPathResource("/images/newPcWaterMark.png");
  370. InputStream inputStreamImg = classPathResource.getInputStream();
  371. Image pcWaterMarkImg = ImageIO.read(inputStreamImg);
  372. classPathResource = new ClassPathResource("/images/newAppletsWaterMark.png");
  373. inputStreamImg = classPathResource.getInputStream();
  374. Image appletsWaterMarkImg = ImageIO.read(inputStreamImg);
  375. String img = ImageUtils.markImageByIcon(type == 1 ? pcWaterMarkImg : appletsWaterMarkImg, image, null);
  376. String imagePath = null;
  377. if (StringUtils.isNotEmpty(img)) {
  378. MultipartFile imgFile = Base64Util.base64ToMultipart(img);
  379. if (null != imgFile) {
  380. imagePath = uploadService.saveFile(imgFile);
  381. }
  382. log.info(">>>>>>>>>>>>>>>>水印图片上传成功:" + imagePath);
  383. } else {
  384. log.info(">>>>>>>>>>>>>>>>水印图片上传失败");
  385. }
  386. return imagePath;
  387. } catch (Exception e) {
  388. e.printStackTrace();
  389. }
  390. return null;
  391. }
  392. @Override
  393. public String generateAuthImage(TemplateVo authTemplate, CmBrandAuthPo auth) {
  394. if (null != authTemplate) {
  395. // 根据模板id设置相关数据
  396. Map<String, Object> templateInfo = getTemplateInfo(authTemplate, auth);
  397. Object templateImage = templateInfo.get("templateImage");
  398. if (null != templateImage) {
  399. String authImage = ImageUtils.generateAuthImage(templateInfo);
  400. log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + authImage);
  401. // 临时图片
  402. File tempFile = new File(authImage);
  403. String imageUrl = null;
  404. try {
  405. imageUrl = imageDomain + "/" + client.uploadFile(authImage);
  406. } catch (Exception e) {
  407. e.printStackTrace();
  408. }
  409. // 删除临时图片
  410. boolean delete = tempFile.delete();
  411. log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时图片:" + delete);
  412. return imageUrl;
  413. } else {
  414. return null;
  415. }
  416. }
  417. return null;
  418. }
  419. private Map<String, Object> getTemplateInfo(TemplateVo template, CmBrandAuthPo auth) {
  420. HashMap<String, Object> map = new HashMap<>();
  421. Integer templateId = template.getTemplateId();
  422. if (1 == templateId) {
  423. map.put("templateImage", template.getTemplateImage());
  424. double rate = 0.15;
  425. if (StringUtils.isNotEmpty(auth.getAuthImageLogo())) {
  426. // 获取授权牌logo位置
  427. try {
  428. ImageIcon imageIcon = new ImageIcon(new URL(template.getTemplateImage()));
  429. Image srcImg = imageIcon.getImage();
  430. int srcWidth = srcImg.getWidth(null);
  431. ImageIcon authImageLogo = new ImageIcon(new URL(auth.getAuthImageLogo()));
  432. Image authLogo = authImageLogo.getImage();
  433. int authLogoWidth = authLogo.getWidth(null);
  434. int x = (srcWidth - (int) Math.round(238 * rate) - authLogoWidth) / 2 + (int) Math.round(238 * rate);
  435. int y = (int) Math.round(1230 * rate);
  436. map.put("addImage1_x", x);
  437. map.put("addImage1_y", y);
  438. map.put("addImage1_image", auth.getAuthImageLogo());
  439. } catch (Exception e) {
  440. e.printStackTrace();
  441. }
  442. }
  443. // 添加认证编号信息
  444. if (StringUtils.isNotEmpty(auth.getAuthCode())) {
  445. map.put("addWord1_content", auth.getAuthCode());
  446. map.put("addWord1_color", "218,185,107");
  447. map.put("addWord1_type", "思源宋体");
  448. map.put("addWord1_style", Font.BOLD);
  449. map.put("addWord1_size", (int) Math.round(90 * rate));
  450. map.put("addWord1_x", (int) Math.round(2168 * rate));
  451. map.put("addWord1_y", (int) Math.round(3157 * rate));
  452. }
  453. // 添加认证日期信息
  454. if (null != auth.getAuthDate()) {
  455. SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
  456. map.put("addWord2_content", format.format(auth.getAuthDate()));
  457. map.put("addWord2_color", "218,185,107");
  458. map.put("addWord2_type", "思源宋体");
  459. map.put("addWord2_style", Font.PLAIN);
  460. map.put("addWord2_size", (int) Math.round(90 * rate));
  461. map.put("addWord2_x", (int) Math.round(2085 * rate));
  462. map.put("addWord2_y", (int) Math.round(3289 * rate));
  463. }
  464. // 添加二维码信息
  465. if (StringUtils.isNotEmpty(template.getQrPosition())) {
  466. String qrCodeLink = zpServer + "/" + auth.getAuthUserId() + "/" + authMapper.getPrefix(auth.getAuthUserId()) + "/approve/club/detail?id=" + auth.getId();
  467. map.put("addQr1_link", qrCodeLink);
  468. map.put("addQr1_size", template.getQrSize());
  469. String[] split = template.getQrPosition().split(",");
  470. if (split.length == 2) {
  471. map.put("addQr1_x", Integer.parseInt(split[0]));
  472. map.put("addQr1_y", Integer.parseInt(split[1]));
  473. }
  474. }
  475. }
  476. return map;
  477. }
  478. @Override
  479. public ResponseJson auditAuth(Integer authId, Integer auditStatus, String invalidReason, Integer auditBy, Integer source) {
  480. if (authId == null) {
  481. return ResponseJson.error("请输入授权id");
  482. }
  483. if (auditStatus == null) {
  484. return ResponseJson.error("请输入审核结果");
  485. }
  486. if (auditStatus == 0 && StringUtils.isEmpty(invalidReason)) {
  487. return ResponseJson.error("请输入审核不通过的原因");
  488. }
  489. source = null == source ? 1 : source;
  490. Date auditTime = new Date();
  491. // 授权状态更新
  492. Integer status = null;
  493. if (auditStatus == 0) {
  494. // 审核不通过,下线授权
  495. status = 0;
  496. } else {
  497. // 审核通过,上线授权
  498. status = 1;
  499. }
  500. if (1 == source) {
  501. authMapper.updateAuthAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
  502. }
  503. if (2 == source) {
  504. authMapper.updateAuthShopAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
  505. }
  506. return ResponseJson.success("审核机构认证成功");
  507. }
  508. @Override
  509. @Transactional(rollbackFor = Exception.class)
  510. public ResponseJson importDataByExcel(MultipartFile file, Integer authUserId, Integer createBy) {
  511. String originalFilename = file.getOriginalFilename();
  512. String randomStr = UUID.randomUUID().toString();
  513. assert originalFilename != null;
  514. int index = originalFilename.lastIndexOf(".");
  515. String extName = originalFilename.substring(index);
  516. String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/";
  517. if ("dev".equals(active)) {
  518. filePath = "D:\\WorkSpace\\file\\tempImport\\";
  519. }
  520. filePath += randomStr + extName;
  521. try {
  522. File tempFile = new File(filePath);
  523. if (!tempFile.exists()) {
  524. tempFile.mkdirs();
  525. }
  526. file.transferTo(tempFile);
  527. return saveExcelData(filePath, authUserId, createBy);
  528. } catch (IOException e) {
  529. e.printStackTrace();
  530. }
  531. log.info(">>>>>>>>>>>>>>>>文件临时路径:" + filePath);
  532. return null;
  533. }
  534. private ResponseJson saveExcelData(String filePath, Integer authUserId, Integer createBy) {
  535. //判断是否为excel类型文件
  536. if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
  537. System.out.println("文件不是excel类型");
  538. }
  539. // 获取供应商品牌
  540. List<String> shopBrands = shopService.getShopBrands(authUserId);
  541. // 授权列表
  542. List<CmBrandAuthPo> authImportList = new ArrayList<>();
  543. try {
  544. FileInputStream fis = new FileInputStream(filePath);
  545. // 得到表格数据
  546. XSSFWorkbook workbook = new XSSFWorkbook(fis);
  547. //得到第一个工作表(机构表)
  548. XSSFSheet authPartySheet = workbook.getSheetAt(0);
  549. //获得表头
  550. Row rowHead = authPartySheet.getRow(0);
  551. //判断表头是否正确
  552. if (9 != rowHead.getLastCellNum() || !"机构名称".equals(rowHead.getCell(0).getStringCellValue())) {
  553. return ResponseJson.error("授权机构表格式错误");
  554. }
  555. // 获得数据的总行数
  556. int authPartyRowNum = authPartySheet.getLastRowNum();
  557. //获得所有数据
  558. for (int i = 1; i <= authPartyRowNum; i++) {
  559. //获得第i行对象
  560. Row authPartyRow = authPartySheet.getRow(i);
  561. if (null == authPartyRow) {
  562. break;
  563. }
  564. Cell cell = null;
  565. // 校验机构名称
  566. cell = authPartyRow.getCell(0);
  567. String authParty = null;
  568. if(null != cell){
  569. cell.setCellType(CellType.STRING);
  570. authParty = cell.getStringCellValue();
  571. }
  572. if (StringUtils.isBlank(authParty)) {
  573. return ResponseJson.error("第" + i + 1 + "行机构名称不能为空");
  574. }
  575. // 校验省市区
  576. cell = authPartyRow.getCell(1);
  577. cell.setCellType(CellType.STRING);
  578. String area = cell.getStringCellValue();
  579. if (StringUtils.isBlank(area)) {
  580. return ResponseJson.error("第" + i + 1 + "行所在地区不能为空");
  581. }
  582. String[] areaSplit = area.split("/");
  583. if (areaSplit.length < 2 || areaSplit.length > 3) {
  584. return ResponseJson.error("第" + i + 1 + "行所在地区格式错误");
  585. }
  586. // 省份
  587. String provinceName = areaSplit[0];
  588. if (StringUtils.isBlank(provinceName)) {
  589. return ResponseJson.error("第" + i + 1 + "行省份不能为空");
  590. }
  591. if (provinceName.length() > 2) {
  592. provinceName = provinceName.substring(0, provinceName.length() - 1).trim();
  593. }
  594. Integer provinceId = authMapper.getProvinceId(provinceName);
  595. // 市名
  596. String cityName = areaSplit[1];
  597. if (StringUtils.isBlank(cityName)) {
  598. return ResponseJson.error("第" + i + 1 + "行市名不能为空");
  599. }
  600. if (cityName.length() > 2) {
  601. cityName = cityName.substring(0, cityName.length() - 1).trim();
  602. }
  603. Integer cityId = authMapper.getCityId(cityName);
  604. Integer townId = null;
  605. if (areaSplit.length > 2) {
  606. // 区名
  607. String townName = areaSplit[2];
  608. if (StringUtils.isNotEmpty(townName) && townName.length() > 2) {
  609. townName = townName.substring(0, townName.length() - 1).trim();
  610. }
  611. List<TownPo> townList = authMapper.getTownList(townName);
  612. for (int j = 0; j < townList.size(); j++) {
  613. TownPo town = townList.get(j);
  614. if (null == townId) {
  615. if (null != cityId) {
  616. if (town.getCityId().equals(cityId)) {
  617. townId = town.getTownId();
  618. }
  619. } else {
  620. Integer checkCityId = authMapper.getCityIdByTownId(town.getTownId());
  621. if (null != provinceId && null != checkCityId) {
  622. Integer checkProvinceId = authMapper.getProvinceIdByCityId(cityId);
  623. if (provinceId.equals(checkProvinceId)) {
  624. cityId = checkCityId;
  625. townId = town.getTownId();
  626. }
  627. }
  628. }
  629. }
  630. }
  631. }
  632. // 校验详细地址
  633. cell = authPartyRow.getCell(2);
  634. cell.setCellType(CellType.STRING);
  635. String address = cell.getStringCellValue();
  636. if (StringUtils.isBlank(address)) {
  637. return ResponseJson.error("第" + i + 1 + "行详细地址不能为空");
  638. }
  639. // 校验经纬度
  640. cell = authPartyRow.getCell(3);
  641. String lngAndLat = null;
  642. BigDecimal lng = null;
  643. BigDecimal lat = null;
  644. if(null != cell){
  645. cell.setCellType(CellType.STRING);
  646. lngAndLat = cell.getStringCellValue();
  647. // String[] split = lngAndLat.split(",");
  648. // lng = new BigDecimal(split[0]);
  649. // lat = new BigDecimal(split[1]);
  650. }
  651. // if (StringUtils.isBlank(lngAndLat)) {
  652. // return ResponseJson.error("第" + i + 1 + "行经纬度不能为空");
  653. // }
  654. // if (2 != split.length) {
  655. // return ResponseJson.error("第" + i + 1 + "行经纬度格式错误");
  656. // }
  657. // 校验联系电话
  658. cell = authPartyRow.getCell(4);
  659. cell.setCellType(CellType.STRING);
  660. String mobile = cell.getStringCellValue();
  661. if (StringUtils.isBlank(mobile)) {
  662. return ResponseJson.error("第" + i + 1 + "行联系电话不能为空");
  663. }
  664. // 认证编号
  665. cell = authPartyRow.getCell(5);
  666. String authCode = null;
  667. if(null != cell){
  668. cell.setCellType(CellType.STRING);
  669. authCode = cell.getStringCellValue();
  670. }
  671. // 认证日期
  672. Date authDate = null;
  673. cell = authPartyRow.getCell(6);
  674. String authDateStr= null;
  675. if(null != cell){
  676. cell.setCellType(CellType.STRING);
  677. authCode = cell.getStringCellValue();
  678. }
  679. if (StringUtils.isNotBlank(authDateStr)) {
  680. SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
  681. authDate = format.parse(authDateStr);
  682. }
  683. // 校验员工人数
  684. Integer empNum = null;
  685. cell = authPartyRow.getCell(7);
  686. cell.setCellType(CellType.STRING);
  687. String empNumStr = cell.getStringCellValue();
  688. if (StringUtils.isBlank(empNumStr)) {
  689. return ResponseJson.error("第" + i + 1 + "行员工人数不能为空");
  690. }
  691. try {
  692. empNum = Integer.parseInt(empNumStr);
  693. } catch (Exception e) {
  694. return ResponseJson.error("第" + i + 1 + "行员工人数格式错误");
  695. }
  696. // 校验店铺备注
  697. cell = authPartyRow.getCell(8);
  698. String remarks =null;
  699. if(null != cell){
  700. cell.setCellType(CellType.STRING);
  701. remarks = cell.getStringCellValue();
  702. }
  703. Integer customFlag = 0;
  704. if (StringUtils.isNotEmpty(remarks)) {
  705. customFlag = 1;
  706. }
  707. CmBrandAuthPo authPo = new CmBrandAuthPo();
  708. authPo.setAuthParty(authParty);
  709. authPo.setProvinceId(provinceId);
  710. authPo.setCityId(cityId);
  711. authPo.setTownId(townId);
  712. authPo.setAddress(address);
  713. authPo.setLng(lng);
  714. authPo.setLat(lat);
  715. authPo.setMobile(mobile);
  716. authPo.setAuthCode(authCode);
  717. authPo.setAuthDate(authDate);
  718. authPo.setAuthImageType(1);
  719. authPo.setEmpNum(empNum);
  720. authPo.setCustomFlag(customFlag);
  721. authPo.setRemarks(remarks);
  722. authImportList.add(authPo);
  723. }
  724. } catch (Exception e) {
  725. e.printStackTrace();
  726. return ResponseJson.error("导入失败,请检查表格数据");
  727. } finally {
  728. // 删除临时数据
  729. File tempFile = new File(filePath);
  730. boolean delete = tempFile.delete();
  731. log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时表格:" + delete);
  732. }
  733. // 保存授权数据
  734. for (int i = 0; i < authImportList.size(); i++) {
  735. CmBrandAuthPo authPo = authImportList.get(i);
  736. // 保存授权机构
  737. authPo.setAuthUserId(authUserId);
  738. authPo.setCreateBy(createBy);
  739. authPo.setCreateSource(1);
  740. authPo.setFirstClubType(5);
  741. // 导入数据
  742. ResponseJson result = saveAuth(authPo, null, true, 1);
  743. if (result.getCode() != 0) {
  744. // 设置手动回滚事务
  745. TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  746. return ResponseJson.error("导入失败");
  747. }
  748. }
  749. return ResponseJson.success("导入成功");
  750. }
  751. /**
  752. * 获取机构关联的机构信息
  753. * 1.7.4版本:
  754. */
  755. @Override
  756. public ResponseJson<List<AuthFormVo>> getRelationgInfo(String snCode, Integer authUserId) {
  757. //根据sn码获取关联这个产品的机构列表
  758. List<ProductFormVo> relationgList = authMapper.getRelationgList(snCode);
  759. String relationgInfo = null;
  760. List<AuthFormVo> authIdList = null;
  761. if (relationgList.size() > 0) {
  762. for (int i = 0; i < relationgList.size(); i++) {
  763. if (null != relationgInfo) {
  764. relationgInfo += ",";
  765. }
  766. relationgInfo += relationgList.get(i).getRelationId();
  767. }
  768. if (null != relationgInfo) {
  769. String[] relationIdList = relationgInfo.split(",");
  770. authIdList = authMapper.getAuthIdList(relationIdList);
  771. }
  772. }
  773. return ResponseJson.success(authIdList);
  774. }
  775. /**
  776. * 1.7.4版本
  777. * 获取可绑定机构机构信息
  778. **/
  779. @Override
  780. public ResponseJson<List<AuthFormVo>> getClubBindAuth(Integer authUserId) {
  781. List<AuthFormVo> clubBindAuth = authMapper.getClubBindAuth(authUserId);
  782. return ResponseJson.success(clubBindAuth);
  783. }
  784. //------------------------------------------v1.7.5上传视频至抖音---------------------------------------------------------------------------------------
  785. ///用户授权(用于获取数据)
  786. /**
  787. * 用户扫码授权,获取code值
  788. * @param response
  789. * @return true :token没过期 false:token过期需重新授权
  790. * @throws IOException
  791. */
  792. @Override
  793. public ResponseJson getDouYingCode(HttpServletResponse response) throws IOException {
  794. //验证是否是第一次登录(根据redis缓存中的token验证)
  795. // long dYaccessTok = redisService.getExpireTime("DYaccessToken");
  796. // boolean s=redisService.exists("DYaccessToken");
  797. // String s1= redisService.get("DyopenId").toString();
  798. //// if(!redisService.exists("DYaccessToken")){
  799. // //验证token是否过期
  800. // long dYaccessToken = redisService.getExpireTime("DYaccessToken");
  801. // if(dYaccessToken<=0){ //tonken过期
  802. // //判断refreshToken是否过期
  803. // long DyrefreshToken = redisService.getExpireTime("DyrefreshToken");
  804. // if(DyrefreshToken>=0){ //refreshToken
  805. // //根据refreshToken刷新token,重新缓存token
  806. // String refreshToken=redisService.get("DyrefreshToken").toString();
  807. // String accessToken = refreshAccessToken(refreshToken);
  808. // redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15);
  809. // boolean flag= redisService.exists("DYaccessToken");
  810. // return ResponseJson.success(true);
  811. // }else{ //根据refreshToken刷新refreshToken(总共可以刷新3次,次数完后需重新扫码授权)
  812. // String refreshToken=redisService.get("DyrefreshToken").toString();
  813. // String newRefreshToken = resetRefreshAccessToken(refreshToken);
  814. // if(StringUtils.isNotEmpty(newRefreshToken)){
  815. // String accessToken = refreshAccessToken(newRefreshToken);
  816. // redisService.set("DYaccessToken",accessToken,60L * 60 * 24 * 15);
  817. // return ResponseJson.success(true);
  818. // }
  819. // }
  820. // }else {
  821. // return ResponseJson.success(true);
  822. // }
  823. // }
  824. //验证token是否过期
  825. // long dYaccessToken = redisService.getExpireTime("DYaccessToken");
  826. return redisService.getExpireTime("DYaccessToken")<0 ? ResponseJson.success(false): ResponseJson.success(true);
  827. // String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  828. // String responestype = "code";//写死为'code'即可
  829. // String scope = "video.data,video.list,trial.whitelist,data.external.item";//应用授权作用域,多个授权作用域以英文逗号(,)分隔
  830. // String redirectUrl = "https://www.caimei365.com";//回调地址,应用中配置
  831. // String state = "false";//用于保持请求和回调的状态
  832. // String code = "https://open.douyin.com/platform/oauth/connect/?client_key=" + clintKey
  833. // + "&response_type=" + responestype + "&scope=" + scope + "&redirect_uri=" + redirectUrl + "&state=" + state;
  834. // response.sendRedirect(code);
  835. }
  836. /**
  837. * 清除抖音授权token缓存
  838. * @return
  839. */
  840. @GetMapping("/clean/douyin/redis")
  841. public ResponseJson cleanDYRedis(){
  842. redisService.remove("DYaccessToken");
  843. redisService.remove("DyrefreshToken");
  844. redisService.remove("DyopenId");
  845. return ResponseJson.success();
  846. }
  847. /**
  848. * 根据用户的code值获取AcessToken
  849. * ccode 用户授权登录code
  850. **/
  851. @Override
  852. public ResponseJson getDouYingAcessToken(String code) throws IOException {
  853. String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  854. String clintSecret = "1dd7446d29e16738787447b771ced2df";//应用唯一标识对应的密钥
  855. String grantType = "authorization_code";//固定值
  856. String requestUrl = "https://open.douyin.com/oauth/access_token/";//请求地址
  857. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  858. //创建httppost对象
  859. HttpPost hp = new HttpPost(requestUrl);
  860. hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  861. // hp.setHeader("Content-Type","application/x-www-form-urlencoded");
  862. //拼接请求参数
  863. List<NameValuePair> list = new ArrayList();
  864. list.add(new BasicNameValuePair("client_key", clintKey));
  865. list.add(new BasicNameValuePair("client_secret", clintSecret));
  866. list.add(new BasicNameValuePair("code", code));
  867. list.add(new BasicNameValuePair("grant_type", grantType));
  868. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
  869. hp.setEntity(entity);
  870. //发送请求
  871. CloseableHttpResponse execute = closeableHttpClient.execute(hp);
  872. HttpEntity he = execute.getEntity();
  873. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  874. //获取access_token,open_id(用于获取视频数据),refresh_token(刷新token)
  875. JSONObject jsonObject =JSONObject.parseObject(result);
  876. String data = jsonObject.getString("data");
  877. JSONObject params =JSONObject.parseObject(data);
  878. String accessToken = params.getString("access_token");
  879. String openId = params.getString("open_id");
  880. String refreshToken = params.getString("refresh_token");
  881. String errorCode = params.getString("error_code");
  882. if(Integer.valueOf(errorCode)>0){return ResponseJson.success("tonken缓存失败",null);}
  883. //用redis缓存access_token,refresh_token
  884. redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15);// * 60 * 24 * 15
  885. redisService.set("DyrefreshToken",refreshToken,60L * 60 * 24 * 30);
  886. redisService.set("DyopenId",openId,60L * 60 * 24 * 30);
  887. EntityUtils.consume(he);
  888. String DYaccessToken=redisService.get("DYaccessToken").toString();
  889. String DyrefreshToken=redisService.get("DyrefreshToken").toString();
  890. String DyopenId=redisService.get("DyopenId").toString();
  891. if (StringUtils.isNotEmpty(DYaccessToken)&&StringUtils.isNotEmpty(DyrefreshToken)&&StringUtils.isNotEmpty(DyopenId)){
  892. return ResponseJson.success();
  893. }else {
  894. return ResponseJson.success("tonken缓存失败",null);
  895. }
  896. }
  897. /**
  898. * 刷新tonken
  899. * @param refreshToken
  900. */
  901. public String refreshAccessToken(String refreshToken){
  902. String requestUrl="https://open.douyin.com/oauth/refresh_token/";
  903. String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  904. String grantType = "refresh_token";//固定值
  905. String accessToken=null;
  906. //创建httppost对象
  907. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  908. HttpPost hp = new HttpPost(requestUrl);
  909. hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
  910. // hp.setHeader("Content-Type","application/x-www-form-urlencoded");
  911. //拼接请求参数
  912. List<NameValuePair> list = new ArrayList();
  913. list.add(new BasicNameValuePair("client_key", clintKey));
  914. list.add(new BasicNameValuePair("grant_type", grantType));
  915. list.add(new BasicNameValuePair("refresh_token", refreshToken));
  916. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
  917. hp.setEntity(entity);
  918. try {
  919. CloseableHttpResponse execute = closeableHttpClient.execute(hp);
  920. HttpEntity he = execute.getEntity();
  921. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  922. JSONObject params=JSONObject.parseObject(result);
  923. String data=params.getString("data");
  924. JSONObject datalist=JSONObject.parseObject(data);
  925. accessToken=datalist.getString("access_token");
  926. EntityUtils.consume(he);
  927. } catch (IOException e) {
  928. e.printStackTrace();
  929. }
  930. hp.setEntity(entity);
  931. return accessToken;
  932. }
  933. /**
  934. * 刷新refreshAccessToken
  935. * @param refreshToken
  936. */
  937. public String resetRefreshAccessToken(String refreshToken){
  938. String requestUrl="https://open.douyin.com/oauth/renew_refresh_token/";
  939. String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
  940. String renewRefreshAccessToken=null;
  941. //创建httppost对象
  942. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  943. HttpPost hp = new HttpPost(requestUrl);
  944. List<NameValuePair> list = new ArrayList();
  945. list.add(new BasicNameValuePair("client_key", clintKey));
  946. list.add(new BasicNameValuePair("refresh_token", refreshToken));
  947. list.add(new BasicNameValuePair("Content-Type", "multipart/form-data"));
  948. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
  949. hp.setEntity(entity);
  950. try {
  951. CloseableHttpResponse execute = closeableHttpClient.execute(hp);
  952. HttpEntity he = execute.getEntity();
  953. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  954. JSONObject jsonObject=JSONObject.parseObject(result);
  955. String data = jsonObject.getString("data");
  956. JSONObject params=JSONObject.parseObject(data);
  957. renewRefreshAccessToken = params.getString("refresh_token");
  958. EntityUtils.consume(he);
  959. } catch (IOException e) {
  960. e.printStackTrace();
  961. }
  962. hp.setEntity(entity);
  963. return renewRefreshAccessToken;
  964. }
  965. //----------------------------------------------------h5的方式上传视频------------------------------------------------
  966. /**
  967. * h5的方式上传视频
  968. * @return
  969. * @throws IOException
  970. */
  971. @Override
  972. public ResponseJson getclientToken(String title,String videoPath,Integer authId) throws IOException {
  973. //获取accessToken
  974. String client_key = "awwwvh9tsnvo54w1";
  975. String client_secret = "1dd7446d29e16738787447b771ced2df";
  976. String grant_type = "client_credential";
  977. String url = "https://open.douyin.com/oauth/client_token/?client_key=" + client_key
  978. + "&client_secret=" + client_secret
  979. + "&grant_type=" + grant_type;
  980. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  981. //创建httppost对象
  982. HttpPost hp = new HttpPost(url);
  983. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  984. builder.setCharset(Consts.UTF_8);
  985. builder.setContentType(ContentType.MULTIPART_FORM_DATA);
  986. //构建参数
  987. HttpEntity entity = builder.build();
  988. hp.setEntity(entity);
  989. CloseableHttpResponse response = null;
  990. String schema=null;
  991. try {
  992. response = closeableHttpClient.execute(hp);
  993. HttpEntity he = response.getEntity();
  994. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  995. //把返回结果转json获取access_token
  996. JSONObject jsonObject=JSONObject.parseObject(result);
  997. String data=jsonObject.getString("data");
  998. JSONObject params=JSONObject.parseObject(data);
  999. String accessToken=params.getString("access_token");
  1000. //根据accesstoken获取tiket
  1001. schema = getDouYingTicket(accessToken, title,videoPath,authId);
  1002. EntityUtils.consume(he);
  1003. } catch (IOException e) {
  1004. e.printStackTrace();
  1005. }
  1006. return ResponseJson.success(schema);
  1007. }
  1008. /**
  1009. * 根据token获取ticket
  1010. **/
  1011. @RequestMapping("/getDouYingTicket")
  1012. public String getDouYingTicket(String clientToken,String title,String videoPath,Integer authId) throws IOException {
  1013. //时间戳
  1014. long l = System.currentTimeMillis();
  1015. String timestamp = String.valueOf(l);
  1016. //随机数
  1017. String noncestr = randomGen(16);
  1018. String uri = "https://open.douyin.com/open/getticket/";
  1019. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  1020. HttpGet httpGet = new HttpGet(uri);
  1021. httpGet.setHeader("access-token", clientToken);
  1022. httpGet.setHeader("Content-Type","application/json");
  1023. CloseableHttpResponse response = null;
  1024. String schema=null;
  1025. try {
  1026. response = closeableHttpClient.execute(httpGet);
  1027. HttpEntity he = response.getEntity();
  1028. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  1029. //获取ticket
  1030. JSONObject jsonObject=JSONObject.parseObject(result);
  1031. String data = jsonObject.getString("data");
  1032. JSONObject params=JSONObject.parseObject(data);
  1033. String ticket = params.getString("ticket");
  1034. //getDouYingshareId
  1035. String shareId = getDouYingshareId(clientToken);
  1036. //保存shareId用于回调时存储item_id
  1037. authMapper.savaShareIdByAuthId(authId,shareId);
  1038. //获取签名 并且用md5加密
  1039. String signature = signatureAlgorithm(ticket, timestamp,noncestr);
  1040. //获取schema(返回前端用于生成二维码发布视频)
  1041. schema = appendSchema(signature, shareId, timestamp,noncestr, title, videoPath);
  1042. EntityUtils.consume(he);
  1043. } catch (IOException e) {
  1044. e.printStackTrace();
  1045. }
  1046. return schema;
  1047. }
  1048. /**
  1049. * 获取签名 并且用md5加密
  1050. * ticket
  1051. **/
  1052. @RequestMapping("/signatureAlgorithm")
  1053. public String signatureAlgorithm(String ticket, String timestamp,String noncestr) {
  1054. TreeMap<String, String> treeMap = new TreeMap<>();
  1055. treeMap.put("nonce_str", noncestr);
  1056. treeMap.put("ticket", ticket);
  1057. treeMap.put("timestamp", timestamp);
  1058. StringBuffer stringBuffer = new StringBuffer();
  1059. Iterator<Map.Entry<String, String>> it = treeMap.entrySet().iterator();
  1060. while (it.hasNext()) {
  1061. Map.Entry<String, String> entry = it.next();
  1062. stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
  1063. }
  1064. String result = stringBuffer.substring(0, stringBuffer.length() - 1);
  1065. //进行md5签名
  1066. String signature = Md5Util.md5(result).toLowerCase();
  1067. return signature;
  1068. }
  1069. /**
  1070. * Schema 生成
  1071. **/
  1072. public String appendSchema(String signature, String shareId, String timestamp,String noncestr,String title,String videoPath) {
  1073. URIBuilder uri = null;
  1074. String schema = null;
  1075. try {
  1076. uri = new URIBuilder("snssdk1128://openplatform/share");// snssdk1128://openplatform/share snssdk1128://deeplink/openplatform
  1077. uri.addParameter("share_type", "h5");//固定h5
  1078. uri.addParameter("client_key", "awwwvh9tsnvo54w1");//应用唯一标识
  1079. uri.addParameter("nonce_str", noncestr);//随机数(必须和签名时的nonce_str一致)
  1080. uri.addParameter("timestamp", timestamp);//时间戳(必须和签名时的timestamp一致)
  1081. uri.addParameter("signature", signature);//签名
  1082. uri.addParameter("state", shareId);//通过方法获取(基于webhook,获取视频发布回调信息,不传则收不到回调信息)
  1083. //https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4
  1084. //视频地址(必须为网络地址,本地地址无法发布)单视频上传
  1085. uri.addParameter("video_path",videoPath);//"https://caimei-oss.oss-cn-shenzhen.aliyuncs.com/beta/authFile/5c7bfb6e-9919-48b1-a905-88a888f22a11.mp4");//https://caimei-oss.oss-cn-shenzhen.aliyuncs.com/beta/authFile/5c7bfb6e-9919-48b1-a905-88a888f22a11.mp4
  1086. uri.addParameter("share_to_publish", "1");//为1则直接发布视频至抖音
  1087. uri.addParameter("title",title);//"给大佐都整emo了");//视频标题
  1088. schema = uri.toString();
  1089. } catch (URISyntaxException e) {
  1090. e.printStackTrace();
  1091. }
  1092. return schema;
  1093. }
  1094. /**
  1095. * 获取shareId 用于生成schema
  1096. **/
  1097. @RequestMapping("/getDouYingshareId")
  1098. public String getDouYingshareId(String clientToken) throws IOException {
  1099. String uri = "https://open.douyin.com/share-id/?need_callback=true&default_hashtag=hashtag";
  1100. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  1101. HttpGet httpGet = new HttpGet(uri);
  1102. httpGet.setHeader("access-token", clientToken);
  1103. CloseableHttpResponse response = null;
  1104. String shareId = "";
  1105. try {
  1106. response = closeableHttpClient.execute(httpGet);
  1107. HttpEntity he = response.getEntity();
  1108. String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
  1109. JSONObject jsonObject=JSONObject.parseObject(result);
  1110. String data = jsonObject.getString("data");
  1111. JSONObject params=JSONObject.parseObject(data);
  1112. shareId = params.getString("share_id");
  1113. EntityUtils.consume(he);
  1114. } catch (IOException e) {
  1115. e.printStackTrace();
  1116. }
  1117. return shareId;
  1118. }
  1119. /**
  1120. * 获取已发布视频列表
  1121. * @param openId 用户唯一标志
  1122. * @param cursor 分页游标, 第一页请求cursor是0, response中会返回下一页请求用到的cursor, 同时response还会返回has_more来表明是否有更多的数据。
  1123. * @param count 每页数量 10
  1124. */
  1125. public String getVideoList(String openId,Long cursor,Integer count,String accessToken){
  1126. String requestUrl="https://open.douyin.com/video/list/?open_id="+openId+"&cursor="+cursor+"&count="+count;
  1127. //创建httppost对象
  1128. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  1129. HttpGet hg = new HttpGet(requestUrl);
  1130. hg.setHeader("Content-Type","application/json");
  1131. hg.addHeader("access-token",accessToken);
  1132. String resultList=null;
  1133. try {
  1134. CloseableHttpResponse execute = closeableHttpClient.execute(hg);
  1135. HttpEntity entity = execute.getEntity();
  1136. String result=EntityUtils.toString(entity,StandardCharsets.UTF_8);
  1137. JSONObject jsonObject = JSONObject.parseObject(result);
  1138. resultList = jsonObject.getString("data");
  1139. // resultList = JSONArray.parseArray(itemIdlist);
  1140. // String itemId = params.getJSONObject(0).get("item_id").toString();
  1141. //根据itemid获取视频的数据(点赞,播放,评论量)
  1142. EntityUtils.consume(entity);
  1143. } catch (IOException e) {
  1144. e.printStackTrace();
  1145. }
  1146. return resultList;
  1147. }
  1148. /**
  1149. * 根据item_id获取单个(多个)视频信息
  1150. * @param openId
  1151. * @param accessToken
  1152. * itemId 多个用,隔开
  1153. * @return
  1154. */
  1155. public String getVideoDataByItemId(String openId, String accessToken,String itemId) {
  1156. String requestUrl = "https://open.douyin.com/video/data/?open_id="+openId;
  1157. CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  1158. HttpPost hp = new HttpPost(requestUrl);
  1159. hp.addHeader("access-token", accessToken);
  1160. hp.addHeader("Content-Type", "application/json");
  1161. // List<NameValuePair> list = new ArrayList<>();
  1162. // list.add(new BasicNameValuePair("item_ids",jsonArray.toString()));
  1163. // JSONObject json = new JSONObject();
  1164. // json.put("item_ids",itemId);
  1165. // json.put("item_ids",itemid1);
  1166. // "{\"item_ids\":[\"@9VwTweWaBd0jMWGuNYwqEc791GHuNf6KPZx5qgiiLVQbbvf860zdRmYqig357zEBpu0x/J8bThza3PQPj7FY1Q==\"]}"
  1167. String s="{\"item_ids\":["+"\""+itemId+"\""+"]}";
  1168. hp.setEntity(new StringEntity(s,"UTF-8"));
  1169. String datastr=null;
  1170. try {
  1171. CloseableHttpResponse execute = closeableHttpClient.execute(hp);
  1172. HttpEntity entity = execute.getEntity();
  1173. String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
  1174. JSONObject params=JSONObject.parseObject(result);
  1175. datastr=params.getString("data");
  1176. // JSONObject data=JSONObject.parseObject(datastr);
  1177. // String list=data.getString("list");
  1178. // System.out.println(list);
  1179. EntityUtils.consume(entity);
  1180. } catch (IOException e) {
  1181. e.printStackTrace();
  1182. }
  1183. return datastr;
  1184. }
  1185. /**
  1186. * 生成随机数
  1187. *
  1188. * @param place
  1189. * @return
  1190. */
  1191. public String randomGen(int place) {
  1192. String base = "wqetryuioplkjhgfdsazxcvbmnABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1193. StringBuffer sb = new StringBuffer();
  1194. Random rd = new Random();
  1195. for (int i = 0; i < place; i++) {
  1196. sb.append(base.charAt(rd.nextInt(base.length())));
  1197. }
  1198. return sb.toString();
  1199. }
  1200. /**
  1201. * 保存视频信息
  1202. * @return
  1203. */
  1204. @Override
  1205. public ResponseJson saveVideoInfo(ChallengeRoundVo cr){
  1206. Date date=new Date();
  1207. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1208. String releaseTime = sf.format(date).replace("T", "");
  1209. authMapper.saveVideoInfo(cr.getUserName(),cr.getCover(),cr.getOssUrl(),cr.getOssName(),cr.getTitle(),releaseTime,cr.getAuthId(),cr.getAuthUserId());
  1210. return ResponseJson.success("保存成功",null);
  1211. }
  1212. /**
  1213. * 根据authid获取authUserId
  1214. * @param authId
  1215. * @return
  1216. */
  1217. @Override
  1218. public boolean getauthUserId(Integer authId){
  1219. String authUserId= authMapper.getauthUserId(authId);
  1220. return StringUtils.isEmpty(authUserId);
  1221. }
  1222. /**
  1223. * 判断是否存在userName
  1224. * @param userName
  1225. * @return
  1226. */
  1227. @Override
  1228. public boolean getuserName(String userName){
  1229. String name= authMapper.getuserName(userName);
  1230. return StringUtils.isEmpty(name);
  1231. }
  1232. /**
  1233. * 验证是否在活动时间内
  1234. * @param releaseTime 发布时间
  1235. * @return
  1236. */
  1237. @Override
  1238. public boolean checkActivityTime(String releaseTime){
  1239. Integer id= authMapper.checkActivityTime(releaseTime);
  1240. return id==null?true:false;
  1241. }
  1242. /**
  1243. * 获取已发布视频列表(前端)
  1244. * @param clubUserName 手机号或者机构名
  1245. * @param status 用户发布状态
  1246. * @param cursor 页码
  1247. * @param count 条数
  1248. * @return
  1249. */
  1250. @Override
  1251. public ResponseJson<PageInfo<ChallengeRoundVo>> getPublishedVideoList(String clubUserName,Integer status,Integer cursor,Integer count,Integer pageNum,Integer pageSize,Integer authUserId){
  1252. PageHelper.startPage(pageNum, pageSize);
  1253. ChallengeActivityVo activityTime = authMapper.getActivityTime(authUserId);
  1254. List<ChallengeRoundVo> listChallengeRoundVo=authMapper.getPublishedVideoList(clubUserName,status,authUserId,activityTime.getStartTime(),activityTime.getEndTime());
  1255. PageInfo<ChallengeRoundVo> pageData = new PageInfo<>(listChallengeRoundVo);
  1256. //调用抖音api获取视频数据
  1257. String dyopenId=null;
  1258. String DYaccessToken=null;
  1259. if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){
  1260. dyopenId=redisService.get("DyopenId").toString();
  1261. DYaccessToken=redisService.get("DYaccessToken").toString();
  1262. }
  1263. Long flag=1l;
  1264. List<DyVideoInfoVo> list=new ArrayList<>();
  1265. //递归获取抖音账号下所有视频数据
  1266. while (flag!=0){
  1267. if (flag==1){flag=0l;}
  1268. String data = getVideoList(dyopenId, flag, count, DYaccessToken);
  1269. JSONObject paramslist = JSONObject.parseObject(data);
  1270. Integer error_code = Integer.valueOf(paramslist.getString("error_code"));
  1271. if(error_code>0){
  1272. //抖音视频数据全部获取完,终止循环
  1273. break;
  1274. }
  1275. String resultList = paramslist.getString("list");
  1276. String cor = paramslist.getString("cursor");
  1277. flag=Long.parseLong(cor);
  1278. List<DyVideoInfoVo> listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class);
  1279. if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){
  1280. for (DyVideoInfoVo dv:listDyVideoInfoVo) {
  1281. list.add(dv);
  1282. }
  1283. }
  1284. }
  1285. //根据itemId给对应视频赋值(点赞量,播放量)
  1286. if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){
  1287. for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) {
  1288. if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){
  1289. ChallengeRoundVo.setDiggCount("0");
  1290. }
  1291. if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){
  1292. ChallengeRoundVo.setPlayCount("0");
  1293. }
  1294. if(list!=null&&list.size()>0){
  1295. for (DyVideoInfoVo dyVideoInfoVo:list) {
  1296. if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){
  1297. StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class);
  1298. ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count());
  1299. ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count());
  1300. break;
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. //根据点赞量降序排序
  1307. // PageHelper.startPage(pageNum, pageSize);
  1308. List<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
  1309. //获取排名数据
  1310. for (ChallengeRoundVo chall:collect) {
  1311. chall.setRankingStatus(1);
  1312. }
  1313. List<ChallengeRoundVo> publishedVideoListNoRanking = authMapper.getPublishedVideoListNoRanking(clubUserName, status, authUserId, activityTime.getStartTime(), activityTime.getEndTime());
  1314. //获取不排名的数据
  1315. if(publishedVideoListNoRanking.size()>0&&listChallengeRoundVo.size()>0){
  1316. for (ChallengeRoundVo noRanking:publishedVideoListNoRanking) {
  1317. noRanking.setRankingStatus(0);
  1318. if(StringUtils.isEmpty(noRanking.getDiggCount())){
  1319. noRanking.setDiggCount("0");
  1320. }
  1321. if(StringUtils.isEmpty(noRanking.getPlayCount())){
  1322. noRanking.setPlayCount("0");
  1323. }
  1324. collect.add(noRanking);
  1325. }
  1326. }else{
  1327. for (ChallengeRoundVo noRanking:publishedVideoListNoRanking) {
  1328. noRanking.setRankingStatus(1);
  1329. if(StringUtils.isEmpty(noRanking.getDiggCount())){
  1330. noRanking.setDiggCount("0");
  1331. }
  1332. if(StringUtils.isEmpty(noRanking.getPlayCount())){
  1333. noRanking.setPlayCount("0");
  1334. }
  1335. collect.add(noRanking);
  1336. }
  1337. }
  1338. PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
  1339. return ResponseJson.success(pageDa);
  1340. }
  1341. /**
  1342. * 获取已发布视频列表(后端)
  1343. * @param mobile
  1344. * @param authParty
  1345. * @param status
  1346. * @param cursor
  1347. * @param count
  1348. * @param authUserId
  1349. * @return
  1350. */
  1351. @Override
  1352. public ResponseJson<PageInfo<ChallengeRoundVo>> getPublishedVideo(String mobile,String authParty,Integer status,Integer cursor,Integer count,Integer authUserId,Integer pageNum,Integer pageSize,String startTIme,String endTime){
  1353. PageHelper.startPage(pageNum, pageSize);
  1354. List<ChallengeRoundVo> listChallengeRoundVo=null;
  1355. ChallengeActivityVo activityTime = authMapper.getActivityTime(authUserId);
  1356. if(StringUtils.isNotEmpty(startTIme)&&StringUtils.isNotEmpty(endTime)){
  1357. listChallengeRoundVo=authMapper.getPublishedVideo(mobile,authParty,status,authUserId,startTIme,endTime);
  1358. }else{
  1359. if(activityTime!=null){
  1360. listChallengeRoundVo=authMapper.getPublishedVideo(mobile,authParty,status,authUserId,activityTime.getStartTime(),activityTime.getEndTime());
  1361. }else{
  1362. listChallengeRoundVo=authMapper.getPublishedVideo(mobile,authParty,status,authUserId,null,null);
  1363. }
  1364. }
  1365. PageInfo<ChallengeRoundVo> pageData = new PageInfo<>(listChallengeRoundVo);
  1366. //调用抖音api获取视频数据
  1367. String dyopenId=null;
  1368. String DYaccessToken=null;
  1369. if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){
  1370. dyopenId=redisService.get("DyopenId").toString();
  1371. DYaccessToken=redisService.get("DYaccessToken").toString();
  1372. }
  1373. Long flag=1l;
  1374. List<DyVideoInfoVo> list=new ArrayList<>();
  1375. //递归获取抖音账号下所有视频数据
  1376. while (flag!=0){
  1377. if (flag==1){flag=0l;}
  1378. String data = getVideoList(dyopenId, flag, count, DYaccessToken);
  1379. JSONObject paramslist = JSONObject.parseObject(data);
  1380. Integer error_code = Integer.valueOf(paramslist.getString("error_code"));
  1381. if(error_code>0){
  1382. //视频数据获取完,终止循环
  1383. break;
  1384. }
  1385. String resultList = paramslist.getString("list");
  1386. String cor = paramslist.getString("cursor");
  1387. flag=Long.parseLong(cor);
  1388. List<DyVideoInfoVo> listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class);
  1389. if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){
  1390. for (DyVideoInfoVo dv:listDyVideoInfoVo) {
  1391. list.add(dv);
  1392. }
  1393. }
  1394. }
  1395. //根据itemId给对应视频赋值(点赞量,播放量)
  1396. if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){
  1397. for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) {
  1398. if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){
  1399. ChallengeRoundVo.setDiggCount("0");
  1400. }
  1401. if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){
  1402. ChallengeRoundVo.setPlayCount("0");
  1403. }
  1404. if(list!=null&&list.size()>0){
  1405. for (DyVideoInfoVo dyVideoInfoVo:list) {
  1406. if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){
  1407. StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class);
  1408. ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count());
  1409. ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count());
  1410. break;
  1411. }
  1412. }
  1413. }
  1414. }
  1415. }
  1416. //根据点赞量降序排序
  1417. // PageHelper.startPage(pageNum, pageSize);
  1418. List<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
  1419. //获取排名数据
  1420. for (ChallengeRoundVo chall:collect) {
  1421. chall.setRankingStatus(1);
  1422. }
  1423. PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
  1424. //获取不排名的数据
  1425. List<ChallengeRoundVo> publishedVideoListNoRanking=null;
  1426. if(StringUtils.isNotEmpty(startTIme)&&StringUtils.isNotEmpty(endTime)){
  1427. publishedVideoListNoRanking = authMapper.getPublishedVideoNoRanking(mobile,authParty,status,authUserId,startTIme,endTime);
  1428. }else{
  1429. if(activityTime!=null){
  1430. publishedVideoListNoRanking = authMapper.getPublishedVideoNoRanking(mobile,authParty,status,authUserId,activityTime.getStartTime(),activityTime.getEndTime());
  1431. }else{
  1432. publishedVideoListNoRanking = authMapper.getPublishedVideoNoRanking(mobile,authParty,status,authUserId,null,null);
  1433. }
  1434. }
  1435. //获取不排名的数据
  1436. if(publishedVideoListNoRanking.size()>0&&listChallengeRoundVo.size()>0){
  1437. for (ChallengeRoundVo noRanking:publishedVideoListNoRanking) {
  1438. noRanking.setRankingStatus(0);
  1439. if(StringUtils.isEmpty(noRanking.getDiggCount())){
  1440. noRanking.setDiggCount("0");
  1441. }
  1442. if(StringUtils.isEmpty(noRanking.getPlayCount())){
  1443. noRanking.setPlayCount("0");
  1444. }
  1445. collect.add(noRanking);
  1446. }
  1447. }else{
  1448. for (ChallengeRoundVo noRanking:publishedVideoListNoRanking) {
  1449. noRanking.setRankingStatus(1);
  1450. if(StringUtils.isEmpty(noRanking.getDiggCount())){
  1451. noRanking.setDiggCount("0");
  1452. }
  1453. if(StringUtils.isEmpty(noRanking.getPlayCount())){
  1454. noRanking.setPlayCount("0");
  1455. }
  1456. collect.add(noRanking);
  1457. }
  1458. }
  1459. return ResponseJson.success(pageDa);
  1460. }
  1461. /**
  1462. * 获取机构已发布视频的机构下拉列表
  1463. * @param authUserId
  1464. * @return
  1465. */
  1466. @Override
  1467. public ResponseJson<List<ChallengeRoundVo>> getAuthPartylist(Integer authUserId){
  1468. return ResponseJson.success(authMapper.getAuthPartylist(authUserId));
  1469. }
  1470. /**
  1471. * 保存活动信息
  1472. * @param startTime
  1473. * @param endTime
  1474. * @param status
  1475. * @return
  1476. */
  1477. @Override
  1478. public ResponseJson saveActivityTime(String startTime,String endTime,Integer status,Integer authUserId){
  1479. //如果数据库有值则修改,没值则新增
  1480. List<ChallengeActivityVo> challengeList = authMapper.checkActivityId();
  1481. List<Integer> authUserIdList=new ArrayList<>();
  1482. for (ChallengeActivityVo ac:challengeList) {
  1483. authUserIdList.add(ac.getAuthUserId());
  1484. }
  1485. if(challengeList.size()<0||!authUserIdList.contains(authUserId)){
  1486. authMapper.saveActivityInfo(startTime,endTime,status,authUserId);
  1487. }else {
  1488. authMapper.upActivityInfo(startTime,endTime,status,authUserId);
  1489. }
  1490. return ResponseJson.success();
  1491. }
  1492. /**
  1493. * 获取活动信息
  1494. * @return
  1495. */
  1496. @Override
  1497. public ResponseJson<ChallengeActivityVo> getActivityTime(Integer authUserId){
  1498. Date date=new Date();
  1499. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1500. String releaseTime = sf.format(date).replace("T", "");
  1501. ChallengeActivityVo activityTime = authMapper.getActivityTime(authUserId);
  1502. //如果当前时间大于结束时间则活动状态置为未开启状态
  1503. if(activityTime!=null&&StringUtils.isNotEmpty(activityTime.getEndTime())){
  1504. if(activityTime.getEndTime().compareTo(releaseTime)<0){
  1505. activityTime.setStatus(0);
  1506. authMapper.upStatusById(activityTime.getId());
  1507. //
  1508. }
  1509. }
  1510. return ResponseJson.success(activityTime);
  1511. }
  1512. /**
  1513. * 判断shareId是否存在
  1514. * @param shareId
  1515. * @return
  1516. */
  1517. @Override
  1518. public boolean getShareId(String shareId){
  1519. return StringUtils.isNotEmpty(authMapper.getShareId(shareId));
  1520. }
  1521. /**
  1522. * 根据ShareId保存itemId (webhook触发时调用)
  1523. * @param shareId
  1524. * @param itemId
  1525. */
  1526. @Override
  1527. public void savaItemIdByShareId(String shareId,String itemId){
  1528. authMapper.savaItemIdByShareId(shareId,itemId);
  1529. }
  1530. @Override
  1531. public ResponseJson<ChallengeActivityVo> getActivitty(Integer authUserId){
  1532. ChallengeActivityVo activityTime = authMapper.getActivityTime(authUserId);
  1533. Date date=new Date();
  1534. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1535. String releaseTime = sf.format(date).replace("T", "");
  1536. if(activityTime!=null){
  1537. //当按钮关闭时,状态皆为已结束,开始时根据时间判断
  1538. if(activityTime.getStatus()==0){
  1539. activityTime.setActivityState(2);
  1540. }else{
  1541. if(activityTime.getStartTime().compareTo(releaseTime)>0){
  1542. activityTime.setActivityState(0);
  1543. }else if(activityTime.getStartTime().compareTo(releaseTime)<0&&activityTime.getEndTime().compareTo(releaseTime)>0){
  1544. activityTime.setActivityState(1);
  1545. }else {
  1546. activityTime.setActivityState(2);
  1547. }
  1548. }
  1549. }
  1550. return ResponseJson.success(activityTime);
  1551. }
  1552. /**
  1553. * 根据authId获取手机号
  1554. * @param authId
  1555. * @return
  1556. */
  1557. @Override
  1558. public String getMobileByAuthId(Integer authId){
  1559. return authMapper.getMobileByAuthId(authId);
  1560. }
  1561. /**
  1562. * 根据authId获取手机号
  1563. * @param authId
  1564. * @return
  1565. */
  1566. @Override
  1567. public String getAuthUserName(Integer authId){
  1568. return authMapper.getAuthUserName(authId);
  1569. }
  1570. /**
  1571. * 保存抖音口令
  1572. * @param authId
  1573. * @return
  1574. */
  1575. @Override
  1576. public void savaDyCommand(Integer authId,String content){
  1577. authMapper.savaDyCommand(authId,content);
  1578. }
  1579. /**
  1580. * 根据authId获取ossName
  1581. * @param videoID
  1582. * @return
  1583. */
  1584. @Override
  1585. public String getOssNameAuthId(Integer videoID){
  1586. return authMapper.getOssNameId(videoID);
  1587. }
  1588. /**
  1589. * 根据authId删除视频
  1590. * @param videoID
  1591. * @return
  1592. */
  1593. @Override
  1594. public void deleteVideoByAuthId(Integer videoID){
  1595. authMapper.deleteVideoById(videoID);
  1596. }
  1597. /**
  1598. * 根据手机号获取发布时间
  1599. * @param userName
  1600. * @return
  1601. */
  1602. @Override
  1603. public String getReleaseTime(String userName){
  1604. return authMapper.getReleaseTime(userName);
  1605. }
  1606. @Override
  1607. public ResponseJson downLoadChoseZip(String fileId,HttpServletResponse response){
  1608. if (fileId.contains(",")) {
  1609. String[] split = fileId.split(",");
  1610. ArrayList<ChallengeRoundVo> fileTreeVos = new ArrayList<>();
  1611. for (String s : split) {
  1612. ChallengeRoundVo file = authMapper.getChallengeRoundInfo(Integer.valueOf(s));
  1613. fileTreeVos.add(file);
  1614. }
  1615. //有package则在服务器固定路径new file.mkdir
  1616. UUID uuid = UUID.randomUUID();
  1617. String zipPath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/" + uuid;
  1618. String filePath = zipPath;
  1619. if ("dev".equals(active)) {
  1620. zipPath = "D:\\caimei-workSpace\\file\\" + uuid;
  1621. filePath = zipPath;
  1622. }
  1623. boolean mkdirs = new File(filePath).mkdirs();
  1624. Assert.isTrue(mkdirs, "文件夹创建失败");
  1625. for (ChallengeRoundVo challengeRoundVo : fileTreeVos) {
  1626. //普通文件直接下载到临时文件夹uuid下
  1627. String fileName = "";
  1628. String ossurl = challengeRoundVo.getOssUrl();
  1629. ossurl.indexOf(".");
  1630. String title=challengeRoundVo.getTitle();
  1631. Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]");
  1632. Matcher matcher = pattern.matcher(title);
  1633. title= matcher.replaceAll("");
  1634. if(title.length()>50){
  1635. title= title.substring(0,50);
  1636. }
  1637. if ("dev".equals(active)) {
  1638. fileName = zipPath + "\\"+title + ossurl.substring(ossurl.lastIndexOf("."));
  1639. } else {
  1640. fileName = zipPath + "/"+title + ossurl.substring(ossurl.lastIndexOf("."));
  1641. }
  1642. OSSUtils.downFileByFilePath("authFile/", challengeRoundVo.getOssName(), fileName);
  1643. // else {
  1644. // //文件夹在uuid文件夹下创建自己包名的文件夹
  1645. // String param = fileTreeVo.getId() + "," + authUserId;
  1646. // String myPath = "";
  1647. // myPath = filePath + "/" + fileTreeVo.getFileName();
  1648. // if ("dev".equals(active)) {
  1649. // myPath = filePath + "\\" + fileTreeVo.getFileName();
  1650. // }
  1651. // boolean dirs = new File(myPath).mkdirs();
  1652. // Assert.isTrue(dirs, "文件夹创建失败");
  1653. // recursion(param, myPath);
  1654. // }
  1655. }
  1656. //压缩
  1657. FileZipUtils.compress(zipPath, "", true);
  1658. String s = zipPath + ".zip";
  1659. String fileName = uuid + ".zip";
  1660. File file = new File(s);
  1661. try {
  1662. if (file.exists()) {
  1663. FileInputStream fileInputStream = new FileInputStream(file);
  1664. ServletOutputStream outputStream = response.getOutputStream();
  1665. // 设置下载文件的mineType,告诉浏览器下载文件类型
  1666. // int i = fileName.lastIndexOf(".");
  1667. // String substring = fileName.substring(i + 1, filePath.length());
  1668. response.setContentType("application/zip");
  1669. // 设置一个响应头,无论是否被浏览器解析,都下载
  1670. response.setHeader("Content-disposition", "attachment; filename=" + fileName);
  1671. byte[] bytes = new byte[1024];
  1672. int len;
  1673. while ((len = fileInputStream.read(bytes)) != -1) {
  1674. outputStream.write(bytes, 0, len);
  1675. }
  1676. fileInputStream.close();
  1677. outputStream.close();
  1678. }
  1679. } catch (IOException e) {
  1680. e.printStackTrace();
  1681. }
  1682. file.delete();
  1683. FileZipUtils.deleteFile(new File(zipPath));
  1684. }else {
  1685. ArrayList<ChallengeRoundVo> fileTreeVos = new ArrayList<>();
  1686. ChallengeRoundVo f = authMapper.getChallengeRoundInfo(Integer.valueOf(fileId));
  1687. fileTreeVos.add(f);
  1688. //有package则在服务器固定路径new file.mkdir
  1689. UUID uuid = UUID.randomUUID();
  1690. String zipPath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/" + uuid;
  1691. String filePath = zipPath;
  1692. if ("dev".equals(active)) {
  1693. zipPath = "D:\\caimei-workSpace\\file\\" + uuid;
  1694. filePath = zipPath;
  1695. }
  1696. boolean mkdirs = new File(filePath).mkdirs();
  1697. Assert.isTrue(mkdirs, "文件夹创建失败");
  1698. for (ChallengeRoundVo challengeRoundVo : fileTreeVos) {
  1699. //普通文件直接下载到临时文件夹uuid下
  1700. String fileName = "";
  1701. String ossurl = challengeRoundVo.getOssUrl();
  1702. String title=challengeRoundVo.getTitle();
  1703. Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]");
  1704. Matcher matcher = pattern.matcher(title);
  1705. title= matcher.replaceAll("");
  1706. if(title.length()>50){
  1707. title= title.substring(0,50);
  1708. }
  1709. if ("dev".equals(active)) {
  1710. fileName = zipPath + "\\"+title +ossurl.substring(ossurl.lastIndexOf("."));
  1711. } else {
  1712. fileName = zipPath + "/"+title + ossurl.substring(ossurl.lastIndexOf("."));
  1713. }
  1714. OSSUtils.downFileByFilePath("authFile/", challengeRoundVo.getOssName(), fileName);
  1715. // else {
  1716. // //文件夹在uuid文件夹下创建自己包名的文件夹
  1717. // String param = fileTreeVo.getId() + "," + authUserId;
  1718. // String myPath = "";
  1719. // myPath = filePath + "/" + fileTreeVo.getFileName();
  1720. // if ("dev".equals(active)) {
  1721. // myPath = filePath + "\\" + fileTreeVo.getFileName();
  1722. // }
  1723. // boolean dirs = new File(myPath).mkdirs();
  1724. // Assert.isTrue(dirs, "文件夹创建失败");
  1725. // recursion(param, myPath);
  1726. // }
  1727. }
  1728. //压缩
  1729. FileZipUtils.compress(zipPath, "", true);
  1730. String s = zipPath + ".zip";
  1731. String fileName = uuid + ".zip";
  1732. File file = new File(s);
  1733. try {
  1734. if (file.exists()) {
  1735. FileInputStream fileInputStream = new FileInputStream(file);
  1736. ServletOutputStream outputStream = response.getOutputStream();
  1737. // 设置下载文件的mineType,告诉浏览器下载文件类型
  1738. // int i = fileName.lastIndexOf(".");
  1739. // String substring = fileName.substring(i + 1, filePath.length());
  1740. response.setContentType("application/zip");
  1741. // 设置一个响应头,无论是否被浏览器解析,都下载
  1742. response.setHeader("Content-disposition", "attachment; filename=" + fileName);
  1743. byte[] bytes = new byte[1024];
  1744. int len;
  1745. while ((len = fileInputStream.read(bytes)) != -1) {
  1746. outputStream.write(bytes, 0, len);
  1747. }
  1748. fileInputStream.close();
  1749. outputStream.close();
  1750. }
  1751. } catch (IOException e) {
  1752. e.printStackTrace();
  1753. }
  1754. file.delete();
  1755. FileZipUtils.deleteFile(new File(zipPath));
  1756. }
  1757. return null;
  1758. }
  1759. /**
  1760. * 根据id获取信息
  1761. *
  1762. */
  1763. public ResponseJson<ChallengeRoundVo> getInfoById(Integer videoId) {
  1764. return ResponseJson.success(authMapper.getChallengeRoundInfo(videoId));
  1765. }
  1766. @Override
  1767. public ResponseJson getDyVidoInfo(Integer authUserId){
  1768. // 获取供应商用户id
  1769. // Integer userIdentity = sysUser.getUserIdentity();
  1770. // Integer authUserId = 2 == userIdentity ? sysUser.getId() : 3 == userIdentity ? sysUser.getParentId() : null;
  1771. String dyopenId=null;
  1772. String DYaccessToken=null;
  1773. Date date=new Date();
  1774. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1775. String now = sf.format(date).replace("T", "");
  1776. if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){
  1777. dyopenId=redisService.get("DyopenId").toString();
  1778. DYaccessToken=redisService.get("DYaccessToken").toString();
  1779. }
  1780. //获取供应商下面所有机构发的视频
  1781. List<ChallengeRoundVo> roundlist = authMapper.getRoundlist();
  1782. if(null !=roundlist && roundlist.size()>0){
  1783. //根据item_id更新视频数据(点赞量,播放量)
  1784. for (ChallengeRoundVo chall:roundlist) {
  1785. //如果当前时间大于活动结束时间则不再统计
  1786. ChallengeActivityVo activityTime = authMapper.getActivityTime(chall.getAuthUserId());
  1787. if(null !=activityTime && now.compareTo(activityTime.getEndTime())<0){
  1788. String data = getVideoDataByItemId(dyopenId, DYaccessToken, chall.getItemId());
  1789. JSONObject paramslist = JSONObject.parseObject(data);
  1790. String resultList=paramslist.getString("list");
  1791. List<DyVideoInfoVo> listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class);
  1792. if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){
  1793. StatisticsVo StatisticsVo= JSONObject.parseObject(listDyVideoInfoVo.get(0).getStatistics(), StatisticsVo.class);
  1794. //更新视频数据到数据库
  1795. authMapper.upVidoInfoById(chall.getId(),StatisticsVo.getDigg_count(),StatisticsVo.getPlay_count());
  1796. }
  1797. }
  1798. }
  1799. }
  1800. return ResponseJson.success();
  1801. }
  1802. }