package com.ichangzuo.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ichangzuo.system.mapper.QnAMapper;
import com.ichangzuo.system.model.bo.QnABO;
import com.ichangzuo.system.model.bo.QnAFullBO;
import com.ichangzuo.system.model.bo.QnAUpdateBO;
import com.ichangzuo.system.model.entity.QnA;
import com.ichangzuo.system.model.query.QnAPageQuery;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class QnAServiceImpl extends ServiceImpl<QnAMapper, QnA> {
    public List<QnABO> listByType(Integer typeId){
        return baseMapper.listByType(typeId);
    }

    public IPage<QnAFullBO> listPage(QnAPageQuery queryParams){
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        return baseMapper.listPage(new Page<>(pageNum, pageSize),queryParams);
    }

    public boolean updateOrSave(QnAUpdateBO bo){
        QnA qna = null;

        if(bo.getHelpId()==null || bo.getHelpId()==0)
            qna = new QnA();
        else
            qna = getById(bo.getHelpId());

        if(qna==null)
            return false;

        qna.setQuestion(bo.getQuestion());
        qna.setAnswer(bo.getAnswer());
        qna.setState(bo.getState());
        qna.setHelpTypeId(bo.getHelpTypeId());
        qna.setAnswerTime((int)(System.currentTimeMillis()/1000));

        return saveOrUpdate(qna);
    }

    public boolean setByIds(String idsStr, Integer set){
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "QnA号列表为空");
        List<Integer> ids = Arrays.stream(idsStr.split(","))
                .map(Integer::parseInt)
                .toList();
        Integer now = (int) (System.currentTimeMillis()/1000);
        boolean result = true;

        for(Integer id: ids){
            result = update(new LambdaUpdateWrapper<QnA>()
                    .eq(QnA::getHelpId, id)
                    .set(QnA::getState, set)
                    .set(QnA::getAnswerTime, now));

            if(!result) break;
        }
        return result;
    }
}
