admin
2025-02-25 30d8e227e8d823b6c38c3b9c90ac2df03b63befe
fanli/src/main/java/com/yeshi/fanli/service/impl/user/UserInfoServiceImpl.java
@@ -1,707 +1,812 @@
package com.yeshi.fanli.service.impl.user;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.yeshi.utils.FileUtil;
import org.yeshi.utils.HttpUtil;
import org.yeshi.utils.tencentcloud.COSManager;
import com.google.gson.Gson;
import com.yeshi.fanli.dao.mybatis.BindingAccountMapper;
import com.yeshi.fanli.dao.mybatis.PayInfoMapper;
import com.yeshi.fanli.dao.mybatis.ScanHistoryMapper;
import com.yeshi.fanli.dao.mybatis.UserInfoMapper;
import com.yeshi.fanli.dao.mybatis.UserShareGoodsHistoryMapper;
import com.yeshi.fanli.dao.mybatis.share.ShareMapper;
import com.yeshi.fanli.entity.bus.user.BindingAccount;
import com.yeshi.fanli.entity.bus.user.UserExtraTaoBaoInfo;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserInfoModifyRecord.ModifyTypeEnum;
import com.yeshi.fanli.exception.user.UserInfoException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.count.HongBaoV2CountService;
import com.yeshi.fanli.service.inter.order.CommonOrderCountService;
import com.yeshi.fanli.service.inter.user.SpreadUserImgService;
import com.yeshi.fanli.service.inter.user.UserInfoModifyRecordService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.integral.IntegralDetailService;
import com.yeshi.fanli.service.inter.user.invite.ThreeSaleSerivce;
import com.yeshi.fanli.service.inter.user.tb.TaoBaoUnionAuthRecordService;
import com.yeshi.fanli.service.inter.user.tb.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.FilePathEnum;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.ThreadUtil;
import com.yeshi.fanli.util.account.UserUtil;
import com.yeshi.fanli.util.user.UserLevelUtil;
import com.yeshi.fanli.vo.user.UserInfoVO;
import net.coobird.thumbnailator.Thumbnails;
@Service
public class UserInfoServiceImpl implements UserInfoService {
   @Resource(name = "taskExecutor")
   private TaskExecutor executor;
   @Resource
   private ThreeSaleSerivce threeSaleSerivce;
   @Resource
   private UserInfoMapper userInfoMapper;
   @Resource
   private BindingAccountMapper bindingAccountMapper;
   @Resource
   private PayInfoMapper payInfoMapper;
   @Resource
   private UserShareGoodsHistoryMapper userShareGoodsHistoryMapper;
   @Resource
   private ScanHistoryMapper scanHistoryMapper;
   @Resource
   private ShareMapper shareMapper;
   @Resource
   private HongBaoV2CountService hongBaoV2CountService;
   @Lazy
   @Resource
   private CommonOrderCountService commonOrderCountService;
   @Resource
   private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
   @Resource
   private TaoBaoUnionAuthRecordService taoBaoUnionAuthRecordService;
   @Resource
   private SpreadUserImgService spreadUserImgService;
   @Lazy
   @Resource
   private IntegralDetailService integralDetailService;
   @Lazy
   @Resource
   private UserInfoModifyRecordService userInfoModifyRecordService;
   public UserInfo getUserByLoginTypeAndOpenId(int loginType, String openid, String appid) {
      List<UserInfo> list = null;
      if (loginType == 1) {
         list = userInfoMapper.listByAppIdAndTaoBaoOpenId(appid, openid);
      } else {
         list = userInfoMapper.listByAppIdAndWXUnionId(appid, openid);
      }
      if (list != null)
         for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getState() == UserInfo.STATE_DELETE
                  || list.get(i).getState() == UserInfo.STATE_DELETE_OUT_OF_DATE) {
               list.remove(i);
               i--;
            }
         }
      if (list != null && list.size() > 0) {
         return list.get(0);
      }
      return null;
   }
   @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
   public UserInfo addUser(UserInfo form, String appid) {
      try {
         LogHelper.test("用户的注册信息:" + new Gson().toJson(form));
         form.setCreatetime(new Date().getTime());
         form.setRank(0);
         String openId = form.getLoginType() == Constant.TAOBAO ? form.getOpenid() : form.getWxUnionId();
         UserInfo find = getUserByLoginTypeAndOpenId(form.getLoginType(), openId, Constant.APPID);
         if (find != null) {
            return find;
         }
         boolean create = createUser(form, appid);
         if (!create) {
            return null;
         }
         int loginType = form.getLoginType();
         // 建的假用户。。
         if (loginType == -1) {
            return form;
         }
         LogHelper.userInfo("添加用户:" + form);
         if (form.getLoginType() == Constant.WEIXIN) {
            ThreadUtil.run(new Runnable() {
               public void run() {
                  UserInfo temp = userInfoMapper.selectByPrimaryKey(form.getId());
                  COSManager cosManager = COSManager.getInstance();
                  InputStream inputStream = HttpUtil.getAsInputStream(temp.getPortrait());
                  String uploadFile = cosManager.uploadFile(inputStream, FilePathEnum.userPortrait.getPath() + UUID.randomUUID().toString()).getUrl();
                  UserInfo updateTemp = new UserInfo(temp.getId());
                  updateTemp.setPortrait(uploadFile);
                  userInfoMapper.updateByPrimaryKeySelective(updateTemp);
               }
            });
         }
      } catch (Exception e) {
         try {
            LogHelper.errorDetailInfo(e);
         } catch (Exception e1) {
            e1.printStackTrace();
         }
         return null;
      }
      return form;
   }
   public boolean createUser(UserInfo form, String appid) {
      long maxUid = userInfoMapper.getMaxUid();
      long dd = (long) (Math.random() * 100);
      if (dd == 0) {
         dd = 1;
      }
      long bid = maxUid;
      long id = bid + dd;
      form.setId(id);
      form.setAppId(appid);
      userInfoMapper.insertSelective(form);
      return true;
   }
   public UserInfo getUserById(long uid) {
      UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
      if (user.getState() != null && user.getState() != UserInfo.STATE_NORMAL)
         return null;
      if (user != null) {
         user.setRankIcon(UserUtil.getRankIcon(user.getRank()));
         user.setRankNamePicture(UserUtil.getRankNamePicture(user.getRank()));
      }
      return user;
   }
   @Transactional
   public void update(UserInfo user) {
      userInfoMapper.updateByPrimaryKeySelective(user);
   }
   public long getUserCount() {
      return userInfoMapper.countAvaiableUser();
   }
   @Transactional
   public void unBindUserInfo(UserInfo user, int type) {
      if (type == Constant.TAOBAO) {
         user.setOpenid("");
         user.setTbName("");
         user.setTbPic("");
         if (!StringUtil.isNullOrEmpty(user.getWxOpenId())) {
            user.setLoginType(Constant.WEIXIN);
            user.setNickName(user.getWxName());
            user.setPortrait(user.getWxPic());
         }
      } else if (type == Constant.WEIXIN) {
         user.setWxName("");
         user.setWxOpenId("");
         user.setWxUnionId("");
         user.setWxPic("");
         if (!StringUtil.isNullOrEmpty(user.getOpenid())) {
            user.setLoginType(Constant.TAOBAO);
            user.setNickName(user.getTbName());
            user.setPortrait(user.getTbPic());
         }
      }
      userInfoMapper.updateByPrimaryKeySelective(user);
   }
   @Transactional
   public void addMoney(UserInfo userInfo, BigDecimal money) {
      userInfoMapper.addHongBaoByUid(userInfo.getId(), money);
   }
   @Override
   public void updateLoginInfo(UserInfo user) {
      UserInfo update = new UserInfo(user.getId());
      update.setLastLoginIp(user.getLastLoginIp());
      update.setLastLoginTime(user.getLastLoginTime());
      userInfoMapper.updateByPrimaryKeySelective(update);
   }
   @Override
   public void cleanPassword(long id) {
      userInfoMapper.cleanPassword(id);
   }
   @Override
   public BigDecimal getNewPeopleHB(Long id) {
      return userInfoMapper.getNewPeopleHB(id);
   }
   @Override
   public UserInfo getUserByIdWithMybatis(long uid) {
      UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
      return UserUtil.filterForClientUser(user);
   }
   @Override
   public long countInfo(Integer userState, String key, Integer keyType, String userRank, Integer days,
         String startTime, String endTime,Integer userType, String level, Integer activeCode) {
      return userInfoMapper.countInfo(userState, key, keyType, userRank, days, startTime, endTime,userType, level, activeCode);
   }
   @Override
   public List<UserInfoVO> queryInfo(long start, int count, Integer userState, String key, Integer keyType,
         String userRank, Integer days, String startTime, String endTime, Integer userType, String level, Integer activeCode) {
      List<UserInfoVO> userList = userInfoMapper.queryInfo(start, count, userState, key, keyType, userRank, days,
            startTime, endTime, userType, level, activeCode);
      if (userList == null || userList.size() == 0) {
         return null;
      }
      for (UserInfoVO userInfoVO : userList) {
         Long uid = userInfoVO.getId();
         String rankName = userInfoVO.getRankName();
         if (rankName == null || rankName.trim().length() == 0) {
            userInfoVO.setRankName("青铜");
            userInfoVO.setRankPicture("http://img.flqapp.com/resource/rank/rank_picture_new_1.png");
         }
         String userLevel = userInfoVO.getUserLevel();
         if (!StringUtil.isNullOrEmpty(userLevel)) {
            userInfoVO.setUserLevel(UserLevelUtil.getByEnumName(userLevel).getName());
         }
         // 累计提现
         userInfoVO.setTotalExtract(payInfoMapper.sumMoneyByUid(uid));
         // 累计订单数量
         userInfoVO.setTotalOrder(commonOrderCountService.countHistoryOrderNum(uid));
         // 累计兑换金币
         userInfoVO.setTotalGoldCoinUsed(integralDetailService.sumUseGoldCoin(uid));
         // 邀请人
         UserInfo boss = threeSaleSerivce.getBoss(uid);
         if (boss == null) {
            userInfoVO.setBossName("");
         } else {
            userInfoVO.setBossName("上级:" + boss.getNickName());
         }
         // 微信号
         String wxId = userInfoVO.getWxId();
         if (StringUtil.isNullOrEmpty(wxId)) {
            userInfoVO.setWxId("");
         } else {
            userInfoVO.setWxId("微信号:" + wxId);
         }
      }
      return userList;
   }
   @Override
   public long queryCount(Integer userState, String key, Integer keyType, String userRank, Integer days,
         String startTime, String endTime,Integer userType, String level, Integer activeCode) {
      return userInfoMapper.queryCount(userState, key, keyType, userRank, days, startTime, endTime,userType, level, activeCode);
   }
   @Override
   public List<UserInfoVO> query(long start, int count, Integer userState, String key, Integer keyType,
         String userRank, Integer days, String startTime, String endTime, Integer orderField, Integer orderMode,
         Integer userType, String level, Integer activeCode) {
      List<UserInfoVO> userList = userInfoMapper.query(start, count, userState, key, keyType, userRank, days,
            startTime, endTime, orderField, orderMode,userType, level, activeCode);
      if (userList == null || userList.size() == 0) {
         return null;
      }
      for (UserInfoVO userInfoVO : userList) {
         // 数据加工处理
         convertUserInfoVOData(userInfoVO);
      }
      return userList;
   }
   public void convertUserInfoVOData(UserInfoVO userInfoVO) {
      String rankName = userInfoVO.getRankName();
      if (rankName == null || rankName.trim().length() == 0) {
         userInfoVO.setRankName("青铜");
         userInfoVO.setRankPicture("http://img.flqapp.com/resource/rank/rank_picture_new_1.png");
      }
      String f_alipayAccount = userInfoVO.getAlipayAccountInvalid();
      if (f_alipayAccount != null && f_alipayAccount.trim().length() > 0) {
         userInfoVO.setAlipayAccountState(1);
      }
      String f_phone = userInfoVO.getPhoneInvalid();
      if (f_phone != null && f_phone.trim().length() > 0) {
         userInfoVO.setPhoneState(1);
      }
      String f_taobaoUid = userInfoVO.getTaobaoUidInvalid();
      if (f_taobaoUid != null && f_taobaoUid.trim().length() > 0) {
         userInfoVO.setTaobaoUidState(1);
      }
      String f_wxUnionId = userInfoVO.getWxUnionIdInvalid();
      if (f_wxUnionId != null && f_wxUnionId.trim().length() > 0) {
         userInfoVO.setWxUnionIdState(1);
      }
      // 最近登录时间
      Long lastLoginTime = userInfoVO.getLastLoginTime();
      if (lastLoginTime != null && lastLoginTime == 0) {
         userInfoVO.setLastLoginTime(null);
      }
      // 显示用户微信 淘宝 老版本存在
      String wxUnionId = userInfoVO.getWxUnionId();
      if (wxUnionId == null || wxUnionId.trim().length() == 0) {
         userInfoVO.setWxName(null);
      }
      // 是否绑定支付宝(购买 + 分享权限)
      String taoBaoUid = userInfoVO.getTaoBaoUid();
      String tbSpecialId = userInfoVO.getTbSpecialId();
      String tbRelationId = userInfoVO.getTbRelationId();
      if (StringUtil.isNullOrEmpty(taoBaoUid) || StringUtil.isNullOrEmpty(tbSpecialId)
            || StringUtil.isNullOrEmpty(tbRelationId)) {
         userInfoVO.setTbName(null);
         userInfoVO.setTaoBaoUid(null);
      }
      Long uid = userInfoVO.getId();
      /* 绑定收款账号信息 */
      List<BindingAccount> account = bindingAccountMapper.selectByUid(uid);
      if (account != null && account.size() > 0) {
         BindingAccount bindingAccount = account.get(0);
         Integer type = bindingAccount.getType();
         if (type != null && type == 1) {
            // 支付宝
            userInfoVO.setAccountAlipay(bindingAccount.getAccount());
            userInfoVO.setAccountName(bindingAccount.getName());
            userInfoVO.setAccountBindId(bindingAccount.getId());
         } else if (type != null && type == 2) {
            // 微信
            userInfoVO.setAccountWX(bindingAccount.getAccount());
            userInfoVO.setAccountNameWX(bindingAccount.getName());
            userInfoVO.setAccountBindIdWX(bindingAccount.getId());
         }
      }
      // 最近一次下单时间
      Date lastOrderTime = hongBaoV2CountService.getLastHongBaoTime(uid);
      if (lastOrderTime != null && lastOrderTime.getTime() != 0) {
         userInfoVO.setLastOrderTime(lastOrderTime.getTime());
      }
      // 今日总订单
      long todayOrder = hongBaoV2CountService.countValidNumberByUid(uid, 1);
      userInfoVO.setTodayOrder(todayOrder);
      // 未领取红包 待入账金额
      BigDecimal unaccountedMoney = hongBaoV2CountService.countWillGetMoneyByUid(uid);
      if (unaccountedMoney == null) {
         unaccountedMoney = new BigDecimal(0);
      }
      userInfoVO.setUnaccountedMoney(unaccountedMoney.toString());
      // 历史总收益
      BigDecimal totalMoneyHistory = hongBaoV2CountService.countMoneyByUidAndState(uid, 3);
      if (totalMoneyHistory == null) {
         totalMoneyHistory = new BigDecimal(0);
      }
      userInfoVO.setTotalMoneyHistory(totalMoneyHistory.toString());
      // 支付宝账号 累计转账总金额
      double totalMoney = payInfoMapper.sumMoneyByUid(uid);
      userInfoVO.setTotalMoney(totalMoney);
      // 累计提现 (暂未计入微信)
      userInfoVO.setTotalExtract(totalMoney);
      // 统计分享个数
      long countUserShares = userShareGoodsHistoryMapper.countUserShares(uid);
      userInfoVO.setCountUserShares(countUserShares);
      // 统计浏览足迹
      long countScanHistory = scanHistoryMapper.countUserScanHistory(uid);
      userInfoVO.setCountScanHistory(countScanHistory);
      // 一度队员数量
      //int firstTeamCount = shareMapper.myFirstTeamCount(uid + "");
      //userInfoVO.setCountLevelOne(firstTeamCount);
      // 二度队员数量
      //int secondTeamCount = shareMapper.mySecondTeamCount(uid + "");
      //userInfoVO.setCountLevelTwo(secondTeamCount);
      String userLevel = userInfoVO.getUserLevel();
      if (!StringUtil.isNullOrEmpty(userLevel)) {
         userInfoVO.setUserLevel(UserLevelUtil.getByEnumName(userLevel).getName());
      }
      String inviteCode = userInfoVO.getInviteCode();
      if (!StringUtil.isNullOrEmpty(inviteCode)) {
         userInfoVO.setInviteCode("已激活");
      } else {
         userInfoVO.setInviteCode("未激活");
      }
   }
   @Override
   public double querySumMoney(String key, Integer userType, Integer days, String startTime, String endTime) {
      return userInfoMapper.querySumMoney(key, userType, days, startTime, endTime);
   }
   @Override
   public UserInfo selectByPKey(Long id) {
      return userInfoMapper.selectByPrimaryKey(id);
   }
   @Override
   public int updateByPrimaryKeySelective(UserInfo record) {
      return userInfoMapper.updateByPrimaryKeySelective(record);
   }
   @Override
   @Transactional
   public void deleteBindInfo(UserInfo user, int type) {
      if (type == 1) {
         user.setOpenid("");
         user.setTbName("");
         user.setTbPic("");
         if (!StringUtil.isNullOrEmpty(user.getWxOpenId())) {
            user.setLoginType(Constant.WEIXIN);
            user.setNickName(user.getWxName());
            user.setPortrait(user.getWxPic());
         }
      } else if (type == 2) {
         user.setWxName("");
         user.setWxOpenId("");
         user.setWxUnionId("");
         user.setWxPic("");
         if (!StringUtil.isNullOrEmpty(user.getOpenid())) {
            user.setLoginType(Constant.TAOBAO);
            user.setNickName(user.getTbName());
            user.setPortrait(user.getTbPic());
         }
      } else if (type == 3) {
         user.setPhone("");
      }
      userInfoMapper.updateByPrimaryKeySelective(user);
   }
   @Override
   public List<Long> longTimeNoLogin(int daysNum, List<Long> list) {
      return userInfoMapper.longTimeNoLogin(daysNum, list);
   }
   /**
    * 根据电话号码、邀请码获取邀请用户
    *
    * @param phone
    * @param inviteCode
    * @return
    */
   @Override
   public UserInfo getUserInfoByInviteCode(String inviteCode) {
      return userInfoMapper.getUserInfoByInviteCode(inviteCode);
   }
   @Override
   public UserInfo getEffectiveUserInfoByPhone(String phone) {
      return userInfoMapper.getEffectiveUserInfoByPhone(phone);
   }
   @Override
   public UserInfo getEffectiveUserInfoByWXUnionId(String unionId) {
      return userInfoMapper.getEffectiveUserInfoByWXUnionId(unionId);
   }
   @Override
   public UserInfo getUserInfo(Long uid) throws UserInfoException {
      if (uid == null) {
         throw new UserInfoException(1, "请求参数为空");
      }
      UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
      if (userInfo == null) {
         throw new UserInfoException(1, "用户不存在");
      }
      if (userInfo.getState() == UserInfo.STATE_FORBIDDEN) {
         throw new UserInfoException(Constant.CODE_FORBIDDEN_USER, Constant.FORBIDDEN_USER_REASON_DESC);
      }
      if (userInfo.getState() == UserInfo.STATE_DELETE || userInfo.getState() == UserInfo.STATE_DELETE_OUT_OF_DATE) {
         throw new UserInfoException(Constant.CODE_FORBIDDEN_USER, "帐户已被删除,请重新登录");
      }
      // 淘宝昵称 组织
      boolean clearOpenid = true;
      UserExtraTaoBaoInfo extraTaoBaoInfo = userExtraTaoBaoInfoService.getByUid(uid);
      if (extraTaoBaoInfo != null) {
         String specialId = extraTaoBaoInfo.getSpecialId();
         String relationId = extraTaoBaoInfo.getRelationId();
         String taoBaoNickName = extraTaoBaoInfo.getTaoBaoNickName();
         if (!StringUtil.isNullOrEmpty(specialId) && !StringUtil.isNullOrEmpty(relationId)) {
            clearOpenid = false;
            userInfo.setOpenid(extraTaoBaoInfo.getTaoBaoUid());
            if (!StringUtil.isNullOrEmpty(taoBaoNickName)) {
               userInfo.setTbName(taoBaoNickName);
            } else {
               String taoBaoUserNick = taoBaoUnionAuthRecordService.getTaoBaoUserNick(uid);
               if (!StringUtil.isNullOrEmpty(taoBaoUserNick)) {
                  userInfo.setTbName(taoBaoUserNick);
               }
            }
         }
      }
      if (clearOpenid) {
         userInfo.setOpenid(null);
      }
      return userInfo;
   }
   @Override
   public BigDecimal getBalance(Long uid) {
      UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
      if (user != null)
         return user.getMyHongBao();
      return null;
   }
   @Override
   public void uploadPortrait(MultipartFile file, Long uid) throws UserInfoException, IOException {
      UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
      if (userInfo == null) {
         throw new UserInfoException(1, "用户不存在");
      }
      // 谷歌压缩图片
      String targetPath = FileUtil.getCacheDir() + "/uploadPortrait_" + uid + "_" + System.currentTimeMillis()
            + ".jpg";
      Thumbnails.of(file.getInputStream()).size(200, 200).toFile(targetPath);
      // 执行上传
      String filePath =FilePathEnum.userPortrait.getPath() + UUID.randomUUID().toString().replace("-", "") + ".jpg";
      String fileLink = COSManager.getInstance().uploadFile(new File(targetPath), filePath).getUrl();
      // 删除本地图片
      if (new File(targetPath).exists()) {
         new File(targetPath).delete();
      }
      // 原头像
      String portrait = userInfo.getPortrait();
      // 更新信息
      userInfo.setPortrait(fileLink);
      userInfoMapper.updateByPrimaryKeySelective(userInfo);
      // 删除原头像
      if (!StringUtil.isNullOrEmpty(portrait)) {
         COSManager.getInstance().deleteFile(portrait);
      }
      userInfoModifyRecordService.addModifyRecord(uid, ModifyTypeEnum.portrait, fileLink);
      executor.execute(new Runnable() {
         @Override
         public void run() {
            try {
               // 删除分享头像信息
               spreadUserImgService.deleteImgUrl(uid);
            } catch (Exception e) {
               try {
                  LogHelper.errorDetailInfo(e);
               } catch (Exception e1) {
                  e1.printStackTrace();
               }
            }
         }
      });
   }
   @Override
   public void saveUserInfo(String nickName, Long uid) throws UserInfoException {
      UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
      if (userInfo == null) {
         throw new UserInfoException(1, "用户不存在");
      }
      userInfo.setNickName(nickName);
      userInfoMapper.updateByPrimaryKeySelective(userInfo);
   }
   @Override
   public List<UserInfo> getAutoExtractUser(int start, int count, BigDecimal minSurplus, String beganDate,
         String endDate) {
      return userInfoMapper.getAutoExtractUser(start, count, minSurplus, beganDate, endDate);
   }
   @Override
   public List<UserInfo> listByType(int type, int page, int count) {
      return userInfoMapper.listByType(type, (page - 1) * count, count);
   }
   @Override
   public long countByType(int type) {
      return userInfoMapper.countByType(type);
   }
   @Override
   public List<UserInfo> getAutoExtractUserTo1212(int start, int count) {
      return userInfoMapper.getAutoExtractUserTo1212(start, count);
   }
   @Override
   public UserInfo selectAvailableByPrimaryKey(Long uid) {
      return userInfoMapper.selectAvailableByPrimaryKey(uid);
   }
}
package com.yeshi.fanli.service.impl.user;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
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 com.yeshi.fanli.util.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.yeshi.utils.FileUtil;
import org.yeshi.utils.HttpUtil;
import org.yeshi.utils.tencentcloud.COSManager;
import com.google.gson.Gson;
import com.yeshi.fanli.dao.mybatis.BindingAccountMapper;
import com.yeshi.fanli.dao.mybatis.PayInfoMapper;
import com.yeshi.fanli.dao.mybatis.ScanHistoryMapper;
import com.yeshi.fanli.dao.mybatis.UserInfoMapper;
import com.yeshi.fanli.dao.mybatis.UserShareGoodsHistoryMapper;
import com.yeshi.fanli.dao.mybatis.share.ShareMapper;
import com.yeshi.fanli.entity.bus.user.BindingAccount;
import com.yeshi.fanli.entity.bus.user.UserExtraTaoBaoInfo;
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserInfoModifyRecord.ModifyTypeEnum;
import com.yeshi.fanli.exception.user.UserInfoException;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.service.inter.count.HongBaoV2CountService;
import com.yeshi.fanli.service.inter.order.CommonOrderCountService;
import com.yeshi.fanli.service.inter.user.SpreadUserImgService;
import com.yeshi.fanli.service.inter.user.UserInfoModifyRecordService;
import com.yeshi.fanli.service.inter.user.UserInfoService;
import com.yeshi.fanli.service.inter.user.integral.IntegralDetailService;
import com.yeshi.fanli.service.inter.user.invite.ThreeSaleSerivce;
import com.yeshi.fanli.service.inter.user.tb.TaoBaoUnionAuthRecordService;
import com.yeshi.fanli.service.inter.user.tb.UserExtraTaoBaoInfoService;
import com.yeshi.fanli.util.account.UserUtil;
import com.yeshi.fanli.util.user.UserLevelUtil;
import com.yeshi.fanli.vo.user.UserInfoVO;
import net.coobird.thumbnailator.Thumbnails;
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource(name = "taskExecutor")
    private TaskExecutor executor;
    @Resource
    private ThreeSaleSerivce threeSaleSerivce;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private BindingAccountMapper bindingAccountMapper;
    @Resource
    private PayInfoMapper payInfoMapper;
    @Resource
    private UserShareGoodsHistoryMapper userShareGoodsHistoryMapper;
    @Resource
    private ScanHistoryMapper scanHistoryMapper;
    @Resource
    private HongBaoV2CountService hongBaoV2CountService;
    @Lazy
    @Resource
    private CommonOrderCountService commonOrderCountService;
    @Resource
    private UserExtraTaoBaoInfoService userExtraTaoBaoInfoService;
    @Resource
    private TaoBaoUnionAuthRecordService taoBaoUnionAuthRecordService;
    @Resource
    private SpreadUserImgService spreadUserImgService;
    @Lazy
    @Resource
    private IntegralDetailService integralDetailService;
    @Lazy
    @Resource
    private UserInfoModifyRecordService userInfoModifyRecordService;
    @Resource
    private RedisManager redisManager;
    @Resource
    private SystemConfigService systemConfigService;
    public UserInfo getUserByLoginTypeAndOpenId(int loginType, String openid, SystemEnum sysetm) {
        List<UserInfo> list = null;
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = sysetm;
        daoQuery.count = 1000;
        if (loginType == 1) {
            daoQuery.openId = openid;
        } else {
            daoQuery.wxUnionId = openid;
        }
        list = userInfoMapper.list(daoQuery);
        if (list != null)
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getState() == UserInfo.STATE_DELETE
                        || list.get(i).getState() == UserInfo.STATE_DELETE_OUT_OF_DATE) {
                    list.remove(i);
                    i--;
                }
            }
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public UserInfo addUser(UserInfo form, SystemEnum sysetm) {
        try {
            LogHelper.test("用户的注册信息:" + new Gson().toJson(form));
            form.setCreatetime(new Date().getTime());
            form.setRank(0);
            String openId = form.getLoginType() == Constant.TAOBAO ? form.getOpenid() : form.getWxUnionId();
            UserInfo find = getUserByLoginTypeAndOpenId(form.getLoginType(), openId, sysetm);
            if (find != null) {
                return find;
            }
            boolean create = createUser(form, sysetm);
            if (!create) {
                return null;
            }
            int loginType = form.getLoginType();
            // 建的假用户。。
            if (loginType == -1) {
                return form;
            }
            LogHelper.userInfo("添加用户:" + form);
            if (form.getLoginType() == Constant.WEIXIN) {
                ThreadUtil.run(new Runnable() {
                    public void run() {
                        UserInfo temp = userInfoMapper.selectByPrimaryKey(form.getId());
                        COSManager cosManager = COSManager.getInstance();
                        InputStream inputStream = HttpUtil.getAsInputStream(temp.getPortrait());
                        String uploadFile = cosManager.uploadFile(inputStream, FilePathEnum.userPortrait.getPath() + UUID.randomUUID().toString()).getUrl();
                        UserInfo updateTemp = new UserInfo(temp.getId());
                        updateTemp.setPortrait(uploadFile);
                        userInfoMapper.updateByPrimaryKeySelective(updateTemp);
                    }
                });
            }
        } catch (Exception e) {
            try {
                LogHelper.errorDetailInfo(e);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return null;
        }
        return form;
    }
    @Transactional
    public boolean createUser(UserInfo form, SystemEnum sysetm) {
        long maxUid = userInfoMapper.getMaxUid();
        long dd = (long) (Math.random() * 100);
        if (dd == 0) {
            dd = 1;
        }
        long bid = maxUid;
        long id = bid + dd;
        form.setId(id);
        form.setSystem(sysetm);
        userInfoMapper.insertSelective(form);
        return true;
    }
    public UserInfo getUserById(long uid) {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user.getState() != null && user.getState() != UserInfo.STATE_NORMAL)
            return null;
        if (user != null) {
            user.setRankIcon(UserUtil.getRankIcon(user.getRank()));
            user.setRankNamePicture(UserUtil.getRankNamePicture(user.getRank()));
        }
        return user;
    }
    @Transactional
    public void update(UserInfo user) {
        userInfoMapper.updateByPrimaryKeySelective(user);
    }
    public long getUserCount() {
        return userInfoMapper.countAvaiableUser();
    }
    @Transactional
    public void unBindUserInfo(UserInfo user, int type) {
        if (type == Constant.TAOBAO) {
            user.setOpenid("");
            user.setTbName("");
            user.setTbPic("");
            if (!StringUtil.isNullOrEmpty(user.getWxOpenId())) {
                user.setLoginType(Constant.WEIXIN);
                user.setNickName(user.getWxName());
                user.setPortrait(user.getWxPic());
            }
        } else if (type == Constant.WEIXIN) {
            user.setWxName("");
            user.setWxOpenId("");
            user.setWxUnionId("");
            user.setWxPic("");
            if (!StringUtil.isNullOrEmpty(user.getOpenid())) {
                user.setLoginType(Constant.TAOBAO);
                user.setNickName(user.getTbName());
                user.setPortrait(user.getTbPic());
            }
        }
        userInfoMapper.updateByPrimaryKeySelective(user);
    }
    @Transactional
    public void addMoney(UserInfo userInfo, BigDecimal money) {
        userInfoMapper.addHongBaoByUid(userInfo.getId(), money);
    }
    @Override
    public void updateLoginInfo(UserInfo user) {
        UserInfo update = new UserInfo(user.getId());
        update.setLastLoginIp(user.getLastLoginIp());
        update.setLastLoginTime(user.getLastLoginTime());
        userInfoMapper.updateByPrimaryKeySelective(update);
    }
    @Override
    public void cleanPassword(long id) {
        userInfoMapper.cleanPassword(id);
    }
    @Override
    public BigDecimal getNewPeopleHB(Long id) {
        return userInfoMapper.getNewPeopleHB(id);
    }
    @Override
    public UserInfo getUserByIdWithMybatis(long uid) {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        return UserUtil.filterForClientUser(user);
    }
    @Override
    public long countInfo(Integer userState, String key, Integer keyType, String userRank, Integer days,
                          String startTime, String endTime, Integer userType, String level, Integer activeCode, SystemEnum system) {
        return userInfoMapper.countInfo(userState, key, keyType, userRank, days, startTime, endTime, userType, level, activeCode, system);
    }
    @Override
    public List<UserInfoVO> queryInfo(long start, int count, Integer userState, String key, Integer keyType,
                                      String userRank, Integer days, String startTime, String endTime, Integer userType, String level, Integer activeCode, SystemEnum system) {
        List<UserInfoVO> userList = userInfoMapper.queryInfo(start, count, userState, key, keyType, userRank, days,
                startTime, endTime, userType, level, activeCode, system);
        if (userList == null || userList.size() == 0) {
            return null;
        }
        for (UserInfoVO userInfoVO : userList) {
            Long uid = userInfoVO.getId();
            String rankName = userInfoVO.getRankName();
            if (rankName == null || rankName.trim().length() == 0) {
                userInfoVO.setRankName("青铜");
                userInfoVO.setRankPicture("http://img.flqapp.com/resource/rank/rank_picture_new_1.png");
            }
            String userLevel = userInfoVO.getUserLevel();
            if (!StringUtil.isNullOrEmpty(userLevel)) {
                userInfoVO.setUserLevel(UserLevelUtil.getByEnumName(userLevel).getName());
            }
            // 累计提现
            userInfoVO.setTotalExtract(payInfoMapper.sumMoneyByUid(uid));
            // 累计订单数量
            userInfoVO.setTotalOrder(commonOrderCountService.countHistoryOrderNum(uid));
            // 累计兑换金币
            userInfoVO.setTotalGoldCoinUsed(Math.abs(integralDetailService.sumUseGoldCoin(uid)));
            // 邀请人
            UserInfo boss = threeSaleSerivce.getBoss(uid);
            if (boss == null) {
                userInfoVO.setBossName("");
            } else {
                userInfoVO.setBossName("邀请人:" + boss.getNickName());
            }
            // 微信号
            String wxId = userInfoVO.getWxId();
            if (StringUtil.isNullOrEmpty(wxId)) {
                userInfoVO.setWxId("");
            } else {
                userInfoVO.setWxId("微信号:" + wxId);
            }
        }
        return userList;
    }
    @Override
    public List<UserInfo> listBySystemAndWXUnionId(SystemEnum system, String unionId) {
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = system;
        daoQuery.count = 1000;
        daoQuery.wxUnionId = unionId;
        return userInfoMapper.list(daoQuery);
    }
    @Override
    public List<UserInfo> listBySystemAndTaoBaoOpenId(SystemEnum system, String openId) {
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = system;
        daoQuery.count = 1000;
        daoQuery.openId = openId;
        return userInfoMapper.list(daoQuery);
    }
    @Override
    public List<UserInfo> listBySystemAndPhone(SystemEnum system, String phone) {
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = system;
        daoQuery.count = 1000;
        daoQuery.phone = phone;
        return userInfoMapper.list(daoQuery);
    }
    @Override
    public SystemEnum getUserSystem(Long uid) {
        String value = redisManager.getCommonString(RedisKeyEnum.getRedisKey(RedisKeyEnum.userSystem, uid + ""));
        if (!StringUtil.isNullOrEmpty(value)) {
            return SystemEnum.valueOf(value);
        }
        UserInfo user = selectByPKey(uid);
        if (user != null) {
            //保存1天
            redisManager.cacheCommonString(RedisKeyEnum.getRedisKey(RedisKeyEnum.userSystem, uid + ""), user.getSystem().name(), 60 * 60 * 24);
            return user.getSystem();
        }
        return null;
    }
    @Override
    public long queryCount(Integer userState, String key, Integer keyType, String userRank, Integer days,
                           String startTime, String endTime, Integer userType, String level, Integer activeCode, SystemEnum system) {
        return userInfoMapper.queryCount(userState, key, keyType, userRank, days, startTime, endTime, userType, level, activeCode, system);
    }
    @Override
    public List<UserInfoVO> query(long start, int count, Integer userState, String key, Integer keyType,
                                  String userRank, Integer days, String startTime, String endTime, Integer orderField, Integer orderMode,
                                  Integer userType, String level, Integer activeCode, SystemEnum system) {
        List<UserInfoVO> userList = userInfoMapper.query(start, count, userState, key, keyType, userRank, days,
                startTime, endTime, orderField, orderMode, userType, level, activeCode, system);
        if (userList == null || userList.size() == 0) {
            return null;
        }
        for (UserInfoVO userInfoVO : userList) {
            // 数据加工处理
            convertUserInfoVOData(userInfoVO);
        }
        return userList;
    }
    public void convertUserInfoVOData(UserInfoVO userInfoVO) {
        String rankName = userInfoVO.getRankName();
        if (rankName == null || rankName.trim().length() == 0) {
            userInfoVO.setRankName("青铜");
            userInfoVO.setRankPicture("http://img.flqapp.com/resource/rank/rank_picture_new_1.png");
        }
        String f_alipayAccount = userInfoVO.getAlipayAccountInvalid();
        if (f_alipayAccount != null && f_alipayAccount.trim().length() > 0) {
            userInfoVO.setAlipayAccountState(1);
        }
        String f_phone = userInfoVO.getPhoneInvalid();
        if (f_phone != null && f_phone.trim().length() > 0) {
            userInfoVO.setPhoneState(1);
        }
        String f_taobaoUid = userInfoVO.getTaobaoUidInvalid();
        if (f_taobaoUid != null && f_taobaoUid.trim().length() > 0) {
            userInfoVO.setTaobaoUidState(1);
        }
        String f_wxUnionId = userInfoVO.getWxUnionIdInvalid();
        if (f_wxUnionId != null && f_wxUnionId.trim().length() > 0) {
            userInfoVO.setWxUnionIdState(1);
        }
        // 最近登录时间
        Long lastLoginTime = userInfoVO.getLastLoginTime();
        if (lastLoginTime != null && lastLoginTime == 0) {
            userInfoVO.setLastLoginTime(null);
        }
        // 显示用户微信 淘宝 老版本存在
        String wxUnionId = userInfoVO.getWxUnionId();
        if (wxUnionId == null || wxUnionId.trim().length() == 0) {
            userInfoVO.setWxName(null);
        }
        // 是否绑定支付宝(购买 + 分享权限)
        String taoBaoUid = userInfoVO.getTaoBaoUid();
        String tbSpecialId = userInfoVO.getTbSpecialId();
        String tbRelationId = userInfoVO.getTbRelationId();
        if (StringUtil.isNullOrEmpty(taoBaoUid) || StringUtil.isNullOrEmpty(tbSpecialId)
                || StringUtil.isNullOrEmpty(tbRelationId)) {
            userInfoVO.setTbName(null);
            userInfoVO.setTaoBaoUid(null);
        }
        Long uid = userInfoVO.getId();
        /* 绑定收款账号信息 */
        List<BindingAccount> account = bindingAccountMapper.selectByUid(uid);
        if (account != null && account.size() > 0) {
            BindingAccount bindingAccount = account.get(0);
            Integer type = bindingAccount.getType();
            if (type != null && type == 1) {
                // 支付宝
                userInfoVO.setAccountAlipay(bindingAccount.getAccount());
                userInfoVO.setAccountName(bindingAccount.getName());
                userInfoVO.setAccountBindId(bindingAccount.getId());
            } else if (type != null && type == 2) {
                // 微信
                userInfoVO.setAccountWX(bindingAccount.getAccount());
                userInfoVO.setAccountNameWX(bindingAccount.getName());
                userInfoVO.setAccountBindIdWX(bindingAccount.getId());
            }
        }
        // 最近一次下单时间
        Date lastOrderTime = hongBaoV2CountService.getLastHongBaoTime(uid);
        if (lastOrderTime != null && lastOrderTime.getTime() != 0) {
            userInfoVO.setLastOrderTime(lastOrderTime.getTime());
        }
        // 今日总订单
        long todayOrder = hongBaoV2CountService.countValidNumberByUid(uid, 1);
        userInfoVO.setTodayOrder(todayOrder);
        // 未领取红包 待入账金额
        BigDecimal unaccountedMoney = hongBaoV2CountService.countWillGetMoneyByUid(uid);
        if (unaccountedMoney == null) {
            unaccountedMoney = new BigDecimal(0);
        }
        userInfoVO.setUnaccountedMoney(unaccountedMoney.toString());
        // 历史总收益
        BigDecimal totalMoneyHistory = hongBaoV2CountService.countMoneyByUidAndState(uid, 3);
        if (totalMoneyHistory == null) {
            totalMoneyHistory = new BigDecimal(0);
        }
        userInfoVO.setTotalMoneyHistory(totalMoneyHistory.toString());
        // 支付宝账号 累计转账总金额
        double totalMoney = payInfoMapper.sumMoneyByUid(uid);
        userInfoVO.setTotalMoney(totalMoney);
        // 累计提现 (暂未计入微信)
        userInfoVO.setTotalExtract(totalMoney);
        // 统计分享个数
        long countUserShares = userShareGoodsHistoryMapper.countUserShares(uid);
        userInfoVO.setCountUserShares(countUserShares);
        // 统计浏览足迹
        long countScanHistory = scanHistoryMapper.countUserScanHistory(uid);
        userInfoVO.setCountScanHistory(countScanHistory);
        // 一度队员数量
        //int firstTeamCount = shareMapper.myFirstTeamCount(uid + "");
        //userInfoVO.setCountLevelOne(firstTeamCount);
        // 二度队员数量
        //int secondTeamCount = shareMapper.mySecondTeamCount(uid + "");
        //userInfoVO.setCountLevelTwo(secondTeamCount);
        String userLevel = userInfoVO.getUserLevel();
        if (!StringUtil.isNullOrEmpty(userLevel)) {
            userInfoVO.setUserLevel(UserLevelUtil.getByEnumName(userLevel).getName());
        }
        String inviteCode = userInfoVO.getInviteCode();
        if (!StringUtil.isNullOrEmpty(inviteCode)) {
            userInfoVO.setInviteCode("已激活");
        } else {
            userInfoVO.setInviteCode("未激活");
        }
    }
    @Override
    public double querySumMoney(String key, Integer userType, Integer days, String startTime, String endTime) {
        return userInfoMapper.querySumMoney(key, userType, days, startTime, endTime);
    }
    @Override
    public UserInfo selectByPKey(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }
    @Override
    public int updateByPrimaryKeySelective(UserInfo record) {
        return userInfoMapper.updateByPrimaryKeySelective(record);
    }
    @Override
    @Transactional
    public void deleteBindInfo(UserInfo user, int type) {
        if (type == 1) {
            user.setOpenid("");
            user.setTbName("");
            user.setTbPic("");
            if (!StringUtil.isNullOrEmpty(user.getWxOpenId())) {
                user.setLoginType(Constant.WEIXIN);
                user.setNickName(user.getWxName());
                user.setPortrait(user.getWxPic());
            }
        } else if (type == 2) {
            user.setWxName("");
            user.setWxOpenId("");
            user.setWxUnionId("");
            user.setWxPic("");
            if (!StringUtil.isNullOrEmpty(user.getOpenid())) {
                user.setLoginType(Constant.TAOBAO);
                user.setNickName(user.getTbName());
                user.setPortrait(user.getTbPic());
            }
        } else if (type == 3) {
            user.setPhone("");
        }
        userInfoMapper.updateByPrimaryKeySelective(user);
    }
    @Override
    public List<Long> longTimeNoLogin(int daysNum, List<Long> list) {
        return userInfoMapper.longTimeNoLogin(daysNum, list);
    }
    /**
     * 根据电话号码、邀请码获取邀请用户
     *
     * @param inviteCode
     * @return
     */
    @Override
    public UserInfo getUserInfoByInviteCode(String inviteCode) {
        return userInfoMapper.getUserInfoByInviteCode(inviteCode);
    }
    @Override
    public UserInfo getEffectiveUserInfoByPhone(String phone, SystemEnum system) {
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = system;
        daoQuery.count = 1000;
        daoQuery.phone = phone;
        daoQuery.state = UserInfo.STATE_NORMAL;
        List<UserInfo> userInfoList = userInfoMapper.list(daoQuery);
        return userInfoList != null && userInfoList.size() > 0 ? userInfoList.get(0) : null;
    }
    @Override
    public UserInfo getEffectiveUserInfoByWXUnionId(String unionId, SystemEnum system) {
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = system;
        daoQuery.count = 1000;
        daoQuery.wxUnionId = unionId;
        daoQuery.state = UserInfo.STATE_NORMAL;
        List<UserInfo> userInfoList = userInfoMapper.list(daoQuery);
        return userInfoList != null && userInfoList.size() > 0 ? userInfoList.get(0) : null;
    }
    @Override
    public UserInfo getEffectiveUserInfoByQQOpenId(String opneId, SystemEnum sysetm) {
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = sysetm;
        daoQuery.count = 1000;
        daoQuery.qqOpenId = opneId;
        daoQuery.state = UserInfo.STATE_NORMAL;
        List<UserInfo> userInfoList = userInfoMapper.list(daoQuery);
        return userInfoList != null && userInfoList.size() > 0 ? userInfoList.get(0) : null;
    }
    @Override
    public UserInfo getEffectiveUserInfoByOpenId(String openId, SystemEnum sysetm) {
        UserInfoMapper.DaoQuery daoQuery = new UserInfoMapper.DaoQuery();
        daoQuery.system = sysetm;
        daoQuery.count = 1000;
        daoQuery.openId = openId;
        daoQuery.state = UserInfo.STATE_NORMAL;
        List<UserInfo> userInfoList = userInfoMapper.list(daoQuery);
        return userInfoList != null && userInfoList.size() > 0 ? userInfoList.get(0) : null;
    }
    @Override
    public UserInfo getUserInfo(Long uid) throws UserInfoException {
        if (uid == null) {
            throw new UserInfoException(1, "请求参数为空");
        }
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
        if (userInfo == null) {
            throw new UserInfoException(1, "用户不存在");
        }
        if (userInfo.getState() == UserInfo.STATE_FORBIDDEN) {
            throw new UserInfoException(Constant.CODE_FORBIDDEN_USER, Constant.FORBIDDEN_USER_REASON_DESC);
        }
        if (userInfo.getState() == UserInfo.STATE_DELETE || userInfo.getState() == UserInfo.STATE_DELETE_OUT_OF_DATE) {
            throw new UserInfoException(Constant.CODE_FORBIDDEN_USER, "帐户已被删除,请重新登录");
        }
        // 淘宝昵称 组织
        boolean clearOpenid = true;
        UserExtraTaoBaoInfo extraTaoBaoInfo = userExtraTaoBaoInfoService.getByUid(uid);
        if (extraTaoBaoInfo != null) {
            String specialId = extraTaoBaoInfo.getSpecialId();
            String relationId = extraTaoBaoInfo.getRelationId();
            String taoBaoNickName = extraTaoBaoInfo.getTaoBaoNickName();
            if (!StringUtil.isNullOrEmpty(specialId) && !StringUtil.isNullOrEmpty(relationId)) {
                clearOpenid = false;
                userInfo.setOpenid(extraTaoBaoInfo.getTaoBaoUid());
                if (!StringUtil.isNullOrEmpty(taoBaoNickName)) {
                    userInfo.setTbName(taoBaoNickName);
                } else {
                    String taoBaoUserNick = taoBaoUnionAuthRecordService.getTaoBaoUserNick(uid);
                    if (!StringUtil.isNullOrEmpty(taoBaoUserNick)) {
                        userInfo.setTbName(taoBaoUserNick);
                    }
                }
            }
        }
        if (clearOpenid) {
            userInfo.setOpenid(null);
        }
        return userInfo;
    }
    @Override
    public BigDecimal getBalance(Long uid) {
        UserInfo user = userInfoMapper.selectByPrimaryKey(uid);
        if (user != null)
            return user.getMyHongBao();
        return null;
    }
    @Override
    public void uploadPortrait(MultipartFile file, Long uid) throws UserInfoException, IOException {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
        if (userInfo == null) {
            throw new UserInfoException(1, "用户不存在");
        }
        // 谷歌压缩图片
        String targetPath = FileUtil.getCacheDir() + "/uploadPortrait_" + uid + "_" + System.currentTimeMillis()
                + ".jpg";
        Thumbnails.of(file.getInputStream()).size(200, 200).toFile(targetPath);
        // 执行上传
        String filePath = FilePathEnum.userPortrait.getPath() + UUID.randomUUID().toString().replace("-", "") + ".jpg";
        String fileLink = COSManager.getInstance().uploadFile(new File(targetPath), filePath).getUrl();
        // 删除本地图片
        if (new File(targetPath).exists()) {
            new File(targetPath).delete();
        }
        // 原头像
        String portrait = userInfo.getPortrait();
        // 更新信息
        userInfo.setPortrait(fileLink);
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
        // 删除原头像
        if (!StringUtil.isNullOrEmpty(portrait)) {
            COSManager.getInstance().deleteFile(portrait);
        }
        userInfoModifyRecordService.addModifyRecord(uid, ModifyTypeEnum.portrait, fileLink);
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 删除分享头像信息
                    spreadUserImgService.deleteImgUrl(uid);
                } catch (Exception e) {
                    try {
                        LogHelper.errorDetailInfo(e);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
    }
    @Override
    public void saveUserInfo(String nickName, Long uid) throws UserInfoException {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
        if (userInfo == null) {
            throw new UserInfoException(1, "用户不存在");
        }
        userInfo.setNickName(nickName);
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }
    @Override
    public List<UserInfo> getAutoExtractUser(int start, int count, BigDecimal minSurplus, String beganDate,
                                             String endDate) {
        return userInfoMapper.getAutoExtractUser(start, count, minSurplus, beganDate, endDate);
    }
    @Override
    public List<UserInfo> listByType(int type, int page, int count) {
        return userInfoMapper.listByType(type, (page - 1) * count, count);
    }
    @Override
    public long countByType(int type) {
        return userInfoMapper.countByType(type);
    }
    @Override
    public List<UserInfo> getAutoExtractUserTo1212(int start, int count) {
        return userInfoMapper.getAutoExtractUserTo1212(start, count);
    }
    @Override
    public UserInfo selectAvailableByPrimaryKey(Long uid) {
        return userInfoMapper.selectAvailableByPrimaryKey(uid);
    }
    @Override
    public String getDefaultNickName(SystemEnum system, Long uid) {
        return systemConfigService.getValueCache(SystemConfigKeyEnum.defaultNickNamePrefix, system) + uid;
    }
    @Override
    public String getDefaultNickName(Long uid) {
        SystemEnum system = getUserSystem(uid);
        return getDefaultNickName(system, uid);
    }
    @Override
    public String getDefaultPortrait(SystemEnum system) {
        return systemConfigService.getValueCache(SystemConfigKeyEnum.defaultPortrait, system);
    }
    @Override
    public String getDefaultPortrait(Long uid) {
        SystemEnum system = getUserSystem(uid);
        return getDefaultPortrait(system);
    }
}