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

import cn.newfeifan.mall.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.newfeifan.mall.module.distri.controller.admin.socialstatus.bo.SocialStatusBO;
import cn.newfeifan.mall.module.distri.dal.dataobject.duser.DuserDO;
import cn.newfeifan.mall.module.distri.dal.mysql.duser.DuserMapper;
import cn.newfeifan.mall.module.distri.enums.SocialStatusEnum;
import cn.newfeifan.mall.module.distri.service.socialstatus.SocialStatusService;
import cn.newfeifan.mall.module.distri.service.socialstatuschangelog.SocialStatusChangeLogService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Objects;

import static cn.newfeifan.mall.module.distri.constant.DistriConstants.PT_ID;

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

    @Resource
    private DuserMapper duserMapper;
    @Resource
    private SocialStatusChangeLogService socialStatusChangeLogService;

    @Resource
    private SocialStatusService socialStatusService;

    @Override
    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));
    }

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