package org.sky.scientific.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.secure.utils.SecureUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.mapper.FeedBackMapper;
import org.sky.scientific.mapper.FeedBackReplyMapper;
import org.sky.scientific.pojo.entity.FeedBackEntity;
import org.sky.scientific.pojo.entity.FeedBackReplyEntity;
import org.sky.scientific.service.IFeedBackService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 服务实现类
 */
@Service
@AllArgsConstructor
public class FeedBackServiceImpl extends BaseServiceImpl<FeedBackMapper, FeedBackEntity> implements IFeedBackService {

	private final FeedBackReplyMapper replyMapper;

	@Override
	public IPage<FeedBackEntity> selectFeedBackPage(IPage<FeedBackEntity> page, FeedBackEntity dto) {
		dto.setTenantId(SecureUtil.getTenantId());
		List<FeedBackEntity> list = baseMapper.selectFeedBackPage(page, dto);
		for (FeedBackEntity feedBack : list) {
			LambdaQueryWrapper<FeedBackReplyEntity> eq = Wrappers.<FeedBackReplyEntity>lambdaQuery()
				.eq(FeedBackReplyEntity::getFeedbackId, feedBack.getId())
				.orderByDesc(FeedBackReplyEntity::getReplyTime);
			List<FeedBackReplyEntity> replyList = replyMapper.selectList(eq);
			feedBack.setReplyList(replyList);
		}
		return page.setRecords(list);
	}

	@Override
	public boolean submit(FeedBackEntity dto) {
		boolean result;
		dto.setTenantId(SecureUtil.getTenantId());
		if (Func.isNull(dto.getId())) {
			//新增
			result = this.save(dto);
		} else {
			//修改
			result = this.updateById(dto);
		}
		return result;
	}

	@Override
	public boolean reply(FeedBackReplyEntity dto) {
		if (Func.isNull(dto.getFeedbackId())) {
			throw new ServiceException("");
		}
		dto.setReplyUser(SecureUtil.getUserId());
		dto.setReplyTime(new Date());
		return replyMapper.insert(dto) == 1;
	}
}
