package com.persagy.dmp.message.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.persagy.dmp.common.constant.ValidEnum;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.message.dao.MessageMapper;
import com.persagy.dmp.message.model.vo.MessageVO;
import com.persagy.dmp.message.model.vo.SenderRegister;
import com.persagy.dmp.message.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息 服务实现
 * @author Charlie Yu
 * @date 2021-05-24
 */
@Service
@Transactional
@Primary
public class MessageServiceImpl extends ServiceImpl<MessageMapper, MessageVO> implements IMessageService {

    @Autowired
    private MessageMapper dao;

    @Override
    public boolean initParam(SenderRegister register) {
        return true;
    }

    /**
     * 发送消息
     * @param vo
     */
    @Override
    public void send(MessageVO vo){
        List<MessageVO> voList = new ArrayList<>();
        if(vo != null){
            voList.add(vo);
        }
        insertMessage(voList);
    }

    /**
     * 分页查询消息类型
     * @param page 分页条件
     * @param queryWrapper 查询条件
     * @return
     */
    @Override
    public Page queryByCondition(Page page, Wrapper<MessageVO> queryWrapper) {
        return dao.selectPage(page, queryWrapper);
    }

    /**
     * 新增消息
     * @param voList
     * @return
     */
    @Override
    public List<MessageVO> insertMessage(List<MessageVO> voList) {
        //保存消息
        saveBatch(voList);
        return voList;
    }

    /**
     * 修改消息
     * @param voList
     * @return
     */
    @Override
    public List<MessageVO> updateMessage(List<MessageVO> voList) {
        //批量保存消息
        saveOrUpdateBatch(voList);
        return voList;
    }

    /**
     * 删除消息
     * @param ids
     */
    @Override
    public void deleteMessage(List<String> ids) {
        List<MessageVO> voList = load(ids);
        if(CollUtil.isEmpty(voList)){
            throw new BusinessException("消息类型不存在");
        }
        //数据置为无效状态
        voList.forEach(item->item.setValid(ValidEnum.FALSE.getType()));
        saveOrUpdateBatch(voList);
    }

    /**
     * 根据id查询消息
     * * @param id
     * @return
     */
    @Override
    public MessageVO load(String id) {
        return getById(id);
    }

    /**
     * 根据id批量查询消息
     * @param ids
     * @return
     */
    public List<MessageVO> load(List<String> ids) {
        return dao.selectBatchIds(ids);
    }
}
