package com.hzya.frame.sysnew.integtationTask.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.dateutil.DateUtil;
import com.hzya.frame.sysnew.integtationTask.IIntegrationTaskCacheableService;
import com.hzya.frame.sysnew.integtationTask.entity.IntegrationTaskEntity;
import com.hzya.frame.sysnew.integtationTask.dao.IIntegrationTaskDao;
import com.hzya.frame.sysnew.integtationTask.service.IIntegrationTaskService;
import com.hzya.frame.sysnew.integtationTaskLiving.dao.IIntegrationTaskLivingDao;
import com.hzya.frame.sysnew.integtationTaskLiving.entity.IntegrationTaskLivingEntity;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import com.hzya.frame.web.quartz.QuartzJobFactoryUtils;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

import com.hzya.frame.basedao.service.impl.BaseService;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * 集成任务(IntegrationTask)表服务实现类
 *
 * @author makejava
 * @since 2024-05-06 15:36:12
 */
@Service(value = "integrationTaskService")
public class IntegrationTaskServiceImpl extends BaseService<IntegrationTaskEntity, String> implements IIntegrationTaskService {

    private IIntegrationTaskDao integrationTaskDao;
    @Resource
    private IIntegrationTaskLivingDao iIntegrationTaskLivingDao;
    @Resource
    private IIntegrationTaskCacheableService iIntegrationTaskCacheableService;

    @Autowired
    public void setIntegrationTaskDao(IIntegrationTaskDao dao) {
        this.integrationTaskDao = dao;
        this.dao = dao;
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询任务列表分页
     * @Date 11:52 上午 2024/3/27
     **/
    @Override
    public JsonResultEntity queryEntityPage(JSONObject jsonObject) {
        IntegrationTaskEntity entity = getData("jsonStr", jsonObject, IntegrationTaskEntity.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<IntegrationTaskEntity> list = integrationTaskDao.queryByLike(entity);
        PageInfo pageInfo = new PageInfo(list);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询任务列表
     * @Date 11:52 上午 2024/3/27
     **/
    @Override
    public JsonResultEntity queryEntity(JSONObject jsonObject) {
        IntegrationTaskEntity entity = getData("jsonStr", jsonObject, IntegrationTaskEntity.class);
        if (entity == null) {
            entity = new IntegrationTaskEntity();
        }
        List<IntegrationTaskEntity> list = integrationTaskDao.queryByLike(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", list);
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 保存任务
     * @Date 2:36 下午 2024/3/27
     **/
    @Override
    public JsonResultEntity saveEntity(JSONObject jsonObject) {
        IntegrationTaskEntity entity = getData("jsonStr", jsonObject, IntegrationTaskEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getTaskName() == null || "".equals(entity.getTaskName())) {
            return BaseResult.getFailureMessageEntity("请先输入任务名称");
        }
        if (entity.getTaskApp() == null || "".equals(entity.getTaskApp())) {
            return BaseResult.getFailureMessageEntity("请先选择应用");
        }
        if (entity.getTaskPlugin() == null || "".equals(entity.getTaskPlugin())) {
            return BaseResult.getFailureMessageEntity("请先选择应用插件");
        }
        entity.setCreate();
        List<IntegrationTaskEntity> integrationTaskEntityMaxCode = integrationTaskDao.IntegrationTaskEntity_maxCode(entity);
        if (integrationTaskEntityMaxCode != null && integrationTaskEntityMaxCode.size() > 0) {
            String taskCode = "Task-" + integrationTaskEntityMaxCode.get(0).getTaskCode();
            entity.setTaskCode(taskCode);
        } else {
            String nowDateString = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
            String taskCode = "Task-" + nowDateString + "-0000";
            entity.setTaskCode(taskCode);
        }
        //保存
        integrationTaskDao.save(entity);
        //保存实例表
        IntegrationTaskLivingEntity integrationTaskLivingEntity = new IntegrationTaskLivingEntity();
        integrationTaskLivingEntity.setTaskId(entity.getId());
        integrationTaskLivingEntity.setTaskCode(entity.getTaskCode());
        integrationTaskLivingEntity.setTaskName(entity.getTaskName());
        integrationTaskLivingEntity.setTaskStatus("2");
        integrationTaskLivingEntity.setRunNum(0);
        integrationTaskLivingEntity.setCreate();
        iIntegrationTaskLivingDao.save(integrationTaskLivingEntity);
        //任务状态1、启用2、停用
        if (entity.getTaskStatus() != null && "1".equals(entity.getTaskStatus())) {
            JSONObject jsonObjectMap = new JSONObject();
            jsonObjectMap.put("integrationTaskId", entity.getId());//任务id
            jsonObjectMap.put("integrationTaskLivingId", integrationTaskLivingEntity.getId());//实例id
            //根据cron，定时执行任务
            try {
                QuartzJobFactoryUtils.createJob(jsonObjectMap);
            } catch (Exception e) {
                logger.error("新增任务成功，创建任务失败");
                return BaseResult.getSuccessMessageEntity("新增任务成功，创建定时任务失败，请联系管理员", entity);
            }
        }
        return BaseResult.getSuccessMessageEntity("新增任务成功", entity);
    }


    /**
     * @param entity
     * @return boolean
     * @Author lvleigang
     * @Description 校验人员是否已经有配置
     * @Date 10:00 上午 2024/4/1
     **/
    private boolean checkIsUse(IntegrationTaskEntity entity) {
        IntegrationTaskEntity checkEntity = new IntegrationTaskEntity();
        checkEntity.setTaskCode(entity.getTaskCode());
        checkEntity.setSts("Y");//启用
        if (integrationTaskDao.getCount(checkEntity) > 0) {
            return false;
        }
        return true;
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 获取任务
     * @Date 2:36 下午 2024/3/27
     **/
    @Override
    public JsonResultEntity getEntity(JSONObject jsonObject) {
        IntegrationTaskEntity entity = getData("jsonStr", jsonObject, IntegrationTaskEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity = iIntegrationTaskCacheableService.getIntegrationTaskEntity(entity.getId());
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("获取任务失败");
        }
        return BaseResult.getSuccessMessageEntity("获取任务成功", entity);
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 修改任务
     * @Date 2:37 下午 2024/3/27
     **/
    @Override
    public JsonResultEntity updateEntity(JSONObject jsonObject) {
        IntegrationTaskEntity entity = getData("jsonStr", jsonObject, IntegrationTaskEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getTaskCode() == null || "".equals(entity.getTaskCode())) {
            return BaseResult.getFailureMessageEntity("请先输入任务编码");
        }
        if (entity.getTaskName() == null || "".equals(entity.getTaskName())) {
            return BaseResult.getFailureMessageEntity("请先输入任务名称");
        }
        if (entity.getTaskApp() == null || "".equals(entity.getTaskApp())) {
            return BaseResult.getFailureMessageEntity("请先选择应用");
        }
        if (entity.getTaskPlugin() == null || "".equals(entity.getTaskPlugin())) {
            return BaseResult.getFailureMessageEntity("请先选择应用插件");
        }
        entity.setUpdate();
        //保存
        entity = iIntegrationTaskCacheableService.updateIntegrationTaskEntity(entity);
        //实例表
        IntegrationTaskLivingEntity integrationTaskLivingEntity = new IntegrationTaskLivingEntity();
        integrationTaskLivingEntity.setTaskId(entity.getId());
        integrationTaskLivingEntity.setSts("Y");
        List<IntegrationTaskLivingEntity> integrationTaskLivingEntities = iIntegrationTaskLivingDao.queryBase(integrationTaskLivingEntity);
        if (integrationTaskLivingEntities != null && integrationTaskLivingEntities.size() == 1) {
            integrationTaskLivingEntity = integrationTaskLivingEntities.get(0);
        } else {
            throw new BaseSystemException("系统错误，请联系管理员");
        }
        //任务状态1、启用2、停用
        if (entity.getTaskStatus() != null && "1".equals(entity.getTaskStatus())) {
            JSONObject jsonObjectMap = new JSONObject();
            jsonObjectMap.put("integrationTaskId", entity.getId());//任务id
            jsonObjectMap.put("integrationTaskLivingId", integrationTaskLivingEntity.getId());//实例id
            //根据cron，定时执行任务
            try {
                QuartzJobFactoryUtils.createJob(jsonObjectMap);
            } catch (Exception e) {
                logger.error("修改任务成功，创建任务失败");
                return BaseResult.getSuccessMessageEntity("修改任务成功，修改定时任务失败，请联系管理员", entity);
            }
        } else if (entity.getTaskStatus() != null && "2".equals(entity.getTaskStatus())) {
            //停用的时候，由定时任务里面触发不自动停止任务
        }
        return BaseResult.getSuccessMessageEntity("修改任务成功,修改定时任务成功");
    }


    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 删除任务
     * @Date 2:37 下午 2024/3/27
     **/
    @Override
    public JsonResultEntity deleteEntity(JSONObject jsonObject) {
        IntegrationTaskEntity entity = getData("jsonStr", jsonObject, IntegrationTaskEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity.setUpdate();
        iIntegrationTaskCacheableService.deleteIntegrationTaskEntity(entity);
        return BaseResult.getSuccessMessageEntity("删除任务成功");
    }


    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 启用停用任务
     * @Date 2:37 下午 2024/3/27
     **/
    @Override
    public JsonResultEntity enableDisableEntity(JSONObject jsonObject) {
        IntegrationTaskEntity entity = getData("jsonStr", jsonObject, IntegrationTaskEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getTaskStatus() == null || "".equals(entity.getTaskStatus())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity.setUpdate();
        entity = iIntegrationTaskCacheableService.updateIntegrationTaskEntity(entity);
        if ("1".equals(entity.getTaskStatus())) {
            //实例表
            IntegrationTaskLivingEntity integrationTaskLivingEntity = new IntegrationTaskLivingEntity();
            integrationTaskLivingEntity.setTaskId(entity.getId());
            integrationTaskLivingEntity.setSts("Y");
            List<IntegrationTaskLivingEntity> integrationTaskLivingEntities = iIntegrationTaskLivingDao.queryBase(integrationTaskLivingEntity);
            if (integrationTaskLivingEntities != null && integrationTaskLivingEntities.size() == 1) {
                integrationTaskLivingEntity = integrationTaskLivingEntities.get(0);
            } else {
                throw new BaseSystemException("系统错误，请联系管理员");
            }
            JSONObject jsonObjectMap = new JSONObject();
            jsonObjectMap.put("integrationTaskId", entity.getId());//任务id
            jsonObjectMap.put("integrationTaskLivingId", integrationTaskLivingEntity.getId());//实例id
            //根据cron，定时执行任务
            try {
                QuartzJobFactoryUtils.createJob(jsonObjectMap);
            } catch (Exception e) {
                logger.error("修改任务成功，创建任务失败");
                return BaseResult.getSuccessMessageEntity("修改任务成功，修改定时任务失败，请联系管理员", entity);
            }
            return BaseResult.getSuccessMessageEntity("启用任务成功");
        } else {
            //停用的时候，由定时任务里面触发不自动停止任务
            return BaseResult.getSuccessMessageEntity("停用任务成功");
        }
    }

}
