package org.wcs.serve.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.mapper.intf.AppQuartzConfigService;
import org.wcs.model.dto.serve.quartz.AddQuartzConfigReq;
import org.wcs.model.dto.serve.quartz.QuartzReq;
import org.wcs.model.dto.serve.quartz.UpdateQuartzConfigReq;
import org.wcs.model.po.app.AppQuartzConfig;
import org.wcs.model.vo.serve.AppServeDataResponse;
import org.wcs.model.vo.serve.AppServeResponse;
import org.wcs.model.vo.serve.quartz.QueryResp;
import org.wcs.plugin.quartz.QuartzComponent;
import org.wcs.plugin.quartz.QuartzJobBean;
import org.wcs.serve.service.intf.IQuartzService;
import org.wcs.utils.AppBeanUtils;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class QuartzService implements IQuartzService {

    private final AppQuartzConfigService quartzConfigService;
    private final QuartzComponent quartzComponent;


    /**
     * 查询定时任务
     * @param quartzReq 查询参数
     * @return 结果
     */
    @Override
    public AppServeDataResponse<List<QueryResp>> query(QuartzReq quartzReq) {
        List<AppQuartzConfig> quartzConfigs = quartzConfigService.queryIndistinct(quartzReq.getClassName(), quartzReq.getJobDesc());
        if(quartzConfigs == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        List<QueryResp> queryRespList = AppBeanUtils.copyListProperties(quartzConfigs, QueryResp::new);
        return AppServeResponseFactory.success("查询成功", queryRespList);
    }

    /**
     * 添加一个定时任务
     * @param addQuartzConfigReq 定时任务数据
     * @return 结果
     */
    @Override
    public AppServeResponse addQuartzConfig(AddQuartzConfigReq addQuartzConfigReq) {
        Boolean isHave = quartzConfigService.exist(addQuartzConfigReq.getClassName());
        if(isHave == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        if(isHave) {
            return AppServeResponseFactory.fail("该记录已经存在，请勿重复添加", null);
        }
        AppQuartzConfig insertQuartzConfig = new AppQuartzConfig();
        AppBeanUtils.copyProperties(addQuartzConfigReq, insertQuartzConfig);
        int insertCount = quartzConfigService.insert(insertQuartzConfig);
        if(insertCount == 0) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        return AppServeResponseFactory.success(String.format("添加成功，添加了 %d 条记录", insertCount));
    }

    /**
     * 删除定时任务数据
     * @param className 删除的类名
     * @return 删除结果
     */
    @Override
    public AppServeResponse deleteQuartzConfig(String className) {
        boolean stopResult = false;
        boolean deleteResult = false;
        List<QuartzJobBean> quartzJobBeans = quartzComponent.getQuartzJobBeans();
        List<QuartzJobBean> thisBeans = quartzJobBeans.stream().filter(quartzJobBean -> quartzJobBean.getJobName().equals(className)).toList();
        if(!thisBeans.isEmpty()) {
            QuartzJobBean quartzJobBean = thisBeans.getFirst();
            stopResult = quartzComponent.stopQuartzJob(quartzJobBean.getJobName());
            deleteResult = quartzComponent.deleteQuartzJob(quartzJobBean.getJobName());
        }
        int deleteDataResult = quartzConfigService.delete(className);
        if(deleteDataResult == 0) {
            return AppServeResponseFactory.fail(String.format("删除失败，请刷新后再试：%s;%s", stopResult, deleteResult));
        }
        return AppServeResponseFactory.success(String.format("删除成功：%s;%s", stopResult, deleteResult));
    }

    /**
     * 停止定时任务
     * @param className 任务名称
     * @return 结果
     */
    @Override
    public AppServeResponse stopQuartzJob(String className) {
        List<QuartzJobBean> quartzJobBeans = quartzComponent.getQuartzJobBeans();
        List<QuartzJobBean> thisBeans = quartzJobBeans.stream().filter(quartzJobBean -> quartzJobBean.getJobName().equals(className)).toList();
        if(!thisBeans.isEmpty()) {
            QuartzJobBean quartzJobBean = thisBeans.getFirst();
            boolean stopResult = quartzComponent.stopQuartzJob(quartzJobBean.getJobName());
            if(!stopResult) {
                return AppServeResponseFactory.fail("定时任务停止失败");
            }
            return AppServeResponseFactory.success("定时任务停止成功");
        }
        return AppServeResponseFactory.fail("定时任务不存在");
    }

    /**
     * 启动定时任务
     * @param className 任务名称
     * @return 结果
     */
    @Override
    public AppServeResponse startQuartzJob(String className) {
        AppQuartzConfig quartzConfig = quartzConfigService.queryByClassName(className);
        if(quartzConfig == null) {
            return AppServeResponseFactory.fail("数据服务异常或数据不存在，请刷新后再试");
        }
        List<QuartzJobBean> quartzJobBeans = quartzComponent.getQuartzJobBeans();
        List<QuartzJobBean> thisBeans = quartzJobBeans.stream().filter(quartzJobBean -> quartzJobBean.getJobName().equals(className)).toList();
        if(!thisBeans.isEmpty()) {
            QuartzJobBean quartzJobBean = thisBeans.getFirst();
            quartzJobBean.setCron(quartzConfig.getCron());
            boolean deleteResult = quartzComponent.deleteQuartzJob(quartzJobBean.getJobName());
            if(!deleteResult) {
                return AppServeResponseFactory.fail("定时任务预清理失败");
            }
            boolean quartzJob = quartzComponent.createQuartzJob(quartzJobBean, quartzJobBean.getCron());
            if(!quartzJob) {
                return AppServeResponseFactory.fail("定时任务创建失败");
            }
            return AppServeResponseFactory.success("定时任务创建成功");
        }
        return AppServeResponseFactory.fail("定时任务不存在");
    }

    /**
     * 更新定时任务数据
     * @param updateQuartzConfigReq 更新数据
     * @return 更新结果
     */
    @Override
    public AppServeResponse updateQuartzConfig(UpdateQuartzConfigReq updateQuartzConfigReq) {
        AppQuartzConfig quartzConfig = new AppQuartzConfig();
        AppBeanUtils.copyProperties(updateQuartzConfigReq, quartzConfig);
        int updateCount = quartzConfigService.update(quartzConfig);
        if(updateCount == 0) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        return AppServeResponseFactory.success(String.format("更新成功，更新了 %d 条记录", updateCount));
    }
}
