AuthServiceImpl.java 82 KB

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