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.CcdiBaseStaff;
import com.ruoyi.info.collection.domain.CcdiStaffFmyRelation;
import com.ruoyi.info.collection.domain.dto.CcdiStaffFmyRelationAddDTO;
import com.ruoyi.info.collection.domain.excel.CcdiStaffFmyRelationExcel;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.StaffFmyRelationImportFailureVO;
import com.ruoyi.info.collection.enums.GenderEnum;
import com.ruoyi.info.collection.mapper.CcdiBaseStaffMapper;
import com.ruoyi.info.collection.mapper.CcdiStaffFmyRelationMapper;
import com.ruoyi.info.collection.service.ICcdiStaffFmyRelationImportService;
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.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 员工亲属关系异步导入服务层处理
 *
 * @author ruoyi
 * @date 2026-02-09
 */
@Service
@EnableAsync
public class CcdiStaffFmyRelationImportServiceImpl implements ICcdiStaffFmyRelationImportService {

    private static final Logger log = LoggerFactory.getLogger(CcdiStaffFmyRelationImportServiceImpl.class);
    private static final String SHEET_NAME = "员工亲属关系信息";
    private static final int EXCEL_DATA_START_ROW = 2;

    @Resource
    private CcdiStaffFmyRelationMapper relationMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CcdiBaseStaffMapper baseStaffMapper;

    @Override
    @Async
    @Transactional
    public void importRelationAsync(List<CcdiStaffFmyRelationExcel> excelList, String taskId, String userName) {
        importRelationSync(excelList, taskId, userName);
    }

    @Override
    @Transactional
    public Map<String, String> importRelationSync(List<CcdiStaffFmyRelationExcel> excelList, String taskId, String userName) {
        long startTime = System.currentTimeMillis();

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

        List<CcdiStaffFmyRelation> newRecords = new ArrayList<>();
        List<StaffFmyRelationImportFailureVO> failures = new ArrayList<>();

        // 批量验证员工身份证号是否存在
        Set<String> excelPersonIds = excelList.stream()
                .map(CcdiStaffFmyRelationExcel::getPersonId)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toSet());

        Set<String> existingPersonIds = new HashSet<>();
        if (!excelPersonIds.isEmpty()) {
            ImportLogUtils.logBatchQueryStart(log, taskId, "员工身份证号", excelPersonIds.size());

            LambdaQueryWrapper<CcdiBaseStaff> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(CcdiBaseStaff::getIdCard)
                   .in(CcdiBaseStaff::getIdCard, excelPersonIds);

            List<CcdiBaseStaff> existingStaff = baseStaffMapper.selectList(wrapper);
            existingPersonIds = existingStaff.stream()
                    .map(CcdiBaseStaff::getIdCard)
                    .collect(Collectors.toSet());

            ImportLogUtils.logBatchQueryComplete(log, taskId, "员工身份证号", existingPersonIds.size());
        }

        // ========== 第一步：批量唯一性校验 ==========
        // 1. 提取Excel中所有的relationCertNo（personId已在前面提取）
        Set<String> excelRelationCertNos = new HashSet<>();
        for (CcdiStaffFmyRelationExcel excel : excelList) {
            if (StringUtils.isNotEmpty(excel.getRelationCertNo())) {
                excelRelationCertNos.add(excel.getRelationCertNo());
            }
        }

        // 2. 批量查询数据库中已存在的记录
        Set<String> existingKeys = new HashSet<>();
        if (!excelRelationCertNos.isEmpty()) {
            ImportLogUtils.logBatchQueryStart(log, taskId, "已存在的亲属关系", excelList.size());
            List<CcdiStaffFmyRelation> existingRecords = relationMapper.selectExistingRelations(
                new ArrayList<>(excelPersonIds),
                new ArrayList<>(excelRelationCertNos)
            );

            // 3. 构建已存在记录的唯一键集合（personId + relationCertNo）
            for (CcdiStaffFmyRelation existing : existingRecords) {
                String key = existing.getPersonId() + "|" + existing.getRelationCertNo();
                existingKeys.add(key);
            }
            ImportLogUtils.logBatchQueryComplete(log, taskId, "亲属关系", existingKeys.size());
        }

        // ========== 第二步：处理数据 ==========
        // 用于跟踪Excel文件内已处理的唯一键
        Set<String> processedKeys = new HashSet<>();

        for (int i = 0; i < excelList.size(); i++) {
            CcdiStaffFmyRelationExcel excel = excelList.get(i);

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

                // 验证数据
                validateRelationData(addDTO);

                // 身份证号存在性检查（在基本验证之后）
                if (!existingPersonIds.contains(excel.getPersonId())) {
                    throw new RuntimeException(String.format(
                        "第%d行: 身份证号[%s]不存在于员工信息表中，请先添加员工信息",
                        i + 1, excel.getPersonId()));
                }

                // 生成唯一键
                String uniqueKey = excel.getPersonId() + "|" + excel.getRelationCertNo();

                // 检查是否在文件内重复
                if (processedKeys.contains(uniqueKey)) {
                    throw new RuntimeException(String.format("员工[%s]的关系人[%s]在导入文件中重复", excel.getPersonId(), excel.getRelationCertNo()));
                }

                // 检查是否在数据库中已存在（批量校验的结果）
                if (existingKeys.contains(uniqueKey)) {
                    throw new RuntimeException(String.format("员工[%s]的关系人[%s]已存在", excel.getPersonId(), excel.getRelationCertNo()));
                }

                // 从已验证和转换过的addDTO创建relation对象
                CcdiStaffFmyRelation relation = new CcdiStaffFmyRelation();
                BeanUtils.copyProperties(addDTO, relation);

                relation.setCreatedBy(userName);
                relation.setUpdatedBy(userName);
                relation.setIsEmpFamily(true);
                relation.setIsCustFamily(false);
                relation.setDataSource("IMPORT");
                // 显式设置状态为有效（status=1）
                relation.setStatus(1);

                newRecords.add(relation);
                processedKeys.add(uniqueKey);

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

            } catch (Exception e) {
                StaffFmyRelationImportFailureVO failure = new StaffFmyRelationImportFailureVO();
                BeanUtils.copyProperties(excel, failure);
                failure.setSheetName(SHEET_NAME);
                failure.setRowNum(i + EXCEL_DATA_START_ROW);
                failure.setErrorMessage(e.getMessage());
                failures.add(failure);

                // 记录验证失败日志
                String keyData = String.format("员工身份证号=%s, 关系人=%s(%s)",
                        excel.getPersonId(), 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:staffFmyRelation:" + 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);

        return newRecords.stream()
                .filter(item -> StringUtils.isNotEmpty(item.getRelationCertNo()) && StringUtils.isNotEmpty(item.getPersonId()))
                .collect(Collectors.toMap(
                        CcdiStaffFmyRelation::getRelationCertNo,
                        CcdiStaffFmyRelation::getPersonId,
                        (left, right) -> left,
                        LinkedHashMap::new
                ));
    }

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

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

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

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

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

    /**
     * 验证员工亲属关系数据
     *
     * @param addDTO 新增DTO
     */
    private void validateRelationData(CcdiStaffFmyRelationAddDTO addDTO) {
        // 验证必填字段
        if (StringUtils.isEmpty(addDTO.getPersonId())) {
            throw new RuntimeException("员工身份证号不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getRelationType())) {
            throw new RuntimeException("关系类型不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getRelationName())) {
            throw new RuntimeException("关系人姓名不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getRelationCertType())) {
            throw new RuntimeException("关系人证件类型不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getRelationCertNo())) {
            throw new RuntimeException("关系人证件号码不能为空");
        }

        // 验证身份证号格式
        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}[\\dXx]$")) {
            throw new RuntimeException("员工身份证号格式不正确");
        }

        // 验证手机号格式（如果提供）
        if (StringUtils.isNotEmpty(addDTO.getMobilePhone1()) && !addDTO.getMobilePhone1().matches("^1[3-9]\\d{9}$")) {
            throw new RuntimeException("手机号码1格式不正确");
        }
        if (StringUtils.isNotEmpty(addDTO.getMobilePhone2()) && !addDTO.getMobilePhone2().matches("^1[3-9]\\d{9}$")) {
            throw new RuntimeException("手机号码2格式不正确");
        }

        // 验证性别值（如果提供）
        if (StringUtils.isNotEmpty(addDTO.getGender())) {
            try {
                // 使用GenderEnum进行标准化，支持中文（男、女、其他）和英文（M、F、O）
                String normalizedGender = GenderEnum.normalize(addDTO.getGender());
                addDTO.setGender(normalizedGender);
            } catch (IllegalArgumentException e) {
                throw new RuntimeException("性别只能是：男、女、其他 或 M、F、O");
            }
        }

        validateAnnualIncome(addDTO.getAnnualIncome(), "家庭成员年收入");
    }

    private void validateAnnualIncome(BigDecimal annualIncome, String fieldLabel) {
        if (annualIncome == null) {
            return;
        }
        if (annualIncome.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException(fieldLabel + "不能为负数");
        }
        if (annualIncome.scale() > 2) {
            throw new RuntimeException(fieldLabel + "最多保留2位小数");
        }
    }
}
