package com.rf.psychological.plan.service.impl;

import com.rf.psychological.plan.dao.model.PlanMessageEntity;
import com.rf.psychological.plan.dao.repository.PlanMessageRepository;
import com.rf.psychological.plan.service.PlanMessageService;
import com.rf.psychological.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author:zzf
 * @Date:2022/6/22:16:02
 * @Description:
 */
@Service
public class PlanMessageServiceImpl implements PlanMessageService {


    @Autowired
    private PlanMessageRepository plaMessageRepository;

    /**
     * 保存
     *
     * @param planMessageEntity
     */
    @Override
    public void save(PlanMessageEntity planMessageEntity) {
        this.plaMessageRepository.save(planMessageEntity);
    }

    /**
     * find by id
     *
     * @param id
     * @return
     */
    @Override
    public PlanMessageEntity findById(String id) {
        return this.plaMessageRepository.findById(id).orElse(null);
    }

    /**
     * delete by id
     *
     * @param id
     */
    @Override
    public void deleteById(String id) {
        this.plaMessageRepository.deleteById(id);
    }

    /**
     * planId 查询
     *
     * @param planId
     * @return
     */
    @Override
    public List<PlanMessageEntity> findByPlanId(String planId) {
        return this.plaMessageRepository.findByPlanId(planId);
    }

    /**
     * 查询符合发送消息条件
     *
     * @return
     */
    @Override
    public List<PlanMessageEntity> findToSendMessage() {
        Specification<PlanMessageEntity> specification = (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            //状态为打开
            predicateList.add(cb.equal(root.get("afc"), Constant.MAGIC_NUM_1));
            //未提醒
            predicateList.add(cb.equal(root.get("status"),Constant.MAGIC_NUM_0));
            //时间小于等于当前时间
            predicateList.add(cb.lessThanOrEqualTo(root.get("noticeTime"),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
            query.where(cb.and(predicateList.toArray(new Predicate[0])));
            query.orderBy(cb.asc(root.get("orders")));
            return query.getRestriction();
        };
        return this.plaMessageRepository.findAll(specification);
    }
}
