yujian
2019-05-13 efdac57e87ef0ca1a525d13bb5b742c560607ae2
fanli/src/main/java/com/yeshi/fanli/controller/client/ShareController.java
@@ -12,33 +12,57 @@
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.yeshi.utils.BigDecimalUtil;
import org.yeshi.utils.HttpUtil;
import org.yeshi.utils.JsonUtil;
import org.yeshi.utils.taobao.TbImgUtil;
import com.yeshi.fanli.dto.share.ShareInfoDTO;
import com.yeshi.fanli.entity.accept.AcceptData;
import com.yeshi.fanli.entity.bus.share.UserShareGoodsGroup;
import com.yeshi.fanli.entity.bus.share.UserShareGoodsHistory;
import com.yeshi.fanli.entity.bus.share.UserShareGoodsRecord;
import com.yeshi.fanli.entity.bus.share.UserShareGoodsRecord.ShareSourceTypeEnum;
import com.yeshi.fanli.entity.bus.user.UserExtraTaoBaoInfo;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserInfoExtra;
import com.yeshi.fanli.entity.dynamic.DynamicInfo;
import com.yeshi.fanli.entity.dynamic.GoodsPicture;
import com.yeshi.fanli.entity.system.BusinessSystem;
import com.yeshi.fanli.entity.system.SystemClientParams;
import com.yeshi.fanli.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.fanli.entity.taobao.TaoBaoGoodsBriefExtra;
import com.yeshi.fanli.entity.taobao.TaoBaoLink;
import com.yeshi.fanli.entity.taobao.TaoKeAppInfo;
import com.yeshi.fanli.exception.ShareGoodsException;
import com.yeshi.fanli.exception.goods.ShareGoodsTextTemplateException;
import com.yeshi.fanli.exception.share.UserShareGoodsRecordException;
import com.yeshi.fanli.exception.taobao.TaobaoGoodsDownException;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.config.SystemClientParamsService;
import com.yeshi.fanli.service.inter.dynamic.DynamicInfoService;
import com.yeshi.fanli.service.inter.goods.CommonGoodsService;
import com.yeshi.fanli.service.inter.goods.ShareGoodsService;
import com.yeshi.fanli.service.inter.goods.ShareGoodsTextTemplateService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoManageService;
import com.yeshi.fanli.service.inter.monitor.MonitorService;
import com.yeshi.fanli.service.inter.user.SpreadUserImgService;
import com.yeshi.fanli.service.inter.user.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.service.inter.user.UserInfoExtraService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserShareGoodsGroupService;
import com.yeshi.fanli.service.inter.user.UserShareGoodsRecordService;
import com.yeshi.fanli.util.AESUtil;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.RedisManager;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TaoBaoConstant;
import com.yeshi.fanli.util.account.UserUtil;
import com.yeshi.fanli.util.cache.TaoBaoGoodsCacheUtil;
import com.yeshi.fanli.util.factory.MonitorFactory;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
import com.yeshi.fanli.util.taobao.TaoKeApiUtil;
import com.yeshi.fanli.vo.msg.ClientTextStyleVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@@ -71,6 +95,31 @@
   @Resource
   private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
   @Resource
   private UserInfoService userInfoService;
   @Resource
   private TaoBaoGoodsCacheUtil taoBaoGoodsCacheUtil;
   @Resource
   private RedisManager redisManager;
   @Resource
   private ShareGoodsTextTemplateService shareGoodsTextTemplateService;
   @Resource
   private SystemClientParamsService systemClientParamsService;
   @Resource
   private DynamicInfoService dynamicInfoService;
   @Resource
   private UserInfoExtraService userInfoExtraService;
   @Resource
   private SpreadUserImgService spreadUserImgService;
   // 获取商品分享链接
   @RequestMapping(value = "getGoodsShareUrl")
   public void getGoodsShareUrl(AcceptData acceptData, long id, PrintWriter out) {
@@ -95,6 +144,12 @@
         return;
      }
      UserInfo user = userInfoService.getUserByIdWithMybatis(uid);
      if (user != null && user.getState() != UserInfo.STATE_NORMAL) {
         out.print(JsonUtil.loadFalseResult(Constant.CODE_FORBIDDEN_USER, Constant.FORBIDDEN_USER_REASON_DESC));
         return;
      }
      if (auctionId == null || auctionId <= 0) {
         out.print(JsonUtil.loadFalseResult(2, "商品ID不能为空"));
         return;
@@ -103,7 +158,7 @@
      UserExtraTaoBaoInfo extraInfo = userExtraTaoBaoInfoService.getByUid(uid);
      try {
         String relationId = null;
         if (extraInfo.getRelationId() != null && extraInfo.getRelationValid() != null
         if (extraInfo != null && extraInfo.getRelationId() != null && extraInfo.getRelationValid() != null
               && extraInfo.getRelationValid() == true)
            relationId = extraInfo.getRelationId();
         TaoBaoLink taoBaoLink = shareGoodsService.getTaoBaoLinkForShare(uid, auctionId, relationId);
@@ -129,19 +184,26 @@
         String shopType = taoBaoLink.getGoods().getUserType() == 0 ? "淘宝价" : "天猫价";
         if (StringUtil.isNullOrEmpty(taoBaoLink.getGoods().getCouponInfo())) {
            String text = configService.get("goods_share_text_nocoupon");
            shareText = text.replace("[标题]", taoBaoLink.getGoods().getTitle()).replace("[在售价]",
                  "¥" + taoBaoLink.getGoods().getZkPrice());
            String text = shareGoodsTextTemplateService.getCommonTemplate(uid);
            if (StringUtil.isNullOrEmpty(text))
               text = configService.get("goods_share_text_nocoupon");
            shareText = text.replace("{标题}", taoBaoLink.getGoods().getTitle()).replace("{商品原价}",
                  MoneyBigDecimalUtil.getWithNoZera(taoBaoLink.getGoods().getZkPrice()) + "");
         } else// 有券
         {
            String text = configService.get("goods_share_text_coupon");
            shareText = text.replace("[标题]", taoBaoLink.getGoods().getTitle())
                  .replace("[在售价]", "¥" + taoBaoLink.getGoods().getZkPrice())
                  .replace("[优惠券金额]",
                        "¥" + BigDecimalUtil.getWithNoZera(taoBaoLink.getGoods().getCouponAmount()).toString())
                  .replace("[券后价]", "¥" + TaoBaoUtil.getAfterUseCouplePrice(taoBaoLink.getGoods()));
            String text = shareGoodsTextTemplateService.geteCouponTemplate(uid);
            if (StringUtil.isNullOrEmpty(text))
               text = configService.get("goods_share_text_coupon");
            shareText = text.replace("{标题}", taoBaoLink.getGoods().getTitle())
                  .replace("{商品原价}", MoneyBigDecimalUtil.getWithNoZera(taoBaoLink.getGoods().getZkPrice()) + "")
                  .replace("{优惠券面额}",
                        MoneyBigDecimalUtil.getWithNoZera(taoBaoLink.getGoods().getCouponAmount()).toString())
                  .replace("{优惠券价}", TaoBaoUtil.getAfterUseCouplePrice(taoBaoLink.getGoods()) + "");
         }
         shareText = shareText.replace("[价格类型]", shopType);
         shareText = shareText.replace("{店铺类型}", shopType)
               .replace("{月销量}", TaoBaoUtil.getSaleCount(taoBaoLink.getGoods().getBiz30day()))
               .replace("{领券短链}", shortLink).replace("{淘口令}", taoBaoLink.getTaoToken());
         data.put("shareText", shareText);
         String descText = shareText.replace(taoBaoLink.getGoods().getTitle(), "").trim();
         if (descText.startsWith("\\r\\n"))
@@ -350,4 +412,382 @@
      }
   }
   /**
    * 预览分享模板
    *
    * @param acceptData
    * @param uid
    * @param template
    * @param goodsId
    * @param hasCoupon
    * @param out
    */
   @RequestMapping(value = "viewShareTextTemplate", method = RequestMethod.POST)
   public void preViewShareTextTemplate(AcceptData acceptData, Long uid, String template, Long goodsId,
         Boolean hasCoupon, PrintWriter out) {
      if (uid == null) {
         out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
         return;
      }
      if (goodsId == null) {
         out.print(JsonUtil.loadFalseResult(3, "商品ID不能为空"));
         return;
      }
      TaoBaoGoodsBrief goods = taoBaoGoodsCacheUtil.getCommonTaoBaoGoodsInfo(goodsId);
      if (goods == null)
         try {
            goods = redisManager.getTaoBaoGoodsBrief(goodsId);
         } catch (TaobaoGoodsDownException e) {
            goods = null;
         }
      if (goods == null) {
         out.print(JsonUtil.loadFalseResult(4, "商品已下架"));
         return;
      }
      if (StringUtil.isNullOrEmpty(template))
         template = getShareTemplate(uid, hasCoupon);
      // 校验券模板是否正确
      if (hasCoupon) {
         // 有券商品
         try {
            shareGoodsTextTemplateService.isCouponTemplateRight(template);
         } catch (ShareGoodsTextTemplateException e) {
            out.print(JsonUtil.loadFalseResult(5, e.getMsg()));
            return;
         }
      } else {
         // 普通商品
         try {
            shareGoodsTextTemplateService.isCommonTemplateRight(template);
         } catch (ShareGoodsTextTemplateException e) {
            out.print(JsonUtil.loadFalseResult(5, e.getMsg()));
            return;
         }
      }
      // 查询是否有分享
      UserShareGoodsHistory userShareHistory = shareGoodsService.getShareGoodsHistory(uid, goods.getAuctionId());
      String url = String.format("http://%s%s?uid=%s&id=%s&appType=flq", configService.getH5Host(),
            Constant.systemCommonConfig.getShareGoodsPagePath(), AESUtil.encrypt(uid + "", Constant.UIDAESKEY),
            goods.getAuctionId() + "");
      String shortLink = HttpUtil.getShortLink(url);
      String token = "";
      if (userShareHistory != null) {
         token = userShareHistory.getTkCode();
      }
      if (StringUtil.isNullOrEmpty(token)) {
         TaoKeAppInfo app = new TaoKeAppInfo();
         app.setAdzoneId(TaoBaoConstant.TAOBAO_RELATION_PID_DEFAULT.split("_")[3]);
         app.setAppKey(TaoBaoConstant.TAOBAO_AUTH_APPKEY);
         app.setAppSecret(TaoBaoConstant.TAOBAO_AUTH_APPSECRET);
         app.setPid(TaoBaoConstant.TAOBAO_RELATION_PID_DEFAULT);
         TaoBaoGoodsBrief goodsLink = TaoKeApiUtil.specialConvertCoupon(goods.getAuctionId(), app);
         if (goodsLink != null)
            token = TaoKeApiUtil.getTKToken(goods.getPictUrl(), goods.getTitle(),
                  StringUtil.isNullOrEmpty(goodsLink.getCouponLink()) ? goodsLink.getAuctionUrl()
                        : goodsLink.getCouponLink());
      }
      String content = shareGoodsTextTemplateService.createContentByTemplate(template, uid, goods, token, shortLink,
            hasCoupon);
      JSONObject data = new JSONObject();
      data.put("content", content);
      out.print(JsonUtil.loadTrueResult(data));
   }
   /**
    * 保存模板
    *
    * @param acceptData
    * @param uid
    * @param hasCoupon
    * @param template
    * @param out
    */
   @RequestMapping(value = "saveShareTextTemplate", method = RequestMethod.POST)
   public void saveShareTextTemplate(AcceptData acceptData, Long uid, Boolean hasCoupon, String template,
         PrintWriter out) {
      if (StringUtil.isNullOrEmpty(template)) {
         out.print(JsonUtil.loadFalseResult(1, "分享模板为空"));
         return;
      }
      // 校验券模板是否正确
      if (hasCoupon) {
         // 有券商品
         try {
            shareGoodsTextTemplateService.isCouponTemplateRight(template);
            shareGoodsTextTemplateService.saveCouponTemplate(uid, template);
            out.print(JsonUtil.loadTrueResult(""));
         } catch (ShareGoodsTextTemplateException e) {
            out.print(JsonUtil.loadFalseResult(5, e.getMsg()));
            return;
         }
      } else {
         // 普通商品
         try {
            shareGoodsTextTemplateService.isCommonTemplateRight(template);
            shareGoodsTextTemplateService.saveCommonTemplate(uid, template);
            out.print(JsonUtil.loadTrueResult(""));
         } catch (ShareGoodsTextTemplateException e) {
            out.print(JsonUtil.loadFalseResult(5, e.getMsg()));
            return;
         }
      }
   }
   /**
    * 还原模板
    *
    * @param acceptData
    * @param uid
    * @param hasCoupon
    *            -是否有券
    * @param out
    */
   @RequestMapping(value = "resetShareTextTemplate", method = RequestMethod.POST)
   public void resetShareTextTemplate(AcceptData acceptData, Long uid, Long goodsId, Boolean hasCoupon,
         PrintWriter out) {
      if (uid == null) {
         out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
         return;
      }
      if (hasCoupon) {
         shareGoodsTextTemplateService.resetCouponTemplate(uid);
      } else {
         shareGoodsTextTemplateService.resetCommonTemplate(uid);
      }
      if (goodsId != null) {
         preViewShareTextTemplate(acceptData, uid, null, goodsId, hasCoupon, out);
         return;
      }
      out.print(JsonUtil.loadTrueResult(""));
   }
   private String getShareTemplate(Long uid, boolean hasCoupon) {
      if (hasCoupon) {
         String template = shareGoodsTextTemplateService.geteCouponTemplate(uid);
         if (StringUtil.isNullOrEmpty(template))
            template = configService.get("goods_share_text_coupon");
         return template;
      } else {
         String template = shareGoodsTextTemplateService.getCommonTemplate(uid);
         if (StringUtil.isNullOrEmpty(template))
            template = configService.get("goods_share_text_nocoupon");
         return template;
      }
   }
   /**
    * 获取分享模板
    *
    * @param acceptData
    * @param uid
    * @param hasCoupon
    * @param out
    */
   @RequestMapping(value = "getShareTextTemplate", method = RequestMethod.POST)
   public void getShareTextTemplate(AcceptData acceptData, Long uid, Boolean hasCoupon, PrintWriter out) {
      if (uid == null) {
         out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
         return;
      }
      JSONObject data = new JSONObject();
      data.put("template", getShareTemplate(uid, hasCoupon));
      out.print(JsonUtil.loadTrueResult(data));
   }
   /**
    * 获取分享模板编辑规则
    *
    * @param acceptData
    * @param out
    */
   @RequestMapping(value = "getShareTextTemplateRules", method = RequestMethod.POST)
   public void getShareTextTemplateRules(AcceptData acceptData, PrintWriter out) {
      out.print(JsonUtil.loadTrueResult(configService.get("share_goods_template_rules")));
   }
   /**
    * 查询顶部分类
    * @param acceptData
    * @param page
    * @param cid
    * @param out
    */
   @RequestMapping(value = "shareDynamic", method = RequestMethod.POST)
   public void shareDynamic(AcceptData acceptData, String id, Long uid, PrintWriter out) {
      try {
         if (uid == null || uid <= 0) {
            out.print(JsonUtil.loadFalseResult(1, "用户未登录"));
            return;
         }
         if (StringUtil.isNullOrEmpty(id)) {
            out.print(JsonUtil.loadFalseResult("参数不能为空"));
            return;
         }
         DynamicInfo dynamicInfo = dynamicInfoService.getById(id);
         if (dynamicInfo == null) {
            out.print(JsonUtil.loadFalseResult("该动态信息已不存在"));
            return;
         }
         JSONObject data = new JSONObject();
         // 分类id
         long cid = dynamicInfo.getClassId();
         if (cid == 1) {    // 热销单品
            // 文字内容
            data.put("title", JsonUtil.getApiCommonGson().toJson(dynamicInfo.getTitle()));
            // 分享奖金
            ClientTextStyleVO desc = dynamicInfo.getDesc();
            String content = desc.getContent();
            int index = content.indexOf("¥");
            data.put("shareMoney", new BigDecimal(content.substring(index + 1, content.length())));
            // 分享链接
            String url = String.format("http://%s/share_mushGoods.html?uid=%s&shareId=%s&source=%s",
                  configService.getH5Host(), AESUtil.encrypt(uid + "", Constant.UIDAESKEY), id, "dynamic");
            String shortLink = HttpUtil.getShortLink(url);
            if (!StringUtil.isNullOrEmpty(shortLink)) {
               url = shortLink;
            }
            data.put("clickUrl", url);
            // 分享文字图标
            String imgs = configService.get("goods_share_notify_imgs");
            JSONArray array = JSONArray.fromObject(imgs);
            int p = (int) (array.size() * Math.random());
            if (p < array.size()) {
               data.put("notifyPicture", array.optString(p));
            }
            UserExtraTaoBaoInfo extraInfo = userExtraTaoBaoInfoService.getByUid(uid);
            String relationId = null;
            if (extraInfo != null && extraInfo.getRelationId() != null && extraInfo.getRelationValid() != null
                  && extraInfo.getRelationValid() == true) {
               relationId = extraInfo.getRelationId();
            }
            TaoBaoLink taoBaoLink = shareGoodsService.getTaoBaoLinkForShare(uid, 42472466270L, relationId);
            // 淘宝口令
            data.put("token", taoBaoLink.getTaoToken());
            // 商品图片链接
            data.put("shareLink", TbImgUtil.getTBSizeImg(taoBaoLink.getGoods().getPictUrl(), 500));
            // 帮助链接
            data.put("helpLink","https://img.alicdn.com/imgextra/i1/2200656425615/O1CN01dst9HQ1rLiPN7xmhD_!!0-item_pic.jpg");
            // 分享提醒
            data.put("notifyDesc", configService.get("goods_share_notify"));
         } else if (cid == 2) {    // 推荐好货
            List<TaoBaoGoodsBrief> listGoods = new ArrayList<TaoBaoGoodsBrief>();
            List<GoodsPicture> listImgs = dynamicInfo.getImgs();
            for (GoodsPicture goodsPicture: listImgs) {
               TaoBaoGoodsBriefExtra goods = goodsPicture.getGoods();
               listGoods.add(goods);
            }
            String title = "";
            List<ClientTextStyleVO> listTitle = dynamicInfo.getTitle();
            for (ClientTextStyleVO textStyleVO: listTitle) {
               title = title + textStyleVO.getContent();
            }
            if (title.length() > 250) {
               title = title.substring(0, 250);
            }
            // 文字内容
            data.put("title", JsonUtil.getApiCommonGson().toJson(dynamicInfo.getTitle()));
            // 分享奖金
            ClientTextStyleVO desc = dynamicInfo.getDesc();
            String content = desc.getContent();
            int index = content.indexOf("¥");
            data.put("shareMoney", new BigDecimal(content.substring(index + 1, content.length())));
            // 分享文字图标
            String notifyImgs = configService.get("goods_share_notify_imgs");
            JSONArray array = JSONArray.fromObject(notifyImgs);
            int p = (int) (array.size() * Math.random());
            if (p < array.size()) {
               data.put("notifyPicture", array.optString(p));
            }
            ShareInfoDTO shareInfo = userShareGoodsRecordService.saveShareRecord(uid, ShareSourceTypeEnum.activity, title, listGoods);
            data.put("shareId", shareInfo.getShareId());
            data.put("clickUrl", shareInfo.getCodeUrl());
            // 商品图片链接
            data.put("shareLink", shareInfo.getShareUrl());
            // 帮助链接
            data.put("helpLink","https://img.alicdn.com/imgextra/i1/2200656425615/O1CN01dst9HQ1rLiPN7xmhD_!!0-item_pic.jpg");
            // 分享提醒
            data.put("notifyDesc", configService.get("goods_share_notify"));
         } else if (cid == 4) { // 邀请分享
            String inviteCode = null;
            UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
            if (userInfoExtra != null && !StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
               inviteCode = userInfoExtra.getInviteCode();
            } else {
               out.print(JsonUtil.loadFalseResult(9001, "邀请码未激活"));
               return;
            }
            Integer showType = dynamicInfo.getShowType();
            if (showType == 0) {  // 无图分享
               String shortLink = UserUtil.getInviteShortLink(uid);
               List<ClientTextStyleVO> listTitle = dynamicInfo.getTitle();
               for (ClientTextStyleVO textStyleVO: listTitle) {
                  String content = textStyleVO.getContent();
                  content = content.replace("邀请码", inviteCode);
                  content = content.replace("邀请链接", shortLink);
                  textStyleVO .setContent(content);
               }
               data.put("title", listTitle);
            } else { // 有图分享
               // 1、邀请规则
               BusinessSystem system = new BusinessSystem();
               system.setCreatetime(java.lang.System.currentTimeMillis());
               system.setPlatform(1);
               system.setId(4L);
               String key = "inviteRules"; // key值
               SystemClientParams values = systemClientParamsService.getSystemClientParamsBySystemAndKey(system, key);
               String valueN = values.getValue();
               String valueBr = valueN.replace("\n", "<br><br>");
               data.put("inviteRules", valueBr);
               // 邀请链接
               String shortLink = HttpUtil.getShortLink("http://" + Constant.wxGZConfig.getLoginHost() + "/"
                     + Constant.systemCommonConfig.getProjectName() + "/client/threeShareNew?uid=" + uid);
               data.put("inviteLink", shortLink);
               // 邀请图片
               List<GoodsPicture> imgs = dynamicInfo.getImgs();
               String imgLink = spreadUserImgService.getUserSpreadImg(uid, imgs.get(0).getUrl());
               data.put("imgLink", imgLink);
            }
         }
         out.print(JsonUtil.loadTrueResult(data));
      } catch (Exception e) {
         out.print(JsonUtil.loadFalseResult("分享记录失败"));
         e.printStackTrace();
      }
   }
}