package com.ygtx.gxt.task;

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

import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.framework.web.service.SysPermissionService;
import com.ygtx.gxt.domain.GxtRepairOrder;
import com.ygtx.gxt.domain.GxtRepairOrderFlow;
import com.ygtx.gxt.mapper.GxtRepairOrderMapper;
import com.ygtx.gxt.service.IGxtRepairOrderService;
import com.ygtx.gxt.service.IGxtRepairOrderFlowService;

import com.ygtx.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 维修工单自动归档任务
 * 每小时执行，将已完成复运操作且评分3天后的工单自动归档
 *
 * @author lingma
 * @date 2025-11-04
 */
@EnableScheduling
@Component("repairOrderArchiveTask")
public class RepairOrderArchiveTask {

    private static final Logger log = LoggerFactory.getLogger(RepairOrderArchiveTask.class);

    @Autowired
    private IGxtRepairOrderService repairOrderService;

    @Autowired
    private IGxtRepairOrderFlowService repairOrderFlowService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private GxtRepairOrderMapper gxtRepairOrderMapper;

    /**
     * 每小时执行定时任务
     * 查找已完成复运操作且评分为非空的工单，并进行归档
     */
    //@Scheduled(cron = "0 0/3 * * * ?")
//    @Scheduled(cron = "0 0 * * * ?")
    public void archiveRepairOrders() {
        log.info("开始执行维修工单自动归档任务");
        SysUser userAdmin = userMapper.selectUserByUserName("admin");
        Set<String> permissions = permissionService.getMenuPermission(userAdmin);
        LoginUser loginUser = new LoginUser(userAdmin,permissions);

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                loginUser,
                null,
                loginUser.getAuthorities()
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);
        try {
            // 构造查询条件：已完成复运操作且评分为非空的工单
            GxtRepairOrder queryOrder = new GxtRepairOrder();
            queryOrder.setWorkOrderStatus("to_archive"); // 待归档状态
            List<GxtRepairOrder> orders = repairOrderService.selectGxtRepairOrderList(queryOrder);

            int archiveCount = 0;
            for (GxtRepairOrder order : orders) {
                // 检查是否满足归档条件（最后操作时间已过去3天）
                if (shouldArchive(order)) {
                    // 执行归档操作
                    archiveOrder(order);
                    archiveCount++;
                }
            }

            log.info("维修工单自动归档任务执行完成，共归档 {} 个工单", archiveCount);
        } catch (Exception e) {
            log.error("执行维修工单自动归档任务时发生异常", e);
        }
    }

    /**
     * 判断工单是否满足归档条件
     * 条件：已完成复运操作且评分3天后（以较晚的时间为准）
     *
     * @param order 维修工单
     * @return 是否满足归档条件
     */
    private boolean shouldArchive(GxtRepairOrder order) {
        /*// 获取工单的复运时间和评分时间
        Date restartTime = order.getRestartTime();
        Date scoreTime = null;

        // 通过查询工单流转记录获取评分时间
        GxtRepairOrderFlow flowQuery = new GxtRepairOrderFlow();
        flowQuery.setOrderId(order.getId());
        flowQuery.setActionType("rating");
        List<GxtRepairOrderFlow> flows = repairOrderFlowService.selectGxtRepairOrderFlowList(flowQuery);

        if (!flows.isEmpty()) {
            // 获取最后一次评分的时间
            scoreTime = flows.get(flows.size() - 1).getActionTime();
        }

        // 如果没有复运时间或评分时间，则不满足归档条件
        if (restartTime == null || scoreTime == null) {
            return false;
        }

        // 取复运时间和评分时间中较晚的一个作为基准时间
        Date lastOperationTime = restartTime.after(scoreTime) ? restartTime : scoreTime;*/
        Date lastOperationTime = null;
        GxtRepairOrderFlow flowQuery = new GxtRepairOrderFlow();
        flowQuery.setOrderId(order.getId());
        flowQuery.setActionType("to_archive");
        List<GxtRepairOrderFlow> flows = repairOrderFlowService.selectGxtRepairOrderFlowList(flowQuery);

        if (!flows.isEmpty()) {
            // 获取最后一次评分的时间
            lastOperationTime = flows.get(flows.size() - 1).getActionTime();
        }
        if (lastOperationTime == null) {
            return false;
        }
        // 检查最后操作时间是否已过去3天
        Date now = DateUtils.getNowDate();
        Date threeDaysAfterLastOperation = DateUtils.addDays(lastOperationTime, 3);

        return now.after(threeDaysAfterLastOperation);
    }

    /**
     * 对工单进行归档操作
     *
     * @param order 需要归档的工单
     */
    private void archiveOrder(GxtRepairOrder order) {
        // 更新工单状态为已归档
        order.setWorkOrderStatus("archived");
        gxtRepairOrderMapper.updateGxtRepairOrder(order);

        // 添加归档流程记录
        GxtRepairOrderFlow flow = new GxtRepairOrderFlow();
        flow.setOrderId(order.getId());
        flow.setOrderCode(order.getWorkOrderProjectNo());
        flow.setActionType("archive");
        flow.setFromStatus("to_archive");
        flow.setToStatus("archived");
        flow.setOperatorId(1L); // 系统自动操作，使用系统用户ID
        flow.setOperatorName("系统自动");
        flow.setActionTime(DateUtils.getNowDate());
        flow.setActionRemark("系统自动归档工单");

        repairOrderFlowService.insertGxtRepairOrderFlow(flow);

        log.info("工单 {} 已成功归档", order.getWorkOrderProjectNo());
    }
}
