package com.kxs.user.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.util.R;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.product.api.feign.RemoteKxsProductService;
import com.kxs.user.api.model.KxsUserLevelLog;
import com.kxs.user.api.vo.kxsapp.userPresetLevel.UserPresetLogVO;
import com.kxs.user.biz.constant.enums.UserErrorTypeEnum;
import com.kxs.user.biz.mapper.KxsUserLevelLogMapper;
import com.kxs.user.biz.mapper.KxsUserPresetLogMapper;
import com.kxs.user.api.model.KxsUserPresetLog;
import com.kxs.user.biz.service.KxsUserPresetLogService;
import com.kxs.user.biz.service.KxsUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户预设职级日志表(KxsUserPresetLog)表服务实现类
 *
 * @author 系统
 * @since 2024-01-03 09:39:56
 */
@Service("kxsUserPresetLogService")
@RequiredArgsConstructor
public class KxsUserPresetLogServiceImpl extends ServiceImpl<KxsUserPresetLogMapper, KxsUserPresetLog> implements KxsUserPresetLogService {

    private final RemoteKxsProductService remoteKxsProductService;

    private final KxsUserLevelLogMapper kxsUserLevelLogMapper;

    private final KxsUserService userService;
    @Override
    public IPage<UserPresetLogVO> logList(Page<UserPresetLogVO> page) {

        Long userId = SecurityUtils.getUser().getId();

        return baseMapper.logList(page, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R preUserLevel(KxsUserPresetLog param) {
        if(param.getStartTime() == null || param.getEndTime() == null || param.getPresetLevel() == null){
            return R.failed("参数不能为空");
        }
        //判断是否符合条件
        R<Boolean> booleanR = remoteKxsProductService.checkUserPreLevelTicket(param.getUserId(), param.getPresetLevel(), SecurityConstants.FROM_IN);
        if(!booleanR.getData()){
            return R.failed("用户未达标");
        }
        Long userId = SecurityUtils.getUser().getId();
        //查询用户是否在其伞下
        if(!userService.checkUserIsChildren(userId.intValue(), param.getUserId())){
            return R.failed(UserErrorTypeEnum.USER_NOT_EXIST.getDescription());
        }

        param.setCreateById(userId.intValue());
        baseMapper.insert(param);
        //添加日志
        KxsUserLevelLog kxsUserLevelLog = new KxsUserLevelLog();
        kxsUserLevelLog.setUserId(param.getUserId());
        kxsUserLevelLog.setPresetLevel(param.getPresetLevel());
        kxsUserLevelLog.setEndTime(param.getEndTime());
        kxsUserLevelLog.setStartTime(param.getStartTime());
        kxsUserLevelLog.setCreateById(userId.intValue());
        kxsUserLevelLogMapper.insert(kxsUserLevelLog);
        return R.ok();
    }
}

