package com.aucma.base.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aucma.base.domain.BaseDeviceParamVal;
import com.aucma.base.domain.ProcessSnapshot;
import com.aucma.base.mapper.ProcessSnapshotMapper;
import com.aucma.base.service.IDeviceParamReadFacade;
import com.aucma.base.service.IProcessSnapshotService;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.SecurityUtils;

/**
 * 工艺快照Service实现
 *
 * @author Cascade
 * @date 2026-01-19
 */
@Service
public class ProcessSnapshotServiceImpl implements IProcessSnapshotService {
    @Autowired
    private ProcessSnapshotMapper processSnapshotMapper;

    @Autowired
    private IDeviceParamReadFacade deviceParamReadFacade;

    @Override
    public ProcessSnapshot selectProcessSnapshotBySnapshotId(Long snapshotId) {
        return processSnapshotMapper.selectProcessSnapshotBySnapshotId(snapshotId);
    }

    @Override
    public List<ProcessSnapshot> selectProcessSnapshotList(ProcessSnapshot processSnapshot) {
        return processSnapshotMapper.selectProcessSnapshotList(processSnapshot);
    }

    @Override
    public int insertProcessSnapshot(ProcessSnapshot processSnapshot) {
        if (processSnapshot.getSnapshotTime() == null) {
            processSnapshot.setSnapshotTime(new Date());
        }
        if (processSnapshot.getIsFlag() == null || processSnapshot.getIsFlag().isEmpty()) {
            processSnapshot.setIsFlag("1");
        }
        processSnapshot.setCreateBy(SecurityUtils.getUsername());
        processSnapshot.setCreateTime(DateUtils.getNowDate());
        return processSnapshotMapper.insertProcessSnapshot(processSnapshot);
    }

    @Override
    public int updateProcessSnapshot(ProcessSnapshot processSnapshot) {
        processSnapshot.setUpdateBy(SecurityUtils.getUsername());
        processSnapshot.setUpdateTime(DateUtils.getNowDate());
        return processSnapshotMapper.updateProcessSnapshot(processSnapshot);
    }

    @Override
    public int deleteProcessSnapshotBySnapshotId(Long snapshotId) {
        return processSnapshotMapper.deleteProcessSnapshotBySnapshotId(snapshotId);
    }

    @Override
    public int deleteProcessSnapshotBySnapshotIds(Long[] snapshotIds) {
        return processSnapshotMapper.deleteProcessSnapshotBySnapshotIds(snapshotIds);
    }

    @Override
    public ProcessSnapshot selectSnapshotDetail(Long snapshotId) {
        ProcessSnapshot snapshot = processSnapshotMapper.selectProcessSnapshotBySnapshotId(snapshotId);
        if (snapshot != null && snapshot.getDeviceCode() != null && snapshot.getSnapshotTime() != null) {
            // 为什么这样做：快照详情已经不是“查单表最近一分钟”这么简单，
            // 统一交给 Facade 后才能同时兼容 OLD 单表、NEW 月分表和跨月查询。
            List<BaseDeviceParamVal> paramList = deviceParamReadFacade.listParamsByTimePoint(
                    snapshot.getDeviceCode(), snapshot.getSnapshotTime(), 60);
            snapshot.setParamList(paramList);
        }
        return snapshot;
    }

    @Override
    public List<Map<String, Object>> compareSnapshots(Long snapshotId1, Long snapshotId2) {
        ProcessSnapshot snapshot1 = processSnapshotMapper.selectProcessSnapshotBySnapshotId(snapshotId1);
        ProcessSnapshot snapshot2 = processSnapshotMapper.selectProcessSnapshotBySnapshotId(snapshotId2);

        if (snapshot1 == null || snapshot2 == null) {
            return null;
        }

        if (!snapshot1.getDeviceCode().equals(snapshot2.getDeviceCode())) {
            return null;
        }

        // 为什么这样做：快照对比本质是两个时间点的参数差异对比，
        // 由统一参数能力负责底层路由后，快照服务才不用继续感知物理表结构。
        return deviceParamReadFacade.compareParamsByTimePoint(
                snapshot1.getDeviceCode(),
                snapshot1.getSnapshotTime(),
                snapshot2.getSnapshotTime(),
                60);
    }

    /**
     * 创建调试备份
     */
    @Override
    public int createDebugBackup(String deviceCode, String moldCode, String productCode, String backupName) {
        ProcessSnapshot snapshot = new ProcessSnapshot();
        snapshot.setDeviceCode(deviceCode);
        snapshot.setSnapshotTime(new Date());
        snapshot.setSnapshotType("BACKUP");
        snapshot.setMoldCode(moldCode);
        snapshot.setProductCode(productCode);
        snapshot.setBackupName(backupName);
        snapshot.setIsDefault("0");
        snapshot.setIsFlag("1");
        snapshot.setCreateBy(SecurityUtils.getUsername());
        snapshot.setCreateTime(DateUtils.getNowDate());
        return processSnapshotMapper.insertProcessSnapshot(snapshot);
    }

    /**
     * 查询调试备份列表
     */
    @Override
    public List<ProcessSnapshot> getDebugBackups(String moldCode, String deviceCode, String productCode) {
        ProcessSnapshot query = new ProcessSnapshot();
        query.setSnapshotType("BACKUP");
        if (moldCode != null && !moldCode.isEmpty()) {
            query.setMoldCode(moldCode);
        }
        if (deviceCode != null && !deviceCode.isEmpty()) {
            query.setDeviceCode(deviceCode);
        }
        if (productCode != null && !productCode.isEmpty()) {
            query.setProductCode(productCode);
        }
        return processSnapshotMapper.selectProcessSnapshotList(query);
    }

    /**
     * 获取默认备份
     */
    @Override
    public ProcessSnapshot getDefaultBackup(String moldCode, String deviceCode, String productCode) {
        ProcessSnapshot query = new ProcessSnapshot();
        query.setSnapshotType("BACKUP");
        query.setMoldCode(moldCode);
        query.setDeviceCode(deviceCode);
        query.setProductCode(productCode);
        query.setIsDefault("1");
        List<ProcessSnapshot> list = processSnapshotMapper.selectProcessSnapshotList(query);
        return list != null && !list.isEmpty() ? list.get(0) : null;
    }

    /**
     * 设为默认备份
     */
    @Override
    public int setDefaultBackup(Long snapshotId) {
        ProcessSnapshot current = processSnapshotMapper.selectProcessSnapshotBySnapshotId(snapshotId);
        if (current == null || !"BACKUP".equals(current.getSnapshotType())) {
            return 0;
        }

        // 取消其他备份的默认状态
        ProcessSnapshot query = new ProcessSnapshot();
        query.setSnapshotType("BACKUP");
        query.setMoldCode(current.getMoldCode());
        query.setDeviceCode(current.getDeviceCode());
        query.setProductCode(current.getProductCode());
        query.setIsDefault("1");
        List<ProcessSnapshot> defaultList = processSnapshotMapper.selectProcessSnapshotList(query);
        for (ProcessSnapshot ps : defaultList) {
            ps.setIsDefault("0");
            ps.setUpdateBy(SecurityUtils.getUsername());
            ps.setUpdateTime(DateUtils.getNowDate());
            processSnapshotMapper.updateProcessSnapshot(ps);
        }

        // 设置当前备份为默认
        current.setIsDefault("1");
        current.setUpdateBy(SecurityUtils.getUsername());
        current.setUpdateTime(DateUtils.getNowDate());
        return processSnapshotMapper.updateProcessSnapshot(current);
    }

    /**
     * 应用备份（获取备份参数详情）
     */
    @Override
    public ProcessSnapshot applyDebugBackup(Long snapshotId) {
        return selectSnapshotDetail(snapshotId);
    }
}
