package com.ruoyi.xq.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.UserExtend;
import com.ruoyi.xq.domain.UserInvite;
import com.ruoyi.xq.dto.admin.user.UserInviteAdminVo;
import com.ruoyi.xq.dto.app.invite.UserInviteListVo;
import com.ruoyi.xq.dto.common.user.MinUser;
import com.ruoyi.xq.manager.ShareManager;
import com.ruoyi.xq.mapper.UserInviteMapper;
import com.ruoyi.xq.service.UserExtendService;
import com.ruoyi.xq.service.UserInviteService;
import com.ruoyi.xq.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 用户邀请Service业务层处理
 *
 * @author 77
 * @date 2024-03-13
 */
@Slf4j
@Service
public class UserInviteServiceImpl extends ServiceImpl<UserInviteMapper, UserInvite> implements UserInviteService {

    @Autowired
    private UserService userService;
    @Autowired
    private ShareManager shareManager;
    @Autowired
    private UserExtendService userExtendService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindInvite(Long userId, String inviteCode) {
        User user = userService.getById(userId);
        User inviteUser = userService.getByUsercode(inviteCode);
        if(user == null || inviteUser == null){
            throw new ServiceException("用户不存在，邀请用户不存在");
        }
        // TODO 添加判断，不允许设置自己为邀请人
        // TODO 加锁
        UserInvite userInvite = this.getOne(Wrappers.lambdaQuery(UserInvite.class)
                .eq(UserInvite::getInviteId, inviteUser.getId())
                .eq(UserInvite::getUserId, userId)
                .last("limit 1"));
        if(userInvite == null){
            userInvite = new UserInvite();
            userInvite.setUserId(userId);
            userInvite.setUsercode(user.getUsercode());
            userInvite.setInviteId(inviteUser.getId());
            userInvite.setInviteCode(inviteUser.getUsercode());
        }
        userInvite.setCashbackTotal(BigDecimal.ZERO);
        this.saveOrUpdate(userInvite);
        userService.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId, userId)
                .set(User::getInviteId, inviteUser.getId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unBindInviteUser(Long userId) {
        this.remove(Wrappers.lambdaQuery(UserInvite.class)
                .eq(UserInvite::getUserId, userId));
        userService.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId, userId)
                .set(User::getInviteId, null));
    }

    @Override
    public Page<UserInviteAdminVo> pageAdmin(PageQuery pageQuery, UserInviteAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(), bo);
    }

    @Override
    public UserInvite getByUserId(Long sourceUserId) {
        return this.getOne(Wrappers.lambdaQuery(UserInvite.class).eq(UserInvite::getUserId, sourceUserId).last("limit 1"));
    }

    @Override
    public String share(Long userId) {
        UserExtend userExtend = userExtendService.getByUserId(userId);
        if(userExtend != null && StringUtils.isNotBlank(userExtend.getShareUrl())){
            return userExtend.getShareUrl();
        }
        MinUser minUser = userService.getMinUserById(userId);
        if(minUser == null){
            throw new ServiceException("当前用户不存在");
        }
        return shareManager.genShareUrl(minUser.getUsercode());
    }

    @Override
    public IPage<UserInviteListVo> pageApp(PageQuery pageQuery, Long userId) {
        return baseMapper.pageApp(pageQuery.build(),userId);
    }
}
