admin
2024-10-16 62a447d89331aee1feae7724c7616aa1bb2cfe79
fanli/src/main/java/com/yeshi/fanli/service/impl/tlj/UserTaoLiJinRecordServiceImpl.java
@@ -1,499 +1,641 @@
package com.yeshi.fanli.service.impl.tlj;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.BigDecimalUtil;
import com.yeshi.fanli.dao.mybatis.tlj.UserTaoLiJinRecordMapper;
import com.yeshi.fanli.dto.msg.MsgOtherTaoLiJinContentDTO;
import com.yeshi.fanli.dto.taobao.TaoLiJinDTO;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinDetail;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinDetail.TaoLiJinDetailTypeEnum;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinOrigin;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinRecord;
import com.yeshi.fanli.entity.bus.user.UserMoneyExtra;
import com.yeshi.fanli.entity.goods.CommonGoods;
import com.yeshi.fanli.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.fanli.exception.taobao.TaoKeApiException;
import com.yeshi.fanli.exception.tlj.UserTaoLiJinRecordException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.goods.CommonGoodsService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoManageService;
import com.yeshi.fanli.service.inter.msg.UserOtherMsgNotificationService;
import com.yeshi.fanli.service.inter.taobao.ShareHotGoodsService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoBuyRelationMapService;
import com.yeshi.fanli.service.inter.tlj.ConfigTaoLiJinService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinDetailService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinOriginService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinRecordService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinReportService;
import com.yeshi.fanli.service.inter.user.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.service.inter.user.UserInfoExtraService;
import com.yeshi.fanli.service.inter.user.UserMoneyExtraService;
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.factory.CommonGoodsFactory;
import com.yeshi.fanli.util.taobao.TaoKeApiUtil;
import com.yeshi.fanli.util.taobao.TaoLiJinUtil;
import com.yeshi.fanli.vo.msg.ClientTextStyleVO;
import com.yeshi.fanli.vo.user.UserTaoLiJinRecordVO;
@Service
public class UserTaoLiJinRecordServiceImpl implements UserTaoLiJinRecordService {
   @Resource(name = "taskExecutor")
   private TaskExecutor executor;
   @Resource
   private RedisManager redisManager;
   @Resource
   private UserTaoLiJinRecordMapper userTaoLiJinRecordMapper;
   @Resource
   private CommonGoodsService commonGoodsService;
   @Resource
   private HongBaoManageService hongBaoManageService;
   @Resource
   private UserMoneyExtraService userMoneyExtraService;
   @Resource
   private UserTaoLiJinReportService userTaoLiJinReportService;
   @Resource
   private UserTaoLiJinDetailService userTaoLiJinDetailService;
   @Resource
   private UserTaoLiJinOriginService userTaoLiJinOriginService;
   @Resource
   private ConfigTaoLiJinService configTaoLiJinService;
   @Resource
   private UserOtherMsgNotificationService userOtherMsgNotificationService;
   @Resource
   private UserInfoExtraService userInfoExtraService;
   @Resource
   private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
   @Resource
   private TaoBaoBuyRelationMapService taoBaoBuyRelationMapService;
   @Resource
   private ShareHotGoodsService shareHotGoodsService;
   @Override
   public UserTaoLiJinRecord selectByPrimaryKey(Long id) {
      return userTaoLiJinRecordMapper.selectByPrimaryKey(id);
   }
   @Transactional
   @Override
   public UserTaoLiJinRecord createSelfBuyTaoLiJin(Long uid, int totalNum, TaoBaoGoodsBrief goods)
         throws UserTaoLiJinRecordException {
      Date date = new Date();
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
      SimpleDateFormat formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String date_str = format.format(date);
      String sendEndTime_str = date_str + " 22:00:00";
      String useEndTime_str = date_str + " 23:59:59";
      /* 创建淘礼金 */
      String name = "自购淘礼金红包";
      // 发放开始时间
      Date sendStartTime = date;
      // 发放截止时间 - 分享当日22:00
      Date sendEndTime = null;
      // 使用结束日期 - 分享当日 23:59
      Date useEndTime = null;
      try {
         sendEndTime = formatStr.parse(sendEndTime_str);
         useEndTime = formatStr.parse(useEndTime_str);
      } catch (ParseException e2) {
         e2.printStackTrace();
      }
      // 新人红包 自购一元
      BigDecimal perface = new BigDecimal(1);
      if (goods.getMaterialLibType() == null || goods.getMaterialLibType() == 0) {// 非返利库商品
         String relationId = null;
         try {
            relationId = taoBaoBuyRelationMapService.getRelationId(uid);
         } catch (Exception e) {
            LogHelper.errorDetailInfo(e, "uid:" + uid, null);
         }
         if (StringUtil.isNullOrEmpty(relationId)) {
            throw new UserTaoLiJinRecordException(101, "渠道未备案");
         }
         UserTaoLiJinRecord record = createUserTaoLiJin(1, uid, goods.getAuctionId(), perface, 1, name,
               sendStartTime, sendEndTime, null, useEndTime, TaoBaoConstant.TAOBAO_RELATION_AS_SPECIAL_PID);
         record.setSendUrl(record.getSendUrl() + "&relationId=" + relationId);
         UserTaoLiJinRecord updateRecoed=new UserTaoLiJinRecord();
         updateRecoed.setId(record.getId());
         updateRecoed.setSendUrl(record.getSendUrl());
         userTaoLiJinRecordMapper.updateByPrimaryKeySelective(record);
         return record;
      } else {// 返利库商品
         return createUserTaoLiJin(1, uid, goods.getAuctionId(), perface, 1, name, sendStartTime, sendEndTime, null,
               useEndTime, TaoBaoConstant.TAOBAO_SPECIAL_PID_DEFAULT);
      }
   }
   @Transactional
   @Override
   public UserTaoLiJinRecord createShareTaoLiJin(Long uid, int totalNum, TaoBaoGoodsBrief goods)
         throws UserTaoLiJinRecordException {
      String relationId = userExtraTaoBaoInfoService.getRelationIdByUid(uid);
      if (StringUtil.isNullOrEmpty(relationId))
         throw new UserTaoLiJinRecordException(101, "渠道未授权");
      Date date = new Date();
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
      SimpleDateFormat formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String date_str = format.format(date);
      String sendEndTime_str = date_str + " 22:00:00";
      String useEndTime_str = date_str + " 23:59:59";
      /* 创建淘礼金 */
      String name = "分享淘礼金红包";
      // 发放开始时间
      Date sendStartTime = date;
      // 发放截止时间 - 分享当日22:00
      Date sendEndTime = null;
      // 使用结束日期 - 分享当日 23:59
      Date useEndTime = null;
      try {
         sendEndTime = formatStr.parse(sendEndTime_str);
         useEndTime = formatStr.parse(useEndTime_str);
      } catch (ParseException e2) {
         e2.printStackTrace();
      }
      boolean isNewUser = userInfoExtraService.isNewUser(uid);
      if (isNewUser) {
         // 判定为老用户: 新人只要使用了新人红包,也就是那1块钱,那么,他看到的分享爆款中的商品-就只能分享。
         long countRecord = userTaoLiJinRecordMapper.countRecordByUid(uid);
         if (countRecord > 0) {
            isNewUser = false;
         }
      }
      BigDecimal perface = null;
      if (isNewUser) {
         perface = new BigDecimal(1);
      } else {
         // 计算推广红包
         String warningRate = configTaoLiJinService.getValueByKey("warning_value");
         perface = TaoLiJinUtil.getSpreadMoney(warningRate, goods);
      }
      UserTaoLiJinRecord record = createUserTaoLiJin(2, uid, goods.getAuctionId(), perface, totalNum, name,
            sendStartTime, sendEndTime, null, useEndTime, TaoBaoConstant.TAOBAO_RELATION_PID_DEFAULT);
      String sendUrl = record.getSendUrl() + "&relationId=" + relationId;
      record.setSendUrl(sendUrl);
      UserTaoLiJinRecord updateRecoed=new UserTaoLiJinRecord();
      updateRecoed.setId(record.getId());
      updateRecoed.setSendUrl(sendUrl);
      userTaoLiJinRecordMapper.updateByPrimaryKeySelective(record);
      return record;
   }
   @Override
   @Transactional
   public UserTaoLiJinRecord createUserTaoLiJin(int origin, Long uid, Long auctionId, BigDecimal perface, int totalNum,
         String name, Date sendStartTime, Date sendEndTime, Date useStartTime, Date useEndTime, String pid)
         throws UserTaoLiJinRecordException {
      // 用户剩余可以淘礼金验证
      UserMoneyExtra userMoneyExtra = userMoneyExtraService.selectByPrimaryKey(uid);
      if (userMoneyExtra == null || userMoneyExtra.getTlj() == null) {
         throw new UserTaoLiJinRecordException(101, "红包余额不足");
      }
      // 过期
      userTaoLiJinOriginService.overdueHongBao(uid);
      // 总推广红包
      BigDecimal totalMoney = MoneyBigDecimalUtil.mul(perface, new BigDecimal(totalNum));
      // 自购时的红包余额
      if (origin == 1) {
         BigDecimal tljSelf = userMoneyExtra.getTljSelf();
         if (tljSelf == null || tljSelf.compareTo(totalMoney) < 0) {
            throw new UserTaoLiJinRecordException(101, "自购红包余额不足");
         }
      }
      // 分享时的红包余额
      BigDecimal tlj = userMoneyExtra.getTlj();
      if (tlj == null || tlj.compareTo(totalMoney) < 0) {
         throw new UserTaoLiJinRecordException(101, "分享红包余额不足");
      }
      // 创建淘礼金红包
      TaoLiJinDTO taoLiJinDTO = null;
      try {
         taoLiJinDTO = TaoKeApiUtil.createTaoLiJin(auctionId, name, perface, totalNum, sendStartTime,
               sendEndTime, useStartTime, useEndTime, pid);
      } catch (TaoKeApiException e) {
         LogHelper.errorDetailInfo(e);
         executor.execute(new Runnable() {
            @Override
            public void run() {
               if (e.getCode() == TaoKeApiException.CODE_TLJ_FORBIDDEN) {
                  // 该商品不支持创建淘礼金红包
                  shareHotGoodsService.deleteByGoodsId(auctionId);
               } else if (e.getCode() == TaoKeApiException.CODE_TLJ_NO_MONEY) {
                  // 官方玩法钱包余额不足  TODO
               }
            }
         });
      }
      if (taoLiJinDTO == null) {
         throw new UserTaoLiJinRecordException(101, "淘宝API推广红包创建失败");
      }
      // 保存记录
      UserTaoLiJinRecord record = new UserTaoLiJinRecord();
      record.setUid(uid);
      record.setGoodsId(auctionId);
      record.setName(name);
      record.setPerFace(perface);
      record.setTotalNum(totalNum);
      record.setSendStartTime(sendStartTime);
      record.setSendEndTime(sendEndTime);
      record.setUseStartTime(useStartTime);
      record.setUseEndTime(useEndTime);
      record.setRightsId(taoLiJinDTO.getRightsId());
      record.setSendUrl(taoLiJinDTO.getSendUrl());
      record.setCreateTime(new Date());
      if (origin == 1) { //  自购
         record.setUseType(1);
      } else { //  分享
         record.setUseType(2);
      }
      userTaoLiJinRecordMapper.insertSelective(record);
      BigDecimal surplusTlj = MoneyBigDecimalUtil.sub(tlj, totalMoney);
      UserMoneyExtra updateExtra = new UserMoneyExtra();
      updateExtra.setUid(uid);
      if (origin == 1) { // 剩余淘礼金-- 自购
         updateExtra.setTljSelf(MoneyBigDecimalUtil.sub(userMoneyExtra.getTljSelf(), totalMoney));
      }
      updateExtra.setTlj(surplusTlj);
      updateExtra.setUpdateTime(new Date());
      userMoneyExtraService.updateByPrimaryKeySelective(updateExtra);
      record.setSurplusMoney(surplusTlj);
      // 异步
      String rightsId = taoLiJinDTO.getRightsId();
      executor.execute(new Runnable() {
         @Override
         public void run() {
            try {
               // 插入明细
               UserTaoLiJinDetail detail = new UserTaoLiJinDetail();
               detail.setUid(uid);
               detail.setMoney(new BigDecimal("-" + totalMoney));
               detail.setTitle(TaoLiJinDetailTypeEnum.reduce.getDesc());
               detail.setType(TaoLiJinDetailTypeEnum.reduce);
               detail.setCreateTime(new Date());
               userTaoLiJinDetailService.insertSelective(detail);
            } catch (Exception e) {
               LogHelper.errorDetailInfo(e);
            }
            // 成功使用红包
            try {
               BigDecimal total = totalMoney;
               BigDecimal lastMoney = null;
               BigDecimal zero = new BigDecimal(0);
               // 修改余额
               List<UserTaoLiJinOrigin> list = userTaoLiJinOriginService.getSurplusLiJin(uid);
               if (list != null && list.size() > 0) {
                  for (UserTaoLiJinOrigin taoLiJinOrigin : list) {
                     if (total.compareTo(zero) < 1) {
                        break;
                     }
                     BigDecimal moneySurplus = taoLiJinOrigin.getMoneySurplus();
                     lastMoney = total;
                     total = MoneyBigDecimalUtil.sub(total, moneySurplus);
                     if (total.compareTo(zero) >= 0) {
                        moneySurplus = zero;
                     } else {
                        moneySurplus = MoneyBigDecimalUtil.sub(moneySurplus, lastMoney);
                     }
                     UserTaoLiJinOrigin usertlj = new UserTaoLiJinOrigin();
                     usertlj.setId(taoLiJinOrigin.getId());
                     usertlj.setMoneySurplus(moneySurplus);
                     usertlj.setUpdateTime(new Date());
                     userTaoLiJinOriginService.updateByPrimaryKeySelective(usertlj);
                  }
               }
            } catch (Exception e) {
               LogHelper.errorDetailInfo(e);
            }
            // 创建报告
            try {
               userTaoLiJinReportService.insertDefault(rightsId);
            } catch (Exception e) {
               LogHelper.errorDetailInfo(e);
            }
            if (origin == 1) {
               return; //  自购不推送消息
            }
            // 使用成功消息
            try {
               String beizhu = "未被领取/使用的部分将会退回";
               SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd hh.mm");
               String time = sd.format(new Date());
               MsgOtherTaoLiJinContentDTO content = new MsgOtherTaoLiJinContentDTO();
               content.setState("红包扣除");
               content.setSource(time + " 创建的分享记录");
               content.setMoney(totalMoney);
               userOtherMsgNotificationService.taoLiJinMsg(uid, beizhu, content);
            } catch (Exception e) {
               LogHelper.errorDetailInfo(e);
            }
            // 检测商品是否存在
            try {
               CommonGoods commonGoods = commonGoodsService.getCommonGoodsByGoodsIdAndGoodsType(auctionId,
                     CommonGoods.GOODS_TYPE_TB);
               if (commonGoods == null) {
                  TaoBaoGoodsBrief taoBaoGoodsBrief = redisManager.getTaoBaoGoodsBrief(auctionId);
                  if (taoBaoGoodsBrief != null) {
                     commonGoodsService.addCommonGoods(CommonGoodsFactory.create(taoBaoGoodsBrief));
                  }
               }
            } catch (Exception e) {
               LogHelper.errorDetailInfo(e);
            }
         }
      });
      return record;
   }
   @Override
   public List<UserTaoLiJinRecordVO> getRecordByUid(long start, int count, Long uid) {
      List<UserTaoLiJinRecordVO> list = userTaoLiJinRecordMapper.getRecordByUid(start, count, uid);
      if (list == null || list.size() == 0) {
         return list;
      }
      List<Long> listGoodsId = new ArrayList<Long>();
      for (UserTaoLiJinRecordVO userTaoLiJinRecordVO : list) {
         listGoodsId.add(userTaoLiJinRecordVO.getAuctionId());
      }
      if (listGoodsId.size() == 0) {
         return null;
      }
      List<CommonGoods> listGoods = commonGoodsService.getByListGoodsId(listGoodsId);
      if (listGoods == null || listGoods.size() == 0) {
         return null;
      }
      // 组织相关数据
      for (UserTaoLiJinRecordVO userTaoLiJinRecordVO : list) {
         long auctionId = userTaoLiJinRecordVO.getAuctionId().longValue();
         // 商品信息
         for (int i = 0; i < listGoods.size(); i++) {
            CommonGoods commonGoods = listGoods.get(i);
            long goodsId = commonGoods.getGoodsId().longValue();
            if (auctionId == goodsId) {
               userTaoLiJinRecordVO.setTitle(commonGoods.getTitle());
               userTaoLiJinRecordVO.setPictUrl(commonGoods.getPicture());
               if (CommonGoods.SHOP_TYPE_TB == commonGoods.getShopType()) {
                  userTaoLiJinRecordVO.setUserType(0);
               } else {
                  userTaoLiJinRecordVO.setUserType(1);
               }
               break;
            }
         }
         // 计算剩余未领取数量
         int winNum = userTaoLiJinRecordVO.getWinNum();
         int totalNum = userTaoLiJinRecordVO.getTotalNum();
         userTaoLiJinRecordVO.setSurplusNum(totalNum - winNum);
         // 计算分享奖金
         BigDecimal shareMoney = new BigDecimal(0);
         BigDecimal commission = userTaoLiJinRecordVO.getCommission();
         if (commission != null && commission.compareTo(shareMoney) > 0) {
            BigDecimal shareRate = hongBaoManageService.getShareRate();
            shareMoney = MoneyBigDecimalUtil.mul(commission, MoneyBigDecimalUtil.div(shareRate, new BigDecimal(100)));
            shareMoney = BigDecimalUtil.getWithNoZera(shareMoney);
         }
         ClientTextStyleVO desc = new ClientTextStyleVO();
         desc.setColor("#FFFFFF");
         desc.setContent("预估分享奖金:¥" + shareMoney);
         desc.setBottomColor("#E8AE48");
         userTaoLiJinRecordVO.setDesc(desc);
      }
      return list;
   }
   @Override
   public long countRecordByUid(Long uid) {
      return userTaoLiJinRecordMapper.countRecordByUid(uid);
   }
   @Override
   public long countShareRecordByUid(Long uid) {
      return userTaoLiJinRecordMapper.countShareRecordByUid(uid);
   }
   @Override
   public long countTodayNum(Long uid) {
      return userTaoLiJinRecordMapper.countTodayNum(uid);
   }
   @Override
   public BigDecimal getShareHongBaoByUidAndGoodsId(Long uid, Long goodsId) {
      return userTaoLiJinRecordMapper.getShareHongBaoByUidAndGoodsId(uid, goodsId);
   }
   @Override
   public UserTaoLiJinRecord getByRightsId(String rightsId) {
      return userTaoLiJinRecordMapper.getByRightsId(rightsId);
   }
}
package com.yeshi.fanli.service.impl.tlj;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import com.yeshi.fanli.entity.SystemEnum;
import com.yeshi.fanli.entity.SystemPIDInfo;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.manger.PIDManager;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yeshi.utils.BigDecimalUtil;
import org.yeshi.utils.DateUtil;
import com.yeshi.fanli.dao.mybatis.tlj.UserTaoLiJinRecordMapper;
import com.yeshi.fanli.dto.msg.MsgOtherTaoLiJinContentDTO;
import com.yeshi.fanli.dto.taobao.TaoLiJinDTO;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinDetail;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinDetail.TaoLiJinDetailTypeEnum;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinGiveRecord;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinOrigin;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinRecord;
import com.yeshi.fanli.entity.bus.user.TokenRecord;
import com.yeshi.fanli.entity.bus.user.TokenRecord.TokenTypeEnum;
import com.yeshi.fanli.entity.bus.user.vip.UserLevelEnum;
import com.yeshi.fanli.entity.bus.user.UserMoneyExtra;
import com.yeshi.fanli.entity.goods.CommonGoods;
import com.yeshi.fanli.entity.system.ConfigKeyEnum;
import com.yeshi.goods.facade.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.common.entity.taobao.TaoKeAppInfo;
import com.yeshi.fanli.exception.taobao.TaoKeApiException;
import com.yeshi.fanli.exception.tlj.TaoLiJinCreateException;
import com.yeshi.fanli.exception.tlj.UserTaoLiJinRecordException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.goods.CommonGoodsService;
import com.yeshi.fanli.service.inter.money.UserMoneyExtraService;
import com.yeshi.fanli.service.inter.msg.UserOtherMsgNotificationService;
import com.yeshi.fanli.service.inter.order.config.HongBaoManageService;
import com.yeshi.fanli.service.inter.taobao.ShareHotGoodsService;
import com.yeshi.fanli.service.inter.taobao.TaoBaoBuyRelationMapService;
import com.yeshi.fanli.service.inter.tlj.ConfigTaoLiJinService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinDetailService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinGiveRecordService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinOriginService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinRecordService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinReportService;
import com.yeshi.fanli.service.inter.user.TokenRecordService;
import com.yeshi.fanli.service.inter.user.UserInfoExtraService;
import com.yeshi.fanli.service.inter.user.tb.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.util.Constant;
import org.yeshi.utils.MoneyBigDecimalUtil;
import com.yeshi.fanli.util.RedisManager;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TaoBaoConstant;
import com.yeshi.fanli.util.TokenUtil;
import com.yeshi.fanli.util.factory.CommonGoodsFactory;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
import com.yeshi.fanli.util.taobao.TaoKeApiUtil;
import com.yeshi.fanli.util.taobao.TaoLiJinUtil;
import com.yeshi.common.vo.ClientTextStyleVO;
import com.yeshi.fanli.vo.user.UserTaoLiJinRecordVO;
@Service
public class UserTaoLiJinRecordServiceImpl implements UserTaoLiJinRecordService {
    @Resource(name = "taskExecutor")
    private TaskExecutor executor;
    @Resource
    private RedisManager redisManager;
    @Resource
    private ConfigService configService;
    @Resource
    private UserTaoLiJinRecordMapper userTaoLiJinRecordMapper;
    @Resource
    private CommonGoodsService commonGoodsService;
    @Resource
    private HongBaoManageService hongBaoManageService;
    @Resource
    private UserMoneyExtraService userMoneyExtraService;
    @Resource
    private UserTaoLiJinReportService userTaoLiJinReportService;
    @Resource
    private UserTaoLiJinDetailService userTaoLiJinDetailService;
    @Resource
    private UserTaoLiJinOriginService userTaoLiJinOriginService;
    @Resource
    private ConfigTaoLiJinService configTaoLiJinService;
    @Resource
    private UserOtherMsgNotificationService userOtherMsgNotificationService;
    @Resource
    private UserInfoExtraService userInfoExtraService;
    @Resource
    private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
    @Resource
    private TaoBaoBuyRelationMapService taoBaoBuyRelationMapService;
    @Resource
    private ShareHotGoodsService shareHotGoodsService;
    @Resource
    private TokenRecordService tokenRecordService;
    @Resource
    private UserTaoLiJinGiveRecordService userTaoLiJinGiveRecordService;
    @Resource
    private UserInfoService userInfoService;
    @Override
    public UserTaoLiJinRecord selectByPrimaryKey(Long id) {
        return userTaoLiJinRecordMapper.selectByPrimaryKey(id);
    }
    @Resource
    private PIDManager pidManager;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserTaoLiJinRecord createSelfBuyTaoLiJin(Long uid, BigDecimal couplePrice, TaoBaoGoodsBrief goods)
            throws UserTaoLiJinRecordException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date_str = format.format(date);
        String sendEndTime_str = date_str + " 22:00:00";
        String useEndTime_str = date_str + " 23:59:59";
        /* 创建淘礼金 */
        String name = "自购淘礼金红包";
        // 发放开始时间
        Date sendStartTime = date;
        // 发放截止时间 - 分享当日22:00
        Date sendEndTime = null;
        // 使用结束日期 - 分享当日 23:59
        Date useEndTime = null;
        try {
            sendEndTime = formatStr.parse(sendEndTime_str);
            useEndTime = formatStr.parse(useEndTime_str);
        } catch (ParseException e2) {
            e2.printStackTrace();
        }
        if (!TaoBaoUtil.isSpecialGoods(goods.getMaterialLibType())) {// 非返利库商品
            String relationId = null;
            try {
                relationId = taoBaoBuyRelationMapService.getRelationId(uid);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e, "uid:" + uid, null);
            }
            if (StringUtil.isNullOrEmpty(relationId)) {
                throw new UserTaoLiJinRecordException(101, "渠道未备案");
            }
            UserTaoLiJinRecord record = createUserTaoLiJin(1, uid, goods.getAuctionId(), couplePrice, 1, name,
                    sendStartTime, sendEndTime, null, useEndTime, pidManager.getPidCache(SystemEnum.blks, Constant.SOURCE_TYPE_TAOBAO, SystemPIDInfo.PidType.fanliChannel));
            record.setSendUrl(record.getSendUrl() + "&relationId=" + relationId);
            UserTaoLiJinRecord updateRecoed = new UserTaoLiJinRecord();
            updateRecoed.setId(record.getId());
            updateRecoed.setSendUrl(record.getSendUrl());
            userTaoLiJinRecordMapper.updateByPrimaryKeySelective(record);
            return record;
        } else {// 返利库商品
            return createUserTaoLiJin(1, uid, goods.getAuctionId(), couplePrice, 1, name, sendStartTime, sendEndTime, null,
                    useEndTime,  pidManager.getPidCache(SystemEnum.blks, Constant.SOURCE_TYPE_TAOBAO, SystemPIDInfo.PidType.fanli));
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserTaoLiJinRecord createShareTaoLiJin(Long uid, int totalNum, TaoBaoGoodsBrief goods)
            throws UserTaoLiJinRecordException {
        String relationId = userExtraTaoBaoInfoService.getRelationIdByUid(uid);
        if (StringUtil.isNullOrEmpty(relationId))
            throw new UserTaoLiJinRecordException(101, "渠道未授权");
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date_str = format.format(date);
        String sendEndTime_str = date_str + " 22:00:00";
        String useEndTime_str = date_str + " 23:59:59";
        /* 创建淘礼金 */
        String name = "分享淘礼金红包";
        // 发放开始时间
        Date sendStartTime = date;
        // 发放截止时间 - 分享当日22:00
        Date sendEndTime = null;
        // 使用结束日期 - 分享当日 23:59
        Date useEndTime = null;
        try {
            sendEndTime = formatStr.parse(sendEndTime_str);
            useEndTime = formatStr.parse(useEndTime_str);
        } catch (ParseException e2) {
            e2.printStackTrace();
        }
        boolean isNewUser = userInfoExtraService.isNewUser(uid);
        if (isNewUser) {
            // 判定为老用户: 新人只要使用了新人红包,也就是那1块钱,那么,他看到的分享爆款中的商品-就只能分享。
            long countRecord = userTaoLiJinRecordMapper.countRecordByUid(uid);
            if (countRecord > 0) {
                isNewUser = false;
            }
        }
        BigDecimal perface = null;
        if (isNewUser) {
            perface = new BigDecimal(1);
        } else {
            // 计算推广红包
            String warningRate = configTaoLiJinService.getValueByKey("warning_value", new Date());
            perface = TaoLiJinUtil.getSpreadMoney(warningRate, goods);
        }
        UserTaoLiJinRecord record = createUserTaoLiJin(2, uid, goods.getAuctionId(), perface, totalNum, name,
                sendStartTime, sendEndTime, null, useEndTime, TaoBaoConstant.TAOBAO_TLJ_RELATION_PID_DEFAULT);
        String sendUrl = record.getSendUrl() + "&relationId=" + relationId;
        record.setSendUrl(sendUrl);
        UserTaoLiJinRecord updateRecoed = new UserTaoLiJinRecord();
        updateRecoed.setId(record.getId());
        updateRecoed.setSendUrl(sendUrl);
        userTaoLiJinRecordMapper.updateByPrimaryKeySelective(record);
        return record;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserTaoLiJinRecord createUserTaoLiJin(int origin, Long uid, String auctionId, BigDecimal perface, int totalNum,
                                                 String name, Date sendStartTime, Date sendEndTime, Date useStartTime, Date useEndTime, String pid)
            throws UserTaoLiJinRecordException {
        // 用户剩余可以淘礼金验证
        UserMoneyExtra userMoneyExtra = userMoneyExtraService.selectByPrimaryKey(uid);
        if (userMoneyExtra == null || userMoneyExtra.getTlj() == null) {
            throw new UserTaoLiJinRecordException(101, "红包余额不足");
        }
        // 过期 -取消收回
        // userTaoLiJinOriginService.overdueHongBao(uid);
        // 总推广红包
        BigDecimal totalMoney = MoneyBigDecimalUtil.mul(perface, new BigDecimal(totalNum));
        // 自购时的红包余额
        if (origin == 1) {
            BigDecimal tljSelf = userMoneyExtra.getTljSelf();
            if (tljSelf == null || tljSelf.compareTo(totalMoney) < 0) {
                throw new UserTaoLiJinRecordException(101, "自购红包余额不足");
            }
        }
        // 分享时的红包余额
        BigDecimal tlj = userMoneyExtra.getTlj();
        if (tlj == null || tlj.compareTo(totalMoney) < 0) {
            throw new UserTaoLiJinRecordException(101, "分享红包余额不足");
        }
        // 创建淘礼金红包
        TaoLiJinDTO taoLiJinDTO = null;
        try {
            taoLiJinDTO = TaoKeApiUtil.createTaoLiJin(auctionId, name, perface, totalNum, sendStartTime, sendEndTime,
                    useStartTime, useEndTime,
                    new TaoKeAppInfo(TaoBaoConstant.TAOBAO_AUTH_APPKEY, TaoBaoConstant.TAOBAO_AUTH_APPSECRET, pid));
        } catch (TaoLiJinCreateException e) {
            LogHelper.errorDetailInfo(e);
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    if (e.getCode() == TaoLiJinCreateException.CODE_TLJ_FORBIDDEN) {
                        // 该商品不支持创建淘礼金红包
                        shareHotGoodsService.deleteByGoodsId(auctionId);
                    } else if (e.getCode() == TaoLiJinCreateException.CODE_TLJ_NO_MONEY) {
                        // 官方玩法钱包余额不足 TODO
                    }
                }
            });
        } catch (TaoKeApiException e1) {
        }
        if (taoLiJinDTO == null) {
            throw new UserTaoLiJinRecordException(101, "淘宝API推广红包创建失败");
        }
        // 保存记录
        UserTaoLiJinRecord record = new UserTaoLiJinRecord();
        record.setUid(uid);
        record.setGoodsId(auctionId);
        record.setName(name);
        record.setPerFace(perface);
        record.setTotalNum(totalNum);
        record.setSendStartTime(sendStartTime);
        record.setSendEndTime(sendEndTime);
        record.setUseStartTime(useStartTime);
        record.setUseEndTime(useEndTime);
        record.setRightsId(taoLiJinDTO.getRightsId());
        record.setSendUrl(taoLiJinDTO.getSendUrl());
        record.setCreateTime(new Date());
        if (origin == 1) { // 自购
            record.setUseType(1);
        } else { // 分享
            record.setUseType(2);
        }
        userTaoLiJinRecordMapper.insertSelective(record);
        BigDecimal surplusTlj = MoneyBigDecimalUtil.sub(tlj, totalMoney);
        UserMoneyExtra updateExtra = new UserMoneyExtra();
        updateExtra.setUid(uid);
        if (origin == 1) { // 剩余淘礼金-- 自购
            updateExtra.setTljSelf(MoneyBigDecimalUtil.sub(userMoneyExtra.getTljSelf(), totalMoney));
        }
        updateExtra.setTlj(surplusTlj);
        updateExtra.setUpdateTime(new Date());
        userMoneyExtraService.updateByPrimaryKeySelective(updateExtra);
        record.setSurplusMoney(surplusTlj);
        // 异步
        String rightsId = taoLiJinDTO.getRightsId();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 插入明细
                    UserTaoLiJinDetail detail = new UserTaoLiJinDetail();
                    detail.setUid(uid);
                    detail.setMoney(new BigDecimal("-" + totalMoney));
                    detail.setTitle(TaoLiJinDetailTypeEnum.reduce.getDesc());
                    detail.setType(TaoLiJinDetailTypeEnum.reduce);
                    detail.setCreateTime(new Date());
                    userTaoLiJinDetailService.insertSelective(detail);
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
                // 成功使用红包
                try {
                    BigDecimal total = totalMoney;
                    BigDecimal lastMoney = null;
                    BigDecimal zero = new BigDecimal(0);
                    // 修改余额
                    List<UserTaoLiJinOrigin> list = userTaoLiJinOriginService.getSurplusLiJin(uid);
                    if (list != null && list.size() > 0) {
                        for (UserTaoLiJinOrigin taoLiJinOrigin : list) {
                            if (total.compareTo(zero) < 1) {
                                break;
                            }
                            BigDecimal moneySurplus = taoLiJinOrigin.getMoneySurplus();
                            lastMoney = total;
                            total = MoneyBigDecimalUtil.sub(total, moneySurplus);
                            if (total.compareTo(zero) >= 0) {
                                moneySurplus = zero;
                            } else {
                                moneySurplus = MoneyBigDecimalUtil.sub(moneySurplus, lastMoney);
                            }
                            UserTaoLiJinOrigin usertlj = new UserTaoLiJinOrigin();
                            usertlj.setId(taoLiJinOrigin.getId());
                            usertlj.setMoneySurplus(moneySurplus);
                            usertlj.setUpdateTime(new Date());
                            userTaoLiJinOriginService.updateByPrimaryKeySelective(usertlj);
                        }
                    }
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
                // 创建报告
                try {
                    userTaoLiJinReportService.insertDefault(rightsId);
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
                if (origin == 1) {
                    return; // 自购不推送消息
                }
                // 使用成功消息
                try {
                    String beizhu = "未被领取或领取后未使用部分退回";
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                    String time = sd.format(new Date());
                    MsgOtherTaoLiJinContentDTO content = new MsgOtherTaoLiJinContentDTO();
                    content.setState("红包扣除");
                    content.setSource(time + " 创建的分享记录");
                    content.setMoney(totalMoney);
                    //userOtherMsgNotificationService.taoLiJinMsg(uid, beizhu, content);
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
                // 检测商品是否存在
                try {
                    CommonGoods commonGoods = commonGoodsService.getCommonGoodsByGoodsIdAndGoodsType(auctionId,
                            CommonGoods.GOODS_TYPE_TB);
                    if (commonGoods == null) {
                        TaoBaoGoodsBrief taoBaoGoodsBrief = redisManager.getTaoBaoGoodsBrief(auctionId);
                        if (taoBaoGoodsBrief != null) {
                            commonGoodsService.addCommonGoods(CommonGoodsFactory.create(taoBaoGoodsBrief));
                        }
                    }
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
            }
        });
        return record;
    }
    @Override
    public List<UserTaoLiJinRecordVO> getRecordByUid(long start, int count, Long uid) {
        List<UserTaoLiJinRecordVO> list = userTaoLiJinRecordMapper.getRecordByUid(start, count, uid);
        if (list == null || list.size() == 0) {
            return list;
        }
        List<String> listGoodsId = new ArrayList<>();
        for (UserTaoLiJinRecordVO userTaoLiJinRecordVO : list) {
            listGoodsId.add(userTaoLiJinRecordVO.getAuctionId());
        }
        if (listGoodsId.size() == 0) {
            return null;
        }
        List<CommonGoods> listGoods = commonGoodsService.getByListGoodsId(listGoodsId, Constant.SOURCE_TYPE_TAOBAO);
        if (listGoods == null || listGoods.size() == 0) {
            return null;
        }
        // 组织相关数据
        for (UserTaoLiJinRecordVO userTaoLiJinRecordVO : list) {
            String auctionId = userTaoLiJinRecordVO.getAuctionId();
            // 商品信息
            for (int i = 0; i < listGoods.size(); i++) {
                CommonGoods commonGoods = listGoods.get(i);
                String goodsId = commonGoods.getGoodsId();
                if (TaoBaoUtil.isEqual(auctionId , goodsId)) {
                    userTaoLiJinRecordVO.setTitle(commonGoods.getTitle());
                    userTaoLiJinRecordVO.setPictUrl(commonGoods.getPicture());
                    if (CommonGoods.SHOP_TYPE_TB == commonGoods.getShopType()) {
                        userTaoLiJinRecordVO.setUserType(0);
                    } else {
                        userTaoLiJinRecordVO.setUserType(1);
                    }
                    break;
                }
            }
            // 计算剩余未领取数量
            int winNum = userTaoLiJinRecordVO.getWinNum();
            int totalNum = userTaoLiJinRecordVO.getTotalNum();
            userTaoLiJinRecordVO.setSurplusNum(totalNum - winNum);
            SystemEnum system = userInfoService.getUserSystem(uid);
            // 计算分享奖金
            BigDecimal shareMoney = new BigDecimal(0);
            BigDecimal commission = userTaoLiJinRecordVO.getCommission();
            if (commission != null && commission.compareTo(shareMoney) > 0) {
                BigDecimal shareRate = hongBaoManageService.getShareRate(UserLevelEnum.daRen, system);
                shareMoney = MoneyBigDecimalUtil.mul(commission,
                        MoneyBigDecimalUtil.div(shareRate, new BigDecimal(100)));
                shareMoney = BigDecimalUtil.getWithNoZera(shareMoney);
            }
            ClientTextStyleVO desc = new ClientTextStyleVO();
            desc.setColor("#FFFFFF");
            desc.setContent("预估分享奖金:¥" + shareMoney);
            desc.setBottomColor("#E8AE48");
            userTaoLiJinRecordVO.setDesc(desc);
        }
        return list;
    }
    @Override
    public long countRecordByUid(Long uid) {
        return userTaoLiJinRecordMapper.countRecordByUid(uid);
    }
    @Override
    public long countShareRecordByUid(Long uid) {
        return userTaoLiJinRecordMapper.countShareRecordByUid(uid);
    }
    @Override
    public long countTodayNum(Long uid) {
        return userTaoLiJinRecordMapper.countTodayNum(uid);
    }
    @Override
    public BigDecimal getShareHongBaoByUidAndGoodsId(Long uid, Long goodsId) {
        return userTaoLiJinRecordMapper.getShareHongBaoByUidAndGoodsId(uid, goodsId);
    }
    @Override
    public UserTaoLiJinRecord getByRightsId(String rightsId) {
        return userTaoLiJinRecordMapper.getByRightsId(rightsId);
    }
    @Override
    public String giveTaolijin(Long uid, BigDecimal amount) throws UserTaoLiJinRecordException {
        if (uid == null || amount == null)
            throw new UserTaoLiJinRecordException(1, "参数不正确");
        String giveMin = configTaoLiJinService.getValueByKey("give_min_amount");
        if (amount.compareTo(new BigDecimal(giveMin)) < 0)
            throw new UserTaoLiJinRecordException(1, "赠送推广红包金额至少" + giveMin + "元");
        // 用户剩余可以淘礼金验证
        UserMoneyExtra userMoneyExtra = userMoneyExtraService.selectByPrimaryKey(uid);
        if (userMoneyExtra == null || userMoneyExtra.getTlj() == null)
            throw new UserTaoLiJinRecordException(1, "红包余额不足");
        BigDecimal tlj = userMoneyExtra.getTlj();
        if (amount.compareTo(tlj) > 0)
            throw new UserTaoLiJinRecordException(1, "红包余额不足");
        Date nowDate = new Date();
        // 赠送记录
        UserTaoLiJinGiveRecord giveRecord = new UserTaoLiJinGiveRecord();
        giveRecord.setAmount(amount);
        giveRecord.setGiveUid(uid);
        giveRecord.setState(UserTaoLiJinGiveRecord.STATE_INIT);
        giveRecord.setGiveTime(nowDate);
        giveRecord.setEndTime(DateUtil.plusDayDate(Constant.GIVE_DAYS, new Date()));
        userTaoLiJinGiveRecordService.insertSelective(giveRecord);
        // 口令记录
        TokenRecord tokenRecord = new TokenRecord();
        tokenRecord.setUid(uid);
        tokenRecord.setIdentify(giveRecord.getId() + "");
        tokenRecord.setType(TokenTypeEnum.taoLiJin);
        tokenRecord.setStartTime(nowDate);
        tokenRecord.setEndTime(DateUtil.plusDayDate(Constant.TOKEN_DAYS, new Date()));
        tokenRecord.setState(0);
        tokenRecordService.insertSelective(tokenRecord);
        // 创建口令
        String token = TokenUtil.createToken(tokenRecord.getId());
        tokenRecord.setToken(token);
        tokenRecordService.updateByPrimaryKeySelective(tokenRecord);
        // 更新余额
        UserMoneyExtra updateExtra = new UserMoneyExtra();
        updateExtra.setUid(uid);
        updateExtra.setTlj(MoneyBigDecimalUtil.sub(tlj, amount));
        updateExtra.setUpdateTime(new Date());
        userMoneyExtraService.updateByPrimaryKeySelective(updateExtra);
        SystemEnum system = userInfoService.getUserSystem(uid);
        String tips = configTaoLiJinService.getValueByKey("give_taolijin_tips");
        String projectChineseName = Constant.systemCommonConfig.getProjectChineseName();
        while (tips.contains("{APP名称}")) {
            tips = tips.replace("{APP名称}", projectChineseName);
        }
        tips = tips.replace("{口令}", token).replace("{下载链接}", configService.getValue(ConfigKeyEnum.appDownLink.getKey(), system)).replace("{面额}",
                amount.setScale(0).toString());
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 插入明细
                    UserTaoLiJinDetail detail = new UserTaoLiJinDetail();
                    detail.setUid(uid);
                    detail.setMoney(new BigDecimal("-" + amount));
                    detail.setTitle(TaoLiJinDetailTypeEnum.give.getDesc());
                    detail.setType(TaoLiJinDetailTypeEnum.give);
                    detail.setCreateTime(new Date());
                    userTaoLiJinDetailService.insertSelective(detail);
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
                // 成功使用红包
                try {
                    BigDecimal total = amount;
                    BigDecimal lastMoney = null;
                    BigDecimal zero = new BigDecimal(0);
                    // 修改余额
                    List<UserTaoLiJinOrigin> list = userTaoLiJinOriginService.getSurplusLiJin(uid);
                    if (list != null && list.size() > 0) {
                        for (UserTaoLiJinOrigin taoLiJinOrigin : list) {
                            if (total.compareTo(zero) < 1) {
                                break;
                            }
                            BigDecimal moneySurplus = taoLiJinOrigin.getMoneySurplus();
                            lastMoney = total;
                            total = MoneyBigDecimalUtil.sub(total, moneySurplus);
                            if (total.compareTo(zero) >= 0) {
                                moneySurplus = zero;
                            } else {
                                moneySurplus = MoneyBigDecimalUtil.sub(moneySurplus, lastMoney);
                            }
                            UserTaoLiJinOrigin usertlj = new UserTaoLiJinOrigin();
                            usertlj.setId(taoLiJinOrigin.getId());
                            usertlj.setMoneySurplus(moneySurplus);
                            usertlj.setUpdateTime(new Date());
                            userTaoLiJinOriginService.updateByPrimaryKeySelective(usertlj);
                        }
                    }
                } catch (Exception e) {
                    LogHelper.errorDetailInfo(e);
                }
            }
        });
        return tips;
    }
}