AuthServiceImpl.java 81 KB

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