package cn.iocoder.yudao.module.course.service.impl;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.course.entity.SchoolCommission;
import cn.iocoder.yudao.module.course.mapper.SchoolCommissionMapper;
import cn.iocoder.yudao.module.course.service.SchoolCommissionService;
import cn.iocoder.yudao.module.course.vo.SchoolCommissionVO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 提成记录 Service 实现类
 *
 * @author 若依
 */
@Service
@Validated
public class SchoolCommissionServiceImpl extends ServiceImpl<SchoolCommissionMapper, SchoolCommission> implements SchoolCommissionService {

    @Resource
    private SchoolCommissionMapper schoolCommissionMapper;

    @Resource
    private AdminUserApi userApi;


    /**
     * 分页查询提成记录
     *
     * @param page      分页参数
     * @param pageReqVO {@link SchoolCommissionVO}
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.course.vo.SchoolCommissionVO>
     * @author PQZ
     * @date 14:00 2025/2/19
     **/
    @Override
    public IPage<SchoolCommissionVO> queryPage(Page<SchoolCommissionVO> page, SchoolCommissionVO pageReqVO) {
        return schoolCommissionMapper.queryPage(pageReqVO,page);
    }

    /**
     * 创建提成记录
     */
    @Override
    public boolean createSchoolCommission(SchoolCommissionVO entity) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        String userName = user.getNickname();

        SchoolCommission commission = new SchoolCommission();
        BeanUtils.copyProperties(entity, commission);

        commission.setCheckId(userId);
        commission.setCheckName(userName);
        commission.setCreateTime(LocalDateTime.now());
        commission.setUpdateTime(LocalDateTime.now());

        if (!this.save(commission)) {
            throw new RuntimeException("创建提成记录失败");
        }

        return true;
    }
}
