123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452 |
- package com.caimei.service.auth.impl;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.caimei.components.RedisService;
- import com.caimei.config.FastDfsClient;
- import com.caimei.mapper.cmMapper.AuthMapper;
- import com.caimei.mapper.cmMapper.AuthProductMapper;
- import com.caimei.mapper.ldmMapper.LdmMapper;
- import com.caimei.model.ResponseJson;
- import com.caimei.model.po.*;
- import com.caimei.model.vo.*;
- import com.caimei.service.auth.AuthProductService;
- import com.caimei.service.auth.AuthService;
- import com.caimei.service.auth.ShopService;
- import com.caimei.service.auth.UploadService;
- import com.caimei.utils.Base64Util;
- import com.caimei.utils.ImageUtils;
- import com.caimei.utils.Md5Util;
- import com.github.pagehelper.PageHelper;
- import com.github.pagehelper.PageInfo;
- import lombok.extern.slf4j.Slf4j;
- import lombok.val;
- import org.apache.commons.lang3.ObjectUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.http.Consts;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.utils.URIBuilder;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- import org.apache.poi.ss.usermodel.*;
- import org.apache.poi.xssf.usermodel.*;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.transaction.interceptor.TransactionAspectSupport;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
- import javax.annotation.Resource;
- import javax.imageio.ImageIO;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.Font;
- import java.io.*;
- import java.math.BigDecimal;
- import java.net.URISyntaxException;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.List;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- /**
- * Description
- *
- * @author : Aslee
- * @date : 2021/5/11
- */
- @Slf4j
- @Service
- public class AuthServiceImpl implements AuthService {
- @Resource
- private AuthMapper authMapper;
- @Resource
- private LdmMapper ldmMapper;
- @Value("${caimei.zpapi}")
- private String zpServer;
- private AuthProductService authProductService;
- @Autowired
- public void setAuthProductService(AuthProductService authProductService) {
- this.authProductService = authProductService;
- }
- private ShopService shopService;
- @Autowired
- public void setShopService(ShopService shopService) {
- this.shopService = shopService;
- }
- private UploadService uploadService;
- @Autowired
- public void setUploadService(UploadService uploadService) {
- this.uploadService = uploadService;
- }
- @Value("${spring.profiles.active}")
- private String active;
- @Autowired
- private FastDfsClient client;
- @Value("${caimei.imageDomain}")
- private String imageDomain;
- @Resource
- private RedisService redisService;
- @Override
- public ResponseJson<PageInfo<AuthVo>> getAuthList(Integer listType, Integer authUserId, String authParty,
- String mobile, Integer status, Integer starFlag, Integer auditStatus,
- Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus,String authCode, Integer pageNum, Integer pageSize) {
- listType = null == listType ? 1 : listType;
- PageHelper.startPage(pageNum, pageSize);
- List<AuthVo> authList = authMapper.getAuthList(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus,authCode);
- PageInfo<AuthVo> pageData = new PageInfo<>(authList);
- return ResponseJson.success(pageData);
- }
- @Override
- public ResponseJson<PageInfo<AuthVo>> getAuthListAll(Integer listType, Integer authUserId, String authParty,
- String mobile, Integer status, Integer starFlag, Integer auditStatus,
- Integer lowerAuditStatus, Integer shopAuditStatus, Integer sendStatus, String name, String snCode, Integer pageNum, Integer pageSize) {
- listType = null == listType ? 1 : listType;
- PageHelper.startPage(pageNum, pageSize);
- List<AuthVo> authList = authMapper.getAuthListAll(listType, authUserId, authParty, mobile, status, starFlag, auditStatus, lowerAuditStatus, shopAuditStatus, sendStatus, name, snCode);
- PageInfo<AuthVo> pageData = new PageInfo<>(authList);
- return ResponseJson.success(pageData);
- }
- @Override
- public ResponseJson updateAuthStatus(Integer authId, Integer status) {
- if (null == authId) {
- return ResponseJson.error("请输入授权id");
- }
- if (null == status) {
- return ResponseJson.error("请输入要更新的状态值");
- }
- authMapper.updateAuthStatusByAuthId(authId, status);
- if (0 == status) {
- return ResponseJson.success("下线品牌授权成功");
- } else {
- return ResponseJson.success("上线品牌授权成功");
- }
- }
- @Override
- public ResponseJson deleteAuth(Integer authId) {
- if (null == authId) {
- return ResponseJson.error("参数异常,请输入授权id");
- }
- // 删除品牌授权
- authMapper.deleteAuthByAuthId(authId);
- // 删除轮播图
- authMapper.deleteBanner(authId);
- // 删除商品及商品参数
- List<Integer> productIdList = authProductService.getProductIdsByAuthId(authId);
- productIdList.forEach(productId -> {
- if (null != productId) {
- authProductService.deleteProduct(productId);
- }
- });
- return ResponseJson.success("删除品牌授权成功");
- }
- @Override
- public ResponseJson<AuthFormVo> getAuthFormData(Integer authId) {
- if (null == authId) {
- return ResponseJson.error("参数异常,机构id不能为空", null);
- }
- AuthFormVo authFormVo = authMapper.getAuthFormById(authId);
- //该机构关联机构用集合形式返回便于前端赋值
- if (null != authFormVo.getRelationId() && !"".equals(authFormVo.getRelationId())) {
- String[] relationIdList = authFormVo.getRelationId().split(",");
- List<AuthFormVo> authIdList = authMapper.getAuthIdList(relationIdList);
- authFormVo.setReleationClubList(authIdList);
- }
- if (null != authFormVo.getLng()) {
- authFormVo.setLngAndLat(authFormVo.getLng() + "," + authFormVo.getLat());
- }
- List<String> bannerList = authMapper.getBannerList(authId);
- authFormVo.setBannerList(bannerList);
- return ResponseJson.success(authFormVo);
- }
- @Override
- public ResponseJson<List<AuthVo>> getAuthSelectList(Integer authUserId) {
- List<AuthVo> authList = authMapper.getAuthList(1, authUserId, null, null, null, null, null, null, null, null,null);
- return ResponseJson.success(authList);
- }
- @Override
- public ResponseJson importLdmImage(Integer authUserId) {
- List<LdmDataPo> ldmClubData = ldmMapper.getLdmClubData(null, 0);
- ldmClubData.forEach(ldmClub -> {
- String pic2 = ldmClub.getPic2();
- String pic3 = ldmClub.getPic3();
- String pic4 = ldmClub.getPic4();
- List<AuthVo> authList = authMapper.getAuthByNameAndAddress(ldmClub.getAuthParty(), ldmClub.getAddress());
- if (null != authList && authList.size() > 0) {
- if (authList.size() > 1) {
- log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:对应门店过多,门店名称:" + ldmClub.getAuthParty());
- } else {
- AuthVo auth = authList.get(0);
- Integer authId = auth.getAuthId();
- if (StringUtils.isNotEmpty(pic2) || StringUtils.isNotEmpty(pic3) || StringUtils.isNotEmpty(pic4)) {
- authMapper.deleteBanner(authId);
- insertBanner(pic2, authId);
- insertBanner(pic3, authId);
- insertBanner(pic4, authId);
- }
- if (StringUtils.isNotEmpty(ldmClub.getRemarks())) {
- authMapper.updateRemarks(authId, ldmClub.getRemarks());
- }
- }
- } else {
- log.info(">>>>>>>>>>>>>>>>>>>>>导入ldm门店图错误:找不到对应门店,门店名称:" + ldmClub.getAuthParty());
- }
- });
- return ResponseJson.success();
- }
- @Override
- public ResponseJson checkAuth(Integer authId) {
- authMapper.checkAuth(authId);
- return ResponseJson.success();
- }
- @Override
- public ResponseJson starAuth(Integer authId, Integer starFlag, String starNum) {
- authMapper.starAuth(authId, starFlag, starNum);
- return ResponseJson.success();
- }
- private void insertBanner(String pic, Integer authId) {
- if (StringUtils.isNotEmpty(pic)) {
- String imagePath = "https://wangdian.skinovachina.com" + pic;
- String fileName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
- try {
- String banner = uploadService.saveFileByUrl(imagePath, fileName);
- authMapper.insertBanner(authId, banner);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- @Override
- public ResponseJson saveAuth(CmBrandAuthPo auth, List<String> bannerList, boolean importFlag, Integer source) {
- Integer authId = auth.getId();
- boolean insertFlag = null == authId;
- AuthVo dbAuth = null;
- if (!insertFlag) {
- dbAuth = authMapper.getAuthById(authId);
- }
- String authParty = auth.getAuthParty();
- if (StringUtils.isBlank(authParty)) {
- return ResponseJson.error("参数异常,请输入授权机构名称");
- }
- if (null == auth.getFirstClubType()) {
- return ResponseJson.error("请勾选机构类型");
- }
- if ((1 == auth.getFirstClubType() || 2 == auth.getFirstClubType()) && null == auth.getSecondClubType()) {
- return ResponseJson.error("请勾选二级机构类型");
- }
- if (1 == auth.getFirstClubType() && StringUtils.isEmpty(auth.getMedicalLicenseImage())) {
- return ResponseJson.error("请上传医疗许可证");
- }
- if (null == auth.getEmpNum()) {
- return ResponseJson.error("请输入员工人数");
- }
- if (1 == source) {
- if (null == auth.getCreateBy()) {
- return ResponseJson.error("参数异常,请输入创建人id");
- }
- /*if (1 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImageLogo())) {
- return ResponseJson.error("授权牌logo不能为空");
- }*/
- if (2 == auth.getAuthImageType() && StringUtils.isEmpty(auth.getAuthImage())) {
- return ResponseJson.error("授权牌不能为空");
- }
- } else {
- // 机构添加默认模板库生成
- auth.setAuthImageType(1);
- }
- if (!importFlag) {
- if (null == auth.getProvinceId() || null == auth.getCityId() || null == auth.getTownId() || StringUtils.isEmpty(auth.getAddress()) || null == auth.getLng() || null == auth.getLat()) {
- return ResponseJson.error("参数异常,地址信息异常");
- }
- if (StringUtils.isEmpty(auth.getLogo())) {
- return ResponseJson.error("参数异常,请上传机构logo");
- }
- if (null == bannerList || bannerList.size() <= 0) {
- return ResponseJson.error("参数异常,请上传轮播图");
- }
- }
- // 供应商保存,直接上线;机构保存,需要供应商审核通过后才上线
- if (null != dbAuth && 1 != dbAuth.getAuditStatus()) {
- // 被驳回的数据,编辑变为待审核状态
- auth.setStatus(2);
- auth.setAuditStatus(2);
- } else {
- auth.setStatus(1 == source ? 1 : 2);
- auth.setAuditStatus(1 == source ? 1 : 2);
- }
- Integer adminUserId = authMapper.getAdminUserId();
- auth.setAuditBy(adminUserId);
- auth.setAuditTime(new Date());
- if (1 == source) {
- auth.setShopAuditBy(auth.getCreateBy());
- auth.setShopAuditTime(new Date());
- }
- auth.setDelFlag(0);
- auth.setCheckFlag(0);
- auth.setShopAuditStatus(1 == source ? 1 : 2);
- /*
- 保存授权
- */
- if (insertFlag) {
- authMapper.insertAuth(auth);
- } else {
- authMapper.updateAuthByAuthId(auth);
- // 删除原有的轮播图
- authMapper.deleteBanner(auth.getId());
- }
- // 保存之后生成授权牌和水印授权牌
- String authImage = null;
- if (1 == auth.getAuthImageType()) {
- // 模板库生成
- // 获取对应模板
- TemplateVo authTemplate = authMapper.getAuthTemplate(auth.getId(), null, 1);
- authImage = generateAuthImage(authTemplate, auth);
- auth.setAuthImage(authImage);
- }
- // 添加水印
- if (StringUtils.isNotEmpty(auth.getAuthImage())) {
- auth.setPcAuthImage(addWaterMark(auth.getAuthImage(), 1));
- auth.setAppletsAuthImage(addWaterMark(auth.getAuthImage(), 2));
- authMapper.updateAuthImage(auth);
- }
- // 保存轮播图
- if (null != bannerList) {
- bannerList.forEach(banner -> authMapper.insertBanner(auth.getId(), banner));
- }
- return ResponseJson.success("保存品牌授权成功", auth);
- }
- @Override
- public String addWaterMark(String image, Integer type) {
- try {
- //type:1pc,2applets
- ClassPathResource classPathResource = new ClassPathResource("/images/newPcWaterMark.png");
- InputStream inputStreamImg = classPathResource.getInputStream();
- Image pcWaterMarkImg = ImageIO.read(inputStreamImg);
- classPathResource = new ClassPathResource("/images/newAppletsWaterMark.png");
- inputStreamImg = classPathResource.getInputStream();
- Image appletsWaterMarkImg = ImageIO.read(inputStreamImg);
- String img = ImageUtils.markImageByIcon(type == 1 ? pcWaterMarkImg : appletsWaterMarkImg, image, null);
- String imagePath = null;
- if (StringUtils.isNotEmpty(img)) {
- MultipartFile imgFile = Base64Util.base64ToMultipart(img);
- if (null != imgFile) {
- imagePath = uploadService.saveFile(imgFile);
- }
- log.info(">>>>>>>>>>>>>>>>水印图片上传成功:" + imagePath);
- } else {
- log.info(">>>>>>>>>>>>>>>>水印图片上传失败");
- }
- return imagePath;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- @Override
- public String generateAuthImage(TemplateVo authTemplate, CmBrandAuthPo auth) {
- if (null != authTemplate) {
- // 根据模板id设置相关数据
- Map<String, Object> templateInfo = getTemplateInfo(authTemplate, auth);
- Object templateImage = templateInfo.get("templateImage");
- if (null != templateImage) {
- String authImage = ImageUtils.generateAuthImage(templateInfo);
- log.info("【图片上传】>>>>>>>>>>>>>>>>图片临时路径:" + authImage);
- // 临时图片
- File tempFile = new File(authImage);
- String imageUrl = null;
- try {
- imageUrl = imageDomain + "/" + client.uploadFile(authImage);
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 删除临时图片
- boolean delete = tempFile.delete();
- log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时图片:" + delete);
- return imageUrl;
- } else {
- return null;
- }
- }
- return null;
- }
- private Map<String, Object> getTemplateInfo(TemplateVo template, CmBrandAuthPo auth) {
- HashMap<String, Object> map = new HashMap<>();
- Integer templateId = template.getTemplateId();
- if (1 == templateId) {
- map.put("templateImage", template.getTemplateImage());
- double rate = 0.15;
- if (StringUtils.isNotEmpty(auth.getAuthImageLogo())) {
- // 获取授权牌logo位置
- try {
- ImageIcon imageIcon = new ImageIcon(new URL(template.getTemplateImage()));
- Image srcImg = imageIcon.getImage();
- int srcWidth = srcImg.getWidth(null);
- ImageIcon authImageLogo = new ImageIcon(new URL(auth.getAuthImageLogo()));
- Image authLogo = authImageLogo.getImage();
- int authLogoWidth = authLogo.getWidth(null);
- int x = (srcWidth - (int) Math.round(238 * rate) - authLogoWidth) / 2 + (int) Math.round(238 * rate);
- int y = (int) Math.round(1230 * rate);
- map.put("addImage1_x", x);
- map.put("addImage1_y", y);
- map.put("addImage1_image", auth.getAuthImageLogo());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 添加认证编号信息
- if (StringUtils.isNotEmpty(auth.getAuthCode())) {
- map.put("addWord1_content", auth.getAuthCode());
- map.put("addWord1_color", "218,185,107");
- map.put("addWord1_type", "思源宋体");
- map.put("addWord1_style", Font.BOLD);
- map.put("addWord1_size", (int) Math.round(90 * rate));
- map.put("addWord1_x", (int) Math.round(2168 * rate));
- map.put("addWord1_y", (int) Math.round(3157 * rate));
- }
- // 添加认证日期信息
- if (null != auth.getAuthDate()) {
- SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
- map.put("addWord2_content", format.format(auth.getAuthDate()));
- map.put("addWord2_color", "218,185,107");
- map.put("addWord2_type", "思源宋体");
- map.put("addWord2_style", Font.PLAIN);
- map.put("addWord2_size", (int) Math.round(90 * rate));
- map.put("addWord2_x", (int) Math.round(2085 * rate));
- map.put("addWord2_y", (int) Math.round(3289 * rate));
- }
- // 添加二维码信息
- if (StringUtils.isNotEmpty(template.getQrPosition())) {
- String qrCodeLink = zpServer + "/" + auth.getAuthUserId() + "/" + authMapper.getPrefix(auth.getAuthUserId()) + "/approve/club/detail?id=" + auth.getId();
- map.put("addQr1_link", qrCodeLink);
- map.put("addQr1_size", template.getQrSize());
- String[] split = template.getQrPosition().split(",");
- if (split.length == 2) {
- map.put("addQr1_x", Integer.parseInt(split[0]));
- map.put("addQr1_y", Integer.parseInt(split[1]));
- }
- }
- }
- return map;
- }
- @Override
- public ResponseJson auditAuth(Integer authId, Integer auditStatus, String invalidReason, Integer auditBy, Integer source) {
- if (authId == null) {
- return ResponseJson.error("请输入授权id");
- }
- if (auditStatus == null) {
- return ResponseJson.error("请输入审核结果");
- }
- if (auditStatus == 0 && StringUtils.isEmpty(invalidReason)) {
- return ResponseJson.error("请输入审核不通过的原因");
- }
- source = null == source ? 1 : source;
- Date auditTime = new Date();
- // 授权状态更新
- Integer status = null;
- if (auditStatus == 0) {
- // 审核不通过,下线授权
- status = 0;
- } else {
- // 审核通过,上线授权
- status = 1;
- }
- if (1 == source) {
- authMapper.updateAuthAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
- }
- if (2 == source) {
- authMapper.updateAuthShopAuditStatus(authId, status, auditStatus, invalidReason, auditBy, auditTime);
- }
- return ResponseJson.success("审核机构认证成功");
- }
- @Override
- @Transactional(rollbackFor = Exception.class)
- public ResponseJson importDataByExcel(MultipartFile file, Integer authUserId, Integer createBy) {
- String originalFilename = file.getOriginalFilename();
- String randomStr = UUID.randomUUID().toString();
- assert originalFilename != null;
- int index = originalFilename.lastIndexOf(".");
- String extName = originalFilename.substring(index);
- String filePath = "/mnt/newdatadrive/data/runtime/jar-instance/zplma/tempFile/";
- if ("dev".equals(active)) {
- filePath = "D:\\WorkSpace\\file\\tempImport\\";
- }
- filePath += randomStr + extName;
- try {
- File tempFile = new File(filePath);
- if (!tempFile.exists()) {
- tempFile.mkdirs();
- }
- file.transferTo(tempFile);
- return saveExcelData(filePath, authUserId, createBy);
- } catch (IOException e) {
- e.printStackTrace();
- }
- log.info(">>>>>>>>>>>>>>>>文件临时路径:" + filePath);
- return null;
- }
- private ResponseJson saveExcelData(String filePath, Integer authUserId, Integer createBy) {
- //判断是否为excel类型文件
- if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
- System.out.println("文件不是excel类型");
- }
- // 获取供应商品牌
- List<String> shopBrands = shopService.getShopBrands(authUserId);
- // 授权列表
- List<CmBrandAuthPo> authImportList = new ArrayList<>();
- try {
- FileInputStream fis = new FileInputStream(filePath);
- // 得到表格数据
- XSSFWorkbook workbook = new XSSFWorkbook(fis);
- //得到第一个工作表(机构表)
- XSSFSheet authPartySheet = workbook.getSheetAt(0);
- //获得表头
- Row rowHead = authPartySheet.getRow(0);
- //判断表头是否正确
- if (9 != rowHead.getLastCellNum() || !"机构名称".equals(rowHead.getCell(0).getStringCellValue())) {
- return ResponseJson.error("授权机构表格式错误");
- }
- // 获得数据的总行数
- int authPartyRowNum = authPartySheet.getLastRowNum();
- //获得所有数据
- for (int i = 1; i <= authPartyRowNum; i++) {
- //获得第i行对象
- Row authPartyRow = authPartySheet.getRow(i);
- if (null == authPartyRow) {
- break;
- }
- Cell cell = null;
- // 校验机构名称
- cell = authPartyRow.getCell(0);
- cell.setCellType(CellType.STRING);
- String authParty = cell.getStringCellValue();
- if (StringUtils.isBlank(authParty)) {
- return ResponseJson.error("第" + i + 1 + "行机构名称不能为空");
- }
- // 校验省市区
- cell = authPartyRow.getCell(1);
- cell.setCellType(CellType.STRING);
- String area = cell.getStringCellValue();
- if (StringUtils.isBlank(area)) {
- return ResponseJson.error("第" + i + 1 + "行所在地区不能为空");
- }
- String[] areaSplit = area.split("/");
- if (areaSplit.length < 2 || areaSplit.length > 3) {
- return ResponseJson.error("第" + i + 1 + "行所在地区格式错误");
- }
- // 省份
- String provinceName = areaSplit[0];
- if (StringUtils.isBlank(provinceName)) {
- return ResponseJson.error("第" + i + 1 + "行省份不能为空");
- }
- if (provinceName.length() > 2) {
- provinceName = provinceName.substring(0, provinceName.length() - 1).trim();
- }
- Integer provinceId = authMapper.getProvinceId(provinceName);
- // 市名
- String cityName = areaSplit[1];
- if (StringUtils.isBlank(cityName)) {
- return ResponseJson.error("第" + i + 1 + "行市名不能为空");
- }
- if (cityName.length() > 2) {
- cityName = cityName.substring(0, cityName.length() - 1).trim();
- }
- Integer cityId = authMapper.getCityId(cityName);
- Integer townId = null;
- if (areaSplit.length > 2) {
- // 区名
- String townName = areaSplit[2];
- if (StringUtils.isNotEmpty(townName) && townName.length() > 2) {
- townName = townName.substring(0, townName.length() - 1).trim();
- }
- List<TownPo> townList = authMapper.getTownList(townName);
- for (int j = 0; j < townList.size(); j++) {
- TownPo town = townList.get(j);
- if (null == townId) {
- if (null != cityId) {
- if (town.getCityId().equals(cityId)) {
- townId = town.getTownId();
- }
- } else {
- Integer checkCityId = authMapper.getCityIdByTownId(town.getTownId());
- if (null != provinceId && null != checkCityId) {
- Integer checkProvinceId = authMapper.getProvinceIdByCityId(cityId);
- if (provinceId.equals(checkProvinceId)) {
- cityId = checkCityId;
- townId = town.getTownId();
- }
- }
- }
- }
- }
- }
- // 校验详细地址
- cell = authPartyRow.getCell(2);
- cell.setCellType(CellType.STRING);
- String address = cell.getStringCellValue();
- if (StringUtils.isBlank(address)) {
- return ResponseJson.error("第" + i + 1 + "行详细地址不能为空");
- }
- // 校验经纬度
- cell = authPartyRow.getCell(3);
- cell.setCellType(CellType.STRING);
- String lngAndLat = cell.getStringCellValue();
- if (StringUtils.isBlank(lngAndLat)) {
- return ResponseJson.error("第" + i + 1 + "行经纬度不能为空");
- }
- String[] split = lngAndLat.split(",");
- if (2 != split.length) {
- return ResponseJson.error("第" + i + 1 + "行经纬度格式错误");
- }
- BigDecimal lng = new BigDecimal(split[0]);
- BigDecimal lat = new BigDecimal(split[1]);
- // 校验联系电话
- cell = authPartyRow.getCell(4);
- cell.setCellType(CellType.STRING);
- String mobile = cell.getStringCellValue();
- if (StringUtils.isBlank(mobile)) {
- return ResponseJson.error("第" + i + 1 + "行联系电话不能为空");
- }
- // 认证编号
- cell = authPartyRow.getCell(5);
- cell.setCellType(CellType.STRING);
- String authCode = cell.getStringCellValue();
- // 认证日期
- Date authDate = null;
- cell = authPartyRow.getCell(6);
- cell.setCellType(CellType.STRING);
- String authDateStr = cell.getStringCellValue();
- if (StringUtils.isNotBlank(authDateStr)) {
- SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
- authDate = format.parse(authDateStr);
- }
- // 校验员工人数
- Integer empNum = null;
- cell = authPartyRow.getCell(7);
- cell.setCellType(CellType.STRING);
- String empNumStr = cell.getStringCellValue();
- if (StringUtils.isBlank(empNumStr)) {
- return ResponseJson.error("第" + i + 1 + "行员工人数不能为空");
- }
- try {
- empNum = Integer.parseInt(empNumStr);
- } catch (Exception e) {
- return ResponseJson.error("第" + i + 1 + "行员工人数格式错误");
- }
- // 校验店铺备注
- cell = authPartyRow.getCell(8);
- cell.setCellType(CellType.STRING);
- String remarks = cell.getStringCellValue();
- Integer customFlag = 0;
- if (StringUtils.isNotEmpty(remarks)) {
- customFlag = 1;
- }
- CmBrandAuthPo authPo = new CmBrandAuthPo();
- authPo.setAuthParty(authParty);
- authPo.setProvinceId(provinceId);
- authPo.setCityId(cityId);
- authPo.setTownId(townId);
- authPo.setAddress(address);
- authPo.setLng(lng);
- authPo.setLat(lat);
- authPo.setMobile(mobile);
- authPo.setAuthCode(authCode);
- authPo.setAuthDate(authDate);
- authPo.setAuthImageType(1);
- authPo.setEmpNum(empNum);
- authPo.setCustomFlag(customFlag);
- authPo.setRemarks(remarks);
- authImportList.add(authPo);
- }
- } catch (Exception e) {
- e.printStackTrace();
- return ResponseJson.error("导入失败,请检查表格数据");
- } finally {
- // 删除临时数据
- File tempFile = new File(filePath);
- boolean delete = tempFile.delete();
- log.info("【图片上传】>>>>>>>>>>>>>>>>删除临时表格:" + delete);
- }
- // 保存授权数据
- for (int i = 0; i < authImportList.size(); i++) {
- CmBrandAuthPo authPo = authImportList.get(i);
- // 保存授权机构
- authPo.setAuthUserId(authUserId);
- authPo.setCreateBy(createBy);
- authPo.setCreateSource(1);
- authPo.setFirstClubType(5);
- // 导入数据
- ResponseJson result = saveAuth(authPo, null, true, 1);
- if (result.getCode() != 0) {
- // 设置手动回滚事务
- TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
- return ResponseJson.error("导入失败");
- }
- }
- return ResponseJson.success("导入成功");
- }
- /**
- * 获取机构关联的机构信息
- * 1.7.4版本:
- */
- @Override
- public ResponseJson<List<AuthFormVo>> getRelationgInfo(String snCode, Integer authUserId) {
- //根据sn码获取关联这个产品的机构列表
- List<ProductFormVo> relationgList = authMapper.getRelationgList(snCode);
- String relationgInfo = null;
- List<AuthFormVo> authIdList = null;
- if (relationgList.size() > 0) {
- for (int i = 0; i < relationgList.size(); i++) {
- if (null != relationgInfo) {
- relationgInfo += ",";
- }
- relationgInfo += relationgList.get(i).getRelationId();
- }
- if (null != relationgInfo) {
- String[] relationIdList = relationgInfo.split(",");
- authIdList = authMapper.getAuthIdList(relationIdList);
- }
- }
- return ResponseJson.success(authIdList);
- }
- /**
- * 1.7.4版本
- * 获取可绑定机构机构信息
- **/
- @Override
- public ResponseJson<List<AuthFormVo>> getClubBindAuth(Integer authUserId) {
- List<AuthFormVo> clubBindAuth = authMapper.getClubBindAuth(authUserId);
- return ResponseJson.success(clubBindAuth);
- }
- //------------------------------------------v1.7.5上传视频至抖音---------------------------------------------------------------------------------------
- ///用户授权(用于获取数据)
- /**
- * 用户扫码授权,获取code值
- * @param response
- * @return true :token没过期 false:token过期需重新授权
- * @throws IOException
- */
- @Override
- public ResponseJson getDouYingCode(HttpServletResponse response) throws IOException {
- //验证是否是第一次登录(根据redis缓存中的token验证)
- // long dYaccessTok = redisService.getExpireTime("DYaccessToken");
- // boolean s=redisService.exists("DYaccessToken");
- // String s1= redisService.get("DyopenId").toString();
- //// if(!redisService.exists("DYaccessToken")){
- // //验证token是否过期
- // long dYaccessToken = redisService.getExpireTime("DYaccessToken");
- // if(dYaccessToken<=0){ //tonken过期
- // //判断refreshToken是否过期
- // long DyrefreshToken = redisService.getExpireTime("DyrefreshToken");
- // if(DyrefreshToken>=0){ //refreshToken
- // //根据refreshToken刷新token,重新缓存token
- // String refreshToken=redisService.get("DyrefreshToken").toString();
- // String accessToken = refreshAccessToken(refreshToken);
- // redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15);
- // boolean flag= redisService.exists("DYaccessToken");
- // return ResponseJson.success(true);
- // }else{ //根据refreshToken刷新refreshToken(总共可以刷新3次,次数完后需重新扫码授权)
- // String refreshToken=redisService.get("DyrefreshToken").toString();
- // String newRefreshToken = resetRefreshAccessToken(refreshToken);
- // if(StringUtils.isNotEmpty(newRefreshToken)){
- // String accessToken = refreshAccessToken(newRefreshToken);
- // redisService.set("DYaccessToken",accessToken,60L * 60 * 24 * 15);
- // return ResponseJson.success(true);
- // }
- // }
- // }else {
- // return ResponseJson.success(true);
- // }
- // }
- //验证token是否过期
- // long dYaccessToken = redisService.getExpireTime("DYaccessToken");
- return redisService.getExpireTime("DYaccessToken")<0 ? ResponseJson.success(false): ResponseJson.success(true);
- // String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
- // String responestype = "code";//写死为'code'即可
- // String scope = "video.data,video.list,trial.whitelist,data.external.item";//应用授权作用域,多个授权作用域以英文逗号(,)分隔
- // String redirectUrl = "https://www.caimei365.com";//回调地址,应用中配置
- // String state = "false";//用于保持请求和回调的状态
- // String code = "https://open.douyin.com/platform/oauth/connect/?client_key=" + clintKey
- // + "&response_type=" + responestype + "&scope=" + scope + "&redirect_uri=" + redirectUrl + "&state=" + state;
- // response.sendRedirect(code);
- }
- /**
- * 根据用户的code值获取AcessToken
- * ccode 用户授权登录code
- **/
- @Override
- public ResponseJson getDouYingAcessToken(String code) throws IOException {
- String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
- String clintSecret = "1dd7446d29e16738787447b771ced2df";//应用唯一标识对应的密钥
- String grantType = "authorization_code";//固定值
- String requestUrl = "https://open.douyin.com/oauth/access_token/";//请求地址
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- //创建httppost对象
- HttpPost hp = new HttpPost(requestUrl);
- hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
- // hp.setHeader("Content-Type","application/x-www-form-urlencoded");
- //拼接请求参数
- List<NameValuePair> list = new ArrayList();
- list.add(new BasicNameValuePair("client_key", clintKey));
- list.add(new BasicNameValuePair("client_secret", clintSecret));
- list.add(new BasicNameValuePair("code", code));
- list.add(new BasicNameValuePair("grant_type", grantType));
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
- hp.setEntity(entity);
- //发送请求
- CloseableHttpResponse execute = closeableHttpClient.execute(hp);
- HttpEntity he = execute.getEntity();
- String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
- //获取access_token,open_id(用于获取视频数据),refresh_token(刷新token)
- JSONObject jsonObject =JSONObject.parseObject(result);
- String data = jsonObject.getString("data");
- JSONObject params =JSONObject.parseObject(data);
- String accessToken = params.getString("access_token");
- String openId = params.getString("open_id");
- String refreshToken = params.getString("refresh_token");
- String errorCode = params.getString("error_code");
- if(Integer.valueOf(errorCode)>0){return ResponseJson.success("tonken缓存失败",null);}
- //用redis缓存access_token,refresh_token
- redisService.set("DYaccessToken",accessToken , 60L * 60 * 24 * 15);// * 60 * 24 * 15
- redisService.set("DyrefreshToken",refreshToken,60L * 60 * 24 * 30);
- redisService.set("DyopenId",openId,60L * 60 * 24 * 30);
- EntityUtils.consume(he);
- String DYaccessToken=redisService.get("DYaccessToken").toString();
- String DyrefreshToken=redisService.get("DyrefreshToken").toString();
- String DyopenId=redisService.get("DyopenId").toString();
- if (StringUtils.isNotEmpty(DYaccessToken)&&StringUtils.isNotEmpty(DyrefreshToken)&&StringUtils.isNotEmpty(DyopenId)){
- return ResponseJson.success();
- }else {
- return ResponseJson.success("tonken缓存失败",null);
- }
- }
- /**
- * 刷新tonken
- * @param refreshToken
- */
- public String refreshAccessToken(String refreshToken){
- String requestUrl="https://open.douyin.com/oauth/refresh_token/";
- String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
- String grantType = "refresh_token";//固定值
- String accessToken=null;
- //创建httppost对象
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpPost hp = new HttpPost(requestUrl);
- hp.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
- // hp.setHeader("Content-Type","application/x-www-form-urlencoded");
- //拼接请求参数
- List<NameValuePair> list = new ArrayList();
- list.add(new BasicNameValuePair("client_key", clintKey));
- list.add(new BasicNameValuePair("grant_type", grantType));
- list.add(new BasicNameValuePair("refresh_token", refreshToken));
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
- hp.setEntity(entity);
- try {
- CloseableHttpResponse execute = closeableHttpClient.execute(hp);
- HttpEntity he = execute.getEntity();
- String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
- JSONObject params=JSONObject.parseObject(result);
- String data=params.getString("data");
- JSONObject datalist=JSONObject.parseObject(data);
- accessToken=datalist.getString("access_token");
- EntityUtils.consume(he);
- } catch (IOException e) {
- e.printStackTrace();
- }
- hp.setEntity(entity);
- return accessToken;
- }
- /**
- * 刷新refreshAccessToken
- * @param refreshToken
- */
- public String resetRefreshAccessToken(String refreshToken){
- String requestUrl="https://open.douyin.com/oauth/renew_refresh_token/";
- String clintKey = "awwwvh9tsnvo54w1";//应用唯一标识
- String renewRefreshAccessToken=null;
- //创建httppost对象
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpPost hp = new HttpPost(requestUrl);
- List<NameValuePair> list = new ArrayList();
- list.add(new BasicNameValuePair("client_key", clintKey));
- list.add(new BasicNameValuePair("refresh_token", refreshToken));
- list.add(new BasicNameValuePair("Content-Type", "multipart/form-data"));
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, StandardCharsets.UTF_8);
- hp.setEntity(entity);
- try {
- CloseableHttpResponse execute = closeableHttpClient.execute(hp);
- HttpEntity he = execute.getEntity();
- String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
- JSONObject jsonObject=JSONObject.parseObject(result);
- String data = jsonObject.getString("data");
- JSONObject params=JSONObject.parseObject(data);
- renewRefreshAccessToken = params.getString("refresh_token");
- EntityUtils.consume(he);
- } catch (IOException e) {
- e.printStackTrace();
- }
- hp.setEntity(entity);
- return renewRefreshAccessToken;
- }
- //----------------------------------------------------h5的方式上传视频------------------------------------------------
- /**
- * h5的方式上传视频
- * @return
- * @throws IOException
- */
- @Override
- public ResponseJson getclientToken(String title,String videoPath,Integer authId) throws IOException {
- //获取accessToken
- String client_key = "awwwvh9tsnvo54w1";
- String client_secret = "1dd7446d29e16738787447b771ced2df";
- String grant_type = "client_credential";
- String url = "https://open.douyin.com/oauth/client_token/?client_key=" + client_key
- + "&client_secret=" + client_secret
- + "&grant_type=" + grant_type;
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- //创建httppost对象
- HttpPost hp = new HttpPost(url);
- MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.setCharset(Consts.UTF_8);
- builder.setContentType(ContentType.MULTIPART_FORM_DATA);
- //构建参数
- HttpEntity entity = builder.build();
- hp.setEntity(entity);
- CloseableHttpResponse response = null;
- String schema=null;
- try {
- response = closeableHttpClient.execute(hp);
- HttpEntity he = response.getEntity();
- String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
- //把返回结果转json获取access_token
- JSONObject jsonObject=JSONObject.parseObject(result);
- String data=jsonObject.getString("data");
- JSONObject params=JSONObject.parseObject(data);
- String accessToken=params.getString("access_token");
- //根据accesstoken获取tiket
- schema = getDouYingTicket(accessToken, title,videoPath,authId);
- EntityUtils.consume(he);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return ResponseJson.success(schema);
- }
- /**
- * 根据token获取ticket
- **/
- @RequestMapping("/getDouYingTicket")
- public String getDouYingTicket(String clientToken,String title,String videoPath,Integer authId) throws IOException {
- //时间戳
- long l = System.currentTimeMillis();
- String timestamp = String.valueOf(l);
- //随机数
- String noncestr = randomGen(16);
- String uri = "https://open.douyin.com/open/getticket/";
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpGet httpGet = new HttpGet(uri);
- httpGet.setHeader("access-token", clientToken);
- httpGet.setHeader("Content-Type","application/json");
- CloseableHttpResponse response = null;
- String schema=null;
- try {
- response = closeableHttpClient.execute(httpGet);
- HttpEntity he = response.getEntity();
- String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
- //获取ticket
- JSONObject jsonObject=JSONObject.parseObject(result);
- String data = jsonObject.getString("data");
- JSONObject params=JSONObject.parseObject(data);
- String ticket = params.getString("ticket");
- //getDouYingshareId
- String shareId = getDouYingshareId(clientToken);
- //保存shareId用于回调时存储item_id
- authMapper.savaShareIdByAuthId(authId,shareId);
- //获取签名 并且用md5加密
- String signature = signatureAlgorithm(ticket, timestamp,noncestr);
- //获取schema(返回前端用于生成二维码发布视频)
- schema = appendSchema(signature, shareId, timestamp,noncestr, title, videoPath);
- EntityUtils.consume(he);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return schema;
- }
- /**
- * 获取签名 并且用md5加密
- * ticket
- **/
- @RequestMapping("/signatureAlgorithm")
- public String signatureAlgorithm(String ticket, String timestamp,String noncestr) {
- TreeMap<String, String> treeMap = new TreeMap<>();
- treeMap.put("nonce_str", noncestr);
- treeMap.put("ticket", ticket);
- treeMap.put("timestamp", timestamp);
- StringBuffer stringBuffer = new StringBuffer();
- Iterator<Map.Entry<String, String>> it = treeMap.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<String, String> entry = it.next();
- stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
- }
- String result = stringBuffer.substring(0, stringBuffer.length() - 1);
- //进行md5签名
- String signature = Md5Util.md5(result).toLowerCase();
- return signature;
- }
- /**
- * Schema 生成
- **/
- public String appendSchema(String signature, String shareId, String timestamp,String noncestr,String title,String videoPath) {
- URIBuilder uri = null;
- String schema = null;
- try {
- uri = new URIBuilder("snssdk1128://openplatform/share");
- uri.addParameter("share_type", "h5");//固定h5
- uri.addParameter("client_key", "awwwvh9tsnvo54w1");//应用唯一标识
- uri.addParameter("nonce_str", noncestr);//随机数(必须和签名时的nonce_str一致)
- uri.addParameter("timestamp", timestamp);//时间戳(必须和签名时的timestamp一致)
- uri.addParameter("signature", signature);//签名
- uri.addParameter("state", shareId);//通过方法获取(基于webhook,获取视频发布回调信息,不传则收不到回调信息)
- //https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4
- //视频地址(必须为网络地址,本地地址无法发布)单视频上传
- 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
- uri.addParameter("share_to_publish", "1");//为1则直接发布视频至抖音
- uri.addParameter("title",title);//"给大佐都整emo了");//视频标题
- schema = uri.toString();
- } catch (URISyntaxException e) {
- e.printStackTrace();
- }
- return schema;
- }
- /**
- * 获取shareId 用于生成schema
- **/
- @RequestMapping("/getDouYingshareId")
- public String getDouYingshareId(String clientToken) throws IOException {
- String uri = "https://open.douyin.com/share-id/?need_callback=true&default_hashtag=hashtag";
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpGet httpGet = new HttpGet(uri);
- httpGet.setHeader("access-token", clientToken);
- CloseableHttpResponse response = null;
- String shareId = "";
- try {
- response = closeableHttpClient.execute(httpGet);
- HttpEntity he = response.getEntity();
- String result = EntityUtils.toString(he, StandardCharsets.UTF_8);
- JSONObject jsonObject=JSONObject.parseObject(result);
- String data = jsonObject.getString("data");
- JSONObject params=JSONObject.parseObject(data);
- shareId = params.getString("share_id");
- EntityUtils.consume(he);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return shareId;
- }
- /**
- * 获取已发布视频列表
- * @param openId 用户唯一标志
- * @param cursor 分页游标, 第一页请求cursor是0, response中会返回下一页请求用到的cursor, 同时response还会返回has_more来表明是否有更多的数据。
- * @param count 每页数量 10
- */
- public String getVideoList(String openId,Long cursor,Integer count,String accessToken){
- String requestUrl="https://open.douyin.com/video/list/?open_id="+openId+"&cursor="+cursor+"&count="+count;
- //创建httppost对象
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpGet hg = new HttpGet(requestUrl);
- hg.setHeader("Content-Type","application/json");
- hg.addHeader("access-token",accessToken);
- String resultList=null;
- try {
- CloseableHttpResponse execute = closeableHttpClient.execute(hg);
- HttpEntity entity = execute.getEntity();
- String result=EntityUtils.toString(entity,StandardCharsets.UTF_8);
- JSONObject jsonObject = JSONObject.parseObject(result);
- resultList = jsonObject.getString("data");
- // resultList = JSONArray.parseArray(itemIdlist);
- // String itemId = params.getJSONObject(0).get("item_id").toString();
- //根据itemid获取视频的数据(点赞,播放,评论量)
- EntityUtils.consume(entity);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return resultList;
- }
- /**
- * 生成随机数
- *
- * @param place
- * @return
- */
- public String randomGen(int place) {
- String base = "wqetryuioplkjhgfdsazxcvbmnABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- StringBuffer sb = new StringBuffer();
- Random rd = new Random();
- for (int i = 0; i < place; i++) {
- sb.append(base.charAt(rd.nextInt(base.length())));
- }
- return sb.toString();
- }
- /**
- * 保存视频信息
- * @return
- */
- @Override
- public ResponseJson saveVideoInfo(ChallengeRoundVo cr){
- Date date=new Date();
- SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String releaseTime = sf.format(date).replace("T", "");
- authMapper.saveVideoInfo(cr.getUserName(),cr.getCover(),cr.getOssUrl(),cr.getOssName(),cr.getTitle(),releaseTime,cr.getAuthId(),cr.getAuthUserId());
- return ResponseJson.success("保存成功",null);
- }
- /**
- * 根据authid获取authUserId
- * @param authId
- * @return
- */
- @Override
- public boolean getauthUserId(Integer authId){
- String authUserId= authMapper.getauthUserId(authId);
- return StringUtils.isEmpty(authUserId);
- }
- /**
- * 判断是否存在userName
- * @param userName
- * @return
- */
- @Override
- public boolean getuserName(String userName){
- String name= authMapper.getuserName(userName);
- return StringUtils.isEmpty(name);
- }
- /**
- * 验证是否在活动时间内
- * @param releaseTime 发布时间
- * @return
- */
- @Override
- public boolean checkActivityTime(String releaseTime){
- Integer id= authMapper.checkActivityTime(releaseTime);
- return id==null?true:false;
- }
- /**
- * 获取已发布视频列表(前端)
- * @param clubUserName 手机号或者机构名
- * @param status 用户发布状态
- * @param cursor 页码
- * @param count 条数
- * @return
- */
- @Override
- public ResponseJson<PageInfo<ChallengeRoundVo>> getPublishedVideoList(String clubUserName,Integer status,Integer cursor,Integer count,Integer authUserId,Integer pageNum,Integer pageSize){
- PageHelper.startPage(pageNum, pageSize);
- List<ChallengeRoundVo> listChallengeRoundVo=authMapper.getPublishedVideoList(clubUserName,status,authUserId);
- PageInfo<ChallengeRoundVo> pageData = new PageInfo<>(listChallengeRoundVo);
- //调用抖音api获取视频数据
- String dyopenId=null;
- String DYaccessToken=null;
- if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){
- dyopenId=redisService.get("DyopenId").toString();
- DYaccessToken=redisService.get("DYaccessToken").toString();
- }
- Long flag=1l;
- List<DyVideoInfoVo> list=new ArrayList<>();
- while (flag!=0){
- if (flag==1){flag=0l;}
- String data = getVideoList(dyopenId, flag, count, DYaccessToken);
- JSONObject paramslist = JSONObject.parseObject(data);
- Integer error_code = Integer.valueOf(paramslist.getString("error_code"));
- if(error_code>0){
- break;
- }
- String resultList = paramslist.getString("list");
- String cor = paramslist.getString("cursor");
- flag=Long.parseLong(cor);
- List<DyVideoInfoVo> listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class);
- if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){
- for (DyVideoInfoVo dv:listDyVideoInfoVo) {
- list.add(dv);
- }
- }
- }
- if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){
- for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) {
- if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){
- ChallengeRoundVo.setDiggCount("0");
- }
- if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){
- ChallengeRoundVo.setPlayCount("0");
- }
- if(list!=null&&list.size()>0){
- for (DyVideoInfoVo dyVideoInfoVo:list) {
- if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){
- StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class);
- ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count());
- ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count());
- break;
- }
- }
- }
- }
- }
- //根据点赞量降序排序
- // PageHelper.startPage(pageNum, pageSize);
- List<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
- PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
- return ResponseJson.success(pageDa);
- }
- /**
- * 获取已发布视频列表(后端)
- * @param mobile
- * @param authParty
- * @param status
- * @param cursor
- * @param count
- * @param authUserId
- * @return
- */
- @Override
- public ResponseJson<PageInfo<ChallengeRoundVo>> getPublishedVideo(String mobile,String authParty,Integer status,Integer cursor,Integer count,Integer authUserId,Integer pageNum,Integer pageSize){
- PageHelper.startPage(pageNum, pageSize);
- List<ChallengeRoundVo> listChallengeRoundVo=authMapper.getPublishedVideo(mobile,authParty,status,authUserId);
- PageInfo<ChallengeRoundVo> pageData = new PageInfo<>(listChallengeRoundVo);
- //调用抖音api获取视频数据
- String dyopenId=null;
- String DYaccessToken=null;
- if(redisService.getExpireTime("DyopenId")>0&&redisService.getExpireTime("DYaccessToken")>0){
- dyopenId=redisService.get("DyopenId").toString();
- DYaccessToken=redisService.get("DYaccessToken").toString();
- }
- Long flag=1l;
- List<DyVideoInfoVo> list=new ArrayList<>();
- while (flag!=0){
- if (flag==1){flag=0l;}
- String data = getVideoList(dyopenId, flag, count, DYaccessToken);
- JSONObject paramslist = JSONObject.parseObject(data);
- Integer error_code = Integer.valueOf(paramslist.getString("error_code"));
- if(error_code>0){
- break;
- }
- String resultList = paramslist.getString("list");
- String cor = paramslist.getString("cursor");
- flag=Long.parseLong(cor);
- List<DyVideoInfoVo> listDyVideoInfoVo= JSONArray.parseArray(resultList, DyVideoInfoVo.class);
- if(listDyVideoInfoVo!=null&&listDyVideoInfoVo.size()>0){
- for (DyVideoInfoVo dv:listDyVideoInfoVo) {
- list.add(dv);
- }
- }
- }
- if(listChallengeRoundVo!=null&&listChallengeRoundVo.size()>0){
- for (ChallengeRoundVo ChallengeRoundVo:listChallengeRoundVo) {
- if(StringUtils.isEmpty(ChallengeRoundVo.getDiggCount())){
- ChallengeRoundVo.setDiggCount("0");
- }
- if(StringUtils.isEmpty(ChallengeRoundVo.getPlayCount())){
- ChallengeRoundVo.setPlayCount("0");
- }
- if(list!=null&&list.size()>0){
- for (DyVideoInfoVo dyVideoInfoVo:list) {
- if(dyVideoInfoVo.getItem_id().equals(ChallengeRoundVo.getItemId())){
- StatisticsVo StatisticsVo= JSONObject.parseObject(dyVideoInfoVo.getStatistics(), StatisticsVo.class);
- ChallengeRoundVo.setDiggCount(StatisticsVo.getDigg_count());
- ChallengeRoundVo.setPlayCount(StatisticsVo.getPlay_count());
- break;
- }
- }
- }
- }
- }
- //根据点赞量降序排序
- // PageHelper.startPage(pageNum, pageSize);
- List<ChallengeRoundVo> collect = listChallengeRoundVo.stream().sorted(Comparator.comparing(ChallengeRoundVo::getDiggCount).reversed().thenComparing(ChallengeRoundVo::getPlayCount, Comparator.reverseOrder())).collect(Collectors.toList());//先以属性一升序,升序结果进行属性一降序,再进行属性二降序
- PageInfo<ChallengeRoundVo> pageDa = new PageInfo<>(collect);
- return ResponseJson.success(pageDa);
- }
- /**
- * 获取机构已发布视频的机构下拉列表
- * @param authUserId
- * @return
- */
- @Override
- public ResponseJson<List<ChallengeRoundVo>> getAuthPartylist(Integer authUserId){
- return ResponseJson.success(authMapper.getAuthPartylist(authUserId));
- }
- /**
- * 保存活动信息
- * @param startTime
- * @param endTime
- * @param status
- * @return
- */
- @Override
- public ResponseJson saveActivityTime(String startTime,String endTime,Integer status,Integer authUserId){
- //如果数据库有值则修改,没值则新增
- List<ChallengeActivityVo> challengeList = authMapper.checkActivityId();
- List<Integer> authUserIdList=new ArrayList<>();
- for (ChallengeActivityVo ac:challengeList) {
- authUserIdList.add(ac.getAuthUserId());
- }
- if(challengeList.size()<0||!authUserIdList.contains(authUserId)){
- authMapper.saveActivityInfo(startTime,endTime,status,authUserId);
- }else {
- authMapper.upActivityInfo(startTime,endTime,status,authUserId);
- }
- return ResponseJson.success();
- }
- /**
- * 获取活动信息
- * @return
- */
- @Override
- public ResponseJson<ChallengeActivityVo> getActivityTime(Integer authUserId){
- return ResponseJson.success(authMapper.getActivityTime(authUserId));
- }
- /**
- * 判断shareId是否存在
- * @param shareId
- * @return
- */
- @Override
- public boolean getShareId(String shareId){
- return StringUtils.isNotEmpty(authMapper.getShareId(shareId));
- }
- /**
- * 根据ShareId保存itemId (webhook触发时调用)
- * @param shareId
- * @param itemId
- */
- @Override
- public void savaItemIdByShareId(String shareId,String itemId){
- authMapper.savaItemIdByShareId(shareId,itemId);
- }
- @Override
- public ResponseJson<ChallengeActivityVo> getActivitty(Integer authUserId){
- ChallengeActivityVo activityTime = authMapper.getActivityTime(authUserId);
- Date date=new Date();
- SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String releaseTime = sf.format(date).replace("T", "");
- if(activityTime!=null){
- if(activityTime.getStartTime().compareTo(releaseTime)>0){
- activityTime.setActivityState(0);
- }else if(activityTime.getStartTime().compareTo(releaseTime)<0&&activityTime.getEndTime().compareTo(releaseTime)>0){
- activityTime.setActivityState(1);
- }else {
- activityTime.setActivityState(2);
- }
- }
- return ResponseJson.success(activityTime);
- }
- /**
- * 根据authId获取手机号
- * @param authId
- * @return
- */
- @Override
- public String getMobileByAuthId(Integer authId){
- return authMapper.getMobileByAuthId(authId);
- }
- /**
- * 根据authId获取手机号
- * @param authId
- * @return
- */
- @Override
- public String getAuthUserName(Integer authId){
- return authMapper.getAuthUserName(authId);
- }
- /**
- * 保存抖音口令
- * @param authId
- * @return
- */
- @Override
- public void savaDyCommand(Integer authId,String content){
- authMapper.savaDyCommand(authId,content);
- }
- }
|