package iot.lidee.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import iot.lidee.framework.mybatis.mapper.BaseMapperX;
import iot.lidee.iot.mapper.bygz.*;
import iot.lidee.iot.model.bygz.SyncDataContainer;
import iot.lidee.iot.service.IDeviceDataSyncService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class DeviceDataSyncServiceImpl implements IDeviceDataSyncService {

    private static final Logger logger = LoggerFactory.getLogger(DeviceMaintenanceRepairServiceImpl.class);

    private static final int DEFAULT_BATCH_SIZE = 500;

    @Resource
    private ByManagementGdMapper byManagementGdMapper;

    @Resource
    private ByManagementJlMapper byManagementJlMapper;

    @Resource
    private ByManagementPlanMapper byManagementPlanMapper;

    @Resource
    private ByManagementYsMapper byManagementYsMapper;

    @Resource
    private DevGzbxMapper devGzbxMapper;

    @Resource
    private DevGzbxWxgdMapper devGzbxWxgdMapper;

    @Resource
    private DeviceArchivesMapper deviceArchivesMapper;

    @Resource
    private SblxMapper sblxMapper;

    /**
     * 同步数据到主数据库
     * 将各类设备和保养维修数据从源数据库同步到主数据库，包括设备档案、保养工单、保养记录、保养计划、
     * 保养验收、故障报修、维修工单、生产线等数据
     * 
     * @param data 同步数据容器，包含待同步的各类数据列表
     */
    @Override
    public void syncDataToMaster(SyncDataContainer data) {

        // 同步设备信息
        syncData(deviceArchivesMapper, data.getDevices(), "设备信息");
        
        // 同步保养信息
        syncData(byManagementGdMapper, data.getGdList(), "保养工单");
        syncData(byManagementJlMapper, data.getJlList(), "保养记录");
        syncData(byManagementPlanMapper, data.getPlanList(), "保养计划");
        syncData(byManagementYsMapper, data.getYsList(), "保养验收");
        
        // 同步维修信息
        syncData(devGzbxMapper, data.getGzbxList(), "故障报修");
        syncData(devGzbxWxgdMapper, data.getWxgdList(), "维修工单");
        
        // 同步生产线
        syncData(sblxMapper, data.getSblxList(), "生产线");

    }

    /**
     * 通用方法
     * @param mapper 数据访问接口
     * @param dataList 数据列表
     * @param dataTypeName 数据类型名称（用于日志）
     */
    public <T, M extends BaseMapperX<T>> void syncData(M mapper, List<T> dataList, String dataTypeName) {
        if (dataList == null || dataList.isEmpty()) {
            logger.warn("{}数据为空，跳过同步", dataTypeName);
            return;
        }

        try {
            logger.info("开始同步{}，数据量：{}", dataTypeName, dataList.size());
            mapper.delete(new QueryWrapper<>());
            mapper.insertBatch(dataList, DEFAULT_BATCH_SIZE);
            logger.info("{}同步完成", dataTypeName);
        } catch (Exception e) {
            logger.error("同步{}失败", dataTypeName, e);
            throw e;
        }
    }
}
