package com.ygtx.gxt.task;

import java.util.Date;
import java.util.List;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.gxt.domain.GxtWorkOrder;
import com.ygtx.gxt.mapper.GxtWorkOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工单定时任务
 * 负责工单的自动化处理，如自动归档等
 *
 * @author ygtx
 * @date 2025-10-29
 */
@Component
public class GxtWorkOrderScheduledTask
{
    private static final Logger logger = LoggerFactory.getLogger(GxtWorkOrderScheduledTask.class);

    @Autowired
    private GxtWorkOrderMapper gxtWorkOrderMapper;

    /**
     * 自动归档待归档工单
     * 将待归档状态超过3天的工单自动更新为已归档
     * 执行频率：每天凌晨2点执行一次
     */
//    @Scheduled(cron = "0 0 2 * * *")
//    @Scheduled(cron = "*/30 * * * * *")
    @Transactional
    public void archiveExpiredWorkOrders()
    {
        try
        {
            logger.info("========== 开始执行工单自动归档任务 ==========");

            // 计算3天前的时间
            Date thresholdDate = DateUtils.addDays(DateUtils.getNowDate(), -3);

            // 查询所有待归档状态且已超过3天的工单
            List<GxtWorkOrder> expiredOrders = gxtWorkOrderMapper.selectExpiredWorkOrders("to_archive", thresholdDate);

            if (expiredOrders == null || expiredOrders.isEmpty())
            {
                logger.info("没有需要归档的工单");
                logger.info("========== 工单自动归档任务执行完成 ==========");
                return;
            }

            logger.info("找到 {} 个待归档工单需要归档", expiredOrders.size());

            // 处理每个过期的工单
            int successCount = 0;
            int failureCount = 0;

            for (GxtWorkOrder order : expiredOrders)
            {
                try
                {
                    // 更新工单状态为已归档
                    order.setWorkOrderStatus("archived");
                    order.setUpdateTime(DateUtils.getNowDate());

                    int result = gxtWorkOrderMapper.updateGxtWorkOrder(order);

                    if (result > 0)
                    {
                        successCount++;
                        logger.info("工单 {} 已自动归档", order.getWorkOrderProjectNo());
                    }
                    else
                    {
                        failureCount++;
                        logger.warn("工单 {} 归档失败", order.getWorkOrderProjectNo());
                    }
                }
                catch (Exception e)
                {
                    failureCount++;
                    logger.error("处理工单 " + order.getWorkOrderProjectNo() + " 时出现异常", e);
                }
            }

            logger.info("工单自动归档任务完成，成功: {}，失败: {}", successCount, failureCount);
            logger.info("========== 工单自动归档任务执行完成 ==========");
        }
        catch (Exception e)
        {
            logger.error("执行工单自动归档任务时出现异常", e);
        }
    }

}
