package com.fizz.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fizz.business.domain.BizSendJob;
import com.fizz.business.domain.BizSendJobGroup;
import com.fizz.business.domain.BizSendJobItem;
import com.fizz.business.domain.CrmPdiPlan;
import com.fizz.business.domain.vo.BizSendTemplateItemVO;
import com.fizz.business.domain.vo.BizSendTemplateVO;
import com.fizz.business.domain.vo.SendJobLastSuccessVO;
import com.fizz.business.mapper.BizSendJobGroupMapper;
import com.fizz.business.mapper.BizSendJobItemMapper;
import com.fizz.business.mapper.BizSendJobMapper;
import com.fizz.business.mapper.CrmPdiPlanMapper;
import com.fizz.business.service.IBizSendTemplateService;
import com.fizz.business.service.ISendJobQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SendJobQueryServiceImpl implements ISendJobQueryService {

    @Autowired
    private BizSendJobMapper jobMapper;

    @Autowired
    private BizSendJobGroupMapper groupMapper;

    @Autowired
    private BizSendJobItemMapper itemMapper;

    @Autowired
    private IBizSendTemplateService templateService;

    @Autowired
    private CrmPdiPlanMapper planMapper;

    @Override
    public SendJobLastSuccessVO getLastSuccess(String groupType) {
        // 1. 根据 groupType 从 group 表中找到所有相关的 job_id
        List<BizSendJobGroup> groupsWithType = groupMapper.selectList(
                new LambdaQueryWrapper<BizSendJobGroup>().eq(BizSendJobGroup::getGroupType, groupType)
        );

        if (CollectionUtils.isEmpty(groupsWithType)) {
            // 如果一个相关的 group 都没有，直接走 fallback 逻辑
            return getFallbackValues(groupType);
        }

        List<Integer> jobIds = groupsWithType.stream()
                .map(BizSendJobGroup::getJobId)
                .distinct()
                .collect(Collectors.toList());

        // 2. 在这些 job_id 中，找到状态为 COMPLETED 且时间最新的一个 job
        BizSendJob lastJob = jobMapper.selectOne(
                new LambdaQueryWrapper<BizSendJob>()
                        .in(BizSendJob::getJobId, jobIds)
                        .eq(BizSendJob::getStatus, "COMPLETED")
                        .orderByDesc(BizSendJob::getFinishTime)
                        .last("LIMIT 1")
        );

        // 如果找到了，直接返回上次成功的值
        if (lastJob != null) {
            List<BizSendJobGroup> groups = groupMapper.selectList(
                    new LambdaQueryWrapper<BizSendJobGroup>()
                            .eq(BizSendJobGroup::getJobId, lastJob.getJobId())
            );
            if (groups != null && !groups.isEmpty()) {
                List<Integer> groupIdsForJob = groups.stream().map(BizSendJobGroup::getGroupId).collect(Collectors.toList());
                List<BizSendJobItem> items = itemMapper.selectList(
                        new LambdaQueryWrapper<BizSendJobItem>()
                                .in(BizSendJobItem::getGroupId, groupIdsForJob)
                                .eq(BizSendJobItem::getResultStatus, "SUCCESS")
                                .orderByAsc(BizSendJobItem::getItemId)
                );

                Map<String, String> values = new HashMap<>();
                for (BizSendJobItem it : items) {
                    if (it.getParamCode() == null) continue;
                    values.put(it.getParamCode(), it.getValueRaw());
                }

                SendJobLastSuccessVO vo = new SendJobLastSuccessVO();
                vo.setJobId(lastJob.getJobId());
                vo.setLastSendTime(lastJob.getFinishTime());
                vo.setValues(values);
                // 添加一个标志，告诉前端这是真实发送过的值
                vo.setIsFromHistory(true);
                return vo;
            }
        }

        // 如果没找到符合条件的 job，走 fallback 逻辑
        return getFallbackValues(groupType);
    }

    private SendJobLastSuccessVO getFallbackValues(String groupType) {
        if ("FURNACE".equalsIgnoreCase(groupType)) {
            return getFurnaceTemplateValues();
        } else if ("DRIVE".equalsIgnoreCase(groupType)) {
            return getDrivePlanValues();
        }
        return null; // 其他情况返回 null
    }

    /**
     * 获取炉火工艺模板的默认值
     */
    private SendJobLastSuccessVO getFurnaceTemplateValues() {
        // "FURNACE_DEFAULT" 是前端写死的模板编码
        BizSendTemplateVO template = templateService.getTemplateWithItems("FURNACE_DEFAULT");
        if (template == null || template.getItems() == null || template.getItems().isEmpty()) {
            return createEmptyResponse("Furnace template 'FURNACE_DEFAULT' not found or is empty.");
        }

        Map<String, String> values = new HashMap<>();
        for (BizSendTemplateItemVO item : template.getItems()) {
            if (item.getEnabled() && item.getParamCode() != null) {
                values.put(item.getParamCode(), item.getDefaultValueRaw());
            }
        }

        SendJobLastSuccessVO vo = new SendJobLastSuccessVO();
        vo.setValues(values);
        // 标志为非历史值
        vo.setIsFromHistory(false);
        return vo;
    }

    /**
     * 获取当前计划的传动参数
     */
    private SendJobLastSuccessVO getDrivePlanValues() {
        // 优先找 PRODUCING 或 ONLINE 状态的计划，按更新时间倒序取最新的一个
        CrmPdiPlan currentPlan = planMapper.selectOne(
                new LambdaQueryWrapper<CrmPdiPlan>()
                        .in(CrmPdiPlan::getStatus, "PRODUCING", "ONLINE")
                        .orderByDesc(CrmPdiPlan::getUpdateTime)
                        .last("LIMIT 1")
        );

        // 如果没有正在生产的，就找第一个 READY 的计划
        if (currentPlan == null) {
            currentPlan = planMapper.selectOne(
                    new LambdaQueryWrapper<CrmPdiPlan>()
                            .eq(CrmPdiPlan::getStatus, "READY")
                            .orderByAsc(CrmPdiPlan::getSeqid)
                            .last("LIMIT 1")
            );
        }

        if (currentPlan == null) {
            return createEmptyResponse("未找到活跃或就绪的计划");
        }

        // 将 CrmPdiPlan 对象的字段反射为 Map
        Map<String, String> values = new HashMap<>();
        Field[] fields = CrmPdiPlan.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object value = field.get(currentPlan);
                if (value != null) {
                    values.put(field.getName(), String.valueOf(value));
                }
            } catch (IllegalAccessException e) {
                // 忽略无法访问的字段
            }
        }

        SendJobLastSuccessVO vo = new SendJobLastSuccessVO();
        vo.setValues(values);
        vo.setIsFromHistory(false); // 标志为非历史值
        return vo;
    }

    /**
     * 创建一个空的带消息的返回对象
     */
    private SendJobLastSuccessVO createEmptyResponse(String message) {
        SendJobLastSuccessVO vo = new SendJobLastSuccessVO();
        vo.setValues(Collections.singletonMap("_message", message));
        vo.setIsFromHistory(false);
        return vo;
    }
}
