package com.rf.psychological.api.key.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.api.key.dao.model.KeyEntity;
import com.rf.psychological.api.key.dao.repository.KeyRepository;
import com.rf.psychological.api.key.service.KeyService;
import com.rf.psychological.dao.model.DimensionEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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;

/**
 * @Author:zzf
 * @Date:2022/11/2:10:56
 * @Description:
 */
@Service
public class KeyServiceImpl implements KeyService {

    @Autowired
    private KeyRepository keyRepository;
    @Override
    public void save(KeyEntity key) {
        this.keyRepository.save(key);
    }

    @Override
    public List<KeyEntity> find(JSONObject jsonObject) {
        Specification<KeyEntity> subspecification  = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList =  new ArrayList<>();
           if(jsonObject.containsKey("institutionNo") && StringUtils.isNotBlank(jsonObject.getString("institutionNo"))){
                predicateList.add(criteriaBuilder.equal(root.get("institutionNo"),jsonObject.getString("institutionNo")));
           }
            criteriaQuery.where(criteriaBuilder.and(predicateList.toArray(new Predicate[0])));
            return criteriaQuery.getRestriction();
        };
        return this.keyRepository.findAll(subspecification);
    }

    /**
     * 机构编号查询
     *
     * @param institutionNo
     * @return
     */
    @Override
    public KeyEntity find(String institutionNo) {

        return this.keyRepository.findByInstitutionNo(institutionNo);
    }
}
