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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jeeplus.domain.*;
import com.jeeplus.flowable.feign.IAssessApi;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.flowable.feign.IJyProjectApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.feign.AssessFeignApi;
import com.xxl.job.executor.feign.JyProjectAuditFeignApi;
import com.xxl.job.executor.feign.JyProjectUserSealFeignApi;
import com.xxl.job.executor.feign.ReportsSubmitFeignApi;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class SampleXxlJob {
    private static Logger logger = LoggerFactory.getLogger ( SampleXxlJob.class );

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("demoJobHandler")
    public void demoJobHandler() throws Exception {
        XxlJobHelper.log ( "XXL-JOB, Hello World." );

        for (int i = 0; i < 5; i++) {
            XxlJobHelper.log ( "beat at:" + i );
            TimeUnit.SECONDS.sleep ( 2 );
        }
        // default success
    }

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("projectArchiveTask")
    public void projectArchiveTask() throws Exception {
        System.out.println("进来了---");
        String json = SpringUtil.getBean ( AssessFeignApi.class ).getOverdueFilingProjectList();
        List<ProgramProjectListInfo> projectList = JSON.parseObject(json, new TypeReference<List<ProgramProjectListInfo>>() {});

//        List<ProgramProjectListInfo> projectList = pgProjectListService.getOverdueFilingProjectList();
        //遍历查询的项目，对所有项目的归档状态进行调整。添加超期归档状态值（over_archive_status：0：未超期；1：已超期），归档状态，若是0或者空值则调整为6。若为其他值则不进行调整
        for (ProgramProjectListInfo info : projectList) {
            //判定是否以发起归档申请（即归档状态是否为空或者0）
            String archiveStatus = "";
            if(StringUtils.isBlank(info.getArchiveStatus()) || "0".equals(info.getArchiveStatus())){
                archiveStatus = "6";
            }else{
                archiveStatus = info.getArchiveStatus();
            }
            //修改报告归档 归档状态信息
            SpringUtil.getBean ( IAssessApi.class ).updateArchiveStatus(info.getArchiveId(),archiveStatus,"1");
            //对数据进行发送通知
            String taskName = null;
            String titleStr = null;

            //如果当前时间大于过期时间
            //Date类的一个方法，如果info.getAdventDateDate()早于 new Date() 返回true，否则返回false
            if(info.getAgreeTime().before(new Date())){
                taskName = "评估-超期归档";
                titleStr = "项目【"+ info.getName()+"】归档已超期。超期时间："+dateToString(info.getAgreeTime()) +"。";
            }else{
                taskName = "评估-超期归档";
                titleStr = "项目【"+ info.getName()+"】即将归档超期。超期时间："+dateToString(info.getAgreeTime());
            }


            //计算两日期之间的天数
            int interval = Integer.parseInt(this.getInterval(info.getAgreeTime(), new Date()));
            if(interval > 0){
                titleStr = titleStr + "已超期：" + interval + "天。请尽快归还";
            }

            Set<String> noticeUserSet = new HashSet<String>();
            if(StringUtils.isNotBlank(info.getCreateBy())){

                String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(info.getCreateBy());
                UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
//                UserDTO createUser = SpringUtil.getBean ( IUserApi.class ).getById(info.getCreateBy());
                if(null != createUser && StringUtils.isNotBlank(createUser.getId())){
                    noticeUserSet.add(createUser.getId());
                }
            }
            List<String> noticeUserList = new ArrayList<String>(noticeUserSet);
            if(noticeUserList.size()>0){
                MyNoticeList myNotice = new MyNoticeList();
                myNotice.setCreateById("1");
                myNotice.setCreateTime(new Date());
                myNotice.setUpdateById("1");
                myNotice.setUpdateTime(new Date());
                myNotice.setDelFlag(0);
                //根据procInsId获取taskId
                String currentTask = SpringUtil.getBean(IFlowableApi.class).getTaskIdByprocInstId(info.getProcInsId());
                myNotice.setTaskId(currentTask);
                myNotice.setDefId(info.getProcessDefinitionId());
                myNotice.setTitle(titleStr);
                myNotice.setTaskName(taskName);
                myNotice.setLink("结束");
                myNotice.setType("0");
                myNotice.setCreateUser("管理员");
                myNotice.setCreateTime(new Date());

                for (String noticeUserId : noticeUserList) {
                    myNotice.setNoticeId(noticeUserId);
                    String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(info.getCreateBy());
                    UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
                    myNotice.setNoticeName(createUser.getName());
                    //根据taskName和通知人 查询重复数量
                    String myNoticeInfo = JSON.toJSONString(myNotice);
                    Map<String,String> map = new HashMap();
                    map.put("myNoticeInfo", myNoticeInfo);
                    String jsonInfo = SpringUtil.getBean(IFlowableApi.class).getRepetitionCountBymyNoticeTitle(map);
                    MyNoticeList repetitionCountBymyNotice = JSON.parseObject(jsonInfo, new TypeReference<MyNoticeList>() {});

                    if(null == repetitionCountBymyNotice){
                        // 生成id
                        String id = UUID.randomUUID().toString().replace("-", "");
                        myNotice.setId(id);
                        myNotice.setRepetitionCount(0);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).insertMyNotice(map);
                    }else{
                        myNotice.setId(repetitionCountBymyNotice.getId());
                        myNotice.setRepetitionCount(repetitionCountBymyNotice.getRepetitionCount()+1);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).updateMyNotice(map);
                    }
                }
            }
        }
    }

    /**
     * 嘉溢项目校审发送通知
     */
    @XxlJob("projectAuditTask")
    public void projectAuditTask(){
        System.out.println("进来了---");
        //获取逾期的项目
        String json = SpringUtil.getBean(JyProjectAuditFeignApi.class).selectAudit();
        List<JyAudit> projectList = JSON.parseObject(json, new TypeReference<List<JyAudit>>() {});
        if (null != projectList){
            for (JyAudit jyProjectAudit : projectList) {
                String status="";
                //判定是否已发起
                if (StringUtils.isNotBlank(jyProjectAudit.getStatus())|| jyProjectAudit.getStatus().equals("0")){
                    status="6";
                }else {
                    status=jyProjectAudit.getStatus();
                }
                //对逾期状态及审核状态进行修改
                SpringUtil.getBean(JyProjectAuditFeignApi.class).updateStatus(jyProjectAudit.getId(),status,"1");
            }
        }
        String json1 = SpringUtil.getBean(JyProjectAuditFeignApi.class).selectAuditInTime();
        List<JyAudit> jyAudits = JSON.parseObject(json1, new TypeReference<List<JyAudit>>() {});
        for (JyAudit jyAudit : jyAudits) {
            //对数据进行发送通知
            String taskName = null;
            String titleStr = null;
            //获取当前时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currentDate = new Date();
            //将当前时间转化为字符串
            String format = simpleDateFormat.format(currentDate);
            //创建calendar对象
            Calendar instance = Calendar.getInstance();
            //将日期设置为项目通过时间
            instance.setTime(jyAudit.getProjectAgreeTime());
            //往后推一个月
            instance.add(Calendar.MONTH,1);
            //获取推送后的日期
            Date newDate = instance.getTime();
            //计算天数之差
            int interval1 = Integer.parseInt(this.getInterval(currentDate, newDate));
            //如果当前时间小于项目通过一个月后的时间且距离到期时间在五天之内,则发送通知
            if(newDate.after(new Date()) && interval1 <= 5 && interval1 >=0){
                taskName = "嘉溢-项目一级校审";
                titleStr = "项目【"+ jyAudit.getProjectName()+"】即将逾期,";
                titleStr = titleStr + "剩余：" + interval1 + "天。请尽快发起!";
            }
            Set<String> noticeUserSet = new HashSet<String>();
            if(StringUtils.isNotBlank(jyAudit.getCreateById())){

                String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(jyAudit.getCreateById());
                UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
                if(null != createUser && StringUtils.isNotBlank(createUser.getId())){
                    noticeUserSet.add(createUser.getId());
                }
            }
            List<String> noticeUserList = new ArrayList<String>(noticeUserSet);
            if(noticeUserList.size()>0){
                MyNoticeList myNotice = new MyNoticeList();
                myNotice.setCreateById("1");
                myNotice.setCreateTime(new Date());
                myNotice.setUpdateById("1");
                myNotice.setUpdateTime(new Date());
                myNotice.setDelFlag(0);
                //根据procInsId获取taskId
                String currentTask = SpringUtil.getBean(IFlowableApi.class).getTaskIdByprocInstId(jyAudit.getProjectProId());
                myNotice.setTaskId(currentTask);
                myNotice.setDefId(jyAudit.getProjectDeId());
                myNotice.setTitle(titleStr);
                myNotice.setTaskName(taskName);
                myNotice.setLink("结束");
                myNotice.setType("0");
                myNotice.setCreateUser("管理员");
                myNotice.setCreateTime(new Date());

                for (String noticeUserId : noticeUserList) {
                    myNotice.setNoticeId(noticeUserId);
                    String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(jyAudit.getCreateById());
                    UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
                    myNotice.setNoticeName(createUser.getName());
                    //根据taskName和通知人 查询重复数量
                    String myNoticeInfo = JSON.toJSONString(myNotice);
                    Map<String,String> map = new HashMap();
                    map.put("myNoticeInfo", myNoticeInfo);
                    String jsonInfo = SpringUtil.getBean(IFlowableApi.class).getRepetitionCountBymyNoticeTitle(map);
                    MyNoticeList repetitionCountBymyNotice = JSON.parseObject(jsonInfo, new TypeReference<MyNoticeList>() {});

                    if(null == repetitionCountBymyNotice){
                        // 生成id
                        String id = UUID.randomUUID().toString().replace("-", "");
                        myNotice.setId(id);
                        myNotice.setRepetitionCount(0);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).insertMyNotice(map);
                    }else{
                        myNotice.setId(repetitionCountBymyNotice.getId());
                        myNotice.setRepetitionCount(repetitionCountBymyNotice.getRepetitionCount()+1);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).updateMyNotice(map);
                    }
                }
            }
        }


    }


    /**
     * 嘉溢项目外审发送通知
     * @param
     * @return
     */
    @XxlJob("projectOutInstanceTask")
    public void projectOutInstanceTask(){
        System.out.println("进来了---");
        String json = SpringUtil.getBean(JyProjectUserSealFeignApi.class).findSeal();
        List<JyUserSeal> projectList = JSON.parseObject(json, new TypeReference<List<JyUserSeal>>() {});
        if (CollectionUtil.isNotEmpty(projectList)){
            for (JyUserSeal jyUserSeal : projectList) {
                String status="";
                //判定是否已发起
                if (StringUtils.isNotBlank(jyUserSeal.getStatus())|| jyUserSeal.getStatus().equals("0")){
                    status="6";
                }else {
                    status=jyUserSeal.getStatus();
                }
                String[] split = jyUserSeal.getOutInstanceId().split(",");
                for (String s : split) {
                    //对逾期状态及审核状态进行修改
                    SpringUtil.getBean(JyProjectUserSealFeignApi.class).updateSealStatus(s,status,"1");
                }


            }
        }
        String json1 = SpringUtil.getBean(JyProjectUserSealFeignApi.class).findSealInTime();
        List<JyUserSeal> jyUserSeals = JSON.parseObject(json1, new TypeReference<List<JyUserSeal>>() {});
        for (JyUserSeal outInstance : jyUserSeals) {
            //对数据进行发送通知
            String taskName = null;
            String titleStr = null;
            //获取当前时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currentDate = new Date();
            //将当前时间转化为字符串
            String format = simpleDateFormat.format(currentDate);
            //创建calendar对象
            Calendar instance = Calendar.getInstance();
            //将日期设置为用印修改时间
            instance.setTime(outInstance.getUpdateTime());
            //往后推两周
            instance.add(Calendar.DATE,14);
            //获取推送后的日期
            Date newDate = instance.getTime();
            //计算天数之差
            int interval1 = Integer.parseInt(this.getInterval(currentDate, newDate));
            //如果当前时间小于用印修改两个月后的时间且在期限时间三天之内
            if(newDate.after(new Date()) && interval1 <= 3 && interval1 >=0){
                taskName = "嘉溢-项目用印申请";
                titleStr = "项目【"+ outInstance.getProjectName().substring(0,outInstance.getProjectName().lastIndexOf(","))+"】即将逾期,";
                titleStr = titleStr + "剩余：" + interval1 + "天。请尽快发起!";
            }

            Set<String> noticeUserSet = new HashSet<String>();
            if(StringUtils.isNotBlank(outInstance.getCreateById())){

                String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(outInstance.getCreateById());
                UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
                if(null != createUser && StringUtils.isNotBlank(createUser.getId())){
                    noticeUserSet.add(createUser.getId());
                }
            }
            List<String> noticeUserList = new ArrayList<String>(noticeUserSet);
            if(noticeUserList.size()>0){
                MyNoticeList myNotice = new MyNoticeList();
                myNotice.setCreateById("1");
                myNotice.setCreateTime(new Date());
                myNotice.setUpdateById("1");
                myNotice.setUpdateTime(new Date());
                myNotice.setDelFlag(0);
                //根据procInsId获取taskId
                String currentTask = SpringUtil.getBean(IFlowableApi.class).getTaskIdByprocInstId(outInstance.getProcInsId());
                myNotice.setTaskId(currentTask);
                myNotice.setDefId(outInstance.getProcessDefinitionId());
                myNotice.setTitle(titleStr);
                myNotice.setTaskName(taskName);
                myNotice.setLink("结束");
                myNotice.setType("0");
                myNotice.setCreateUser("管理员");
                myNotice.setCreateTime(new Date());

                for (String noticeUserId : noticeUserList) {
                    myNotice.setNoticeId(noticeUserId);
                    String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(outInstance.getCreateById());
                    UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
                    myNotice.setNoticeName(createUser.getName());
                    //根据taskName和通知人 查询重复数量
                    String myNoticeInfo = JSON.toJSONString(myNotice);
                    Map<String,String> map = new HashMap();
                    map.put("myNoticeInfo", myNoticeInfo);
                    String jsonInfo = SpringUtil.getBean(IFlowableApi.class).getRepetitionCountBymyNoticeTitle(map);
                    MyNoticeList repetitionCountBymyNotice = JSON.parseObject(jsonInfo, new TypeReference<MyNoticeList>() {});

                    if(null == repetitionCountBymyNotice){
                        // 生成id
                        String id = UUID.randomUUID().toString().replace("-", "");
                        myNotice.setId(id);
                        myNotice.setRepetitionCount(0);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).insertMyNotice(map);
                    }else{
                        myNotice.setId(repetitionCountBymyNotice.getId());
                        myNotice.setRepetitionCount(repetitionCountBymyNotice.getRepetitionCount()+1);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).updateMyNotice(map);
                    }
                }
            }
        }

    }


    /**
     * 嘉溢项目-报批签发 发送通知
     * @param
     * @return
     */
    @XxlJob("reportsSubmitTask")
    public void reportsSubmitTask(){
        System.out.println("进来了---");
        //获取报批签发逾期的数据
        String json = SpringUtil.getBean ( ReportsSubmitFeignApi.class ).findReportsSubmitListExccedTime();
        List<JyProjectReportsSubmitInfo> jyProjectReportsSubmitInfos=JSON.parseObject(json,new TypeReference<List<JyProjectReportsSubmitInfo>>(){});
        for (JyProjectReportsSubmitInfo jyProjectReportsSubmitInfo : jyProjectReportsSubmitInfos) {
            //修改报批签发状态
            SpringUtil.getBean( IJyProjectApi.class).updateExceedTimeStatus(jyProjectReportsSubmitInfo.getId(),jyProjectReportsSubmitInfo.getStatus(),"1");
        }
        //获取报批签发未逾期的数据
        String json1 = SpringUtil.getBean ( ReportsSubmitFeignApi.class ).findReportsSubmitListInTime();
        List<JyProjectReportsSubmitInfo> jyProjectReportsSubmitInfoList=JSON.parseObject(json1,new TypeReference<List<JyProjectReportsSubmitInfo>>(){});
        for (JyProjectReportsSubmitInfo jyProjectReportsSubmitInfo : jyProjectReportsSubmitInfoList) {
            //对数据进行发送通知
            String taskName = null;
            String titleStr = null;
            //创建calendar对象
            Calendar instance = Calendar.getInstance();
            //将日期设置为用印修改时间
            instance.setTime(jyProjectReportsSubmitInfo.getFirstSubmitTime());
            //往后推两周
            instance.add(Calendar.MONTH,2);
            //获取推送后的日期
            Date newDate = instance.getTime();
            //计算天数之差
            int interval1 = Integer.parseInt(this.getInterval(new Date(), newDate));
            //如果当前时间小于首次发起报批签发两个月后的时间且在期限时间七天之内
            if(newDate.after(new Date()) && interval1 <= 7 && interval1 >=0){
                taskName = "嘉溢-报批签发";
                titleStr = "项目【"+ jyProjectReportsSubmitInfo.getProjectName().substring(0,jyProjectReportsSubmitInfo.getProjectName().lastIndexOf(","))+"】还未完成,";
                titleStr = titleStr + "剩余：" + interval1 + "天。请尽快发起!";
            }

            Set<String> noticeUserSet = new HashSet<String>();
            //发送通知
            if(StringUtils.isNotBlank(jyProjectReportsSubmitInfo.getCreateById())){

                String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(jyProjectReportsSubmitInfo.getCreateById());
                UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
                if(null != createUser && StringUtils.isNotBlank(createUser.getId())){
                    noticeUserSet.add(createUser.getId());
                }
            }
            List<String> noticeUserList = new ArrayList<String>(noticeUserSet);
            if(noticeUserList.size()>0){
                MyNoticeList myNotice = new MyNoticeList();
                myNotice.setCreateById("1");
                myNotice.setCreateTime(new Date());
                myNotice.setUpdateById("1");
                myNotice.setUpdateTime(new Date());
                myNotice.setDelFlag(0);
                //根据procInsId获取taskId
                String currentTask = SpringUtil.getBean(IFlowableApi.class).getTaskIdByprocInstId(jyProjectReportsSubmitInfo.getProcInsId());
                myNotice.setTaskId(currentTask);
                myNotice.setDefId(jyProjectReportsSubmitInfo.getProcessDefinitionId());
                myNotice.setTitle(titleStr);
                myNotice.setTaskName(taskName);
                myNotice.setLink("结束");
                myNotice.setType("0");
                myNotice.setCreateUser("管理员");
                myNotice.setCreateTime(new Date());

                for (String noticeUserId : noticeUserList) {
                    myNotice.setNoticeId(noticeUserId);
                    String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(jyProjectReportsSubmitInfo.getCreateById());
                    UserDTO createUser = JSON.parseObject(byIdForXXL, new TypeReference<UserDTO>() {});
                    myNotice.setNoticeName(createUser.getName());
                    //根据taskName和通知人 查询重复数量
                    String myNoticeInfo = JSON.toJSONString(myNotice);
                    Map<String,String> map = new HashMap();
                    map.put("myNoticeInfo", myNoticeInfo);
                    String jsonInfo = SpringUtil.getBean(IFlowableApi.class).getRepetitionCountBymyNoticeTitle(map);
                    MyNoticeList repetitionCountBymyNotice = JSON.parseObject(jsonInfo, new TypeReference<MyNoticeList>() {});

                    if(null == repetitionCountBymyNotice){
                        // 生成id
                        String id = UUID.randomUUID().toString().replace("-", "");
                        myNotice.setId(id);
                        myNotice.setRepetitionCount(0);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).insertMyNotice(map);
                    }else{
                        myNotice.setId(repetitionCountBymyNotice.getId());
                        myNotice.setRepetitionCount(repetitionCountBymyNotice.getRepetitionCount()+1);

                        myNoticeInfo = JSON.toJSONString(myNotice);
                        map.put("myNoticeInfo", myNoticeInfo);
                        SpringUtil.getBean ( IFlowableApi.class ).updateMyNotice(map);
                    }
                }
            }
        }




    }




    public static String dateToString(Date date) {
        SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式
        return sformat.format(date);
    }

    /**
     * 计算两日期相差天数
     * @param beginDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public String getInterval(Date beginDate, Date endDate){
        long day = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            if(beginDate != null){
                String begin = sdf.format(beginDate);
                beginDate  = sdf.parse(begin);
            }
            if(endDate!= null){
                String end= sdf.format(endDate);
                endDate= sdf.parse(end);
            }
        } catch (Exception e){
            e.getMessage();
        }
        day = (endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
        return String.valueOf(day);
    }

    /**
     * 2、分片广播任务
     */
    @XxlJob("shardingJobHandler")
    public void shardingJobHandler() throws Exception {

        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex ( );
        int shardTotal = XxlJobHelper.getShardTotal ( );

        XxlJobHelper.log ( "分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal );

        // 业务逻辑
        for (int i = 0; i < shardTotal; i++) {
            if ( i == shardIndex ) {
                XxlJobHelper.log ( "第 {} 片, 命中分片开始处理", i );
            } else {
                XxlJobHelper.log ( "第 {} 片, 忽略", i );
            }
        }

    }


    /**
     * 3、命令行任务
     */
    @XxlJob("commandJobHandler")
    public void commandJobHandler() throws Exception {
        String command = XxlJobHelper.getJobParam ( );
        int exitValue = -1;

        BufferedReader bufferedReader = null;
        try {
            // command process
            ProcessBuilder processBuilder = new ProcessBuilder ( );
            processBuilder.command ( command );
            processBuilder.redirectErrorStream ( true );

            Process process = processBuilder.start ( );
            //Process process = Runtime.getRuntime().exec(command);

            BufferedInputStream bufferedInputStream = new BufferedInputStream ( process.getInputStream ( ) );
            bufferedReader = new BufferedReader ( new InputStreamReader ( bufferedInputStream ) );

            // command log
            String line;
            while ((line = bufferedReader.readLine ( )) != null) {
                XxlJobHelper.log ( line );
            }

            // command exit
            process.waitFor ( );
            exitValue = process.exitValue ( );
        } catch (Exception e) {
            XxlJobHelper.log ( e );
        } finally {
            if ( bufferedReader != null ) {
                bufferedReader.close ( );
            }
        }

        if ( exitValue == 0 ) {
            // default success
        } else {
            XxlJobHelper.handleFail ( "command exit value(" + exitValue + ") is failed" );
        }

    }


    /**
     * 4、跨平台Http任务
     * 参数示例：
     * "url: http://www.baidu.com\n" +
     * "method: get\n" +
     * "data: content\n";
     */
    @XxlJob("httpJobHandler")
    public void httpJobHandler() throws Exception {

        // param parse
        String param = XxlJobHelper.getJobParam ( );
        if ( param == null || param.trim ( ).length ( ) == 0 ) {
            XxlJobHelper.log ( "param[" + param + "] invalid." );

            XxlJobHelper.handleFail ( );
            return;
        }

        String[] httpParams = param.split ( "\n" );
        String url = null;
        String method = null;
        String data = null;
        for (String httpParam : httpParams) {
            if ( httpParam.startsWith ( "url:" ) ) {
                url = httpParam.substring ( httpParam.indexOf ( "url:" ) + 4 ).trim ( );
            }
            if ( httpParam.startsWith ( "method:" ) ) {
                method = httpParam.substring ( httpParam.indexOf ( "method:" ) + 7 ).trim ( ).toUpperCase ( );
            }
            if ( httpParam.startsWith ( "data:" ) ) {
                data = httpParam.substring ( httpParam.indexOf ( "data:" ) + 5 ).trim ( );
            }
        }

        // param valid
        if ( url == null || url.trim ( ).length ( ) == 0 ) {
            XxlJobHelper.log ( "url[" + url + "] invalid." );

            XxlJobHelper.handleFail ( );
            return;
        }
        if ( method == null || !Arrays.asList ( "GET", "POST" ).contains ( method ) ) {
            XxlJobHelper.log ( "method[" + method + "] invalid." );

            XxlJobHelper.handleFail ( );
            return;
        }
        boolean isPostMethod = method.equals ( "POST" );

        // request
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        try {
            // connection
            URL realUrl = new URL ( url );
            connection = (HttpURLConnection) realUrl.openConnection ( );

            // connection setting
            connection.setRequestMethod ( method );
            connection.setDoOutput ( isPostMethod );
            connection.setDoInput ( true );
            connection.setUseCaches ( false );
            connection.setReadTimeout ( 5 * 1000 );
            connection.setConnectTimeout ( 3 * 1000 );
            connection.setRequestProperty ( "connection", "Keep-Alive" );
            connection.setRequestProperty ( "Content-Type", "application/json;charset=UTF-8" );
            connection.setRequestProperty ( "Accept-Charset", "application/json;charset=UTF-8" );

            // do connection
            connection.connect ( );

            // data
            if ( isPostMethod && data != null && data.trim ( ).length ( ) > 0 ) {
                DataOutputStream dataOutputStream = new DataOutputStream ( connection.getOutputStream ( ) );
                dataOutputStream.write ( data.getBytes ( "UTF-8" ) );
                dataOutputStream.flush ( );
                dataOutputStream.close ( );
            }

            // valid StatusCode
            int statusCode = connection.getResponseCode ( );
            if ( statusCode != 200 ) {
                throw new RuntimeException ( "Http Request StatusCode(" + statusCode + ") Invalid." );
            }

            // result
            bufferedReader = new BufferedReader ( new InputStreamReader ( connection.getInputStream ( ), "UTF-8" ) );
            StringBuilder result = new StringBuilder ( );
            String line;
            while ((line = bufferedReader.readLine ( )) != null) {
                result.append ( line );
            }
            String responseMsg = result.toString ( );

            XxlJobHelper.log ( responseMsg );

            return;
        } catch (Exception e) {
            XxlJobHelper.log ( e );

            XxlJobHelper.handleFail ( );
            return;
        } finally {
            try {
                if ( bufferedReader != null ) {
                    bufferedReader.close ( );
                }
                if ( connection != null ) {
                    connection.disconnect ( );
                }
            } catch (Exception e2) {
                XxlJobHelper.log ( e2 );
            }
        }

    }

    /**
     * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
     */
    @XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
    public void demoJobHandler2() throws Exception {
        XxlJobHelper.log ( "XXL-JOB, Hello World." );
    }

    public void init() {
        logger.info ( "init" );
    }

    public void destroy() {
        logger.info ( "destroy" );
    }


}
