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

import com.alibaba.fastjson2.JSON;
import com.ruoyi.info.collection.domain.CcdiCustFmyRelation;
import com.ruoyi.info.collection.domain.excel.CcdiCustFmyRelationExcel;
import com.ruoyi.info.collection.domain.vo.CustFmyRelationImportFailureVO;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.mapper.CcdiCustFmyRelationMapper;
import com.ruoyi.info.collection.service.ICcdiCustFmyRelationImportService;
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;

/**
 * 信贷客户家庭关系异步导入服务层处理
 *
 * @author ruoyi
 * @date 2026-02-11
 */
@Service
@EnableAsync
public class CcdiCustFmyRelationImportServiceImpl implements ICcdiCustFmyRelationImportService {

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

    @Resource
    private CcdiCustFmyRelationMapper mapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

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

        // 记录导入开始
        ImportLogUtils.logImportStart(log, taskId, "信贷客户家庭关系", excels.size(), userName);

        List<CcdiCustFmyRelation> newRecords = new ArrayList<>();
        List<CustFmyRelationImportFailureVO> failures = new ArrayList<>();

        // 批量查询已存在的 person_id + relation_type + relation_cert_no 组合
        ImportLogUtils.logBatchQueryStart(log, taskId, "已存在的客户家庭关系组合", excels.size());
        Set<String> existingCombinations = getExistingCombinations(excels);
        ImportLogUtils.logBatchQueryComplete(log, taskId, "客户家庭关系组合", existingCombinations.size());

        // 用于跟踪Excel文件内已处理的组合
        Set<String> processedCombinations = new HashSet<>();

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

            try {
                // 验证数据
                validateExcelRow(excel);

                String combination = excel.getPersonId() + "|" + excel.getRelationType() + "|" + excel.getRelationCertNo();

                CcdiCustFmyRelation relation = new CcdiCustFmyRelation();
                BeanUtils.copyProperties(excel, relation);

                if (existingCombinations.contains(combination)) {
                    // 组合已存在,直接报错
                    throw new RuntimeException(String.format(
                            "信贷客户身份证号[%s]、关系类型[%s]和关系人证件号码[%s]的组合已存在,请勿重复导入",
                            excel.getPersonId(), excel.getRelationType(), excel.getRelationCertNo()));
                } else if (processedCombinations.contains(combination)) {
                    // Excel文件内部重复
                    throw new RuntimeException(String.format(
                            "信贷客户身份证号[%s]、关系类型[%s]和关系人证件号码[%s]的组合在导入文件中重复,已跳过此条记录",
                            excel.getPersonId(), excel.getRelationType(), excel.getRelationCertNo()));
                } else {
                    relation.setCreatedBy(userName);
                    relation.setUpdatedBy(userName);

                    // 设置默认值
                    relation.setStatus(1);  // 默认有效状态
                    relation.setIsEmpFamily(false);
                    relation.setIsCustFamily(true);
                    relation.setDataSource("IMPORT");

                    newRecords.add(relation);
                    processedCombinations.add(combination); // 标记为已处理
                }

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

            } catch (Exception e) {
                CustFmyRelationImportFailureVO failure = new CustFmyRelationImportFailureVO();
                BeanUtils.copyProperties(excel, failure);
                failure.setErrorMessage(e.getMessage());
                failures.add(failure);

                // 记录验证失败日志
                String keyData = String.format("信贷客户身份证号=%s, 关系类型=%s, 关系人姓名=%s, 关系人证件号码=%s",
                        excel.getPersonId(), excel.getRelationType(), excel.getRelationName(), excel.getRelationCertNo());
                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:custFmyRelation:" + 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(excels.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, "信贷客户家庭关系",
                excels.size(), result.getSuccessCount(), result.getFailureCount(), duration);
    }

    /**
     * 批量查询已存在的 person_id + relation_type + relation_cert_no 组合
     * 性能优化:一次性查询所有组合,避免N+1查询问题
     *
     * @param excels Excel导入数据列表
     * @return 已存在的组合集合
     */
    private Set<String> getExistingCombinations(List<CcdiCustFmyRelationExcel> excels) {
        // 提取所有的 person_id + relation_type + relation_cert_no 组合
        List<String> combinations = excels.stream()
                .map(excel -> excel.getPersonId() + "|" + excel.getRelationType() + "|" + excel.getRelationCertNo())
                .filter(Objects::nonNull)
                .distinct()  // 去重
                .collect(Collectors.toList());

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

        // 一次性查询所有已存在的组合
        // 优化前:循环调用selectExistingRelations,N次数据库查询
        // 优化后:批量查询,1次数据库查询
        return new HashSet<>(mapper.batchExistsByCombinations(combinations));
    }

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

    /**
     * 验证Excel行数据
     *
     * @param excel Excel数据
     */
    private void validateExcelRow(CcdiCustFmyRelationExcel excel) {
        // 验证必填字段
        if (StringUtils.isEmpty(excel.getPersonId())) {
            throw new RuntimeException("信贷客户身份证号不能为空");
        }
        if (StringUtils.isEmpty(excel.getRelationType())) {
            throw new RuntimeException("关系类型不能为空");
        }
        if (StringUtils.isEmpty(excel.getRelationName())) {
            throw new RuntimeException("关系人姓名不能为空");
        }
        if (StringUtils.isEmpty(excel.getRelationCertType())) {
            throw new RuntimeException("关系人证件类型不能为空");
        }
        if (StringUtils.isEmpty(excel.getRelationCertNo())) {
            throw new RuntimeException("关系人证件号码不能为空");
        }

        // 验证身份证号格式(18位)
        if (!excel.getPersonId().matches("^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[0-9Xx]$")) {
            throw new RuntimeException("信贷客户身份证号格式不正确,必须为18位有效身份证号");
        }

        // 验证字段长度
        if (excel.getRelationName().length() > 50) {
            throw new RuntimeException("关系人姓名长度不能超过50个字符");
        }
        if (excel.getRelationType().length() > 20) {
            throw new RuntimeException("关系类型长度不能超过20个字符");
        }
        if (excel.getRelationCertNo().length() > 50) {
            throw new RuntimeException("关系人证件号码长度不能超过50个字符");
        }
        if (StringUtils.isNotEmpty(excel.getRelationDesc()) && excel.getRelationDesc().length() > 500) {
            throw new RuntimeException("关系描述长度不能超过500个字符");
        }
    }

    /**
     * 更新导入状态
     */
    private void updateImportStatus(String taskId, String status, ImportResult result) {
        String key = "import:custFmyRelation:" + 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);
    }

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

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

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

    @Override
    public ImportStatusVO getImportStatus(String taskId) {
        String key = "import:custFmyRelation:" + 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;
    }

    /**
     * 验证Excel行数据(兼容旧接口)
     */
    @Override
    public String validateExcelRow(CcdiCustFmyRelationExcel excel, Integer rowNum) {
        try {
            validateExcelRow(excel);
            return null; // 校验通过
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}
