package com.ruoyi.cai.service.impl;

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.Anchor;
import com.ruoyi.cai.domain.AnchorApply;
import com.ruoyi.cai.domain.User;
import com.ruoyi.cai.dto.admin.vo.AnchorApplyAdminVo;
import com.ruoyi.cai.dto.app.vo.AnchorJoinHomeVo;
import com.ruoyi.cai.enums.AuditStatusEnum;
import com.ruoyi.cai.enums.GenderEnum;
import com.ruoyi.cai.enums.SystemConfigEnum;
import com.ruoyi.cai.manager.SystemConfigManager;
import com.ruoyi.cai.mapper.AnchorApplyMapper;
import com.ruoyi.cai.notice.YunxinHttpService;
import com.ruoyi.cai.service.AnchorApplyService;
import com.ruoyi.cai.service.AnchorService;
import com.ruoyi.cai.service.UserService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 播主申请管理Service业务层处理
 *
 * @author 77
 * @date 2023-12-22
 */
@Service
public class AnchorApplyServiceImpl extends ServiceImpl<AnchorApplyMapper, AnchorApply> implements AnchorApplyService {

    @Autowired
    private UserService userService;
    @Autowired
    private AnchorService anchorService;
    @Autowired
    private SystemConfigManager systemConfigManager;
    @Autowired
    private YunxinHttpService yunxinHttpService;

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

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

    @Override
    public AnchorJoinHomeVo joinHome(Long userId) {
        User user = userService.getById(userId);
        AnchorApply anchorApply = this.getByUserId(userId);
        AnchorJoinHomeVo vo = new AnchorJoinHomeVo();
        vo.setFinishStatus(user.getFinishStatus());
        vo.setPhotoStatus(user.getPhotoStatus());
        vo.setCameraStatus(user.getCameraStatus());
        vo.setAgreeProtocol(user.getAgreeProtocol());
        if(anchorApply != null){
            vo.setApplyStatus(user.getStatus());
        }else{
            vo.setApplyStatus(0);
        }
        return vo;
    }

    @Override
    public boolean joinAnchor(Long userId) {
        User user = userService.getById(userId);
        if(user.getIsAnchor() == 1){
            throw new ServiceException("您已经是主播，不能重复申请");
        }
        if(user.getFinishStatus() != 1){
            throw new ServiceException("您还未完善个人资料");
        }
        if(user.getPhotoStatus() != 1){
            throw new ServiceException("请选上传相册");
        }
        if(user.getCameraStatus() != 1){
            throw new ServiceException("您还未完成自拍认证");
        }
        if(user.getAgreeProtocol() != 1){
            throw new ServiceException("您还未同意个人协议");
        }
        AnchorApply anchorApply = this.getByUserId(userId);
        if(anchorApply != null && AuditStatusEnum.AUDITING.getCode().equals(anchorApply.getAuditStatus())){
            throw new ServiceException("您的提交的申请正在审核中请耐心等待");
        }
        anchorApply = new AnchorApply();
        anchorApply.setUserId(userId);
        anchorApply.setAuditStatus(AuditStatusEnum.AUDITING.getCode());
        anchorApply.setCreateTime(LocalDateTime.now());
        this.save(anchorApply);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditAnchorSuccess(Long id) {
        AnchorApply anchorApply = this.getById(id);
        if(anchorApply == null){
            throw new ServiceException("审核失败，数据不存在");
        }
        Long userId = anchorApply.getUserId();
        User user = userService.getById(userId);
        Anchor anchor = anchorService.getByUserId(userId);
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        if(user.getIsAnchor() == 1 || anchor != null){
            throw new ServiceException("改用户已经是主播");
        }
        if(!GenderEnum.WOMEN.getCode().equals(user.getGender())){
            throw new ServiceException("只有女用户可以加入主播");
        }
        boolean boo = userService.update(Wrappers.lambdaUpdate(User.class)
                .eq(User::getId, user.getId()).eq(User::getIsAnchor, 0)
                .set(User::getIsAnchor, 1));
        if(!boo){
            throw new ServiceException("加入主播失败");
        }
        this.update(Wrappers.lambdaUpdate(AnchorApply.class)
                .eq(AnchorApply::getId,id)
                .set(AnchorApply::getAuditTime,LocalDateTime.now())
                .set(AnchorApply::getAuditStatus,AuditStatusEnum.SUCCESS.getCode()));
        Long price = systemConfigManager.getSystemConfigOfLong(SystemConfigEnum.DEFAULT_ANCHOR_PRICE);
        Anchor save = new Anchor();
        save.setUserId(user.getId());
        save.setPrice(price);
        save.setVideoRate(systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_ANCHOR_VIDEO_PRICE));
        save.setGuardRate(systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_ANCHOR_GUARD_PRICE));
        save.setGiftRate(systemConfigManager.getSystemConfigOfBigDecimal(SystemConfigEnum.DEFAULT_ANCHOR_GIFT_PRICE));
        anchorService.save(save);
        yunxinHttpService.passAnchorSendMessage(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditAnchorFail(Long id) {
        AnchorApply anchorApply = this.getById(id);
        if(anchorApply == null){
            return;
        }
        this.update(Wrappers.lambdaUpdate(AnchorApply.class)
                .eq(AnchorApply::getId,id)
                .set(AnchorApply::getAuditTime,LocalDateTime.now())
                .set(AnchorApply::getAuditStatus,AuditStatusEnum.FAIL.getCode()));
    }
}
