package com.liangjian.dataplatform.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.liangjian.dataplatform.member.dao.primary.JobInfoRepository;
import com.liangjian.dataplatform.member.dao.primary.TagRuleRepository;
import com.liangjian.dataplatform.member.dao.primary.TagRuleSecondRepository;
import com.liangjian.dataplatform.member.entity.po.primary.TagRule;
import com.liangjian.dataplatform.member.entity.po.primary.TagRuleSecond;
import com.liangjian.dataplatform.member.entity.vo.TagRuleVo;
import com.liangjian.dataplatform.member.entity.vo.TagRuleVoSecond;
import com.liangjian.dataplatform.member.service.ITagRuleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.Predicate;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: 黄子奇
 * @Date: 2019/9/9 15:21
 */
@Service
public class TagRuleService implements ITagRuleService {

    @Autowired
    private TagRuleRepository tagRuleRepository;
    @Autowired
    private JobInfoRepository jobInfoRepository;
    @Autowired
    private TagRuleSecondRepository tagRuleSecondRepository;

    @PersistenceContext(unitName = "entityManagerFactoryPrimary")
    private EntityManager em;

    @Override
    public Page<TagRuleVo> queryByCondition(Integer object, String name, Boolean isJobActive, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "id");

        Specification<TagRule> specification = (Specification<TagRule>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            if (object != null) {
                list.add(criteriaBuilder.equal(root.get("object"), object));
            }
            if (name != null && !name.isEmpty()) {
                list.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%"));
            }
            if (isJobActive != null) {
                List<String> jobIds = jobInfoRepository.queryByActive(isJobActive).stream()
                        .map(i -> i.getId().toString()).collect(Collectors.toList());
                list.add(root.get("job_id").in(jobIds));
            }
            return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
        };
        Page<TagRule> tagRules = tagRuleRepository.findAll(specification, pageable);
        Page<TagRuleVo> res = tagRules.map(i -> TagRuleVo.transfer(i));
        return res;
    }

    @Override
    public Map<String,Object> getTagRuleOfPage(String name, Boolean isJobActive, Integer pageIndex, Integer pageSize) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        Pageable pageable = PageRequest.of(pageIndex, pageSize, Sort.Direction.DESC, "id");
        StringBuilder getPageSQL=new StringBuilder("select tr.*,job.disable ,job.execution_time as executionTime ,job.repeat_interval as repeatInterval" +
                ",job.interval_unit as intervalUnit from tag_rule_second tr left join tag_rule_job job on tr.id= job.rule_id where 1=1 ");
        StringBuilder getCountSQL=new StringBuilder("select count(1) from tag_rule_second tr left join tag_rule_job job on tr.id= job.rule_id where 1=1");

        if(!StringUtils.isEmpty(name)){
            getPageSQL.append(" and tr.name like concat(%,"+name+",%)");
            getCountSQL.append(" and tr.name like concat(%,"+name+",%)");
        }
        if(isJobActive!=null){
            getPageSQL.append("and job.disable= "+isJobActive);
            getCountSQL.append("and job.disable= "+isJobActive);
        }
        getPageSQL.append("order by tr.id desc limit ").append((pageIndex-1)*pageSize).append(",").append(pageSize);
        List<TagRuleSecond>list= em.createNativeQuery(getPageSQL.toString(),TagRuleSecond.class).getResultList();
        Long count=Long.valueOf(em.createNativeQuery(getCountSQL.toString()).getSingleResult().toString());
        Map<String,Object>resultMap=new HashMap<>();
        resultMap.put("items",list);
        resultMap.put("totalCount",count);
        return resultMap;
        //return ToObject.objsToObject(tagRules,TagRuleSecond.class);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean addTagRule(TagRuleVo vo) {
        vo.setCrtDate(new Date());
        vo.setLastUpdate(new Date());
        TagRule po = TagRuleVo.reTanslate(vo);
        try {
            tagRuleRepository.saveWithCycle(po);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TagRuleSecond addTagRuleSecond(TagRuleVoSecond vo){
        String outputCondition = JSON.toJSONString(vo.getOutputCondition());
        String tagNews= JSON.toJSONString(vo.getTagNews());
        TagRuleSecond tagRuleSecond=new TagRuleSecond(vo.getId(),vo.getName(),vo.getDescription(),vo.getObjectCode(),vo.getObjectColumn(),outputCondition
                ,vo.getOutputType(),vo.getDbId(),vo.getTableId(),tagNews,vo.getAnalysisMethod());
        tagRuleSecondRepository.save(tagRuleSecond);
        return tagRuleSecond;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean saveTagRule(TagRuleVo vo) {
        vo.setLastUpdate(new Date());
        TagRule po = TagRuleVo.reTanslate(vo);
        try {
            tagRuleRepository.saveWithCycle(po);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TagRuleSecond saveTagRuleSecond(TagRuleVoSecond vo) {
        String outputCondition = JSON.toJSONString(vo.getOutputCondition()) ;
        String tagNews= JSON.toJSONString(vo.getTagNews());
        TagRuleSecond tagRuleSecond=new TagRuleSecond(vo.getId(),vo.getName(),vo.getDescription(),vo.getObjectCode(),vo.getObjectColumn(),outputCondition
                ,vo.getOutputType(),vo.getDbId(),vo.getTableId(),tagNews,vo.getAnalysisMethod());
        tagRuleSecondRepository.save(tagRuleSecond);
        return tagRuleSecond;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteTagRule(String id) {
        try {
            tagRuleRepository.deleteById(id);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteTagRuleSecond(Long id) {
        tagRuleSecondRepository.deleteById(id);
        return true;
    }

    @Override
    public Page<TagRule> queryByTagList(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "id");
        Specification<TagRule> specification = (Specification<TagRule>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
        };
        Page<TagRule> tagRules = tagRuleRepository.findAll(specification, pageable);
        return tagRules;
    }
}
