package com.xxl.job.executor.service.jobhandler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.persagy.common.util.HttpClientUtil;
import com.persagy.common.util.HttpClientUtil.HttpResult;
import com.persagy.common.utils.StringUtil;
import com.xxl.job.core.constant.CommonConstant;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;

/**
 * @version 
 * @description 通用的时间规则 调度
 * @company persagy
 * @author zhangqiankun
 * @since 2020年12月3日:	下午6:13:01
 */
@Slf4j
@Component
public class CommonTimeRuleJob {

	@Autowired
	private HttpClientUtil httpClientUtil;
	
	
    @XxlJob(CommonConstant.COMMON_TIME_RULE_JOB)
    public void demoJobHandler() throws Exception {
        XxlJobHelper.log("commonTimeRuleJob start ...");
        log.info("commonTimeRuleJob start ...");
        // param parse
        String param = XxlJobHelper.getJobParam();
        if (StringUtil.isBlank(param)) {
            XxlJobHelper.handleFail("执行参数为空");
            return;
        }
        
        String failMsg = "任务执行失败";
        try {
			JSONObject parseObject = JSONObject.parseObject(param);
			String callBackUrl = parseObject.getString(CommonConstant.CALL_BACK_URL_KEY);
			parseObject.remove(CommonConstant.CALL_BACK_URL_KEY);
			HttpResult httpResult = httpClientUtil.sendPostJson(callBackUrl, parseObject.toJSONString());
			log.info("回调URL: [{}]， 响应结果[{}]", callBackUrl, httpResult.getData());
			
			XxlJobHelper.handleSuccess();
			return;
		} catch (Exception e) {
			log.error("通用定时任务执行失败", e);
			failMsg = e.getMessage();
		} finally {
			log.info("commonTimeRuleJob end ... ");
		}
        XxlJobHelper.handleFail(failMsg);
    }
    
    
    @XxlJob("workTimeEngineJob")
    public void workTimeEngineJob() throws Exception {
        XxlJobHelper.log("workTimeEngineJob start ...");
        log.info("workTimeEngineJob start ...");
        // param parse
        String param = XxlJobHelper.getJobParam();
        if (StringUtil.isBlank(param)) {
            XxlJobHelper.handleFail("执行参数为空");
            return;
        }
        
        String failMsg = "任务执行失败";
        try {
			JSONObject parseObject = JSONObject.parseObject(param);
			String callBackUrl = parseObject.getString("callBackUrl");
			Object taskIds = parseObject.get("id");
			HttpResult httpResult = httpClientUtil.sendPostJson(callBackUrl, taskIds.toString());
			log.info("回调URL: [{}]， 响应结果[{}]", callBackUrl, httpResult.getData());
			
			XxlJobHelper.handleSuccess();
			return;
		} catch (Exception e) {
			log.error("通用定时任务执行失败", e);
			failMsg = e.getMessage();
		} finally {
			log.info("workTimeEngineJob end ... ");
		}
        XxlJobHelper.handleFail(failMsg);
    }
	
}
