package com.fzm.mall.server.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.system.entity.dto.SysNavigationDTO;
import com.fzm.mall.server.admin.system.entity.dto.SysQuestionDTO;
import com.fzm.mall.server.admin.system.entity.dto.SysQuestionSaveDTO;
import com.fzm.mall.server.admin.system.entity.dto.SysQuestionUpdateDTO;
import com.fzm.mall.server.admin.system.model.SysNavigation;
import com.fzm.mall.server.admin.system.model.SysQuestion;
import com.fzm.mall.server.admin.system.mapper.SysQuestionMapper;
import com.fzm.mall.server.admin.system.service.ISysQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.util.CopyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 系统中心-常见问题 服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-03-29
 */
@Service
@Transactional
public class SysQuestionServiceImpl extends ServiceImpl<SysQuestionMapper, SysQuestion> implements ISysQuestionService {

    @Resource
    private SysQuestionMapper questionMapper;

    @Override
    public void save(SysQuestionSaveDTO questionSaveDTO) {
        SysQuestion question = CopyUtil.to(questionSaveDTO, SysQuestion.class);
        question.init();

        questionMapper.insert(question);
    }

    @Override
    public void update(SysQuestionUpdateDTO questionUpdateDTO) {
        SysQuestion question = CopyUtil.to(questionUpdateDTO, SysQuestion.class);
        UpdateWrapper<SysQuestion> wrapper = new UpdateWrapper<>();
        wrapper.eq("question_id", question.getQuestionId())
                .eq("update_time", question.getUpdateTime());
        int update = questionMapper.update(question, wrapper);
        if (update == 0) {
            throw new MyException(MallResponseError.UPDATE_FAIL);
        }
    }

    @Override
    public void delete(String questionId) {
        UpdateWrapper<SysQuestion> wrapper = new UpdateWrapper<>();
        wrapper.eq("question_id", questionId)
                .set("status", true);
        questionMapper.update(null, wrapper);
    }

    @Override
    public SysQuestionDTO read(String questionId) {
        SysQuestion question = questionMapper.read(questionId);
        return CopyUtil.to(question, SysQuestionDTO.class);
    }

    @Override
    public IPage<SysQuestionDTO> page(Page<SysQuestionDTO> page, String keyword, String navigationId) {
        return questionMapper.page(page, keyword, navigationId);
    }
}
