package com.ruoyi.cai.service.impl;

import cn.dev33.satoken.secure.BCrypt;
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.cai.domain.*;
import com.ruoyi.cai.dto.admin.vo.UserAdminVo;
import com.ruoyi.cai.dto.app.query.index.GreetQuery;
import com.ruoyi.cai.dto.app.query.index.UserMapperQuery;
import com.ruoyi.cai.dto.app.query.index.UserQuery;
import com.ruoyi.cai.dto.app.vo.user.UserInfoVo;
import com.ruoyi.cai.dto.app.vo.user.UserListVo;
import com.ruoyi.cai.dto.app.vo.user.OnlineStatusVo;
import com.ruoyi.cai.enums.GenderEnum;
import com.ruoyi.cai.mapper.UserMapper;
import com.ruoyi.cai.service.*;
import com.ruoyi.cai.ws.service.RoomService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户Service业务层处理
 *
 * @author 77
 * @date 2023-12-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private AnchorService anchorService;
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private UserAlbumService userAlbumService;
    @Autowired
    private GuardTotalService guardTotalService;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private UserGiftService userGiftService;
    @Autowired
    private UserOnlineService userOnlineService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserInviteService userInviteService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private DynamicImagesService dynamicImagesService;
    @Autowired
    private UserGreetService userGreetService;
    @Autowired
    private UserMemberService userMemberService;
    @Autowired
    private UserForbidService userForbidService;
    @Autowired
    private AnchorApplyService anchorApplyService;
    @Autowired
    private RoomService roomService;

    @Override
    public User getByUsername(String username) {
        return this.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getMobile,username));
    }

    @Override
    public Page<UserAdminVo> pageAdmin(PageQuery pageQuery, User query) {
        return baseMapper.pageAdmin(pageQuery.build(),query);
    }

    @Override
    public Page<UserListVo> pageApp(PageQuery page, UserQuery query) {
        UserMapperQuery mapperQuery = new UserMapperQuery();
        mapperQuery.setGender(query.getGender());
        if(query.getType() == null || StringUtils.isEmpty(query.getText())){
            return new Page<>();
        }
        if(query.getType() == 1){
            mapperQuery.setUsercodeAndNickname(query.getText());
        }else if(query.getType() == 2){
            mapperQuery.setUsercode(query.getText());
        }else if(query.getType() == 3){
            mapperQuery.setNickname(query.getText());
        }
        return baseMapper.pageApp(page.build(),mapperQuery);
    }

    @Override
    public Page<UserListVo> greetPageApp(PageQuery page, GreetQuery query) {
        return baseMapper.greetPageApp(page.build(),query);
    }

    @Override
    public UserInfoVo info(Long userId) {
        Long currentUserId = LoginHelper.getUserId();
        User user = this.getById(userId);
        if(user == null){
            return null;
        }
        Anchor anchor = anchorService.getByUserId(userId);
        UserInfoVo vo = new UserInfoVo();
        vo.setUserId(userId);
        vo.setIsAnchor(user.getIsAnchor());
        vo.setUsercode(user.getUsercode());
        vo.setNickname(user.getNickname());
        vo.setAvatar(user.getAvatar());
        vo.setPrice(0L);
        vo.setServiceCount(0L);
        if(anchor != null){
            vo.setPrice(anchor.getPrice());
            if(anchor.getOrderSwitch() == 2){ // 不隐藏接单数
                vo.setServiceCount(anchor.getServiceCount());
            }

        }
        vo.setCity(user.getCity());
        vo.setCityId(user.getCityId());
        vo.setFansNum(userFollowService.getFansNumByUserId(userId));
        vo.setStar(userFollowService.checkStar(currentUserId, userId));
        vo.setAlbumList(userAlbumService.getUserAlbum(userId, user.getIsAnchor()));
        // 在线状态
        OnlineStatusVo onlineStatusVo;
        if(user.getIsAnchor() == 1 && anchor != null){
            boolean runningVideo = roomService.checkRunningVideo(userId, anchor.getUserId());
            onlineStatusVo = userOnlineService.onlineStatus(userId,anchor.getOpenVideoStatus(),
                    runningVideo?1:anchor.getVideoStatus(), user.getIsAnchor());
        }else{
            onlineStatusVo = userOnlineService.onlineStatus(userId,0,0, user.getIsAnchor());
        }
        vo.setOnlineStatus(onlineStatusVo);
        if(user.getIsAnchor() == 1){
            vo.setGuardIndexVo(guardTotalService.guardInfoVo(currentUserId,userId,10));
            vo.setDynamicList(dynamicService.selectDynamicImageList(userId,10));
            vo.setGiftList(userGiftService.selectGiftList(userId));
        }
        return vo;
    }

    @Override
    public User getByUserCode(String userCode){
        return this.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUsercode,userCode).last("limit 1"));
    }

    @Override
    public void updateVideoStatus(Long userId, int videoStatus) {
        this.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId,userId)
                .set(User::getVideoStatus,videoStatus));
    }

    @Override
    public boolean agreeProtocol(Long userId) {
        this.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId,userId)
                .set(User::getAgreeProtocol,1));
        return true;
    }

    @Override
    public void checkFinishStatus(Long userId) {
        User user = this.getById(userId);
        if(user == null || user.getFinishStatus() == 1){
            return;
        }
        if(user.getCity() != null && user.getBirthday() != null && GenderEnum.NONE.getCode().equals(user.getGender())){
            this.update(Wrappers.lambdaUpdate(User.class)
                    .eq(User::getId,user.getId())
                    .set(User::getFinishStatus,1));
        }
    }

    @Override
    public void resetPassword(Long userId, String password) {
        if(userId == null || StringUtils.isEmpty(password)){
            throw new ServiceException("参数异常");
        }
        this.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId,userId)
                .set(User::getPassword,BCrypt.hashpw(password)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeUser(Long id) {
        User user = this.getById(id);
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        if(user.getIsUnion() == 1){
            throw new ServiceException("该用户为会长，无法删除，请先前往工会列表解散工会");
        }
        if(user.getType() == 1){
            throw new ServiceException("该员工为内部员工，禁止删除");
        }
        boolean b = this.removeById(id);
        if(!b){
            throw new ServiceException("用户不存在");
        }
        userOnlineService.remove(Wrappers.lambdaQuery(UserOnline.class).eq(UserOnline::getUserId, id));
        userInfoService.remove(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserId, id));
        userInviteService.remove(Wrappers.lambdaQuery(UserInvite.class).eq(UserInvite::getUserId, id));
        userInviteService.remove(Wrappers.lambdaQuery(UserInvite.class).eq(UserInvite::getInviteId, id));
        accountService.remove(Wrappers.lambdaQuery(Account.class).eq(Account::getUserId, id));
        userCountService.remove(Wrappers.lambdaQuery(UserCount.class).eq(UserCount::getUserId, id));
        anchorService.remove(Wrappers.lambdaQuery(Anchor.class).eq(Anchor::getUserId, id));
        userAlbumService.remove(Wrappers.lambdaQuery(UserAlbum.class).eq(UserAlbum::getUserId, id));
        dynamicService.remove(Wrappers.lambdaQuery(Dynamic.class).eq(Dynamic::getUserId, id));
        dynamicImagesService.remove(Wrappers.lambdaQuery(DynamicImages.class).eq(DynamicImages::getUserId, id));
        userFollowService.remove(Wrappers.lambdaQuery(UserFollow.class).eq(UserFollow::getUserId, id));
        userFollowService.remove(Wrappers.lambdaQuery(UserFollow.class).eq(UserFollow::getFollowUser, id));
        userGreetService.remove(Wrappers.lambdaQuery(UserGreet.class).eq(UserGreet::getUserId,id));
        userMemberService.remove(Wrappers.lambdaQuery(UserMember.class).eq(UserMember::getUserId,id));
        userForbidService.remove(Wrappers.lambdaQuery(UserForbid.class).eq(UserForbid::getId,id));
        anchorApplyService.remove(Wrappers.lambdaQuery(AnchorApply.class).eq(AnchorApply::getId,id));
        return true;
    }

}
