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

import com.alibaba.fastjson2.JSON;
import com.ruoyi.info.collection.domain.CcdiCustEnterpriseRelation;
import com.ruoyi.info.collection.domain.dto.CcdiCustEnterpriseRelationAddDTO;
import com.ruoyi.info.collection.domain.excel.CcdiCustEnterpriseRelationExcel;
import com.ruoyi.info.collection.domain.vo.CustEnterpriseRelationImportFailureVO;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.enums.DataSource;
import com.ruoyi.info.collection.enums.EnterpriseSource;
import com.ruoyi.info.collection.mapper.CcdiCustEnterpriseRelationMapper;
import com.ruoyi.info.collection.service.ICcdiCustEnterpriseRelationImportService;
import com.ruoyi.info.collection.service.support.EnterpriseAutoFillService;
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-12
 */
@Service
@EnableAsync
public class CcdiCustEnterpriseRelationImportServiceImpl implements ICcdiCustEnterpriseRelationImportService {

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

    @Resource
    private CcdiCustEnterpriseRelationMapper relationMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private EnterpriseAutoFillService enterpriseAutoFillService;

    @Override
    @Async
    @Transactional
    public void importRelationAsync(List<CcdiCustEnterpriseRelationExcel> excelList, String taskId, String userName) {
        long startTime = System.currentTimeMillis();

        // 记录导入开始
        ImportLogUtils.logImportStart(log, taskId, "信贷客户实体关联", excelList.size(), userName);

        List<CcdiCustEnterpriseRelation> newRecords = new ArrayList<>();
        List<CustEnterpriseRelationImportFailureVO> failures = new ArrayList<>();

        // 【关键差异】不需要验证身份证号是否存在
        // 员工实体关系导入会验证身份证号是否存在于员工表，信贷客户实体关联不需要此验证

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

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

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

            try {
                // 转换为AddDTO进行验证
                CcdiCustEnterpriseRelationAddDTO addDTO = new CcdiCustEnterpriseRelationAddDTO();
                BeanUtils.copyProperties(excel, addDTO);

                // 验证数据（不验证身份证号是否存在）
                validateRelationData(addDTO);

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

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

                if (existingCombinations.contains(combination)) {
                    // 组合已存在，直接报错
                    throw new RuntimeException(String.format("身份证号[%s]和统一社会信用代码[%s]的组合已存在，请勿重复导入",
                            excel.getPersonId(), excel.getSocialCreditCode()));
                } else if (processedCombinations.contains(combination)) {
                    // Excel文件内部重复
                    throw new RuntimeException(String.format("身份证号[%s]和统一社会信用代码[%s]的组合在导入文件中重复,已跳过此条记录",
                            excel.getPersonId(), excel.getSocialCreditCode()));
                } else {
                    relation.setCreatedBy(userName);
                    relation.setUpdatedBy(userName);

                    // 设置默认值
                    relation.setStatus(1);
                    // 信贷客户实体关联的身份标识
                    relation.setIsEmployee(0);
                    relation.setIsEmpFamily(0);
                    relation.setIsCustomer(0);
                    relation.setIsCustFamily(1);  // 信贷客户关联人标识为1
                    relation.setDataSource("IMPORT");

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

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

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

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

        // 批量插入新数据
        if (!newRecords.isEmpty()) {
            enterpriseAutoFillService.ensureExistsBatch(newRecords.stream()
                    .map(item -> new EnterpriseAutoFillService.EnterpriseFillItem(
                            item.getSocialCreditCode(),
                            item.getEnterpriseName(),
                            EnterpriseSource.CREDIT_CUSTOMER.getCode(),
                            DataSource.IMPORT.getCode(),
                            userName
                    ))
                    .toList());
            ImportLogUtils.logBatchOperationStart(log, taskId, "插入",
                    (newRecords.size() + 499) / 500, 500);
            saveBatch(newRecords, 500);
        }

        // 保存失败记录到Redis
        if (!failures.isEmpty()) {
            try {
                String failuresKey = "import:custEnterpriseRelation:" + 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);
    }

    /**
     * 获取导入失败记录
     *
     * @param taskId 任务ID
     * @return 失败记录列表
     */
    @Override
    public List<CustEnterpriseRelationImportFailureVO> getImportFailures(String taskId) {
        String key = "import:custEnterpriseRelation:" + taskId + ":failures";
        Object failuresObj = redisTemplate.opsForValue().get(key);

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

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

    /**
     * 查询导入状态
     *
     * @param taskId 任务ID
     * @return 导入状态信息
     */
    @Override
    public ImportStatusVO getImportStatus(String taskId) {
        String key = "import:custEnterpriseRelation:" + 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;
    }

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

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

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

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

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

    /**
     * 验证信贷客户实体关联数据
     * 【关键差异】不验证身份证号是否存在于员工表
     *
     * @param addDTO 新增DTO
     */
    private void validateRelationData(CcdiCustEnterpriseRelationAddDTO addDTO) {
        // 验证必填字段
        if (StringUtils.isEmpty(addDTO.getPersonId())) {
            throw new RuntimeException("身份证号不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getSocialCreditCode())) {
            throw new RuntimeException("统一社会信用代码不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getEnterpriseName())) {
            throw new RuntimeException("企业名称不能为空");
        }

        // 验证身份证号格式（18位）
        if (!addDTO.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位有效身份证号");
        }

        // 验证统一社会信用代码格式（18位）
        if (!addDTO.getSocialCreditCode().matches("^[0-9A-HJ-NPQRTUWXY]{2}\\d{6}[0-9A-HJ-NPQRTUWXY]{10}$")) {
            throw new RuntimeException("统一社会信用代码格式不正确，必须为18位有效统一社会信用代码");
        }

        // 验证字段长度
        if (StringUtils.isNotEmpty(addDTO.getRelationPersonPost()) && addDTO.getRelationPersonPost().length() > 100) {
            throw new RuntimeException("关联人在企业的职务长度不能超过100个字符");
        }
        if (addDTO.getEnterpriseName().length() > 200) {
            throw new RuntimeException("企业名称长度不能超过200个字符");
        }

        // 【注意】不验证身份证号是否存在于员工表
    }
}
