package cn.newfeifan.mall.module.distri.service.duser;

import cn.newfeifan.mall.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.newfeifan.mall.module.distri.controller.app.integral.vo.IntegralSaveReqVO;
import cn.newfeifan.mall.module.distri.controller.admin.socialstatus.bo.SocialStatusBO;
import cn.newfeifan.mall.module.distri.dal.dataobject.integral.IntegralDO;
import cn.newfeifan.mall.module.distri.dal.dataobject.orderpercentage.OrderPercentageDO;
import cn.newfeifan.mall.module.distri.dal.dataobject.socialstatus.SocialStatusDO;
import cn.newfeifan.mall.module.distri.dal.mysql.orderpercentage.OrderPercentageMapper;
import cn.newfeifan.mall.module.distri.enums.SocialStatusEnum;
import cn.newfeifan.mall.module.distri.service.integral.IntegralService;
import cn.newfeifan.mall.module.distri.service.ptprofitlog.PtProfitLogService;
import cn.newfeifan.mall.module.distri.service.sharepath.SharePathService;
import cn.newfeifan.mall.module.distri.service.socialstatus.SocialStatusService;
import cn.newfeifan.mall.module.distri.service.socialstatuschangelog.SocialStatusChangeLogService;
import cn.newfeifan.mall.module.member.dal.dataobject.user.MemberUserDO;
import cn.newfeifan.mall.module.member.service.signin.MemberSignInRecordService;
import cn.newfeifan.mall.module.member.service.user.MemberUserService;
import cn.newfeifan.mall.module.system.service.user.AdminUserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import cn.newfeifan.mall.module.distri.controller.admin.duser.vo.*;
import cn.newfeifan.mall.module.distri.dal.dataobject.duser.DuserDO;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.module.distri.dal.mysql.duser.DuserMapper;

import java.util.List;
import java.util.Objects;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.distri.constant.DistriConstants.PT_ID;
import static cn.newfeifan.mall.module.distri.enums.ErrorCodeConstants.*;

/**
 * 推荐用户 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class DuserServiceImpl implements DuserService {

    @Resource
    private DuserMapper duserMapper;

    @Resource
    private MemberUserService memberUserService;

    @Resource
    private SharePathService sharePathService;

    @Resource
    private PtProfitLogService ptProfitLogService;

    @Resource
    private OrderPercentageMapper orderPercentageMapper;

    @Resource
    private SocialStatusChangeLogService socialStatusChangeLogService;

    @Resource
    private MemberSignInRecordService memberSignInRecordService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    @Lazy
    private IntegralService integralService;

    @Resource
    private SocialStatusService socialStatusService;


    @Override
    public void hasUserAndCreat(Long userId) {
        checkAndCreat(userId);
    }

    @Override
    public DuserInfoVO getDuserInfo(Long userId) {
        DuserDO duser = getDuserByUser(userId);
        SocialStatusDO socialStatus = socialStatusService.getSocialStatus(duser.getSocialStatusId());

        hasUserAndCreat(userId);
        // 先初始化
        // 判断当前下单人是否有有上级, 如果没有, 创建直推人关系
        sharePathService.createSharePathByUserId(userId);


        List<Long> sonsId = sharePathService.sonsId(userId);
        IntegralDO integral = integralService.getIntegral(userId);
        if (integral == null) {
            throw exception(INTEGRAL_NOT_EXISTS);
        }

        DuserInfoVO.DuserInfoVOBuilder duserInfoVOBuilder = DuserInfoVO.builder()
                .integralDO(integral)
                .descNo(sonsId.size());

        String yesterday = "0";
        String totalLog = "0";
        if (!sonsId.isEmpty()) {
            // 获取昨日贡献值 + 合赢奖
            yesterday = ptProfitLogService.getYesterdayLog(sonsId);
            totalLog = ptProfitLogService.getTotalLog(sonsId);
        }

        Boolean isSign = memberSignInRecordService.isSignIn();
        Boolean isPtSystemUser = adminUserService.isSystemUser(duser.getMobile(), true);
        Boolean isShSystemUser = adminUserService.isSystemUser(duser.getMobile(), false);

        return duserInfoVOBuilder
                .descPrice(Long.parseLong(yesterday))
                .descTotalPrice(Long.parseLong(totalLog))
                .socialUpNeed(duser.getSocialUpNeed())
                .socialStatusId(duser.getSocialStatusId())
                .socialStatusPoint(duser.getSocialStatusPoint())
                .socialStatusLevel(socialStatus.getLevel())
                .socialStatusLevelName(socialStatus.getName())
                .isSign(isSign)
                .isPtSystemUser(isPtSystemUser)
                .isShSystemUser(isShSystemUser)
                .androidRegisterId(memberUserService.getUser(userId).getAndroidRegisterId())
                .categoryId(duser.getCategoryId())
                .build();

    }

    private void checkAndCreat(Long userId) {
        DuserDO duserDO = duserMapper.selectOne(new LambdaQueryWrapperX<DuserDO>().eqIfPresent(DuserDO::getUserId, userId));
        MemberUserDO user = memberUserService.getUser(userId);
        // 判断是否有钱包
        IntegralDO integralDO = integralService.selectByUser(userId);
        if (integralDO == null) {
            // 创建一个钱包
            IntegralSaveReqVO integralSaveReqVO = IntegralSaveReqVO.builder()
                    .userName(user.getUsername())
                    .redCurrentQuota(0L)
                    .freezeQuota(0L)
                    .userId(userId).build();
            Long integralId = integralService.createIntegral(integralSaveReqVO);
            integralDO = new IntegralDO().setId(integralId);
        }
        if (duserDO == null) {
            OrderPercentageDO orderPercentageDO = orderPercentageMapper.selectList().get(0);
            SocialStatusBO socialStatusBO = socialStatusService.calculateSocial(Long.valueOf(orderPercentageDO.getRegisterSocialStatus()));

            // 创建一个新的营销用户
            DuserSaveReqVO duserSaveReqVO = DuserSaveReqVO.builder()
                    .userId(userId)
                    .userName(user.getUsername())
                    .mobile(user.getMobile())
                    .integralId(integralDO.getId())
                    .source(userId)
                    .socialStatusPoint(Long.valueOf(orderPercentageDO.getRegisterSocialStatus()))
                    .socialStatusId(socialStatusBO.getId())
                    .socialUpNeed(socialStatusBO.getSocialUpNeed())
                    .build();
            duserMapper.insert(BeanUtils.toBean(duserSaveReqVO, DuserDO.class));
            socialStatusChangeLogService.createSocialStatusChangeLog(userId, Long.valueOf(orderPercentageDO.getRegisterAncestorSocialStatus()),userId, SocialStatusEnum.REGISTER_SOCIAL);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDuserSocial(Long userId, Long social, Integer socialStatus) {

        //平台不参与身价
        if(Objects.equals(userId, PT_ID)){
            return;
        }

        //计算本次获得的身价
        DuserDO duser = getDuserByUser(userId);
        duser.setSocialStatusPoint(duser.getSocialStatusPoint() + social);

        SocialStatusBO socialStatusBO = socialStatusService.calculateSocial(duser.getSocialStatusPoint());
        duser.setSocialUpNeed(socialStatusBO.getSocialUpNeed());
        duser.setSocialStatusId(socialStatusBO.getId());
        duserMapper.updateById(duser);

        socialStatusChangeLogService.createSocialStatusChangeLog(userId, social,userId, SocialStatusEnum.getSocialStatusEnumByCode(socialStatus));
    }

    @Override
    public DuserDO getDuserByUser(Long id) {
        return duserMapper.selectOne(new LambdaQueryWrapperX<DuserDO>().eq(DuserDO::getUserId, id));
    }

}
