/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.job.controller;

import io.minio.errors.*;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.MinIoUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.job.entity.ScheduleJobEntity;
import io.renren.modules.job.service.ScheduleJobService;
import io.renren.modules.sys.entity.dataset.DataSetDy;
import io.renren.modules.sys.service.DataSetDyService;
import io.renren.modules.sys.service.impl.DataSetDyServiceImpl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 定时任务
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/schedule")
public class ScheduleJobController {
	@Autowired
	private ScheduleJobService scheduleJobService;

	@Autowired
	private DataSetDyService dataSetDyService;
	
	/**
	 * 定时任务列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:schedule:list")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = scheduleJobService.queryPage(params);

		return R.ok().put("page", page);
	}
	
	/**
	 * 定时任务信息
	 */
	@RequestMapping("/info/{dyDataId}")
	@RequiresPermissions("sys:schedule:info")
	public R info(@PathVariable("dyDataId") Long dyDataId){
		Long jobId = dataSetDyService.getById(dyDataId).getJobId();
		ScheduleJobEntity schedule = scheduleJobService.getById(jobId);
		
		return R.ok().put("schedule", schedule);
	}
	
	/**
	 * 保存定时任务
	 */
	@SysLog("保存定时任务")
	@RequestMapping("/save")
	@RequiresPermissions("sys:schedule:save")
	public R save(@RequestBody ScheduleJobEntity scheduleJob){
		ValidatorUtils.validateEntity(scheduleJob);
		
		scheduleJobService.saveJob(scheduleJob);
		
		return R.ok();
	}
	
	/**
	 * 修改定时任务
	 */
	@SysLog("修改定时任务")
	@RequestMapping("/update")
	@RequiresPermissions("sys:schedule:update")
	public R update(@RequestBody Map map){
		ValidatorUtils.validateEntity(map);

		Long datasetId = Long.parseLong(map.get("datasetId").toString());
		String datasetName =(String) map.get("datasetName");
		Long categoryId = Long.parseLong(map.get("categoryId").toString());
		String cronExpression = (String) map.get("cronExpression");
		String remark = (String) map.get("remark");
		DataSetDy dataSetDy = dataSetDyService.getById(datasetId);
		dataSetDy.setDatasetName(datasetName);
		dataSetDy.setCategoryId(categoryId);
		dataSetDy.setRemark(remark);
		dataSetDyService.updateById(dataSetDy);


		ScheduleJobEntity scheduleJobEntity = scheduleJobService.getById(dataSetDy.getJobId());
		scheduleJobEntity.setCronExpression((String) map.get("cronExpression"));
		scheduleJobService.update(scheduleJobEntity);

//
//		// 这里的 scheduleJob.getJobId 实际上是数据集的ID
//		DataSetDy dataSetDy = dataSetDyService.getById(scheduleJob.getJobId());
//		Long jobId = dataSetDy.getJobId();
//		// 通过数据集ID 查询数据集对应的job ID 修正 getJobId 为实际的id
//		scheduleJob.setJobId(jobId);
//
//
//		//同步 数据集名称和标记
//		dataSetDy.setDatasetName(scheduleJob.getBeanName());
//		dataSetDy.setRemark(scheduleJob.getRemark());
//		dataSetDy.setCategoryId(Long.parseLong(scheduleJob.getParams()));
//		System.out.println(dataSetDy);
//		dataSetDyService.updateById(dataSetDy);
//
//		// 固定bean名称 不能让用户修改
//		scheduleJob.setBeanName("demo1");
//		scheduleJob.setParams(null);
////		scheduleJob.setParams(dataSetDy.getDatasetName());
////		scheduleJob.setStatus();
//		scheduleJobService.update(scheduleJob);
		
		return R.ok();
	}
	
	/**
	 * 删除定时任务
	 */
	@SysLog("删除定时任务")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:schedule:delete")
	public R delete(@RequestBody Long[] datasetIds){
		Integer i = 0;
		Long[] jobIds = new Long[100];
		for(Long datasetId:datasetIds){
			System.out.println(datasetId);
			Long jobId = dataSetDyService.getById(datasetId).getJobId();
			DataSetDy dataSetDy = dataSetDyService.getById(datasetId);
			dataSetDyService.removeById(datasetId);
			try {
				MinIoUtils.deleteFile("dydataset",dataSetDy.getDatasetName()+".csv");
			} catch (Exception e) {
				e.printStackTrace();
			}
			i = i+1;
			jobIds[i] = jobId;
		}


		scheduleJobService.deleteBatch(jobIds);
		
		return R.ok();
	}
	
	/**
	 * 立即执行任务
	 */
	@SysLog("立即执行任务")
	@RequestMapping("/run")
	@RequiresPermissions("sys:schedule:run")
	public R run(@RequestBody Long[] jobIds){
		scheduleJobService.run(jobIds);
		
		return R.ok();
	}
	
	/**
	 * 暂停定时任务
	 */
	@SysLog("暂停定时任务")
	@RequestMapping("/pause")
	@RequiresPermissions("sys:schedule:pause")
	public R pause(@RequestBody Long[] jobIds){
		scheduleJobService.pause(jobIds);
		
		return R.ok();
	}
	
	/**
	 * 恢复定时任务
	 */
	@SysLog("恢复定时任务")
	@RequestMapping("/resume")
	@RequiresPermissions("sys:schedule:resume")
	public R resume(@RequestBody Long[] jobIds){
		scheduleJobService.resume(jobIds);
		
		return R.ok();
	}

}
