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

import cn.newfeifan.mall.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.newfeifan.mall.module.distri.controller.admin.partitioncrash.vo.*;
import cn.newfeifan.mall.module.distri.dal.dataobject.partitioncrash.PartitionCrashDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.module.distri.dal.mysql.partitioncrash.PartitionCrashMapper;

import java.util.List;

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

/**
 * 分区碰撞 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class PartitionCrashServiceImpl implements PartitionCrashService {

    @Resource
    private PartitionCrashMapper partitionCrashMapper;

    @Override
    public Long createPartitionCrash(PartitionCrashSaveReqVO createReqVO) {
        // 插入
        PartitionCrashDO partitionCrash = BeanUtils.toBean(createReqVO, PartitionCrashDO.class);
        partitionCrashMapper.insert(partitionCrash);
        // 返回
        return partitionCrash.getId();
    }

    @Override
    public void updatePartitionCrash(PartitionCrashSaveReqVO updateReqVO) {
        // 校验存在
        validatePartitionCrashExists(updateReqVO.getId());
        // 更新
        PartitionCrashDO updateObj = BeanUtils.toBean(updateReqVO, PartitionCrashDO.class);
        partitionCrashMapper.updateById(updateObj);
    }

    @Override
    public void deletePartitionCrash(Long id) {
        // 校验存在
        validatePartitionCrashExists(id);
        // 删除
        partitionCrashMapper.deleteById(id);
    }

    private void validatePartitionCrashExists(Long id) {
        if (partitionCrashMapper.selectById(id) == null) {
            throw exception(PARTITION_CRASH_NOT_EXISTS);
        }
    }

    @Override
    public PartitionCrashDO getPartitionCrash(Long id) {
        return partitionCrashMapper.selectById(id);
    }

    @Override
    public PageResult<PartitionCrashDO> getPartitionCrashPage(PartitionCrashPageReqVO pageReqVO) {
        return partitionCrashMapper.selectPage(pageReqVO);
    }

    @Override
    public Long getResidueSocial(Long userId) {
        Long afterHitQuota = null;
        List<PartitionCrashDO> partitionCrashDOS = partitionCrashMapper.selectList(new LambdaQueryWrapperX<PartitionCrashDO>()
                .eq(PartitionCrashDO::getUserId, userId)
                .orderByDesc(PartitionCrashDO::getCreateTime)
        );
        if(!partitionCrashDOS.isEmpty()){
            afterHitQuota = partitionCrashDOS.get(0).getAfterHitQuota();
        }
        return afterHitQuota == null ? 0L : afterHitQuota;
    }

}