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

import com.rf.psychological.plan.dao.model.PlanGroupEntry;
import com.rf.psychological.plan.dao.repository.PlanGroupRepository;
import com.rf.psychological.plan.service.PlanGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class PlanGroupServiceImpl implements PlanGroupService {

    @Autowired
    private PlanGroupRepository planGroupRepository;
    @Override
    public void save(PlanGroupEntry planGroupEntry) {
        this.planGroupRepository.save(planGroupEntry);
    }

    @Override
    public PlanGroupEntry findById(String id) {
        return this.planGroupRepository.findById(id).orElse(null);

    }

    @Override
    public List<PlanGroupEntry> findByGroupId(String gId) {

        return this.planGroupRepository.findByGroupId(gId);
    }

    @Override
    public Page<PlanGroupEntry> findByPlanId(String planId, int pageNum, int pageSize) {
        Specification<PlanGroupEntry> specification = (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("planId"),planId));

            query.where(cb.and(predicateList.toArray(new Predicate[0])));
            return query.getRestriction();
        };
        return  this.planGroupRepository.findAll(specification, PageRequest.of(pageNum-1,pageSize));
    }

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

    /**
     * 删除测试计划下的所有分组信息
     *
     * @param testPlanId
     */
    @Override
    public void deleteByPlanId(String testPlanId) {
        this.planGroupRepository.deleteByPlanId(testPlanId);
    }
}
