package com.aps.service.impl;

import com.aps.entity.*;
import com.aps.mapper.ProdSceneConfigMapper;
import com.aps.service.ProdSceneConfigService;
import com.aps.service.ProdLaunchOrderService;
import com.aps.service.ProdProcessExecService;
import com.aps.service.ProdEquipmentService;
import com.aps.service.ProdEquipSpecialCalService;
import com.aps.service.ProdOrderProcessService;
import com.aps.common.util.redis.RedisUtils;
import com.aps.service.Algorithm.MaterialRequirementService;
import com.aps.service.plan.SceneService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MyBatis-Plus
 * @since 2025-11-14
 */
@Service
public class ProdSceneConfigServiceImpl extends ServiceImpl<ProdSceneConfigMapper, ProdSceneConfig> implements ProdSceneConfigService {

    @Autowired
    private ProdLaunchOrderService prodLaunchOrderService;

    @Autowired
    private ProdProcessExecService prodProcessExecService;

    @Autowired
    private ProdEquipmentService prodEquipmentService;

    @Autowired
    private ProdEquipSpecialCalService prodEquipSpecialCalService;

    @Autowired
    private ProdOrderProcessService prodOrderProcessService;

    @Autowired
    private SceneService sceneService;

    @Autowired
    @Lazy // 添加@Lazy注解，延迟加载LanuchService，解决循环依赖问题
    private MaterialRequirementService materialRequirementService;


    /**
     * 根据场景ID删除场景及其相关数据
     * @param sceneId 场景ID
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSceneById(String sceneId) {
        // 1. 删除场景相关表数据
        // 删除工单数据
        prodLaunchOrderService.lambdaUpdate()
                .eq(ProdLaunchOrder::getSceneId, sceneId)
                .remove();

        // 删除工序执行数据
        prodProcessExecService.lambdaUpdate()
                .eq(ProdProcessExec::getSceneId, sceneId)
                .remove();

        // 删除设备数据
        prodEquipmentService.lambdaUpdate()
                .eq(ProdEquipment::getSceneId, sceneId)
                .remove();

        // 删除设备特殊日历数据
        prodEquipSpecialCalService.lambdaUpdate()
                .eq(ProdEquipSpecialCal::getSceneId, sceneId)
                .remove();

        // 删除工序关系数据
        prodOrderProcessService.lambdaUpdate()
                .eq(ProdOrderProcess::getSceneId, sceneId)
                .remove();

        // 删除场景对应的染色体文件
        sceneService.deleteChromosomeFile(sceneId);

        // 清除MaterialRequirementService的缓存
        materialRequirementService.clearCache(sceneId);

        // 2. 删除场景配置本身
        return this.removeById(sceneId);
    }
}