package com.aucma.base.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aucma.base.mapper.BaseDeviceParamMapper;
import com.aucma.base.domain.BaseDeviceParam;
import com.aucma.base.service.IBaseDeviceParamService;
import com.aucma.common.exception.ServiceException;
import com.aucma.common.utils.StringUtils;

/**
 * 设备参数Service业务层处理
 * 
 * @author Yinq
 * @date 2023-09-19
 */
@Service
public class BaseDeviceParamServiceImpl implements IBaseDeviceParamService 
{
    @Autowired
    private BaseDeviceParamMapper baseDeviceParamMapper;

    /**
     * 查询设备参数
     * 
     * @param objId 设备参数主键
     * @return 设备参数
     */
    @Override
    public BaseDeviceParam selectBaseDeviceParamByObjId(Long objId)
    {
        return baseDeviceParamMapper.selectBaseDeviceParamByObjId(objId);
    }

    /**
     * 查询设备参数列表
     * 
     * @param baseDeviceParam 设备参数
     * @return 设备参数
     */
    @Override
    public List<BaseDeviceParam> selectBaseDeviceParamList(BaseDeviceParam baseDeviceParam)
    {
        return baseDeviceParamMapper.selectBaseDeviceParamList(baseDeviceParam);
    }

    /**
     * 新增设备参数
     * 
     * @param baseDeviceParam 设备参数
     * @return 结果
     */
    @Override
    public int insertBaseDeviceParam(BaseDeviceParam baseDeviceParam)
    {
        String paramCode = baseDeviceParam.getParamCode();
        int count = baseDeviceParamMapper.countByParamCode(paramCode, null);
        System.out.println(count + paramCode);
        // 校验参数编号唯一
        if (count > 0)
        {
            throw new ServiceException("参数编号已存在：" + paramCode);
        }
        return baseDeviceParamMapper.insertBaseDeviceParam(baseDeviceParam);
    }

    /**
     * 修改设备参数
     * 
     * @param baseDeviceParam 设备参数
     * @return 结果
     */
    @Override
    public int updateBaseDeviceParam(BaseDeviceParam baseDeviceParam)
    {
        String paramCode = baseDeviceParam.getParamCode();
        int count = baseDeviceParamMapper.countByParamCode(paramCode, baseDeviceParam.getObjId());
        System.out.println(count + paramCode + baseDeviceParam.getObjId());
        if (count > 0)
        {
            throw new ServiceException("参数编号已存在：" + baseDeviceParam.getParamCode());
        }
        return baseDeviceParamMapper.updateBaseDeviceParam(baseDeviceParam);
    }

    /**
     * 批量删除设备参数
     * 
     * @param objIds 需要删除的设备参数主键
     * @return 结果
     */
    @Override
    public int deleteBaseDeviceParamByObjIds(Long[] objIds)
    {
        return baseDeviceParamMapper.deleteBaseDeviceParamByObjIds(objIds);
    }

    /**
     * 删除设备参数信息
     * 
     * @param objId 设备参数主键
     * @return 结果
     */
    @Override
    public int deleteBaseDeviceParamByObjId(Long objId)
    {
        return baseDeviceParamMapper.deleteBaseDeviceParamByObjId(objId);
    }

    /**
     * 导入设备参数数据（批量优化版）
     *
     * @param baseDeviceParamList 设备参数数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importDeviceParam(List<BaseDeviceParam> baseDeviceParamList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(baseDeviceParamList) || baseDeviceParamList.size() == 0)
        {
            throw new ServiceException("导入设备参数数据不能为空！");
        }
        
        // 1. 提取所有参数编号，一次性查询已存在的记录
        List<String> paramCodes = baseDeviceParamList.stream()
                .map(BaseDeviceParam::getParamCode)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());
        
        // 2. 批量查询已存在的参数（paramCode -> 实体 映射）
        // Oracle IN 子句限制1000个元素，分批查询（每批900个）
        Map<String, BaseDeviceParam> existMap = new java.util.HashMap<>();
        if (!paramCodes.isEmpty())
        {
            int queryBatchSize = 900;
            for (int i = 0; i < paramCodes.size(); i += queryBatchSize)
            {
                int end = Math.min(i + queryBatchSize, paramCodes.size());
                List<String> batchCodes = paramCodes.subList(i, end);
                List<BaseDeviceParam> existList = baseDeviceParamMapper.selectByParamCodes(batchCodes);
                for (BaseDeviceParam p : existList)
                {
                    existMap.put(p.getParamCode(), p);
                }
            }
        }
        
        // 3. 分类：新增列表、更新列表、跳过列表
        List<BaseDeviceParam> insertList = new ArrayList<>();
        List<BaseDeviceParam> updateList = new ArrayList<>();
        int skipNum = 0;
        Date now = new Date();
        
        for (BaseDeviceParam deviceParam : baseDeviceParamList)
        {
            if (StringUtils.isEmpty(deviceParam.getParamCode()))
            {
                continue;
            }
            BaseDeviceParam exist = existMap.get(deviceParam.getParamCode());
            if (exist == null)
            {
                // 新增
                deviceParam.setCreatedBy(operName);
                deviceParam.setCreatedTime(now);
                insertList.add(deviceParam);
            }
            else if (isUpdateSupport)
            {
                // 更新
                deviceParam.setObjId(exist.getObjId());
                deviceParam.setUpdatedBy(operName);
                deviceParam.setUpdatedTime(now);
                updateList.add(deviceParam);
            }
            else
            {
                skipNum++;
            }
        }
        
        // 4. 批量插入（分批处理，每批100条）
        int insertCount = 0;
        if (!insertList.isEmpty())
        {
            int batchSize = 100;
            for (int i = 0; i < insertList.size(); i += batchSize)
            {
                int end = Math.min(i + batchSize, insertList.size());
                List<BaseDeviceParam> batch = insertList.subList(i, end);
                baseDeviceParamMapper.batchInsertDeviceParam(batch);
                insertCount += batch.size();
            }
        }
        
        // 5. 批量更新（分批处理，每批100条）
        int updateCount = 0;
        if (!updateList.isEmpty())
        {
            int batchSize = 100;
            for (int i = 0; i < updateList.size(); i += batchSize)
            {
                int end = Math.min(i + batchSize, updateList.size());
                List<BaseDeviceParam> batch = updateList.subList(i, end);
                baseDeviceParamMapper.batchUpdateDeviceParam(batch);
                updateCount += batch.size();
            }
        }
        
        // 6. 返回结果
        StringBuilder resultMsg = new StringBuilder();
        resultMsg.append("导入完成！");
        resultMsg.append("<br/>新增：" + insertCount + " 条");
        resultMsg.append("<br/>更新：" + updateCount + " 条");
        if (skipNum > 0)
        {
            resultMsg.append("<br/>跳过（已存在）：" + skipNum + " 条");
        }
        return resultMsg.toString();
    }
}
