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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.*;
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.*;
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.ParseException;
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
    }

    /**
     * 将交接完成的员工账号进行冻结
     */
    @XxlJob("staffHeir")
    public void getList(){
        String list = SpringUtil.getBean(JyUserFeignApi.class).getList();
        List<StaffHeirInfoDTO> staffUserInfoDTOS = JSON.parseObject(list, new TypeReference<List<StaffHeirInfoDTO>>() {});
        for (StaffHeirInfoDTO staffUserInfoDTO : staffUserInfoDTOS) {
            if ("5".equals(staffUserInfoDTO.getStatus())){
                //将员工账号冻结
                SpringUtil.getBean(JyUserFeignApi.class).updateUserById(staffUserInfoDTO.getCreateById(),"0");
            }
        }

    }


    /**
     * 嘉溢转正申请发送通知
     */
    @XxlJob("regularApply")
    public void regularApply() throws ParseException {
        System.out.println("进来了---");
        //获取人员信息
        String list = SpringUtil.getBean(ApplyFeignApi.class).getList();
        List<StaffUserInfoDTO> staffUserInfoDTOS = JSON.parseObject(list, new TypeReference<List<StaffUserInfoDTO>>() {});
        for (StaffUserInfoDTO staffUserInfoDTO : staffUserInfoDTOS) {
            //根据所在部门获取部门主任
            String jyUserList = SpringUtil.getBean(IUserApi.class).getJyUserList();
            List<UserDTO> dtoList = JSON.parseObject(jyUserList, new TypeReference<List<UserDTO>>() {});
            for (UserDTO userDTO : dtoList) {
                if (ObjectUtil.isNotEmpty(userDTO.getPostDTO())){
                    if (userDTO.getPostDTO().getCode().equals("bmzr") && staffUserInfoDTO.getDepartment().equals(userDTO.getOfficeDTO().getId())){
                        //创建时间格式化对象
                        Calendar calendar = Calendar.getInstance();
                        //获取员工入职时间
                        calendar.setTime(staffUserInfoDTO.getInTime());
                        //获取员工试用期限
                        int months=Integer.parseInt(staffUserInfoDTO.getTimeLimit());
                        calendar.add(Calendar.MONTH, months);
                        //获取结束时间
                        Date newDate=calendar.getTime();
                        //获取到当前日期
                        Date beginDate = new Date();
                        //计算时间只差
                        int interval1 = Integer.parseInt(this.getInterval(beginDate, newDate));
                        String taskName = null;
                        String titleStr = null;
                        //如果还剩三天则发送通知
                        if (interval1<=3 && interval1 >=0) {
                            taskName = staffUserInfoDTO.getName()+"转正申请还未提交";
                            titleStr = "距离"+staffUserInfoDTO.getName()+"转正申请提交还剩" + interval1 + "天,请尽快提交";
                            Set<String> noticeUserSet = new HashSet<String>();

                            String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(userDTO.getId());
                            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(staffUserInfoDTO.getProcInsId());
                                myNotice.setTaskId(currentTask);
                                myNotice.setDefId(staffUserInfoDTO.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);
                                    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("monthly")
    public void monthly() throws ParseException {
        System.out.println("进来了---");
        //获取到嘉溢公司全部员工
        String jyUserList = SpringUtil.getBean(IUserApi.class).getJyUserList();
        List<UserDTO> dtoList = JSON.parseObject(jyUserList, new TypeReference<List<UserDTO>>() {});
        //设置每个月的25号
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,25);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String date=year+"-"+month+"-"+day;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date endDate = simpleDateFormat.parse(date);
        //获取到当前日期
        Date beginDate = new Date();
        //计算时间只差
        int interval1 = Integer.parseInt(this.getInterval(beginDate, endDate));
        String taskName = null;
        String titleStr = null;
        //如果还剩三天则发送通知
        if (interval1<=3 && interval1 >=0){
            taskName="月报还未提交";
            titleStr="距离月报提交截至日期还剩"+interval1+"天,请尽快提交";
            //获得月报中的数据
            String list = SpringUtil.getBean(MonthlyApi.class).getList();
            List<MonthlyDTO> monthlyDTOS = JSON.parseObject(list, new TypeReference<List<MonthlyDTO>>() {});
            for (MonthlyDTO monthlyDTO : monthlyDTOS) {
                //遍历嘉溢公司的所有人员
                for (UserDTO userDTO : dtoList) {
                    if (!monthlyDTO.getCreateById().equals(userDTO.getId())){
                        Set<String> noticeUserSet = new HashSet<String>();

                        String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(userDTO.getId());
                        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("");
                            myNotice.setDefId("");
                            myNotice.setTitle(titleStr);
                            myNotice.setTaskName(taskName);
                            myNotice.setLink("结束");
                            myNotice.setType("0");
                            myNotice.setCreateUser("管理员");
                            myNotice.setCreateTime(new Date());

                            for (String noticeUserId : noticeUserList) {
                                myNotice.setNoticeId(noticeUserId);
                                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));
            //如果当前时间小于项目通过一个月后的时间且距离到期时间在五天之内,则发送通知
            taskName = "项目【"+ jyAudit.getProjectName()+"】项目校审";
            if(newDate.after(new Date()) && interval1 <= 5 && interval1 >=0){
                titleStr = "项目【"+ jyAudit.getProjectName()+"】即将逾期,";
                titleStr = titleStr + "剩余：" + interval1 + "天。请尽快发起!";
            }else {
                titleStr = "项目【"+ jyAudit.getProjectName()+"】已逾期";
            }
            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));
            //如果当前时间小于用印修改两个月后的时间且在期限时间三天之内
            taskName = "嘉溢-项目用印申请";
            if(newDate.after(new Date()) && interval1 <= 3 && interval1 >=0){
                titleStr = "项目【"+ outInstance.getProjectName().substring(0,outInstance.getProjectName().lastIndexOf(","))+"】即将逾期,";
                titleStr = titleStr + "剩余：" + interval1 + "天。请尽快发起!";
            }else {
                titleStr = "项目【"+ outInstance.getProjectName().substring(0,outInstance.getProjectName().lastIndexOf(","))+"】已逾期";
            }

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

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

                String byIdForXXL = SpringUtil.getBean(IUserApi.class).getByIdForXXL(jyProjectReportsSubmitInfoDTO.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(jyProjectReportsSubmitInfoDTO.getProcInsId());
                myNotice.setTaskId(currentTask);
                myNotice.setDefId(jyProjectReportsSubmitInfoDTO.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(jyProjectReportsSubmitInfoDTO.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" );
    }


}
