admin
2025-02-25 30d8e227e8d823b6c38c3b9c90ac2df03b63befe
fanli/src/main/java/com/yeshi/fanli/service/impl/user/TokenRecordServiceImpl.java
@@ -1,516 +1,550 @@
package com.yeshi.fanli.service.impl.user;
import java.math.BigDecimal;
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 com.yeshi.fanli.dao.mybatis.user.TokenRecordMapper;
import com.yeshi.fanli.dto.msg.MsgOtherGiveContentDTO;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinGiveRecord;
import com.yeshi.fanli.entity.bus.user.TokenRecord;
import com.yeshi.fanli.entity.bus.user.TokenRecord.TokenTypeEnum;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserInfoExtra;
import com.yeshi.fanli.entity.bus.user.UserSystemCoupon;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponGiveRecord;
import com.yeshi.fanli.entity.system.SystemCoupon.CouponTypeEnum;
import com.yeshi.fanli.exception.tlj.UserTaoLiJinOriginException;
import com.yeshi.fanli.exception.user.TokenRecordException;
import com.yeshi.fanli.exception.user.UserInfoExtraException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.hongbao.ThreeSaleSerivce;
import com.yeshi.fanli.service.inter.msg.UserOtherMsgNotificationService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinGiveRecordService;
import com.yeshi.fanli.service.inter.tlj.UserTaoLiJinOriginService;
import com.yeshi.fanli.service.inter.user.TokenRecordService;
import com.yeshi.fanli.service.inter.user.UserInfoExtraService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponGiveRecordService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.vo.msg.TokenVO;
@Service
public class TokenRecordServiceImpl implements TokenRecordService {
   @Resource(name = "taskExecutor")
   private TaskExecutor executor;
   @Resource
   private TokenRecordMapper tokenRecordMapper;
   @Resource
   private UserInfoService userInfoService;
   @Resource
   private UserSystemCouponService userSystemCouponService;
   @Resource
   private ThreeSaleSerivce threeSaleSerivce;
   @Resource
   private UserTaoLiJinGiveRecordService userTaoLiJinGiveRecordService;
   @Resource
   private UserInfoExtraService userInfoExtraService;
   @Resource
   private UserSystemCouponGiveRecordService userSystemCouponGiveRecordService;
   @Resource
   private UserTaoLiJinOriginService userTaoLiJinOriginService;
   @Resource
   private UserOtherMsgNotificationService userOtherMsgNotificationService;
   @Override
   public void insertSelective(TokenRecord record) {
      record.setCreateTime(new Date());
      record.setUpdateTime(new Date());
      tokenRecordMapper.insertSelective(record);
   }
   @Override
   public TokenRecord getNearByTypeAndIdentify(String type, String identify) {
      return tokenRecordMapper.getNearByTypeAndIdentify(type, identify);
   }
   @Override
   public TokenVO discernToken(String token, Long uid) throws TokenRecordException {
      // TODO token 验证
      TokenRecord rokenRecord = tokenRecordMapper.getByToken(token);
      if (rokenRecord == null)
         throw new TokenRecordException(1, "口令不存在");
      Date now = new Date();
      Date endTimeToken = rokenRecord.getEndTime();
      if (endTimeToken != null && endTimeToken.getTime() < now.getTime())
         throw new TokenRecordException(1, "口令已失效");
      Integer stateTtoken = rokenRecord.getState();
      if (stateTtoken != null && stateTtoken == 1)
         throw new TokenRecordException(1, "口令已失效");
      String nickName = null;
      String portrait = null;
      Long inviteId = rokenRecord.getUid();
      if (inviteId != null) {
         UserInfo inviteUser = userInfoService.selectByPKey(inviteId);
         if (inviteUser != null) {
            nickName = inviteUser.getNickName();
            portrait = inviteUser.getPortrait();
         }
      }
      if (StringUtil.isNullOrEmpty(nickName))
         nickName = Constant.systemCommonConfig.getDefaultNickName();
      if (StringUtil.isNullOrEmpty(portrait))
         portrait = Constant.systemCommonConfig.getDefaultPortrait();
      if (nickName.length() > 6) {
         nickName = nickName.substring(0, 6) + "...";
      }
      TokenVO tokenVO = new TokenVO();
      tokenVO.setToken(token);
      tokenVO.setNickName(nickName + "赠送");
      tokenVO.setPortrait(portrait);
      String identify = rokenRecord.getIdentify();
      if (StringUtil.isNullOrEmpty(identify))
         throw new TokenRecordException(1, "口令标识不存在");
      Integer type = 0;
      boolean state = false;
      List<String> tips = new ArrayList<String>();
      TokenTypeEnum tokenType = rokenRecord.getType();
      if (tokenType == TokenTypeEnum.freeCoupon) {
         type = 10;
         UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(Long.parseLong(identify));
         if (userCoupon == null) {
            tips.add("哎呀,这张免单券已失效了!");
         } else {
            Boolean give = userCoupon.getGive();
            if (give == null)
               give = false;
            if (userCoupon.getState() == UserSystemCoupon.STATE_OVERDUE) {
               tips.add("哎呀,这张免单券已失效了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_END_USE) {
               tips.add("哎呀,这张免单券已被领取了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_CAN_USE) {
               throw new TokenRecordException(1, "口令已失效");
            } else if (give && userCoupon.getState() == UserSystemCoupon.STATE_IN_USE) {
               if (uid == null || uid <= 0)
                  throw new TokenRecordException(1001, "温馨提示,[免单券]需要登录后领取");
               state = true;
               tokenVO.setAmount(1);
               UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
               if (userInfoExtra == null || StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
                  tips.add("确认领取后,你将成为赠送者的一级队员;");
                  tips.add("获赠的免单券,需要激活后才能使用,详情参见免单券激活规则;");
                  tips.add("成功领取后,请到“我的-福利中心”查看。");
               } else {
                  tips.add("获赠的免单券,需要激活后才能使用,详情参见免单券激活规则;");
                  tips.add("成功领取后,请到“我的-福利中心”查看。");
               }
            } else {
               throw new TokenRecordException(1, "口令已失效");
            }
         }
      } else if (tokenType == TokenTypeEnum.rebatePercentCoupon) {
         type = 11;
         UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(Long.parseLong(identify));
         if (userCoupon == null) {
         } else {
            Boolean give = userCoupon.getGive();
            if (give == null)
               give = false;
            if (userCoupon.getState() == UserSystemCoupon.STATE_OVERDUE) {
               tips.add("哎呀,这张返利奖励券已失效了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_END_USE) {
               tips.add("哎呀,这张返利奖励券已被领取了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_CAN_USE) {
               throw new TokenRecordException(1, "口令已失效");
            } else if (give && userCoupon.getState() == UserSystemCoupon.STATE_IN_USE) {
               if (uid == null || uid <= 0)
                  throw new TokenRecordException(1001, "温馨提示,[返利奖励券]需要登录后领取");
               state = true;
               tokenVO.setAmount(1);
               UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
               if (userInfoExtra == null || StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
                  tips.add("确认领取后,你将成为赠送者的一级队员;");
                  tips.add("返利券奖励券,可用于“已到账”的返利订单,在返利的基础上再获得一定比例的返利;");
                  tips.add("成功领取后,请到“我的-福利中心”中查看。");
               } else {
                  tips.add("返利券奖励券,可用于“已到账”的返利订单,在返利的基础上再获得一定比例的返利;");
                  tips.add("成功领取后,请到“我的-福利中心”中查看。");
               }
            } else {
               throw new TokenRecordException(1, "口令已失效");
            }
         }
      } else if (tokenType == TokenTypeEnum.taoLiJin) {
         type = 12;
         UserTaoLiJinGiveRecord giveRecord = userTaoLiJinGiveRecordService
               .selectByPrimaryKey(Long.parseLong(identify));
         if (giveRecord == null || giveRecord.getState() == UserTaoLiJinGiveRecord.STATE_OVERDUE) {
            tips.add("哎呀,推广红包已失效了!");
         } else if (giveRecord.getState() == UserTaoLiJinGiveRecord.STATE_RECEIVE) {
            tips.add("哎呀,推广红包已被领取了!");
         } else {
            if (uid == null || uid <= 0)
               throw new TokenRecordException(1001, "温馨提示,[推广红包]需要登录后领取");
            BigDecimal amount = giveRecord.getAmount();
            state = true;
            tokenVO.setAmount(Integer.parseInt(amount.setScale(0).toString()));
            UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
            if (userInfoExtra == null || StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
               tips.add("确认领取后,你将成为赠送者的一级队员;");
               tips.add("推广红包,可分享爆款商品,让分享订单成单率更高;");
               tips.add("成功领取后,请到“我的-推广红包”中查看。");
            } else {
               tips.add("推广红包,可分享爆款商品,让分享订单成单率更高;");
               tips.add("成功领取后,请到“我的-推广红包”中查看。");
            }
         }
      } else {
         throw new TokenRecordException(1, "无对应类型");
      }
      tokenVO.setTips(tips);
      tokenVO.setState(state);
      tokenVO.setType(type);
      return tokenVO;
   }
   @Override
   public String receiveToken(String token, Long uid) throws TokenRecordException {
      if (uid == null || uid <= 0)
         throw new TokenRecordException(1, "用户未登录");
      if (StringUtil.isNullOrEmpty(token))
         throw new TokenRecordException(1, "口令不能为空");
      TokenRecord rokenRecord = tokenRecordMapper.getByToken(token);
      if (rokenRecord == null)
         throw new TokenRecordException(1, "口令已失效");
      Date now = new Date();
      Date endTimeToken = rokenRecord.getEndTime();
      if (endTimeToken != null && endTimeToken.getTime() < now.getTime())
         throw new TokenRecordException(1, "口令已失效");
      Integer stateTtoken = rokenRecord.getState();
      if (stateTtoken != null && stateTtoken == 1)
         throw new TokenRecordException(1, "口令已失效");
      String identify = rokenRecord.getIdentify();
      if (StringUtil.isNullOrEmpty(identify))
         throw new TokenRecordException(1, "口令标识不存在");
      Long giveUid = rokenRecord.getUid();
      UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
      if (userInfoExtra == null)
         throw new TokenRecordException(1, "用户信息缺失");
      String msg = "领取成功";
      TokenTypeEnum tokenType = rokenRecord.getType();
      if (tokenType == TokenTypeEnum.freeCoupon) {
         long couponId = Long.parseLong(identify);
         UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(couponId);
         if (userCoupon == null)
            throw new TokenRecordException(1, "该券不存在");
         Boolean give = userCoupon.getGive();
         if (give == null)
            give = false;
         if (userCoupon.getState() == UserSystemCoupon.STATE_OVERDUE)
            throw new TokenRecordException(1, "哎呀,这张免单券已失效了!");
         if (userCoupon.getState() == UserSystemCoupon.STATE_END_USE)
            throw new TokenRecordException(1, "哎呀,这张免单券已被领取了!");
         if (userCoupon.getState() == UserSystemCoupon.STATE_CAN_USE)
            throw new TokenRecordException(1, "口令已失效");
         if (give && userCoupon.getState() == UserSystemCoupon.STATE_IN_USE) {
            UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService.getRecordByUidAndCouponId(giveUid, couponId);
            if (giveRecord == null )
               throw new TokenRecordException(1, "口令已失效");
            Date endTime = giveRecord.getEndTime();
            if (endTime != null && endTime.getTime() < now.getTime())
               throw new TokenRecordException(1, "哎呀,这张免单券已失效了!");
            try {
               userSystemCouponService.insertUserCoupon(uid, CouponTypeEnum.freeCoupon.name(), UserSystemCoupon.SOURCE_GIVE);
            } catch (Exception e) {
               LogHelper.errorDetailInfo(e);
               throw new TokenRecordException(1, "领取失败");
            }
            // 更新赠送券信息
            userSystemCouponService.updateGiveRecord(uid, couponId, CouponTypeEnum.freeCoupon.name());
            // 更新赠送记录
            giveRecord.setReceiveUid(uid);
            giveRecord.setReceiveTime(new Date());
            userSystemCouponGiveRecordService.updateByPrimaryKeySelective(giveRecord);
            msg = "领取成功[免单券]成功,请到[我的-福利中心]中查看";
            // 消息 + 队员
            executor.execute(new Runnable() {
               @Override
               public void run() {
                  SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH.mm");
                  boolean addTeam = addInviteTeam(uid, giveUid, userInfoExtra);
                  String beiZhu = "无";
                  if (addTeam)
                     beiZhu = "领取人已经成为你的一级队员";
                  String userName = "无";
                  UserInfo user = userInfoService.selectByPKey(uid);
                  if (user != null && !StringUtil.isNullOrEmpty(user.getNickName()))
                     userName = user.getNickName();
                  MsgOtherGiveContentDTO msgOther = new MsgOtherGiveContentDTO();
                  msgOther.setType(MsgOtherGiveContentDTO.TYEP_COUPON);
                  msgOther.setTitle("赠送免单券");
                  msgOther.setGiveType("你赠送的免单券被成功领取");
                  msgOther.setReceiveInfo("昵称:  " + userName +" ID:" + uid);
                  msgOther.setGiveTime(sd.format(giveRecord.getGiveTime()));
                  msgOther.setReceiveTime(sd.format(new Date()));
                  userOtherMsgNotificationService.tokenGiveMsg(giveUid, beiZhu, msgOther);
               }
            });
         } else {
            throw new TokenRecordException(1, "口令已失效");
         }
      } else if (tokenType == TokenTypeEnum.rebatePercentCoupon) {
         long couponId = Long.parseLong(identify);
         UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(couponId);
         if (userCoupon == null)
            throw new TokenRecordException(1, "该券不存在");
         Boolean give = userCoupon.getGive();
         if (give == null)
            give = false;
         if (userCoupon.getState() == UserSystemCoupon.STATE_OVERDUE)
            throw new TokenRecordException(1, "哎呀,这张返利奖励券已失效了!");
         if (userCoupon.getState() == UserSystemCoupon.STATE_END_USE)
            throw new TokenRecordException(1, "哎呀,这张返利奖励券已被领取了!");
         if (userCoupon.getState() == UserSystemCoupon.STATE_CAN_USE)
            throw new TokenRecordException(1, "口令已失效");
          if (give && userCoupon.getState() == UserSystemCoupon.STATE_IN_USE) {
             UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService.getRecordByUidAndCouponId(giveUid, couponId);
            if (giveRecord == null )
               throw new TokenRecordException(1, "口令已失效");
            Date endTime = giveRecord.getEndTime();
            if (endTime != null && endTime.getTime() < now.getTime())
               throw new TokenRecordException(1, "哎呀,这张返利奖励券已失效了!");
             try {
               userSystemCouponService.insertUserCoupon(uid, CouponTypeEnum.rebatePercentCoupon.name(), UserSystemCoupon.SOURCE_GIVE);
            } catch (Exception e) {
               LogHelper.errorDetailInfo(e);
               throw new TokenRecordException(1, "领取失败");
            }
             // 更新赠送券信息
            userSystemCouponService.updateGiveRecord(uid, couponId, CouponTypeEnum.rebatePercentCoupon.name());
            // 更新赠送记录
            giveRecord.setReceiveUid(uid);
            giveRecord.setReceiveTime(new Date());
            userSystemCouponGiveRecordService.updateByPrimaryKeySelective(giveRecord);
            msg = "领取成功[返利奖励券]成功,请到[我的-福利中心]中查看";
            // 消息 + 队员
            executor.execute(new Runnable() {
               @Override
               public void run() {
                  SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH.mm");
                  boolean addTeam = addInviteTeam(uid, giveUid, userInfoExtra);
                  String beiZhu = "无";
                  if (addTeam)
                     beiZhu = "领取人已经成为你的一级队员";
                  String userName = "无";
                  UserInfo user = userInfoService.selectByPKey(uid);
                  if (user != null && !StringUtil.isNullOrEmpty(user.getNickName()))
                     userName = user.getNickName();
                  MsgOtherGiveContentDTO msgOther = new MsgOtherGiveContentDTO();
                  msgOther.setType(MsgOtherGiveContentDTO.TYEP_COUPON);
                  msgOther.setTitle("赠送奖励券");
                  msgOther.setGiveType("你赠送的奖励券被成功领取");
                  msgOther.setReceiveInfo("昵称:  " + userName +" ID:" + uid);
                  msgOther.setGiveTime(sd.format(giveRecord.getGiveTime()));
                  msgOther.setReceiveTime(sd.format(new Date()));
                  userOtherMsgNotificationService.tokenGiveMsg(giveUid, beiZhu, msgOther);
               }
            });
         } else {
            throw new TokenRecordException(1, "口令已失效");
         }
      } else if (tokenType == TokenTypeEnum.taoLiJin) {
         UserTaoLiJinGiveRecord giveRecord = userTaoLiJinGiveRecordService
               .selectByPrimaryKey(Long.parseLong(identify));
         if (giveRecord == null || giveRecord.getState() == UserTaoLiJinGiveRecord.STATE_OVERDUE) {
            throw new TokenRecordException(1, "哎呀,推广红包已失效了!");
         } else if (giveRecord.getState() == UserTaoLiJinGiveRecord.STATE_RECEIVE) {
            throw new TokenRecordException(1, "哎呀,推广红包已被领取了!");
         } else {
            Date endTime = giveRecord.getEndTime();
            if (endTime != null && endTime.getTime() < now.getTime())
               throw new TokenRecordException(1, "哎呀,推广红包已失效了!");
            BigDecimal amount = giveRecord.getAmount();
            try {
               // 领取
               userTaoLiJinOriginService.receiveFriendsGive(uid, amount);
               // 更新记录
               UserTaoLiJinGiveRecord updateRecord = new UserTaoLiJinGiveRecord();
               updateRecord.setId(Long.parseLong(identify));
               updateRecord.setReceiveTime(new Date());
               updateRecord.setReceiveUid(uid);
               updateRecord.setState(UserTaoLiJinGiveRecord.STATE_RECEIVE);
               userTaoLiJinGiveRecordService.updateByPrimaryKeySelective(updateRecord);
               msg = "领取成功[推广红包]成功,请到[我的-推广红包]中查看";
               // 消息 + 队员
               executor.execute(new Runnable() {
                  @Override
                  public void run() {
                     SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH.mm");
                     boolean addTeam = addInviteTeam(uid, giveUid, userInfoExtra);
                     String beiZhu = "无";
                     if (addTeam)
                        beiZhu = "领取人已经成为你的一级队员";
                     String userName = "无";
                     UserInfo user = userInfoService.selectByPKey(uid);
                     if (user != null && !StringUtil.isNullOrEmpty(user.getNickName()))
                        userName = user.getNickName();
                     MsgOtherGiveContentDTO msgOther = new MsgOtherGiveContentDTO();
                     msgOther.setType(MsgOtherGiveContentDTO.TYEP_COUPON);
                     msgOther.setTitle("赠送推广红包");
                     msgOther.setGiveType("你赠送的推广红包被成功领取");
                     msgOther.setReceiveInfo("昵称:  " + userName +" ID:" + uid);
                     msgOther.setGiveTime(sd.format(giveRecord.getGiveTime()));
                     msgOther.setReceiveTime(sd.format(new Date()));
                     userOtherMsgNotificationService.tokenGiveMsg(giveUid, beiZhu, msgOther);
                  }
               });
            } catch (UserTaoLiJinOriginException e) {
               e.printStackTrace();
            }
         }
      } else {
         throw new TokenRecordException(1, "无对应类型");
      }
      return msg;
   }
   /**
    *     未激活邀请码: 上下级关系确立
    * @param uid
    * @param giveUid
    * @param userInfoExtra
    * @return
    */
   public boolean addInviteTeam(Long uid, Long giveUid, UserInfoExtra userInfoExtra) {
      boolean invite = false;
      if (StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
         UserInfoExtra userInfoExtraGive = userInfoExtraService.getUserInfoExtra(giveUid);
         if (userInfoExtraGive != null ) {
            String inviteCode = userInfoExtraGive.getInviteCode();
            if(!StringUtil.isNullOrEmpty(inviteCode)) {
               try {
                  userInfoExtraService.activateInviteCode(uid, inviteCode);
                  invite = true;
               } catch (UserInfoExtraException e) {
                  e.printStackTrace();
               }
            }
         }
      }
      return invite;
   }
}
package com.yeshi.fanli.service.impl.user;
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.config.SystemConfigKeyEnum;
import com.yeshi.fanli.service.inter.config.SystemConfigService;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import com.yeshi.fanli.dao.mybatis.user.TokenRecordMapper;
import com.yeshi.fanli.entity.accept.AcceptData;
import com.yeshi.fanli.entity.bus.tlj.UserTaoLiJinGiveRecord;
import com.yeshi.fanli.entity.bus.user.TokenRecord;
import com.yeshi.fanli.entity.bus.user.TokenRecord.TokenTypeEnum;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserInfoExtra;
import com.yeshi.fanli.entity.bus.user.UserSystemCoupon;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponGiveRecord;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponRecord;
import com.yeshi.fanli.entity.redpack.RedPackGiveRecord;
import com.yeshi.fanli.entity.system.SystemCoupon;
import com.yeshi.fanli.entity.system.SystemCoupon.CouponTypeEnum;
import com.yeshi.fanli.exception.user.TokenRecordException;
import com.yeshi.fanli.exception.user.UserInfoExtraException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.config.SystemCouponService;
import com.yeshi.fanli.service.inter.money.msg.UserMoneyMsgNotificationService;
import com.yeshi.fanli.service.inter.msg.UserOtherMsgNotificationService;
import com.yeshi.fanli.service.inter.redpack.RedPackGiveRecordService;
import com.yeshi.fanli.service.inter.user.TokenRecordService;
import com.yeshi.fanli.service.inter.user.UserInfoExtraService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponGiveRecordService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponRecordService;
import com.yeshi.fanli.service.inter.user.UserSystemCouponService;
import com.yeshi.fanli.service.inter.user.integral.IntegralGetService;
import com.yeshi.fanli.service.inter.user.invite.ThreeSaleSerivce;
import com.yeshi.fanli.service.inter.user.invite.UserInviteMsgNotificationService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TokenUtil;
import com.yeshi.fanli.util.VersionUtil;
import com.yeshi.fanli.vo.msg.TokenVO;
@Service
public class TokenRecordServiceImpl implements TokenRecordService {
    @Resource(name = "taskExecutor")
    private TaskExecutor executor;
    @Resource
    private TokenRecordMapper tokenRecordMapper;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    @Lazy
    private UserSystemCouponService userSystemCouponService;
    @Resource
    private ThreeSaleSerivce threeSaleSerivce;
    @Resource
    private UserInfoExtraService userInfoExtraService;
    @Resource
    private UserSystemCouponRecordService userSystemCouponRecordService;
    @Resource
    private UserSystemCouponGiveRecordService userSystemCouponGiveRecordService;
    @Resource
    private UserOtherMsgNotificationService userOtherMsgNotificationService;
    @Lazy
    @Resource
    private IntegralGetService integralGetService;
    @Resource
    private SystemCouponService systemCouponService;
    @Resource
    private RedPackGiveRecordService redPackGiveRecordService;
    @Resource
    private SystemConfigService systemConfigService;
    @Override
    public void insertSelective(TokenRecord record) {
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        tokenRecordMapper.insertSelective(record);
    }
    @Override
    public void updateByPrimaryKeySelective(TokenRecord record) {
        tokenRecordMapper.updateByPrimaryKeySelective(record);
    }
    @Override
    public TokenRecord getNearByTypeAndIdentify(String type, String identify) {
        return tokenRecordMapper.getNearByTypeAndIdentify(type, identify);
    }
    @Override
    public TokenRecord getByTypeAndIdentify(String type, String identify) {
        return tokenRecordMapper.getByTypeAndIdentify(type, identify);
    }
    @Override
    public TokenVO discernToken(String token, Long uid, String platform, String version) throws TokenRecordException {
        // 解析口令
        String parseToken = TokenUtil.parseToken(token);
        if (StringUtil.isNullOrEmpty(parseToken))
            throw new TokenRecordException(1, "未发现口令");
        TokenRecord rokenRecord = tokenRecordMapper.getByToken(parseToken);
        if (rokenRecord == null)
            throw new TokenRecordException(1, "口令不存在");
        Long uidToken = rokenRecord.getUid();
        if (uid != null && uidToken != null && uid.longValue() == uidToken.longValue())
            throw new TokenRecordException(1, "不能自己赠送给自己");
        Date now = new Date();
        Date endTimeToken = rokenRecord.getEndTime();
        Integer stateTtoken = rokenRecord.getState();
        if (endTimeToken != null && endTimeToken.getTime() < now.getTime() || (stateTtoken != null && stateTtoken == 1)
                || StringUtil.isNullOrEmpty(rokenRecord.getIdentify()))
            throw new TokenRecordException(1, "口令已失效");
        Integer num = 0;
        Integer type = 0;
        String money = null;
        boolean state = false;
        List<String> tips = new ArrayList<String>();
        String identify = rokenRecord.getIdentify();
        TokenTypeEnum tokenType = rokenRecord.getType();
        if (tokenType == TokenTypeEnum.freeCoupon) {
            type = 10;
            UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService
                    .selectByPrimaryKey(Long.parseLong(identify));
            if (giveRecord == null)
                throw new TokenRecordException(1, "赠送记录不存在");
            Date endTime = giveRecord.getEndTime();
            // 用户券信息
            UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(giveRecord.getCouponId());
            if (userCoupon == null || userCoupon.getGive() == null || !userCoupon.getGive())
                throw new TokenRecordException(1, "券不存在或非赠送状态");
            if (userCoupon.getState() == UserSystemCoupon.STATE_OVERDUE
                    || (endTime != null && endTime.getTime() < now.getTime())) {
                tips.add("哎呀,这张免单券已失效了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_END_USE) {
                tips.add("哎呀,这张免单券已被领取了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_IN_USE) {
                if (uid == null || uid <= 0)
                    throw new TokenRecordException(1001, "温馨提示,[免单券]需要登录后领取");
                state = true;
                UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
                if (userInfoExtra == null || StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
                    tips.add("确认领取后,你将成为赠送人的直接粉丝;");
                    tips.add("获赠的免单券,需要激活后才能使用,详情参见免单券激活规则;");
                    tips.add("成功领取后,请到“我的-福利中心”查看。");
                } else {
                    tips.add("获赠的免单券,需要激活后才能使用,详情参见免单券激活规则;");
                    tips.add("成功领取后,请到“我的-福利中心”查看。");
                }
            } else {
                throw new TokenRecordException(1, "口令已失效");
            }
        } else if (tokenType == TokenTypeEnum.rebatePercentCoupon) {
            type = 11;
            // 赠送记录
            UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService
                    .selectByPrimaryKey(Long.parseLong(identify));
            if (giveRecord == null)
                throw new TokenRecordException(1, "赠送记录不存在");
            Date endTime = giveRecord.getEndTime();
            UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(giveRecord.getCouponId());
            if (userCoupon == null || userCoupon.getGive() == null || !userCoupon.getGive())
                throw new TokenRecordException(1, "券不存在或非赠送状态");
            if (userCoupon.getState() == UserSystemCoupon.STATE_OVERDUE
                    || (endTime != null && endTime.getTime() < now.getTime())) {
                tips.add("哎呀,这张返利奖励券已失效了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_END_USE) {
                tips.add("哎呀,这张返利奖励券已被领取了!");
            } else if (userCoupon.getState() == UserSystemCoupon.STATE_IN_USE) {
                if (uid == null || uid <= 0)
                    throw new TokenRecordException(1001, "温馨提示,[返利奖励券]需要登录后领取");
                state = true;
                UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
                if (userInfoExtra == null || StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
                    tips.add("确认领取后,你将成为赠送人的直接粉丝;");
                    tips.add("板栗快省奖励券,可用于“已到账”的返利订单,在返利的基础上再获得一定比例的返利;");
                    tips.add("成功领取后,请到“我的-福利中心”中查看。");
                } else {
                    tips.add("板栗快省奖励券,可用于“已到账”的返利订单,在返利的基础上再获得一定比例的返利;");
                    tips.add("成功领取后,请到“我的-福利中心”中查看。");
                }
            } else {
                throw new TokenRecordException(1, "口令已失效");
            }
        } else if (tokenType == TokenTypeEnum.redPack) {
            if (!VersionUtil.greaterThan_2_0_5(platform, version))
                throw new TokenRecordException(1, "请升级到最新版");
            type = 13;
            RedPackGiveRecord giveRecord = redPackGiveRecordService.selectByPrimaryKey(Long.parseLong(identify));
            if (giveRecord == null)
                throw new TokenRecordException(1, "口令已失效");
            Date endTime = giveRecord.getEndTime();
            // 赠送面额
            money = giveRecord.getAmount().setScale(2).toString();
            if (giveRecord.getState() == UserTaoLiJinGiveRecord.STATE_OVERDUE
                    || (endTime != null && endTime.getTime() < now.getTime())) {
                tips.add("哎呀,这个红包已失效了!");
            } else if (giveRecord.getState() == UserTaoLiJinGiveRecord.STATE_RECEIVE) {
                tips.add("哎呀,这个红包已被领取了!");
            } else if (giveRecord.getState() == UserTaoLiJinGiveRecord.STATE_INIT) {
                if (uid == null || uid <= 0)
                    throw new TokenRecordException(1001, "温馨提示,[红包]需要登录后领取");
                state = true;
                UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
                if (userInfoExtra == null || StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
                    tips.add("确认领取后,你将成为赠送人的直接粉丝;");
                    tips.add("红包可提现,可购买折扣商品;");
                    tips.add("成功领取后,请到“我的-红包”中查看。");
                } else {
                    tips.add("红包可提现,可购买折扣商品;");
                    tips.add("成功领取后,请到“我的-红包”中查看。");
                }
            }
        } else if (tokenType == TokenTypeEnum.taoLiJin) {
            throw new TokenRecordException(1, "推广红包相关功能已下线!");
        } else {
            throw new TokenRecordException(1, "无对应类型");
        }
        String nickName = null;
        String portrait = null;
        Long inviteId = rokenRecord.getUid();
        if (inviteId != null) {
            UserInfo inviteUser = userInfoService.selectByPKey(inviteId);
            if (inviteUser != null) {
                nickName = inviteUser.getNickName();
                portrait = inviteUser.getPortrait();
            }
        }
        SystemEnum system = userInfoService.getUserSystem(rokenRecord.getUid());
        if (StringUtil.isNullOrEmpty(nickName))
            nickName = systemConfigService.getValueCache(SystemConfigKeyEnum.defaultNickNamePrefix, system) + inviteId;
        if (StringUtil.isNullOrEmpty(portrait))
            portrait = systemConfigService.getValueCache(SystemConfigKeyEnum.defaultPortrait, system);
        if (nickName.length() > 6) {
            nickName = nickName.substring(0, 6) + "...";
        }
        TokenVO tokenVO = new TokenVO();
        tokenVO.setAmount(num);
        tokenVO.setMoney(money);
        tokenVO.setToken(parseToken);
        tokenVO.setNickName(nickName + "赠送");
        tokenVO.setPortrait(portrait);
        tokenVO.setTips(tips);
        tokenVO.setState(state);
        tokenVO.setType(type);
        return tokenVO;
    }
    @Override
    public String receiveToken(String token, Long uid, AcceptData acceptData) throws TokenRecordException {
        if (uid == null || uid <= 0)
            throw new TokenRecordException(1, "用户未登录");
        if (StringUtil.isNullOrEmpty(token))
            throw new TokenRecordException(1, "口令不能为空");
        TokenRecord rokenRecord = tokenRecordMapper.getByToken(token);
        if (rokenRecord == null)
            throw new TokenRecordException(1, "口令已失效");
        Long uidToken = rokenRecord.getUid();
        if (uidToken != null && uid.longValue() == uidToken.longValue())
            throw new TokenRecordException(1, "不能自己赠送给自己");
        Date now = new Date();
        Date endTimeToken = rokenRecord.getEndTime();
        if (endTimeToken != null && endTimeToken.getTime() < now.getTime())
            throw new TokenRecordException(1, "口令已失效");
        Integer stateTtoken = rokenRecord.getState();
        if (stateTtoken != null && stateTtoken == 1)
            throw new TokenRecordException(1, "口令已失效");
        String identify = rokenRecord.getIdentify();
        if (StringUtil.isNullOrEmpty(identify))
            throw new TokenRecordException(1, "口令标识不存在");
        Long giveUid = rokenRecord.getUid();
        UserInfoExtra userInfoExtra = userInfoExtraService.getUserInfoExtra(uid);
        if (userInfoExtra == null)
            throw new TokenRecordException(1, "用户信息缺失");
        String msg = "领取成功";
        TokenTypeEnum tokenType = rokenRecord.getType();
        if (tokenType == TokenTypeEnum.freeCoupon) {
            // 赠送记录
            UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService
                    .selectByPrimaryKey(Long.parseLong(identify));
            if (giveRecord == null)
                throw new TokenRecordException(1, "赠送记录不存在");
            Date endTime = giveRecord.getEndTime();
            if (endTime != null && endTime.getTime() < now.getTime())
                throw new TokenRecordException(1, "赠送记录已过期");
            UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(giveRecord.getCouponId());
            if (userCoupon == null || userCoupon.getGive() == null || !userCoupon.getGive()
                    || userCoupon.getState() != UserSystemCoupon.STATE_IN_USE)
                throw new TokenRecordException(1, "该券不存在或非赠送");
            UserSystemCoupon userSystemCoupon = null;
            try {
                userSystemCoupon = userSystemCouponService.freeCouponWin(uid, CouponTypeEnum.freeCoupon,
                        UserSystemCoupon.SOURCE_GIVE, 1, true);
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
                throw new TokenRecordException(1, "领取失败");
            }
            // 更新状态
            Date date = new Date();
            userCoupon.setId(userCoupon.getId());
            userCoupon.setState(UserSystemCoupon.STATE_END_USE);
            userCoupon.setUseTime(date);
            userCoupon.setUpdateTime(date);
            userSystemCouponService.updateByPrimaryKeySelective(userCoupon);
            // 更新使用记录
            UserSystemCouponRecord useRecord = userSystemCouponRecordService.getNearByUserCouponId(userCoupon.getId());
            if (useRecord != null) {
                UserSystemCouponRecord updateuseRecord = new UserSystemCouponRecord();
                updateuseRecord.setId(useRecord.getId());
                updateuseRecord.setState(UserSystemCouponRecord.STATE_SUCCESS);
                updateuseRecord.setUpdateTime(new Date());
                userSystemCouponRecordService.updateByPrimaryKeySelective(updateuseRecord);
            }
            // 更新赠送记录
            UserSystemCouponGiveRecord updateGiveRecord = new UserSystemCouponGiveRecord();
            updateGiveRecord.setId(giveRecord.getId());
            updateGiveRecord.setReceiveUid(uid);
            updateGiveRecord.setReceiveTime(new Date());
            updateGiveRecord.setState(UserSystemCouponGiveRecord.STATE_RECEIVE);
            if (userSystemCoupon != null) {
                updateGiveRecord.setReceiveId(userSystemCoupon.getId());
            }
            userSystemCouponGiveRecordService.updateByPrimaryKeySelective(updateGiveRecord);
            integralGetService.addGiveFreeCoupon(giveUid);
            msg = "领取成功[免单券]成功,请到[我的-福利中心]中查看";
            // 消息 + 队员
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    addInviteTeam(uid, giveUid, userInfoExtra);
                }
            });
        } else if (tokenType == TokenTypeEnum.rebatePercentCoupon) {
            // 赠送记录
            UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService
                    .selectByPrimaryKey(Long.parseLong(identify));
            if (giveRecord == null)
                throw new TokenRecordException(1, "赠送记录不存在");
            Date endTime = giveRecord.getEndTime();
            if (endTime != null && endTime.getTime() < now.getTime())
                throw new TokenRecordException(1, "赠送记录已过期");
            UserSystemCoupon userCoupon = userSystemCouponService.selectByPrimaryKey(giveRecord.getCouponId());
            if (userCoupon == null || userCoupon.getGive() == null || !userCoupon.getGive()
                    || userCoupon.getState() != UserSystemCoupon.STATE_IN_USE)
                throw new TokenRecordException(1, "该券不存在或非赠送");
            SystemCoupon systemCoupon = userCoupon.getSystemCoupon();
            if (systemCoupon == null)
                throw new TokenRecordException(1, "该券不存在");
            systemCoupon = systemCouponService.selectByPrimaryKey(systemCoupon.getId());
            if (systemCoupon == null)
                throw new TokenRecordException(1, "该券不存在");
            UserSystemCoupon userSystemCoupon = null;
            try {
                userSystemCoupon = userSystemCouponService.rewardCouponWin(uid, UserSystemCoupon.SOURCE_GIVE, 1, true,
                        systemCoupon.getPercent());
            } catch (Exception e) {
                LogHelper.errorDetailInfo(e);
                throw new TokenRecordException(1, "领取失败");
            }
            // 更新状态
            Date date = new Date();
            userCoupon.setId(userCoupon.getId());
            userCoupon.setState(UserSystemCoupon.STATE_END_USE);
            userCoupon.setUseTime(date);
            userCoupon.setUpdateTime(date);
            userSystemCouponService.updateByPrimaryKeySelective(userCoupon);
            // 更新使用记录
            UserSystemCouponRecord useRecord = userSystemCouponRecordService.getNearByUserCouponId(userCoupon.getId());
            if (useRecord != null) {
                UserSystemCouponRecord updateuseRecord = new UserSystemCouponRecord();
                updateuseRecord.setId(useRecord.getId());
                updateuseRecord.setState(UserSystemCouponRecord.STATE_SUCCESS);
                updateuseRecord.setUpdateTime(new Date());
                userSystemCouponRecordService.updateByPrimaryKeySelective(updateuseRecord);
            }
            // 更新赠送记录
            UserSystemCouponGiveRecord updateGiveRecord = new UserSystemCouponGiveRecord();
            updateGiveRecord.setId(giveRecord.getId());
            updateGiveRecord.setReceiveUid(uid);
            updateGiveRecord.setReceiveTime(new Date());
            updateGiveRecord.setState(UserSystemCouponGiveRecord.STATE_RECEIVE);
            if (userSystemCoupon != null) {
                updateGiveRecord.setReceiveId(userSystemCoupon.getId());
            }
            userSystemCouponGiveRecordService.updateByPrimaryKeySelective(updateGiveRecord);
            integralGetService.addGiveRebateCoupon(giveUid);
            msg = "领取成功[返利奖励券]成功,请到[我的-福利中心]中查看";
            // 消息 + 队员
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    addInviteTeam(uid, giveUid, userInfoExtra);
                }
            });
        } else if (tokenType == TokenTypeEnum.redPack) {
            if (!VersionUtil.greaterThan_2_0_5(acceptData.getPlatform(), acceptData.getVersion()))
                throw new TokenRecordException(1, "请升级到最新版");
            msg = "领取红包成功,请到[我的-红包]中查看";
            // 消息 + 队员
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    addInviteTeam(uid, giveUid, userInfoExtra);
                }
            });
        } else if (tokenType == TokenTypeEnum.taoLiJin) {
            throw new TokenRecordException(1, "推广红包相关功能已下线!");
        } else {
            throw new TokenRecordException(1, "无对应类型");
        }
        return msg;
    }
    /**
     * 未激活邀请码: 上下级关系确立
     *
     * @param uid
     * @param giveUid
     * @param userInfoExtra
     * @return
     */
    public boolean addInviteTeam(Long uid, Long giveUid, UserInfoExtra userInfoExtra) {
        boolean invite = false;
        if (StringUtil.isNullOrEmpty(userInfoExtra.getInviteCode())) {
            UserInfoExtra userInfoExtraGive = userInfoExtraService.getUserInfoExtra(giveUid);
            if (userInfoExtraGive != null) {
                String inviteCode = userInfoExtraGive.getInviteCode();
                if (!StringUtil.isNullOrEmpty(inviteCode)) {
                    try {
                        userInfoExtraService.activateInviteCode(uid, inviteCode);
                        invite = true;
                    } catch (UserInfoExtraException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return invite;
    }
    @Override
    public List<TokenRecord> overdueList(int count) {
        return tokenRecordMapper.overdueList(count);
    }
    @Override
    public void overdue(List<TokenRecord> list) {
        if (list == null || list.size() == 0)
            return;
        Date date = new Date();
        for (TokenRecord tokenRecord : list) {
            tokenRecord.setState(1);
            tokenRecord.setUpdateTime(date);
            tokenRecordMapper.updateByPrimaryKeySelective(tokenRecord);
        }
    }
    @Override
    public void invalidByRedPack(Long id) {
        if (id == null)
            return;
        List<String> list = new ArrayList<String>();
        list.add(TokenTypeEnum.redPack.name());
        tokenRecordMapper.invalidByTypeAndIdentify(list, id.toString());
    }
    @Override
    public void invalidByCoupon(Long id) {
        if (id == null)
            return;
        List<String> list = new ArrayList<String>();
        list.add(TokenTypeEnum.freeCoupon.name());
        list.add(TokenTypeEnum.rebatePercentCoupon.name());
        tokenRecordMapper.invalidByTypeAndIdentify(list, id.toString());
    }
}