package com.yc.ship.module.miniapplet.service.problem;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.miniapplet.controller.admin.problem.vo.ProblemPageReqVO;
import com.yc.ship.module.miniapplet.controller.admin.problem.vo.ProblemSaveReqVO;
import com.yc.ship.module.miniapplet.controller.app.problem.vo.AppProblemReqVO;
import com.yc.ship.module.miniapplet.dal.dataobject.problem.ProblemDO;
import com.yc.ship.module.miniapplet.dal.mysql.problem.ProblemMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

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

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.miniapplet.enums.ErrorCodeConstants.PROBLEM_NOT_EXISTS;


/**
 * 问题管理 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class ProblemServiceImpl implements ProblemService {

    @Resource
    private ProblemMapper problemMapper;

    @Override
    public Long createProblem(ProblemSaveReqVO createReqVO) {
        // 插入
        ProblemDO problem = BeanUtils.toBean(createReqVO, ProblemDO.class);
        problem.setId(IdWorker.getId(problem));
        if (problem.getReleaseStatus() == 1) {
            problem.setReleaseTime(LocalDateTime.now());
        }
        problemMapper.insert(problem);
        // 返回
        return problem.getId();
    }

    @Override
    public void updateProblem(ProblemSaveReqVO updateReqVO) {
        // 校验存在
        validateProblemExists(updateReqVO.getId());
        // 更新
        ProblemDO updateObj = BeanUtils.toBean(updateReqVO, ProblemDO.class);
        if (updateObj.getReleaseStatus() == 1) {
            updateObj.setReleaseTime(LocalDateTime.now());
        }
        problemMapper.updateById(updateObj);
    }

    @Override
    public void deleteProblem(Long id) {
        // 校验存在
        validateProblemExists(id);
        // 删除
        problemMapper.deleteById(id);
    }

    private void validateProblemExists(Long id) {
        if (problemMapper.selectById(id) == null) {
            throw exception(PROBLEM_NOT_EXISTS);
        }
    }

    @Override
    public ProblemDO getProblem(Long id) {
        return problemMapper.selectById(id);
    }

    @Override
    public PageResult<ProblemDO> getProblemPage(ProblemPageReqVO pageReqVO) {
        return problemMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ProblemDO> getProblemList(AppProblemReqVO reqVO) {
        return problemMapper.getProblemList(reqVO);
    }

}
