package com.xunhong.erp.turbo.job.handler;


import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.net.HttpCookie;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shenyifei
 */
@Data
@Slf4j
public class XxlJobHandler {
	private String adminAddresses;

	private String userName;

	private String password;

	/**
	 * 查询目前的定时器
	 *
	 * @param start  开始
	 * @param length 结束
	 * @return 返回定时器列表
	 */
	public List<JobGroupDto> pageList(Integer start, Integer length) {
		String path = adminAddresses + XxlJobConstant.JOB_GROUP_PAGE_LIST;
		Map<String, Object> paramMap = new HashMap<>(2);
		paramMap.put("start", start);
		paramMap.put("length", length);
		HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
		if (HttpStatus.HTTP_OK != response.getStatus()) {
			log.info("----XxlJobHandler----:获取执行器失败，请求数据为{}", paramMap);
		}
		JSONObject jsonObject = JSONObject.parseObject(response.body());
		JSONArray data = jsonObject.getJSONArray("data");
		return JSONArray.parseArray(JSONArray.toJSONString(data), JobGroupDto.class);
	}


	/**
	 * 添加任务
	 *
	 * @param cron            定时任务表达式
	 * @param executorHandler 执行器，任务Handler名称Ø
	 * @param executorParam   执行参数
	 * @param jobDesc         任务名称
	 * @return 返回任务ID
	 */
	@SuppressWarnings("unused")
	public int addXxlJob(String cron, String executorHandler, String executorParam, String jobDesc, Integer jobGroup) {
		String path = adminAddresses + XxlJobConstant.ADD_URL;
		Map<String, Object> paramMap = new HashMap<>(20);
		paramMap.put("jobGroup", jobGroup);
		paramMap.put("jobDesc", jobDesc);
		paramMap.put("author", XxlJobConstant.AUTHOR);
		paramMap.put("alarmEmail", XxlJobConstant.ALARM_EMAIL);
		//参数
		paramMap.put("executorParam", executorParam);
		paramMap.put("scheduleType", XxlJobConstant.SCHEDULE_TYPE);
		paramMap.put("scheduleConf", cron);
		paramMap.put("glueType", XxlJobConstant.GLUE_TYPE);
		paramMap.put("executorHandler", executorHandler);
		paramMap.put("executorRouteStrategy", XxlJobConstant.EXECUTOR_ROUTE_STRATEGY);
		paramMap.put("misfireStrategy", XxlJobConstant.MISFIRE_STRATEGY);
		paramMap.put("executorBlockStrategy", XxlJobConstant.EXECUTOR_BLOCK_STRATEGY);
		paramMap.put("executorTimeout", XxlJobConstant.EXECUTOR_TIMEOUT);
		paramMap.put("executorFailRetryCount", XxlJobConstant.EXECUTOR_FAIL_RETRY_COUNT);
		paramMap.put("glueRemark", XxlJobConstant.GLUE_REMARK);
		paramMap.put("triggerStatus", XxlJobConstant.TRIGGER_STATUS);
		HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
		if (HttpStatus.HTTP_OK != response.getStatus()) {
			log.info("----XxlJobHandler----:任务创建失败，任务数据为{}", executorParam);
		}
		JSONObject jsonObject = JSONObject.parseObject(response.body());
		return jsonObject.getIntValue(XxlJobConstant.RESULT_PARAM_NAME);
	}

	/**
	 * 移除任务
	 *
	 * @param jobId 任务ID
	 * @return 返回是否移除
	 */
	@SuppressWarnings("unused")
	public boolean removeJob(int jobId) {
		try {
			String path = adminAddresses + XxlJobConstant.REMOVE_URL;
			Map<String, Object> paramMap = new HashMap<>(1);
			paramMap.put("id", jobId);
			getCookie();
			HttpResponse response = HttpRequest.post(path).form(paramMap).execute();
			JSONObject jsonObject = JSONObject.parseObject(response.body());
			return jsonObject != null && jsonObject.getIntValue("code") == 200;
		} catch (HttpException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 获取admin项目 登录的cookie
	 *
	 * @return 返回Cookie
	 */
	@SuppressWarnings("unused")
	public String getCookie() {
		String path = adminAddresses + XxlJobConstant.LOGIN_URL;
		Map<String, Object> hashMap = new HashMap<>(2);
		hashMap.put("userName", userName);
		hashMap.put("password", password);
		HttpResponse response = HttpRequest.post(path).form(hashMap).execute();
		List<HttpCookie> cookies = response.getCookies();
		StringBuilder sb = new StringBuilder();
		for (HttpCookie cookie : cookies) {
			sb.append(cookie.toString());
		}
		return sb.toString();
	}


	/***
	 * 生成 日期对应的  cron表达式
	 * convert Date to cron ,eg.  "0 06 10 15 1 ? 2014"
	 * @param date  : 时间点
	 * @return 返回定时任务cron表达式
	 */
	@SuppressWarnings("unused")
	public String getCron(Date date) {
		String dateFormat = "ss mm HH dd MM ? yyyy";
		return formatDateByPattern(date, dateFormat);
	}

	/***
	 * 获取时间
	 *
	 * @param date 日期
	 * @param dateFormat : e.g:yyyy-MM-dd HH:mm:ss
	 * @return 返回时间
	 */
	@SuppressWarnings("unused")
	private String formatDateByPattern(Date date, String dateFormat) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		String formatTimeStr = null;
		if (date != null) {
			formatTimeStr = sdf.format(date);
		}
		return formatTimeStr;
	}
}
