package com.kym.service.impl;

import com.github.pagehelper.PageHelper;
import com.kym.common.utils.CommUtil;
import com.kym.entity.Faq;
import com.kym.entity.queryParams.FaqQueryParam;
import com.kym.entity.common.PageBean;
import com.kym.mapper.FaqMapper;
import com.kym.service.FaqService;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * <p>
 * 常见问题 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2024-11-12
 */
@Service
public class FaqServiceImpl extends MyBaseServiceImpl<FaqMapper, Faq> implements FaqService {

    @Override
    public Long add(Faq faq) {
        Optional<Faq> optionalFaq = lambdaQuery().eq(Faq::getQuestion, faq.getQuestion()).oneOpt();
        CommUtil.asserts(optionalFaq.isEmpty(), "问题名称已存在");
        faq.setStatus(Faq.STATUS_启用);
        save(faq);
        return faq.getId();
    }

    @Override
    public void modify(Faq faq) {
        Faq old = getById(faq.getId());
        CommUtil.asserts(old.getStatus() == Faq.STATUS_禁用, "已启用的问题无法编辑，请先禁用");
        //标题重名的校验
        Optional<Faq> optionalFaq = lambdaQuery().eq(Faq::getQuestion, faq.getQuestion()).ne(Faq::getId, faq.getId()).oneOpt();
        CommUtil.asserts(optionalFaq.isEmpty(), "问题名称已存在");
        lambdaUpdate().set(Faq::getQuestion, faq.getQuestion()).set(Faq::getAnswer, faq.getAnswer()).eq(Faq::getId, old.getId()).update();
    }

    @Override
    public Object list(FaqQueryParam query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        var res = lambdaQuery()
                .like(CommUtil.isNotEmptyAndNull(query.getQuestion()), Faq::getQuestion, query.getQuestion())
                .like(CommUtil.isNotEmptyAndNull(query.getAnswer()), Faq::getAnswer, query.getAnswer())
                .eq(CommUtil.isNotEmptyAndNull(query.getStatus()), Faq::getStatus, query.getStatus()).list();
        return new PageBean<>(res);
    }

    @Override
    public Faq detail(long id) {
        return getById(id);

    }

    @Override
    public void status(long id, int status) {
        lambdaUpdate().set(Faq::getStatus, status).eq(Faq::getId, id).update();
    }

    @Override
    public void remove(long id) {
        removeById(id);
    }
}
