package com.ruoyi.info.collection.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.info.collection.domain.CcdiEnterpriseBaseInfo;
import com.ruoyi.info.collection.domain.excel.CcdiIntermediaryEntityExcel;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.IntermediaryEntityImportFailureVO;
import com.ruoyi.info.collection.mapper.CcdiEnterpriseBaseInfoMapper;
import com.ruoyi.info.collection.service.ICcdiIntermediaryEntityImportService;
import com.ruoyi.info.collection.utils.ImportLogUtils;
import com.ruoyi.common.utils.StringUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 实体中介异步导入Service实现
 *
 * @author ruoyi
 * @date 2026-02-06
 */
@Service
@EnableAsync
public class CcdiIntermediaryEntityImportServiceImpl implements ICcdiIntermediaryEntityImportService {

    private static final Logger log = LoggerFactory.getLogger(CcdiIntermediaryEntityImportServiceImpl.class);

    @Resource
    private CcdiEnterpriseBaseInfoMapper entityMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void importEntityAsync(List<CcdiIntermediaryEntityExcel> excelList,
                                  String taskId,
                                  String userName) {
        long startTime = System.currentTimeMillis();

        // 记录导入开始
        ImportLogUtils.logImportStart(log, taskId, "实体中介", excelList.size(), userName);

        List<CcdiEnterpriseBaseInfo> newRecords = new ArrayList<>();
        List<IntermediaryEntityImportFailureVO> failures = new ArrayList<>();

        // 批量查询已存在的统一社会信用代码
        ImportLogUtils.logBatchQueryStart(log, taskId, "已存在的统一社会信用代码", excelList.size());
        Set<String> existingCreditCodes = getExistingCreditCodes(excelList);
        ImportLogUtils.logBatchQueryComplete(log, taskId, "统一社会信用代码", existingCreditCodes.size());

        // 用于检测Excel内部的重复ID
        Set<String> excelProcessedIds = new HashSet<>();

        // 分类数据
        for (int i = 0; i < excelList.size(); i++) {
            CcdiIntermediaryEntityExcel excel = excelList.get(i);

            try {
                // 验证数据
                validateEntityData(excel, existingCreditCodes);

                CcdiEnterpriseBaseInfo entity = new CcdiEnterpriseBaseInfo();
                BeanUtils.copyProperties(excel, entity);

                // 设置数据来源和审计字段
                entity.setDataSource("IMPORT");
                entity.setEntSource("INTERMEDIARY");
                entity.setCreatedBy(userName);
                entity.setUpdatedBy(userName);

                if (existingCreditCodes.contains(excel.getSocialCreditCode())) {
                    // 统一社会信用代码在数据库中已存在,直接报错
                    throw new RuntimeException(String.format("统一社会信用代码[%s]已存在,请勿重复导入", excel.getSocialCreditCode()));
                } else if (excelProcessedIds.contains(excel.getSocialCreditCode())) {
                    // 统一社会信用代码在Excel文件内部重复
                    throw new RuntimeException(String.format("统一社会信用代码[%s]在导入文件中重复,已跳过此条记录", excel.getSocialCreditCode()));
                } else {
                    newRecords.add(entity);
                    excelProcessedIds.add(excel.getSocialCreditCode()); // 标记为已处理
                }

                // 记录进度
                ImportLogUtils.logProgress(log, taskId, i + 1, excelList.size(),
                        newRecords.size(), failures.size());

            } catch (Exception e) {
                failures.add(createFailureVO(excel, e.getMessage()));

                // 记录验证失败日志
                String keyData = String.format("机构名称=%s, 统一社会信用代码=%s",
                        excel.getEnterpriseName(), excel.getSocialCreditCode());
                ImportLogUtils.logValidationError(log, taskId, i + 1, e.getMessage(), keyData);
            }
        }

        // 批量插入新数据
        if (!newRecords.isEmpty()) {
            ImportLogUtils.logBatchOperationStart(log, taskId, "插入",
                    (newRecords.size() + 499) / 500, 500);
            saveBatch(newRecords, 500);
        }

        // 保存失败记录到Redis
        if (!failures.isEmpty()) {
            try {
                String failuresKey = "import:intermediary-entity:" + taskId + ":failures";
                redisTemplate.opsForValue().set(failuresKey, failures, 7, TimeUnit.DAYS);
                ImportLogUtils.logRedisOperation(log, taskId, "保存失败记录", failures.size());
            } catch (Exception e) {
                ImportLogUtils.logRedisError(log, taskId, "保存失败记录", e);
            }
        }

        ImportResult result = new ImportResult();
        result.setTotalCount(excelList.size());
        result.setSuccessCount(newRecords.size());
        result.setFailureCount(failures.size());

        // 更新最终状态
        String finalStatus = result.getFailureCount() == 0 ? "SUCCESS" : "PARTIAL_SUCCESS";
        updateImportStatus(taskId, finalStatus, result);

        // 记录导入完成
        long duration = System.currentTimeMillis() - startTime;
        ImportLogUtils.logImportComplete(log, taskId, "实体中介",
                excelList.size(), result.getSuccessCount(), result.getFailureCount(), duration);
    }

    @Override
    public ImportStatusVO getImportStatus(String taskId) {
        String key = "import:intermediary-entity:" + taskId;
        Boolean hasKey = redisTemplate.hasKey(key);

        if (Boolean.FALSE.equals(hasKey)) {
            throw new RuntimeException("任务不存在或已过期");
        }

        Map<Object, Object> statusMap = redisTemplate.opsForHash().entries(key);

        ImportStatusVO statusVO = new ImportStatusVO();
        statusVO.setTaskId((String) statusMap.get("taskId"));
        statusVO.setStatus((String) statusMap.get("status"));
        statusVO.setTotalCount((Integer) statusMap.get("totalCount"));
        statusVO.setSuccessCount((Integer) statusMap.get("successCount"));
        statusVO.setFailureCount((Integer) statusMap.get("failureCount"));
        statusVO.setProgress((Integer) statusMap.get("progress"));
        statusVO.setStartTime((Long) statusMap.get("startTime"));
        statusVO.setEndTime((Long) statusMap.get("endTime"));
        statusVO.setMessage((String) statusMap.get("message"));

        return statusVO;
    }

    @Override
    public List<IntermediaryEntityImportFailureVO> getImportFailures(String taskId) {
        String key = "import:intermediary-entity:" + taskId + ":failures";
        Object failuresObj = redisTemplate.opsForValue().get(key);

        if (failuresObj == null) {
            return Collections.emptyList();
        }

        return JSON.parseArray(JSON.toJSONString(failuresObj), IntermediaryEntityImportFailureVO.class);
    }

    /**
     * 批量查询已存在的统一社会信用代码
     */
    private Set<String> getExistingCreditCodes(List<CcdiIntermediaryEntityExcel> excelList) {
        List<String> creditCodes = excelList.stream()
                .map(CcdiIntermediaryEntityExcel::getSocialCreditCode)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());

        if (creditCodes.isEmpty()) {
            return Collections.emptySet();
        }

        LambdaQueryWrapper<CcdiEnterpriseBaseInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CcdiEnterpriseBaseInfo::getSocialCreditCode, creditCodes);
        List<CcdiEnterpriseBaseInfo> existingEntities = entityMapper.selectList(wrapper);

        return existingEntities.stream()
                .map(CcdiEnterpriseBaseInfo::getSocialCreditCode)
                .collect(Collectors.toSet());
    }

    /**
     * 批量保存(使用ON DUPLICATE KEY UPDATE)
     */
    private int saveBatchWithUpsert(List<CcdiEnterpriseBaseInfo> list, int batchSize) {
        int totalCount = 0;
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<CcdiEnterpriseBaseInfo> subList = list.subList(i, end);
            int count = entityMapper.importEntityBatch(subList);
            totalCount += count;
        }
        return totalCount;
    }

    /**
     * 从数据库获取已存在的统一社会信用代码
     */
    private Set<String> getExistingCreditCodesFromDb(List<CcdiEnterpriseBaseInfo> records) {
        List<String> creditCodes = records.stream()
                .map(CcdiEnterpriseBaseInfo::getSocialCreditCode)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());

        if (creditCodes.isEmpty()) {
            return Collections.emptySet();
        }

        LambdaQueryWrapper<CcdiEnterpriseBaseInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CcdiEnterpriseBaseInfo::getSocialCreditCode, creditCodes);
        List<CcdiEnterpriseBaseInfo> existing = entityMapper.selectList(wrapper);

        return existing.stream()
                .map(CcdiEnterpriseBaseInfo::getSocialCreditCode)
                .collect(Collectors.toSet());
    }

    /**
     * 创建失败记录VO
     */
    private IntermediaryEntityImportFailureVO createFailureVO(CcdiIntermediaryEntityExcel excel, String errorMsg) {
        IntermediaryEntityImportFailureVO failure = new IntermediaryEntityImportFailureVO();
        BeanUtils.copyProperties(excel, failure);
        failure.setErrorMessage(errorMsg);
        return failure;
    }

    /**
     * 创建失败记录VO(重载方法)
     */
    private IntermediaryEntityImportFailureVO createFailureVO(CcdiEnterpriseBaseInfo record, String errorMsg) {
        CcdiIntermediaryEntityExcel excel = new CcdiIntermediaryEntityExcel();
        BeanUtils.copyProperties(record, excel);
        return createFailureVO(excel, errorMsg);
    }

    /**
     * 批量保存
     */
    private int saveBatch(List<CcdiEnterpriseBaseInfo> list, int batchSize) {
        // 使用真正的批量插入,分批次执行以提高性能
        int totalCount = 0;
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<CcdiEnterpriseBaseInfo> subList = list.subList(i, end);
            int count = entityMapper.insertBatch(subList);
            totalCount += count;
        }
        return totalCount;
    }

    /**
     * 更新导入状态
     */
    private void updateImportStatus(String taskId, String status, ImportResult result) {
        String key = "import:intermediary-entity:" + taskId;
        Map<String, Object> statusData = new HashMap<>();
        statusData.put("status", status);
        statusData.put("successCount", result.getSuccessCount());
        statusData.put("failureCount", result.getFailureCount());
        statusData.put("progress", 100);
        statusData.put("endTime", System.currentTimeMillis());

        if ("SUCCESS".equals(status)) {
            statusData.put("message", "全部成功!共导入" + result.getTotalCount() + "条数据");
        } else {
            statusData.put("message", "成功" + result.getSuccessCount() + "条,失败" + result.getFailureCount() + "条");
        }

        redisTemplate.opsForHash().putAll(key, statusData);
    }

    /**
     * 验证实体中介数据
     *
     * @param excel Excel数据
     * @param existingCreditCodes 已存在的统一社会信用代码集合
     */
    private void validateEntityData(CcdiIntermediaryEntityExcel excel,
                                    Set<String> existingCreditCodes) {
        // 验证必填字段:机构名称
        if (StringUtils.isEmpty(excel.getEnterpriseName())) {
            throw new RuntimeException("机构名称不能为空");
        }

        // 验证必填字段:统一社会信用代码
        if (StringUtils.isEmpty(excel.getSocialCreditCode())) {
            throw new RuntimeException("统一社会信用代码不能为空");
        }

        // 统一社会信用代码格式验证(18位)
        if (excel.getSocialCreditCode().length() != 18) {
            throw new RuntimeException("统一社会信用代码必须为18位");
        }
    }
}
