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

import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.dao.repository.SubjectRepository;
import com.rf.psychological.scale.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
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;
import java.util.Optional;

/**
 * @author zzf
 * @description:
 * @date 2021/5/17 9:44
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectRepository subjectRepository;


    /**
     * 获取量表和认知任务列表
     *
     * @return
     */
    @Override
    public List<SubjectEntity> findAll(int pageNum, int pageSize) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.findAll(beginIndex, pageSize);
    }

    /**
     * 检索，根据中文名或录入人
     *
     * @param pageNum
     * @param pageSize
     * @param searchName
     * @return
     */
    @Override
    public List<SubjectEntity> findByNameOrUploader(int pageNum, int pageSize, String searchName) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.findByNameOrUploader(beginIndex, pageSize, searchName);
    }

    /**
     * 根据名称模糊查询或上传人精确查询总条数
     *
     * @return
     */
    @Override
    public int allNumByNameOrUploader(String searchName) {
        return this.subjectRepository.allNumByNameOrUploader(searchName);
    }

    @Override
    public Optional<SubjectEntity> findById(String id) {
        //Optional<SubjectEntity> byId = this.subjectRepository.findById(id);
        //SubjectEntity subjectEntity = new SubjectEntity();
        //if (byId.isPresent()) {
        //    subjectEntity = byId.get();
        //    subjectEntity.decrypt();
        //}
        return this.subjectRepository.findById(id);
    }

    /**
     * 保存
     *
     * @param subjectEntity
     */
    @Override
    public void save(SubjectEntity subjectEntity) {
        //subjectEntity.encrypt();
        this.subjectRepository.save(subjectEntity);
    }


    @Override
    public void saveBatch(List<SubjectEntity> subjectEntityList) {
       this.subjectRepository.saveAll(subjectEntityList);
    }

    /**
     * 查询
     *
     * @param type 0：量表  1：认知任务
     * @return
     */
    @Override
    public List<SubjectEntity> findAll(String type) {
        return this.subjectRepository.findAll(type);
    }


    /**
     * 热门量表
     *
     * @return
     */
    @Override
    public List<SubjectEntity> findHotScale() {
        return this.subjectRepository.findHotScale();
    }

    /**
     * 最新测试
     *
     * @return
     */
    @Override
    public List<SubjectEntity> findNewScale() {
        return this.subjectRepository.findNewScale();
    }

    /**
     * 总条数
     *
     * @return
     */
    @Override
    public int allNum() {
        return this.subjectRepository.allNum();
    }

    /**
     * 根据名称模糊查询列表
     *
     * @return
     */
    @Override
    public List<SubjectEntity> getSubjectListByName(int pageNum, int pageSize, String searchStr) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.getSubjectListByName(beginIndex, pageSize, searchStr);
    }

    /**
     * 根据名称模糊查询总条数
     *
     * @return
     */
    @Override
    public int allNumByName(String searchStr) {
        return this.subjectRepository.allNumByName(searchStr);
    }

    /**
     * 根据flag查询
     *
     * @return
     */
    @Override
    @Cacheable(value = "subject", key = "#flag",unless = "#result == null ")
    public List<SubjectEntity> getSubjectByFlag(String flag) {
        return this.subjectRepository.getSubjectByFlag(flag);
    }

    /**
     * 根据flag记录测试数
     *
     * @return
     */
    @Override
    public void addTestNum(String flag) {
        this.subjectRepository.addTestNum(flag);
    }

    /**
     * 根据量表中文名查询
     *
     * @return
     */
    @Override
    public SubjectEntity getSubjectByname(String name) {
        ////加密后name
        //String encryptName = DESede.encryptString(name);
        //SubjectEntity subjectByname = this.subjectRepository.getSubjectByname(encryptName);
        //subjectByname.decrypt();
        return this.subjectRepository.getSubjectByname(name);
    }

    @Override
    public List<SubjectEntity> getSubjectListByname(String name, Boolean like) {
        Specification<SubjectEntity> specification = (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if(like){
                predicateList.add(cb.like(root.get("name"),"%"+name+"%"));
            }else{
                predicateList.add(cb.equal(root.get("name"),name));
            }
            query.where(cb.and(predicateList.toArray(new Predicate[predicateList.size()])));
            return query.getRestriction();
        };
        return this.subjectRepository.findAll(specification);
    }

    /**
     * 修改量表测试结果效验状态
     *
     * @return
     */
    @Override
    public void updateScaleStatus(String flag, String status) {
        this.subjectRepository.updateScaleStatus(flag, status);
    }

    /**
     * 根据id修改量表
     *
     * @return
     */
    @Override
    public void updateById(String id, String scoringPrinciple) {
        this.subjectRepository.updateById(id, scoringPrinciple);
    }

    /**
     * 某类别下模糊查询总条数
     *
     * @return
     */
    @Override
    public int allNumByNameCategory(String scaleName, String categoryEname) {
        return this.subjectRepository.allNumByNameCategory(scaleName, categoryEname);
    }

    /**
     * 某类别下根据名称模糊查询列表
     *
     * @return
     */
    @Override
    public List<SubjectEntity> getSubjectListByNameCategory(int pageNum, int pageSize, String scaleName, String categoryEname) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.getSubjectListByNameCategory(beginIndex, pageSize, scaleName, categoryEname);
    }

    /**
     * 某类别下查询总条数
     *
     * @return
     */
    @Override
    public int allNumCategory(String categoryEname) {
        return this.subjectRepository.allNumCategory(categoryEname);
    }

    /**
     * 某类别下所有信息列表
     *
     * @return
     */
    @Override
    public List<SubjectEntity> findAllCategory(int pageNum, int pageSize, String categoryEname) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.findAllCategory(beginIndex, pageSize, categoryEname);
    }

    @Override
    public List<SubjectEntity> getSubjectListByAuth(int pageNum, int pageSize, String scaleName, String institutionNo) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.getSubjectListByAuth(beginIndex, pageSize, scaleName, institutionNo);
    }

    @Override
    public List<SubjectEntity> getSubjectListByAuthAndCategory(int pageNum, int pageSize, String scaleName, String categoryEname, String institutionNo) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.getSubjectListByAuthAndType(beginIndex, pageSize, scaleName, categoryEname, institutionNo);
    }

    @Override
    public int allNumByAuth(String scaleName, String categoryEname, String institutionNo) {
        return this.subjectRepository.allNumByAuth(scaleName, categoryEname, institutionNo);
    }

    @Override
    public Page<SubjectEntity> findUserAuthAndCateEName(String uId, String scaleName, String cateEName, int pageNum, int pageSize) {
        //Page<SubjectEntity> userAuthAndCateEName = this.subjectRepository.findUserAuthAndCateEName(uId, DESede.encryptString(scaleName), cateEName, PageRequest.of(pageNum - 1, pageSize));
        //List<SubjectEntity> content = userAuthAndCateEName.getContent();
        ////将数据进行解密
        //List<SubjectEntity> decryptSubList = decryptList(content);
        //
        return this.subjectRepository.findUserAuthAndCateEName(uId, scaleName, cateEName, PageRequest.of(pageNum - 1, pageSize));
    }

    @Override
    public Page<SubjectEntity> findInstitutionNoSubAuthList(String institutionNo, String searchKey, int pageNum, int pageSize) {
        //Page<SubjectEntity> institutionNoSubAuthList = this.subjectRepository.findInstitutionNoSubAuthList(institutionNo, DESede.encryptString(searchKey), PageRequest.of(pageNum - 1, pageSize));
        //List<SubjectEntity> content = institutionNoSubAuthList.getContent();
        ////将数据进行解密
        //List<SubjectEntity> decryptSubList = decryptList(content);

        return this.subjectRepository.findInstitutionNoSubAuthList(institutionNo, searchKey, PageRequest.of(pageNum - 1, pageSize));
    }

    @Override
    public void update(SubjectEntity subjectEntity) {
        this.subjectRepository.updateSubject(subjectEntity.getDescription(), subjectEntity.getId());
    }

    @Override
    public SubjectEntity getSubjectEntityByFlag(String flag) {
        return this.subjectRepository.getSubjectEntityByFlag(flag);
    }

    /**
     * 查询机构自定义量表列表
     *
     * @return
     */
    @Override
    public List<SubjectEntity> institutionByTC(int pageNum, int pageSize, String institutionNo) {
        int beginIndex = (pageNum - 1) * pageSize;
        return this.subjectRepository.institutionByTC(beginIndex, pageSize, institutionNo);
    }

    @Override
    public int institutionByTCNum(String institutionNo) {
        return this.subjectRepository.institutionByTCNum(institutionNo);
    }

    @Override
    public void deleteSubjectByFlag(String flag) {
        this.subjectRepository.deleteSubjectByFlag(flag);
    }

    @Override
    public List<SubjectEntity> findByFlags(List<String> flags) {

        Specification<SubjectEntity> subspecification  = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList =  new ArrayList<>();
            if(flags != null && flags.size()>0){
                predicateList.add(root.get("flag").in(flags));
            }
            criteriaQuery.where(criteriaBuilder.and(predicateList.toArray(new Predicate[0])));
            return criteriaQuery.getRestriction();
        };

        return subjectRepository.findAll(subspecification);
    }

    @Override
    public List<SubjectEntity> getSubjectListByAuthSeted(int pageNum, int pageSize, String scaleName, String institutionNo, String scaleType) {
        pageNum = (pageNum-1)*pageSize;
        return this.subjectRepository.getSubjectListByAuthSeted(pageNum,pageSize,scaleName,institutionNo,scaleType);
    }

    @Override
    public int getSubjectListByAuthSeted(String scaleName, String institutionNo, String scaleType) {
        return  this.subjectRepository.getSubjectListByAuthSeted(scaleName,institutionNo,scaleType);
    }

    @Override
    public List<SubjectEntity> getRelevantEvaluation(String flag) {
        return  this.subjectRepository.getRelevantEvaluation(flag);
    }

    @Override
    public List<SubjectEntity> getTrendingSearches(int numberFifteen) {
        return this.subjectRepository.getTrendingSearches(numberFifteen);
    }

    @Override
    public Page<SubjectEntity> getsubjectListMultiCondition(String name, String scaleCate, String people, String currentLimit, int pageNum, int pageSize) {
        return this.subjectRepository.getsubjectListMultiCondition(name, scaleCate, people, currentLimit, PageRequest.of(pageNum - 1, pageSize));
    }


    ////解密量表list
    //private List<SubjectEntity> decryptList(List<SubjectEntity> before) {
    //    for (SubjectEntity subjectEntity : before) {
    //        subjectEntity.decrypt();
    //    }
    //    return new ArrayList<>(before);
    //}

}
