package com.jiayue.ipfcst.console.service;

import com.jiayue.ipfcst.common.data.entity.ElectricField;
import com.jiayue.ipfcst.common.data.entity.InitJobClass;
import com.jiayue.ipfcst.common.data.repository.InitJobClassRepository;
import com.jiayue.ipfcst.common.data.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时逻辑
 *
 * @author bizy
 * @version 1.0
 * @since 2018/10/22 11:29
 */
@Service
@Slf4j
public class InitJobClassService extends BaseService {

    private final InitJobClassRepository initJobClassRepository;

    @Autowired
    public InitJobClassService(InitJobClassRepository initJobClassRepository) {

        this.initJobClassRepository = initJobClassRepository;

    }

    /**
     * 根据类型查询
     *
     * @param jobClassType 任务名
     * @return InitJobClass
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<InitJobClass> findByJobClassType(
            String jobClassType) {
        return initJobClassRepository.findByJobClassType(jobClassType);
    }

    /**
     * 查询全部
     *
     * @return InitJobClass
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<InitJobClass> findAll() {
        return initJobClassRepository.findAll();
    }

    /**
     * 保存/更新
     *
     * @param initJobClass 实体
     */
    public void save(InitJobClass initJobClass) {
        try {
            initJobClassRepository.save(initJobClass);
        } catch (Exception e) {
            log.error("系统错误", e);
        }
    }

    /**
     * 删除
     *
     * @param ids id集合
     * @return boolean
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean deleteById(String ids) {
        boolean flag = false;
        try {
            if (ids.isEmpty()) {
            } else {
                String[] id = ids.split(",");
                if (null != id && id.length > 0) {
                    for (String did : id) {
                        initJobClassRepository.deleteById(Integer.parseInt(did));
                    }
                } else {
                    initJobClassRepository.deleteById(Integer.parseInt(ids));
                }
                flag = true;
            }
        } catch (Exception e) {
            log.error("系统错误", e);
        }

        return flag;
    }

    /**
     * 根据条件查询定时任务
     *
     * @param jobClassName 任务名
     * @param page         页码
     * @param size         每页多少条
     * @return map
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Map<String, Object> getInitJobClass(
            String jobClassName, Integer page, Integer size) {
        Map<String, Object> map = new HashMap<>();
        Specification<InitJobClass> specification = this.getDemoQuerySpecification(jobClassName);
        //分页信息
        Pageable pageable = PageRequest.of(page - 1, size); //页码：前端从1开始，jpa从0开始，做个转换
        Page pageUser = initJobClassRepository.findAll(specification, pageable);
        List<InitJobClass> quartzs = pageUser.getContent();// 结果集
        map.put("emps", quartzs);// 结果集
        map.put("count", pageUser.getTotalElements());// 总记录数
//        if (log.isDebugEnabled()) {
//            log.debug("查询记录数：" + pageUser.getContent().size());
//            log.debug("查询结束!");
//        }
        return map;
    }

    /**
     * 封装样例查询条件
     *
     * @param jobClassName 用户名
     * @return 封装好的样例查询条件
     */
    private Specification<InitJobClass> getDemoQuerySpecification(final String jobClassName) {
        return (Specification<InitJobClass>) (root, criteriaQuery, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.like(root.get("jobClassName").as(String.class), "%" + jobClassName + "%"));
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
    }

    /**
     * 根据id查询对象
     *
     * @param id
     * @return InitJobClass
     */
    public InitJobClass findById(String id) {
        return initJobClassRepository.findById(Integer.parseInt(id)).get();
    }

    public InitJobClass findByName(String jobClassName) {
        return initJobClassRepository.findByJobClassName(jobClassName);
    }

    public InitJobClass findByPath(String jobClassPath) {
        return initJobClassRepository.findByJobClassPath(jobClassPath);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveCloud(InitJobClass initJobClass) {
        InitJobClass bean = initJobClassRepository.findByJobClassName(initJobClass.getJobClassName());
        if (bean != null) {
            initJobClass.setId(bean.getId());
        }
        initJobClassRepository.save(initJobClass);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveCloud(List<InitJobClass> initJobClass) {
        if(initJobClass != null && initJobClass.size() > 0){
            initJobClassRepository.deleteAll();
            initJobClassRepository.saveAll(initJobClass);
        }
    }



}
