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

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.info.collection.domain.CcdiBaseStaff;
import com.ruoyi.info.collection.domain.dto.CcdiBaseStaffAddDTO;
import com.ruoyi.info.collection.domain.excel.CcdiBaseStaffExcel;
import com.ruoyi.info.collection.domain.vo.ImportFailureVO;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.mapper.CcdiBaseStaffMapper;
import com.ruoyi.info.collection.service.ICcdiBaseStaffImportService;
import com.ruoyi.info.collection.utils.ImportLogUtils;
import com.ruoyi.common.utils.IdCardUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
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: wkc
 * @CreateTime: 2026-02-06
 */
@Service
@EnableAsync
public class CcdiBaseStaffImportServiceImpl implements ICcdiBaseStaffImportService {

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

    @Resource
    private CcdiBaseStaffMapper baseStaffMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private SysDeptMapper deptMapper;

    @Override
    @Async
    public void importBaseStaffAsync(List<CcdiBaseStaffExcel> excelList, String taskId) {
        importBaseStaffSync(excelList, taskId);
    }

    @Override
    @Transactional
    public Set<String> importBaseStaffSync(List<CcdiBaseStaffExcel> excelList, String taskId) {
        long startTime = System.currentTimeMillis();

        // 记录导入开始
        ImportLogUtils.logImportStart(log, taskId, "员工基础信息", excelList.size(), "系统");

        List<CcdiBaseStaff> newRecords = new ArrayList<>();
        List<ImportFailureVO> failures = new ArrayList<>();

        // 批量查询已存在的员工ID和身份证号
        ImportLogUtils.logBatchQueryStart(log, taskId, "已存在的员工ID", excelList.size());
        Set<Long> existingIds = getExistingStaffIds(excelList);
        Set<String> existingIdCards = getExistingIdCards(excelList);
        ImportLogUtils.logBatchQueryComplete(log, taskId, "员工ID", existingIds.size());
        ImportLogUtils.logBatchQueryComplete(log, taskId, "身份证号", existingIdCards.size());

        // 用于跟踪Excel文件内已处理的主键
        Set<Long> processedStaffIds = new HashSet<>();
        Set<String> processedIdCards = new HashSet<>();

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

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

                validateStaffData(addDTO, existingIds, existingIdCards);

                CcdiBaseStaff staff = new CcdiBaseStaff();
                BeanUtils.copyProperties(excel, staff);

                // 统一检查Excel内重复
                if (processedStaffIds.contains(excel.getStaffId())) {
                    throw new RuntimeException(String.format("员工ID[%d]在导入文件中重复,已跳过此条记录", excel.getStaffId()));
                }
                if (StringUtils.isNotEmpty(excel.getIdCard()) &&
                    processedIdCards.contains(excel.getIdCard())) {
                    throw new RuntimeException(String.format("身份证号[%s]在导入文件中重复,已跳过此条记录", excel.getIdCard()));
                }

                newRecords.add(staff);

                // 统一标记为已处理（只有成功添加到列表后才会执行到这里）
                if (excel.getStaffId() != null) {
                    processedStaffIds.add(excel.getStaffId());
                }
                if (StringUtils.isNotEmpty(excel.getIdCard())) {
                    processedIdCards.add(excel.getIdCard());
                }

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

            } catch (Exception e) {
                ImportFailureVO failure = new ImportFailureVO();
                BeanUtils.copyProperties(excel, failure);
                failure.setSheetName("员工信息");
                failure.setRowNum(i + 2);
                failure.setErrorMessage(e.getMessage());
                failures.add(failure);

                // 记录验证失败日志
                String keyData = String.format("员工ID=%s, 姓名=%s, 身份证号=%s",
                        excel.getStaffId(), excel.getName(), excel.getIdCard());
                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:baseStaff:" + 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("baseStaff", taskId, finalStatus, result);

        // 记录导入完成
        long duration = System.currentTimeMillis() - startTime;
        ImportLogUtils.logImportComplete(log, taskId, "员工基础信息",
                excelList.size(), result.getSuccessCount(), result.getFailureCount(), duration);

        return newRecords.stream()
                .map(CcdiBaseStaff::getIdCard)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toCollection(LinkedHashSet::new));
    }

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

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

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

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

    /**
     * 批量查询已存在的员工ID
     */
    private Set<Long> getExistingStaffIds(List<CcdiBaseStaffExcel> excelList) {
        List<Long> staffIds = excelList.stream()
                .map(CcdiBaseStaffExcel::getStaffId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

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

        List<CcdiBaseStaff> existingStaff = baseStaffMapper.selectBatchIds(staffIds);
        return existingStaff.stream()
                .map(CcdiBaseStaff::getStaffId)
                .collect(Collectors.toSet());
    }

    /**
     * 批量查询数据库中已存在的身份证号
     * @param excelList Excel数据列表
     * @return 已存在的身份证号集合
     */
    private Set<String> getExistingIdCards(List<CcdiBaseStaffExcel> excelList) {
        List<String> idCards = excelList.stream()
                .map(CcdiBaseStaffExcel::getIdCard)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());

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

        LambdaQueryWrapper<CcdiBaseStaff> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CcdiBaseStaff::getIdCard, idCards);
        List<CcdiBaseStaff> existingStaff = baseStaffMapper.selectList(wrapper);

        return existingStaff.stream()
                .map(CcdiBaseStaff::getIdCard)
                .collect(Collectors.toSet());
    }

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

    /**
     * 验证员工数据
     *
     * @param addDTO 新增DTO
     * @param existingIds 已存在的员工ID集合(导入场景使用,传null表示单条新增)
     * @param existingIdCards 已存在的身份证号集合(导入场景使用,传null表示单条新增)
     */
    public void validateStaffData(CcdiBaseStaffAddDTO addDTO, Set<Long> existingIds, Set<String> existingIdCards) {
        // 验证必填字段
        if (StringUtils.isEmpty(addDTO.getName())) {
            throw new RuntimeException("姓名不能为空");
        }
        if (addDTO.getStaffId() == null) {
            throw new RuntimeException("员工ID不能为空");
        }
        if (addDTO.getDeptId() == null) {
            throw new RuntimeException("所属部门不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getIdCard())) {
            throw new RuntimeException("身份证号不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getPhone())) {
            throw new RuntimeException("电话不能为空");
        }
        if (addDTO.getPartyMember() == null) {
            throw new RuntimeException("是否党员不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getStatus())) {
            throw new RuntimeException("状态不能为空");
        }
        validateDeptId(addDTO.getDeptId());

        // 验证身份证号格式
        String idCardError = IdCardUtil.getErrorMessage(addDTO.getIdCard());
        if (idCardError != null) {
            throw new RuntimeException(idCardError);
        }

        // 单条新增场景:检查员工ID和身份证号唯一性
        if (existingIds == null) {
            // 检查员工ID唯一性
            if (baseStaffMapper.selectById(addDTO.getStaffId()) != null) {
                throw new RuntimeException("该员工ID已存在");
            }

            // 检查身份证号唯一性
            LambdaQueryWrapper<CcdiBaseStaff> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CcdiBaseStaff::getIdCard, addDTO.getIdCard());
            if (baseStaffMapper.selectCount(wrapper) > 0) {
                throw new RuntimeException("该身份证号已存在");
            }
        } else {
            if (existingIds.contains(addDTO.getStaffId())) {
                throw new RuntimeException("该员工ID已存在");
            }
            if (existingIdCards != null && existingIdCards.contains(addDTO.getIdCard())) {
                throw new RuntimeException("该身份证号已存在");
            }
        }

        // 验证状态
        if (!"0".equals(addDTO.getStatus()) && !"1".equals(addDTO.getStatus())) {
            throw new RuntimeException("状态只能填写'在职'或'离职'");
        }
        if (addDTO.getPartyMember() != 0 && addDTO.getPartyMember() != 1) {
            throw new RuntimeException("是否党员只能填写'0'或'1'");
        }

        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位小数");
        }
    }

    private void validateDeptId(Long deptId) {
        SysDept dept = deptMapper.selectDeptById(deptId);
        if (dept == null || !"0".equals(dept.getStatus()) || !"0".equals(dept.getDelFlag())) {
            throw new RuntimeException(String.format("所属部门ID[%d]不存在或已停用/删除，请检查机构号", deptId));
        }
    }
}
