package com.tykj.dev.device.policydocument.service.impl;

import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.policydocument.dao.PolicyDocumentDao;
import com.tykj.dev.device.policydocument.entity.PolicyDocVo;
import com.tykj.dev.device.policydocument.entity.PolicyDocument;
import com.tykj.dev.device.policydocument.service.PolicyDocumentService;
import com.tykj.dev.device.user.cache.UserCache;
import com.tykj.dev.device.user.subject.entity.Units;
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.Transient;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName PolicyDocument.java
 * @Description TODO
 * @createTime 2021年05月13日 15:31:00
 */
@Service
public class PolicyDocumentServiceImpl implements PolicyDocumentService {

    @Autowired
    PolicyDocumentDao policyDocumentDao;

    @Autowired
    UserCache userCache;

    @Override
    public PolicyDocument save(PolicyDocument policyDocument) {
        policyDocument.setFileString(FilesUtil.stringFileToList(policyDocument.getFileRetList()));
        return policyDocumentDao.save(policyDocument);
    }

    @Override
    public Page<PolicyDocument> findAllPage(PolicyDocVo policyDocVo) {
        return policyDocumentDao.findAll(getPredicateBuilder(policyDocVo),policyDocVo.getPageable()).map(
                policyDocument -> {
                    policyDocument.setFileRetList(FilesUtil.stringFileToList(policyDocument.getFileString()));
                    policyDocument.setCreateUserName(userCache.findById(policyDocument.getCreateUserId()).getName());
                return policyDocument;
                }
        );
    }

    @Override
    public void deleteById(Integer id) {
       policyDocumentDao.deleteById(id);
    }

    private Specification<PolicyDocument> getPredicateBuilder(PolicyDocVo policyDocVo) {
        PredicateBuilder<PolicyDocument> predicateBuilder = Specifications.and();
        if (policyDocVo != null) {
            if (policyDocVo.getStartTime() != null) {
                predicateBuilder.gt("createTime",policyDocVo.getStartTime());
            }
            if (policyDocVo.getEndTime()!=null){
                predicateBuilder.lt("createTime",policyDocVo.getEndTime());
            }
            if (policyDocVo.getType()!=null){
                predicateBuilder.eq("type",policyDocVo.getType());
            }
        }
        return  predicateBuilder.build();
    }
}
