package cn.iocoder.yudao.module.system.service.extra;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.extra.vo.SafetyCommitmentPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.extra.ElderlyExtraSafetyCommitmentDO;
import cn.iocoder.yudao.module.system.dal.mysql.extra.ElderlyExtraSafetyCommitmentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.ELDERLY_EXTRA_SAFETY_COMMITMENT_NOT_EXISTS;

/**
 * (附件)长者安全承诺书 Service 实现
 *
 * @author 管理员
 */
@Service
@Slf4j
public class ElderlyExtraSafetyCommitmentServiceImpl implements ElderlyExtraSafetyCommitmentService {

    @Resource
    private ElderlyExtraSafetyCommitmentMapper mapper;

    @Override
    public Long create(ElderlyExtraSafetyCommitmentDO createReqVO) {
        mapper.insert(createReqVO);
        return createReqVO.getId();
    }

    @Override
    public void update(ElderlyExtraSafetyCommitmentDO updateReqVO) {
        validateExists(updateReqVO.getId());
        mapper.updateById(updateReqVO);
    }

    @Override
    public void delete(Long id) {
        validateExists(id);
        mapper.deleteById(id);
    }

    @Override
    public PageResult<ElderlyExtraSafetyCommitmentDO> findPage(SafetyCommitmentPageReqVO reqVO) {
        return mapper.selectPage(reqVO);
    }

    @Override
    public ElderlyExtraSafetyCommitmentDO getDetail(Long id) {
        return validateExists(id);
    }

    @Override
    public List<ElderlyExtraSafetyCommitmentDO> getListByElderId(Long elderId) {
        return mapper.selectList(
                new LambdaQueryWrapperX<ElderlyExtraSafetyCommitmentDO>()
                        .eqIfPresent(ElderlyExtraSafetyCommitmentDO::getElderId, elderId)
                        .orderByDesc(ElderlyExtraSafetyCommitmentDO::getCreateTime)
        );
    }

    private ElderlyExtraSafetyCommitmentDO validateExists(Long id) {
        ElderlyExtraSafetyCommitmentDO record = mapper.selectById(id);
        if (record == null) {
            throw exception(ELDERLY_EXTRA_SAFETY_COMMITMENT_NOT_EXISTS);
        }
        return record;
    }

}
