/**
 * 
 */
package com.huatek.busi.service.impl.job;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huatek.busi.common.ScheduleStatus;
import com.huatek.busi.dao.ScheduleJobDao;
import com.huatek.busi.dto.ScheduleJobDto;
import com.huatek.busi.entity.ScheduleJob;
import com.huatek.busi.mapper.ScheduleJobMapper;
import com.huatek.busi.service.job.ScheduleJobService;
import com.huatek.busi.vo.ScheduleJobVo;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.util.uuid.Uuid;

/**
 * @ClassName: ScheduleJobServiceImpl
 * @FullClassPath: com.huatek.busi.service.impl.job.ScheduleJobServiceImpl
 * @Description: 定时任务服务实现
 * @author: Arno
 * @date: Jul 3, 2019 2:35:08 PM
 * @version: 1.0
 */
@Component
@Service(interfaceClass = ScheduleJobService.class)
@Transactional(rollbackFor = Exception.class)
public class ScheduleJobServiceImpl implements ScheduleJobService {

	private Scheduler scheduler;

	@Autowired
	private ScheduleJobDao scheduleJobDao;

	@Autowired
	private ScheduleJobMapper scheduleJobMapper;

	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;

	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init() {
		scheduler = schedulerFactoryBean.getScheduler();
	}

	@Override
	public List<ScheduleJob> findAll() {
		return scheduleJobMapper.findAll();
	}

	@Override
	public Boolean insertScheduleJob(ScheduleJobDto scheduleJobDto){
		ScheduleJob scheduleJob = new ScheduleJob();
		BeanUtils.copyPropertiesWithIgnoreNull(scheduleJobDto, scheduleJob);
		scheduleJob.setId(Uuid.getUUID());
		scheduleJob.setStatus(ScheduleStatus.NORMAL.getValue());
		scheduleJob.setCreateTime(LocalDateTime.now());
		int count = scheduleJobDao.add(scheduleJob);
		try {
			ScheduleManager.createScheduleJob(scheduler, scheduleJob);
		} catch (Exception e) {
			if (e.getMessage().indexOf("CronExpression") > -1) {
			// TODO: handle exception
				throw new OwlException("cron表达式不正确");
			}
		}
		return count > 0 ? true : false;
	}

	@Override
	public Boolean updateScheduleJob(ScheduleJobDto scheduleJobDto) {
		ScheduleJob scheduleJob = new ScheduleJob();
		BeanUtils.copyPropertiesWithIgnoreNull(scheduleJobDto, scheduleJob);
		int count = scheduleJobDao.updateLocal(scheduleJob);
		ScheduleJob scheduleJobInfo = findByPK(scheduleJobDto.getId());
		if (scheduleJobInfo.getStatus().equals(ScheduleStatus.NORMAL.getValue())) {
			ScheduleManager.updateScheduleJob(scheduler, scheduleJob);
		}
		return count > 0 ? true : false;
	}

	@Override
	public ScheduleJob findByPK(String pk) {
		return scheduleJobDao.get(pk);

	}

	@Override
	public void run(String[] jobIds) {
		for (String jobId : jobIds) {
			ScheduleManager.run(scheduler, findByPK(jobId));
		}
	}

	@Override
	public void pause(String[] jobIds) {
		for (String jobId : jobIds) {
			ScheduleManager.pauseJob(scheduler, jobId);
		}
		updateBatch(jobIds, ScheduleStatus.PAUSE.getValue());
	}

	@Override
	public void resume(String[] jobIds) {
		for (String jobId : jobIds) {
			ScheduleManager.resumeJob(scheduler, jobId);
		}
		updateBatch(jobIds, ScheduleStatus.NORMAL.getValue());
	}

	@Override
	public void deleteBatch(String[] jobIds) {
		for(String jobId : jobIds){
			ScheduleManager.deleteScheduleJob(scheduler, jobId);
			scheduleJobDao.del(jobId);
    	}
	}

	@Override
	public int updateBatch(String[] jobIds, int status) {
		for (String jobId : jobIds) {
			ScheduleJob find = findByPK(jobId);
    		find.setStatus(status);
    		scheduleJobDao.updateLocal(find);
		}
    	return jobIds.length;
	}

		
	/**
	 * 分页获取定时任务列表
	 */
	@Override
	public Map<String, Object> findScheduleJobPage(ScheduleJobDto scheduleJobDto) {
		if (scheduleJobDto.getPage() != null && scheduleJobDto.getLimit() != null) {
            PageHelper.startPage(scheduleJobDto.getPage(), scheduleJobDto.getLimit());
        }
        Page<ScheduleJobVo> scheduleJobList = scheduleJobMapper.findScheduleJobPage(scheduleJobDto);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, scheduleJobList.getTotal(), "", scheduleJobList.getResult());
	}

}
