package com.bocloud.ims.service.scheduler;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.model.CloudVendorBean;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.interfaces.resource.SyncService;
import com.bocloud.ims.interfaces.scheduler.CloudVendorTaskService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.service.config.DefaultSchedulingConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author 作者
 * @version 创建时间：2019年4月15日 下午6:04:20 类说明 定时规则修改
 */
@Service
public class CloudVendorTaskServiceImpl implements CloudVendorTaskService {

	private static Logger logger = LoggerFactory.getLogger(CloudVendorTaskServiceImpl.class);

	@Autowired
	private DefaultSchedulingConfigurer defaultSchedulingConfigurer;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private SyncService syncService;

	@Override
	public BocloudResult create(Long vendorId, RequestContext context) {
		try {
			CloudVendor vendor = cloudVendorRepository.query(vendorId);
			Assert.notNull(vendor, "云平台不存在");
			// 等待任务调度初始化完成
			while (!defaultSchedulingConfigurer.inited()) {
				Thread.sleep(5000);
			}
			String taskId = ScheduledTasksConstant.CLOUD_VENDOR + vendor.getUuid();
			defaultSchedulingConfigurer.addTriggerTask(taskId,
					new TriggerTask(new CloudVendorTaskThread(vendor.getId()), new CronTrigger(vendor.getSyncCron())),
					vendor.getSyncCron());
			logger.info("平台-->{}定时同步任务加入成功！定时策略 ：{} ", vendor.getName(), vendor.getSyncCron());
			return new BocloudResult<>(true, "平台定时任务添加成功！");
		} catch (Exception e) {
			logger.error("添加平台定时任务失败 ： {}", e.getMessage());
			return new BocloudResult<>(false, "添加平台定时任务失败 ： {}", e.getMessage());
		}
	}

	@Override
	public BocloudResult remove(Long vendorId, RequestContext context) {
		try {
			logger.info("vendorId :" + vendorId);
			CloudVendor vendor = cloudVendorRepository.query(vendorId);
			Assert.notNull(vendor, "云平台不存在");
			// 等待任务调度初始化完成
			while (!defaultSchedulingConfigurer.inited()) {
				Thread.sleep(5000);
			}
			String taskId = ScheduledTasksConstant.CLOUD_VENDOR + vendor.getUuid();
			defaultSchedulingConfigurer.cancelTriggerTask(taskId);
			logger.info(vendor.getName() + "云平台取消定时同步任务成功！");
			return new BocloudResult<>(true, "平台定时任务取消成功！");
		} catch (Exception e) {
			logger.error("取消平台定时任务失败 ： " + e.getMessage());
			return new BocloudResult<>(false, "取消平台定时任务失败 ： " + e.getMessage());
		}
	}

	@Override
	public BocloudResult modify(CloudVendorBean cloudVendor, RequestContext context) {
		try {
			logger.info("cloudVendor :" + JSONObject.toJSONString(cloudVendor));
			Assert.notNull(cloudVendor, "参数格式错误");
			CloudVendor vendor = cloudVendorRepository.query(cloudVendor.getId());
			Assert.notNull(vendor, "云平台不存在");
			// 等待任务调度初始化完成
			while (!defaultSchedulingConfigurer.inited()) {
				Thread.sleep(5000);
			}
			String taskId = ScheduledTasksConstant.CLOUD_VENDOR + vendor.getUuid();
			defaultSchedulingConfigurer.resetTriggerTask(taskId,
					new TriggerTask(new CloudVendorTaskThread(vendor.getId()),
							new CronTrigger(cloudVendor.getSyncCron())),
					cloudVendor.getSyncCron());
			vendor.setSyncCron(cloudVendor.getSyncCron());
			cloudVendorRepository.update(vendor);
			logger.info(vendor.getName() + " --> 平台定时同步任务【重置】成功！定时策略 ： " + cloudVendor.getSyncCron());
			return new BocloudResult<>(true, "平台定时任务重置成功！");
		} catch (Exception e) {
			logger.error("重置平台定时任务失败 ： " + e.getMessage());
			return new BocloudResult<>(false, "重置平台定时任务失败 ： " + e.getMessage());
		}
	}

	class CloudVendorTaskThread implements Runnable {

		private Long vendorId;

		public CloudVendorTaskThread(Long vendorId) {
			super();
			this.vendorId = vendorId;
		}

		@Override
		public void run() {
			try {
				syncService.sync(vendorId, new RequestContext(RequestContext.Catalog.Manager, 1L, 0L, 0L, null), true);
			} catch (Exception e) {
				logger.error("云平台同步异常：" + e.getMessage());
			}
		}

		public Long getVendorId() {
			return vendorId;
		}

		public void setVendorId(Long vendorId) {
			this.vendorId = vendorId;
		}

	}

}
