AuthServiceImpl.java 63 KB

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