package com.ruoyi.xq.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.xq.domain.ConsumeLog;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.UserExtend;
import com.ruoyi.xq.domain.UserInvite;
import com.ruoyi.xq.enums.consumer.ConsumeLogStatus;
import com.ruoyi.xq.enums.consumer.ConsumerTypeEnum;
import com.ruoyi.xq.enums.user.AccountChangeCodeEnum;
import com.ruoyi.xq.mapper.ConsumeLogMapper;
import com.ruoyi.xq.service.ConsumeLogService;
import com.ruoyi.xq.service.UserExtendService;
import com.ruoyi.xq.service.UserInviteService;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.xq.util.CaiNumUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
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 2024-03-20
 */
@Service
@Slf4j
public class ConsumeLogServiceImpl extends ServiceImpl<ConsumeLogMapper,ConsumeLog> implements ConsumeLogService {

    @Autowired
    private UserInviteService userInviteService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserExtendService userExtendService;

    @Override
    public ConsumeLog calculateInitFenxiao(ConsumeLog consumeLog){
        Long sourceUserId = consumeLog.getSourceUserId();
        UserInvite userInvite = userInviteService.getByUserId(sourceUserId);
        if(userInvite != null){
            User oneUser = userService.getById(userInvite.getInviteId());
            if(oneUser != null){
                UserExtend userExtend = userExtendService.getByUserId(oneUser.getId());
                consumeLog.setOneRate(userExtend.getVipInviteRate());
                consumeLog.setOneUserId(oneUser.getId());
                consumeLog.setOneUsercode(oneUser.getUsercode());
                consumeLog.setOnePhone(oneUser.getMobile());
                consumeLog.setOneJoin(userInvite.getEnableRate());
                consumeLog.setOneAmount(CaiNumUtil.coin(consumeLog.getAmount(),consumeLog.getOneRate()));
            }
        }
        consumeLog.setCalculateStatus(true);
        return consumeLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealFenxiao(Long id,boolean system){
        ConsumeLog consumer = this.getById(id);
        if(consumer == null){
            return;
        }
        if(!ConsumeLogStatus.READY.getCode().equals(consumer.getStatus())){
            // 已经分销完成，无需继续分销
            return;
        }
        if(!BooleanUtils.isTrue(consumer.getCalculateStatus())){
            // 先计算
            boolean update = this.update(Wrappers.lambdaUpdate(ConsumeLog.class)
                    .eq(ConsumeLog::getId, id)
                    .eq(ConsumeLog::getCalculateStatus, false)
                    .set(ConsumeLog::getOpCreate, LocalDateTime.now())
                    .set(ConsumeLog::getCalculateStatus, true));
            if(update){
                consumer = calculateInitFenxiao(consumer);
                consumer.setCalculateStatus(true);
                this.updateById(consumer);
            }
        }
        String opName = "system";
        Long opId = null;
        if(!system){
            LoginUser loginUser = LoginHelper.getLoginUser();
            if(loginUser != null){
                opName = loginUser.getUsername();
                opId = loginUser.getUserId();
            }
        }
        // 分销
        boolean update = this.update(Wrappers.lambdaUpdate(ConsumeLog.class)
                .eq(ConsumeLog::getId, id)
                .eq(ConsumeLog::getStatus, ConsumeLogStatus.READY.getCode())
                .set(ConsumeLog::getOpName, opName)
                .set(ConsumeLog::getOpId, opId)
                .set(ConsumeLog::getStatus, ConsumeLogStatus.ALREADY.getCode()));
        if(!update){
            log.error("无需分销 consumer={}", JSON.toJSONString(consumer));
            return;
        }
        ConsumerTypeEnum code = ConsumerTypeEnum.getByCode(consumer.getType());
        if(code == null){
            log.error("分销失败 BusinessEnum状态错误! consumerLog={}",JSON.toJSONString(consumer));
            throw new ServiceException("分销失败！请联系管理员排查问题！");
        }
        try {
            boolean oneInviteSend = false;
            // 计算一级
            if(consumer.getOneUserId() != null && BooleanUtils.isTrue(consumer.getOneJoin())
                    && consumer.getOneAmount() != null && consumer.getOneAmount().doubleValue() > 0){
                AccountChangeCodeEnum changeCodeEnum = ConsumerTypeEnum.getOneInviteChange(code);
                oneInviteSend = userExtendService.distribution(consumer, consumer.getOneUserId(), consumer.getOneAmount(), changeCodeEnum);
            }
        }catch (Exception e){
            log.error("分销发生未知错误，请联系开发检查!",e);
        }
    }



}
