package com.hzya.frame.web.quartz;


import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.base.PluginBaseEntity;

import com.hzya.frame.sysnew.application.database.dao.ISysApplicationDatabaseDao;
import com.hzya.frame.sysnew.application.database.entity.SysApplicationDatabaseEntity;
import com.hzya.frame.sysnew.application.plugin.entity.SysApplicationPluginEntity;
import com.hzya.frame.sysnew.integtationTask.IIntegrationTaskCacheableService;
import com.hzya.frame.sysnew.integtationTask.entity.IntegrationTaskEntity;
import com.hzya.frame.sysnew.integtationTaskLiving.entity.IntegrationTaskLivingEntity;
import com.hzya.frame.sysnew.integtationTaskLog.dao.IIntegrationTaskLogDao;
import com.hzya.frame.sysnew.integtationTaskLog.entity.IntegrationTaskLogEntity;
import com.hzya.frame.util.PluginUtils;
import com.hzya.frame.uuid.UUIDUtils;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 定时任务运行工厂类
 */
@DisallowConcurrentExecution
public class QuartzJobFactory implements Job {
    private static final Logger logger = LoggerFactory.getLogger(QuartzJobFactory.class);
    @Resource
    private IIntegrationTaskCacheableService iIntegrationTaskCacheableService;
    @Resource
    private IIntegrationTaskLogDao integrationTaskLogDao;
    @Resource
    private ISysApplicationDatabaseDao sysApplicationDatabaseDao;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //当前开始时间
        Date startTime = new Date();
        Date oldStartTime = new Date();

        logger.info("执行定时任务");
        /** 获取JOB明细对象*/
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        /** 获取JobMap对象，用来获取实体类*/
        Map<String, Object> obDataMap = jobDetail.getJobDataMap();
        //获取job数据
        JSONObject jsonObjectMap = new JSONObject(obDataMap);
        JSONObject jobDetails = JSONObject.parseObject(jsonObjectMap.getString("job"));
        //任务id
        String integrationTaskId = jobDetails.getString("integrationTaskId");
        IntegrationTaskEntity integrationTaskEntity = iIntegrationTaskCacheableService.getIntegrationTaskEntity(integrationTaskId);
        //实例id
        String integrationTaskLivingId = jobDetails.getString("integrationTaskLivingId");
        IntegrationTaskLivingEntity integrationTaskLivingEntity = iIntegrationTaskCacheableService.getIntegrationTaskLivingEntity(integrationTaskLivingId);

        if(integrationTaskEntity == null || integrationTaskEntity.getId() == null || "".equals(integrationTaskEntity.getId())){
            logger.error("当前任务不存在，请联系管理员");
            return;
        }
        if(integrationTaskLivingEntity == null || integrationTaskLivingEntity.getId() == null || "".equals(integrationTaskLivingEntity.getId())){
            logger.error("当前任务实例不存在，请联系管理员");
            return;
        }
        if(integrationTaskLivingEntity.getOldStartTime() != null ){
            oldStartTime = integrationTaskLivingEntity.getOldStartTime();
        }

        //判断任务是否启用，存在不启用情况，需要手动把任务关闭
        if(integrationTaskEntity.getTaskStatus() != null && !"1".equals(integrationTaskEntity.getTaskStatus())){
            saveLivingAndDetail(integrationTaskLivingEntity,null,
                    "4","4","当前任务已停止，不执行任务",startTime,startTime,new Date());
            JSONObject stopJson = new JSONObject();
            stopJson.put("jobName",integrationTaskEntity.getTaskName());
            stopJson.put("jobCode",integrationTaskEntity.getTaskCode());
            QuartzJobFactoryUtils.pauseTrigger(stopJson);
            return;
        }
        //任务日志
        IntegrationTaskLogEntity integrationTaskLogEntity = new IntegrationTaskLogEntity();
        integrationTaskLogEntity.setId(UUIDUtils.getUUID());
        integrationTaskLogEntity.setTaskLinvingId(integrationTaskLivingEntity.getId());
        integrationTaskLogEntity.setTaskId(integrationTaskEntity.getId());
        integrationTaskLogEntity.setTaskCode(integrationTaskEntity.getTaskCode());
        integrationTaskLogEntity.setTaskName(integrationTaskEntity.getTaskName());
        integrationTaskLogEntity.setTaskStatus("1");
        integrationTaskLogEntity.setStartTime(startTime);//当前任务开始时间
        integrationTaskLogEntity.setCompanyId(integrationTaskEntity.getCompanyId());
        integrationTaskLogEntity.setOrg_id(integrationTaskEntity.getOrg_id());
        integrationTaskLogEntity.setCreate_user_id(integrationTaskEntity.getCreate_user_id());
        integrationTaskLogEntity.setModify_user_id(integrationTaskEntity.getModify_user_id());
        integrationTaskLogEntity.setCreate_time(new Date());
        integrationTaskLogEntity.setModify_time(new Date());
        integrationTaskLogEntity.setSts("Y");
        integrationTaskLogEntity.setRemark("任务执行中，请等待");
        integrationTaskLogDao.save(integrationTaskLogEntity);
        integrationTaskLivingEntity.setTaskStatus("1");//执行中
        integrationTaskLivingEntity.setStartTime(startTime);
        integrationTaskLivingEntity.setModify_time(new Date());
        iIntegrationTaskCacheableService.updateIntegrationTaskLivingEntity(integrationTaskLivingEntity);
        //判断插件是否启用
        SysApplicationPluginEntity sysApplicationPluginEntity = iIntegrationTaskCacheableService.getSysApplicationPluginEntity(integrationTaskEntity.getTaskPlugin());
        if(sysApplicationPluginEntity == null || sysApplicationPluginEntity.getPluginCode() == null || !"1".equals(sysApplicationPluginEntity.getPluginStatus())){
            saveLivingAndDetail(integrationTaskLivingEntity, integrationTaskLogEntity,
                    "2","3","插件未启用，不执行任务",startTime,startTime,new Date());
            return;
        }
        String sourceCode = null;
        //查找应用的数据源编码
        SysApplicationDatabaseEntity sysApplicationDatabaseEntity = new SysApplicationDatabaseEntity();
        sysApplicationDatabaseEntity.setAppId(sysApplicationPluginEntity.getAppId());
        sysApplicationDatabaseEntity.setSts("Y");
        List<SysApplicationDatabaseEntity> sysApplicationDatabaseEntities = sysApplicationDatabaseDao.queryBase(sysApplicationDatabaseEntity);
        if(sysApplicationDatabaseEntities != null && sysApplicationDatabaseEntities.size() == 1){
            sourceCode = sysApplicationDatabaseEntities.get(0).getSourceCode();
        }

        //查找插件
        PluginBaseEntity pluginBaseEntity = PluginUtils.getPluginsById(sysApplicationPluginEntity.getPluginCode());
        if(pluginBaseEntity == null ){
            saveLivingAndDetail(integrationTaskLivingEntity, integrationTaskLogEntity,
                    "2","3","插件未找到，不执行任务",startTime,startTime,new Date());
            return;
        }
        //调用插件
        JSONObject req = new JSONObject();
        req.put("startTime",oldStartTime);
        req.put("endTime",startTime);
        req.put("sourceCode",sourceCode);
        try {
            JsonResultEntity jsonResultEntity = pluginBaseEntity.executeBusiness(req);
            if(jsonResultEntity.isFlag()){
                //写日志，修改任务实例
                saveLivingAndDetail(integrationTaskLivingEntity, integrationTaskLogEntity,
                        "2","2",jsonResultEntity.getMsg(),startTime,startTime,new Date());
            }else {
                //写日志，修改任务实例
                saveLivingAndDetail(integrationTaskLivingEntity, integrationTaskLogEntity,
                        "3","3",jsonResultEntity.getMsg(),startTime,startTime,new Date());
            }
        } catch (Exception e) {
            saveLivingAndDetail(integrationTaskLivingEntity, integrationTaskLogEntity,
                    "3","3","插件执行失败，请联系管理员",startTime,startTime,new Date());
            logger.error("插件执行失败:"+e.getMessage());
        }
    }

    /**
     * @Author lvleigang
     * @Description   保存任务日志
     * @Date 3:07 下午 2024/5/7
     * @param integrationTaskLivingEntity 任务实例
     * @param livingtype 1、执行中2、待执行3、错误 4、当前任务已停止
     * @param detailtype 1、执行中2、执行成功 3、执行失败 4\当前任务已停止
     * @param msg
     * @return void
     **/
    private void saveLivingAndDetail(IntegrationTaskLivingEntity integrationTaskLivingEntity,
                                     IntegrationTaskLogEntity integrationTaskLogEntity,
                                     String livingtype,String detailtype, String msg,Date oldStartTime,Date startTime,Date endTime) {
        Long interval = (endTime.getTime() - startTime.getTime()) / (1000); // 计算间隔天数
        integrationTaskLivingEntity.setTaskStatus(livingtype);//待执行
        integrationTaskLivingEntity.setOldStartTime(oldStartTime);
        integrationTaskLivingEntity.setStartTime(startTime);
        integrationTaskLivingEntity.setEndTime(endTime);
        integrationTaskLivingEntity.setDiffTime(interval.toString());
        integrationTaskLivingEntity.setRunNum(integrationTaskLivingEntity.getRunNum()+1);
        integrationTaskLivingEntity.setModify_time(new Date());
        iIntegrationTaskCacheableService.updateIntegrationTaskLivingEntity(integrationTaskLivingEntity);
        if(integrationTaskLogEntity != null ){
            integrationTaskLogEntity.setEndTime(endTime);
            integrationTaskLogEntity.setDiffTime(interval.toString());
            integrationTaskLogEntity.setTaskStatus(detailtype);//执行成功
            integrationTaskLogEntity.setRemark(msg);
            integrationTaskLogDao.update(integrationTaskLogEntity);
        }
    }
}
