package org.xyzh.crontab.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xyzh.api.crontab.TaskMetaService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.dto.crontab.TbCrontabTaskMeta;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.crontab.mapper.TaskMetaMapper;

import java.util.Date;
import java.util.List;

/**
 * @description 定时任务元数据服务实现类
 * @filename TaskMetaServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-11-18
 */
@Service
public class TaskMetaServiceImpl implements TaskMetaService {

    private static final Logger logger = LoggerFactory.getLogger(TaskMetaServiceImpl.class);

    @Autowired
    private TaskMetaMapper taskMetaMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbCrontabTaskMeta> createTaskMeta(TbCrontabTaskMeta taskMeta) {
        ResultDomain<TbCrontabTaskMeta> resultDomain = new ResultDomain<>();
        try {
            // 检查meta_id是否已存在
            TbCrontabTaskMeta existing = taskMetaMapper.selectTaskMetaById(taskMeta.getMetaId());
            if (existing != null) {
                resultDomain.fail("任务元数据ID已存在: " + taskMeta.getMetaId());
                return resultDomain;
            }

            // 生成ID
            taskMeta.setID(IDUtils.generateID());
            taskMeta.setCreateTime(new Date());
            taskMeta.setDeleted(false);

            // 默认值
            if (taskMeta.getSortOrder() == null) {
                taskMeta.setSortOrder(0);
            }

            int count = taskMetaMapper.insertTaskMeta(taskMeta);
            if (count > 0) {
                resultDomain.success("创建任务元数据成功", taskMeta);
            } else {
                resultDomain.fail("创建任务元数据失败");
            }
        } catch (Exception e) {
            logger.error("创建任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("创建任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbCrontabTaskMeta> updateTaskMeta(TbCrontabTaskMeta taskMeta) {
        ResultDomain<TbCrontabTaskMeta> resultDomain = new ResultDomain<>();
        try {
            taskMeta.setUpdateTime(new Date());
            int count = taskMetaMapper.updateTaskMeta(taskMeta);
            if (count > 0) {
                resultDomain.success("更新任务元数据成功", taskMeta);
            } else {
                resultDomain.fail("更新任务元数据失败");
            }
        } catch (Exception e) {
            logger.error("更新任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("更新任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> deleteTaskMeta(String metaId) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            int count = taskMetaMapper.deleteTaskMeta(metaId);
            if (count > 0) {
                resultDomain.success("删除任务元数据成功", true);
            } else {
                resultDomain.fail("删除任务元数据失败");
            }
        } catch (Exception e) {
            logger.error("删除任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("删除任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabTaskMeta> getTaskMetaById(String metaId) {
        ResultDomain<TbCrontabTaskMeta> resultDomain = new ResultDomain<>();
        try {
            TbCrontabTaskMeta taskMeta = taskMetaMapper.selectTaskMetaById(metaId);
            if (taskMeta != null) {
                resultDomain.success("查询任务元数据成功", taskMeta);
            } else {
                resultDomain.fail("任务元数据不存在");
            }
        } catch (Exception e) {
            logger.error("查询任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("查询任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabTaskMeta> getTaskMetaByTaskId(String taskId) {
        ResultDomain<TbCrontabTaskMeta> resultDomain = new ResultDomain<>();
        try {
            TbCrontabTaskMeta taskMeta = taskMetaMapper.selectTaskMetaByTaskId(taskId);
            if (taskMeta != null) {
                resultDomain.success("查询任务元数据成功", taskMeta);
            } else {
                resultDomain.fail("任务元数据不存在");
            }
        } catch (Exception e) {
            logger.error("查询任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("查询任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabTaskMeta> getAllTaskMeta() {
        ResultDomain<TbCrontabTaskMeta> resultDomain = new ResultDomain<>();
        try {
            List<TbCrontabTaskMeta> list = taskMetaMapper.selectAllTaskMeta();
            resultDomain.success("查询所有任务元数据成功", list);
        } catch (Exception e) {
            logger.error("查询所有任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("查询所有任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabTaskMeta> getTaskMetaByCategory(String category) {
        ResultDomain<TbCrontabTaskMeta> resultDomain = new ResultDomain<>();
        try {
            List<TbCrontabTaskMeta> list = taskMetaMapper.selectTaskMetaByCategory(category);
            resultDomain.success("查询分类任务元数据成功", list);
        } catch (Exception e) {
            logger.error("查询分类任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("查询分类任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<TbCrontabTaskMeta> getTaskMetaPage(PageRequest<TbCrontabTaskMeta> request) {
        ResultDomain<TbCrontabTaskMeta> resultDomain = new ResultDomain<>();
        try {
            PageParam pageParam = request.getPageParam();
            List<TbCrontabTaskMeta> list = taskMetaMapper.selectTaskMetaPage(request.getFilter(), pageParam);
            int total = taskMetaMapper.countSelectTaskMeta(request.getFilter());
            
            PageDomain<TbCrontabTaskMeta> pageDomain = new PageDomain<>();
            pageDomain.setPageParam(pageParam);
            pageParam.setTotalElements(total);
            pageDomain.setDataList(list);
            
            resultDomain.success("分页查询任务元数据成功", pageDomain);
        } catch (Exception e) {
            logger.error("分页查询任务元数据异常: {}", e.getMessage(), e);
            resultDomain.fail("分页查询任务元数据失败: " + e.getMessage());
        }
        return resultDomain;
    }
}
