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.CcdiStaffEnterpriseRelation;
import com.ruoyi.info.collection.domain.CcdiStaffFmyRelation;
import com.ruoyi.info.collection.domain.dto.CcdiStaffEnterpriseRelationAddDTO;
import com.ruoyi.info.collection.domain.excel.CcdiStaffEnterpriseRelationExcel;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.StaffEnterpriseRelationImportFailureVO;
import com.ruoyi.info.collection.enums.DataSource;
import com.ruoyi.info.collection.enums.EnterpriseSource;
import com.ruoyi.info.collection.mapper.CcdiStaffFmyRelationMapper;
import com.ruoyi.info.collection.mapper.CcdiStaffEnterpriseRelationMapper;
import com.ruoyi.info.collection.service.ICcdiStaffEnterpriseRelationImportService;
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-09
 */
@Service
@EnableAsync
public class CcdiStaffEnterpriseRelationImportServiceImpl implements ICcdiStaffEnterpriseRelationImportService {

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

    @Resource
    private CcdiStaffEnterpriseRelationMapper relationMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CcdiStaffFmyRelationMapper familyRelationMapper;

    @Resource
    private EnterpriseAutoFillService enterpriseAutoFillService;

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

        // 记录导入开始
        ImportLogUtils.logImportStart(log, taskId, "员工亲属实体关联", excelList.size(), userName);

        List<CcdiStaffEnterpriseRelation> newRecords = new ArrayList<>();
        List<StaffEnterpriseRelationImportFailureVO> failures = new ArrayList<>();

        Set<String> excelPersonIds = excelList.stream()
                .map(CcdiStaffEnterpriseRelationExcel::getPersonId)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toSet());

        Map<String, CcdiStaffFmyRelation> validFamilies = new HashMap<>();
        Set<String> knownFamilyCertNos = new HashSet<>();
        Map<String, String> familyNameMap = new HashMap<>();
        if (!excelPersonIds.isEmpty()) {
            ImportLogUtils.logBatchQueryStart(log, taskId, "员工亲属关系", excelPersonIds.size());

            LambdaQueryWrapper<CcdiStaffFmyRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(
                            CcdiStaffFmyRelation::getRelationCertNo,
                            CcdiStaffFmyRelation::getRelationName,
                            CcdiStaffFmyRelation::getPersonId,
                            CcdiStaffFmyRelation::getStatus,
                            CcdiStaffFmyRelation::getIsEmpFamily
                    )
                    .in(CcdiStaffFmyRelation::getRelationCertNo, excelPersonIds);

            List<CcdiStaffFmyRelation> familyRelations = familyRelationMapper.selectList(wrapper);
            for (CcdiStaffFmyRelation familyRelation : familyRelations) {
                knownFamilyCertNos.add(familyRelation.getRelationCertNo());
                familyNameMap.putIfAbsent(familyRelation.getRelationCertNo(), familyRelation.getRelationName());
                if (Boolean.TRUE.equals(familyRelation.getIsEmpFamily()) && Integer.valueOf(1).equals(familyRelation.getStatus())) {
                    validFamilies.putIfAbsent(familyRelation.getRelationCertNo(), familyRelation);
                }
            }

            ImportLogUtils.logBatchQueryComplete(log, taskId, "员工亲属关系", familyRelations.size());
        }

        // 批量查询已存在的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++) {
            CcdiStaffEnterpriseRelationExcel excel = excelList.get(i);

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

                // 验证数据
                validateRelationData(addDTO);

                CcdiStaffFmyRelation familyRelation = validFamilies.get(excel.getPersonId());
                CcdiStaffEnterpriseRelation relation = validateAndBuildEntity(
                        excel,
                        familyRelation,
                        knownFamilyCertNos,
                        existingCombinations,
                        processedCombinations,
                        userName
                );

                newRecords.add(relation);
                processedCombinations.add(excel.getPersonId() + "|" + excel.getSocialCreditCode());

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

            } catch (Exception e) {
                StaffEnterpriseRelationImportFailureVO failure = new StaffEnterpriseRelationImportFailureVO();
                BeanUtils.copyProperties(excel, failure);
                failure.setRelationName(familyNameMap.get(excel.getPersonId()));
                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.EMP_RELATION.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:staffEnterpriseRelation:" + 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<StaffEnterpriseRelationImportFailureVO> getImportFailures(String taskId) {
        String key = "import:staffEnterpriseRelation:" + taskId + ":failures";
        Object failuresObj = redisTemplate.opsForValue().get(key);

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

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

    /**
     * 查询导入状态
     *
     * @param taskId 任务ID
     * @return 导入状态信息
     */
    @Override
    public ImportStatusVO getImportStatus(String taskId) {
        String key = "import:staffEnterpriseRelation:" + 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:staffEnterpriseRelation:" + 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<CcdiStaffEnterpriseRelationExcel> 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<CcdiStaffEnterpriseRelation> list, int batchSize) {
        // 使用真正的批量插入,分批次执行以提高性能
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<CcdiStaffEnterpriseRelation> subList = list.subList(i, end);
            relationMapper.insertBatch(subList);
        }
    }

    /**
     * 验证员工亲属实体关联基础数据
     *
     * @param addDTO 新增DTO
     */
    private void validateRelationData(CcdiStaffEnterpriseRelationAddDTO 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个字符");
        }
    }

    CcdiStaffEnterpriseRelation validateAndBuildEntity(CcdiStaffEnterpriseRelationExcel excel,
                                                       CcdiStaffFmyRelation familyRelation,
                                                       Set<String> knownFamilyCertNos,
                                                       Set<String> existingCombinations,
                                                       Set<String> processedCombinations,
                                                       String userName) {
        String combination = excel.getPersonId() + "|" + excel.getSocialCreditCode();

        if (familyRelation == null) {
            if (knownFamilyCertNos.contains(excel.getPersonId())) {
                throw new RuntimeException("亲属身份证号[" + excel.getPersonId() + "]不是有效员工亲属，请先维护有效的员工亲属关系");
            }
            throw new RuntimeException("亲属身份证号[" + excel.getPersonId() + "]不存在，请先维护员工亲属关系");
        }
        if (existingCombinations.contains(combination)) {
            throw new RuntimeException("亲属身份证号[" + excel.getPersonId() + "]和统一社会信用代码[" + excel.getSocialCreditCode() + "]的组合已存在，请勿重复导入");
        }
        if (processedCombinations.contains(combination)) {
            throw new RuntimeException("亲属身份证号[" + excel.getPersonId() + "]和统一社会信用代码[" + excel.getSocialCreditCode() + "]的组合在导入文件中重复,已跳过此条记录");
        }

        CcdiStaffEnterpriseRelation relation = new CcdiStaffEnterpriseRelation();
        BeanUtils.copyProperties(excel, relation);
        relation.setCreatedBy(userName);
        relation.setUpdatedBy(userName);
        relation.setStatus(1);
        relation.setIsEmployee(0);
        relation.setIsEmpFamily(1);
        relation.setIsCustomer(0);
        relation.setIsCustFamily(0);
        relation.setDataSource("IMPORT");
        return relation;
    }
}
