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

import java.util.Date;

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.DateUtil;
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年9月4日:	上午11:44:36
 */
@Slf4j
@Component
public class WorkCalendarRuleJob {

	@Autowired
	private HttpClientUtil httpClientUtil;
	
	private static final String WORK_DATE_START = "workDateStart";
	private static final String WORK_DATE_END = "workDateEnd";
	private static final String DEFAULT_USER_ID = "systemId";
	
	/**
	 * 0 30 0 * * ?
	 * 
	 * 非自定义已存在的作息时间信息被更新，不存在的被插入，自定义的不动
	 * 
	 * 自定义启动参数
	 * {"callBackUrl":"http://127.0.0.1:9971/v2.0/common/handleParseCalendarRule", "userId":"systemId", 
	 * 	"projectId":"pj1111111111", "workDateStart":"20201206", "workDateEnd":"20201207"}
	 * @param workDateStart workDateEnd
	 * @throws Exception 
	 */
    @XxlJob("workCalendarRuleJob")
    public void demoJobHandler() throws Exception {
        XxlJobHelper.log("workCalendarRuleJob start ...");
        log.info("workCalendarRuleJob start ...");
        
        String param = XxlJobHelper.getJobParam();
        if (StringUtil.isBlank(param)) {
            XxlJobHelper.handleFail("执行参数为空");
            return;
        }
        
        String failMsg = "任务执行失败";
		try {
			Date date = new Date();
			String format = DateUtil.format(date, DateUtil.FORMAT_DATE_YYYYMMDD);
			JSONObject parseObject = JSONObject.parseObject(param);
			String callBackUrl = parseObject.getString(CommonConstant.CALL_BACK_URL_KEY);
			parseObject.remove(CommonConstant.CALL_BACK_URL_KEY);
			if (StringUtil.isBlank(parseObject.getString(CommonConstant.USER_ID))) {
				parseObject.put(CommonConstant.USER_ID, DEFAULT_USER_ID);
			}
			if (StringUtil.isBlank(parseObject.getString(WORK_DATE_START))) {
				parseObject.put(WORK_DATE_START, format);
			}
			if (StringUtil.isBlank(parseObject.getString(WORK_DATE_END))) {
				parseObject.put(WORK_DATE_END, format);
			}
			HttpResult httpResult = this.httpClientUtil.sendPostJson(callBackUrl, parseObject.toJSONString());
			log.info("回调URL: [{}]， 响应结果[{}]", callBackUrl, httpResult.getData());
			
			XxlJobHelper.handleSuccess();
			return;
		} catch (Exception e) {
			log.error("WorkCalendarRuleJob runtime excetpion ... ", e);
			failMsg = e.getMessage();
		} finally {
			log.info("WorkCalendarRuleJob end ... ");
		}
		
		XxlJobHelper.handleFail(failMsg);
    }
    
}
