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.CcdiStaffTransfer;
import com.ruoyi.info.collection.domain.dto.CcdiStaffTransferAddDTO;
import com.ruoyi.info.collection.domain.excel.CcdiStaffTransferExcel;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.StaffTransferImportFailureVO;
import com.ruoyi.info.collection.mapper.CcdiBaseStaffMapper;
import com.ruoyi.info.collection.mapper.CcdiStaffTransferMapper;
import com.ruoyi.info.collection.service.ICcdiStaffTransferImportService;
import com.ruoyi.info.collection.utils.ImportLogUtils;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
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-10
 */
@Slf4j
@Service
@EnableAsync
public class CcdiStaffTransferImportServiceImpl implements ICcdiStaffTransferImportService {

    @Resource
    private CcdiStaffTransferMapper transferMapper;

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CcdiBaseStaffMapper baseStaffMapper;

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

        // 记录导入开始
        ImportLogUtils.logImportStart(log, taskId, "员工调动记录", excelList.size(), userName);

        List<CcdiStaffTransfer> newRecords = new ArrayList<>();
        List<StaffTransferImportFailureVO> failures = new ArrayList<>();

        // 批量查询员工ID存在性
        Set<Long> excelStaffIds = excelList.stream()
                .map(CcdiStaffTransferExcel::getStaffId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Set<Long> existingStaffIds = new HashSet<>();
        if (!excelStaffIds.isEmpty()) {
            ImportLogUtils.logBatchQueryStart(log, taskId, "员工ID", excelStaffIds.size());

            LambdaQueryWrapper<CcdiBaseStaff> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(CcdiBaseStaff::getStaffId)
                   .in(CcdiBaseStaff::getStaffId, excelStaffIds);

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

            ImportLogUtils.logBatchQueryComplete(log, taskId, "员工ID", existingStaffIds.size());
        }

        // 批量查询已存在的唯一键组合
        ImportLogUtils.logBatchQueryStart(log, taskId, "已存在的调动记录", excelList.size());
        Set<String> existingKeys = getExistingTransferKeys(excelList);
        ImportLogUtils.logBatchQueryComplete(log, taskId, "调动记录", existingKeys.size());

        // 用于检测Excel内部的重复键
        Set<String> excelProcessedKeys = new HashSet<>();

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

            try {
                // 员工ID存在性检查
                if (excel.getStaffId() != null && !existingStaffIds.contains(excel.getStaffId())) {
                    throw new RuntimeException(String.format(
                        "第%d行: 员工ID %s 不存在",
                        i + 1, excel.getStaffId()));
                }

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

                // 验证数据
                validateTransferData(addDTO);

                // 生成唯一键
                String uniqueKey = buildUniqueKey(addDTO.getStaffId(), addDTO.getDeptIdBefore(),
                        addDTO.getDeptIdAfter(), addDTO.getTransferDate());

                if (existingKeys.contains(uniqueKey)) {
                    // 数据库中已存在
                    throw new RuntimeException(String.format(
                            "第%d行: 该员工在%s的调动记录已存在（从%s调往%s）",
                            i + 1,
                            addDTO.getTransferDate(),
                            addDTO.getDeptNameBefore(),
                            addDTO.getDeptNameAfter()
                    ));
                } else if (excelProcessedKeys.contains(uniqueKey)) {
                    // Excel内部重复
                    throw new RuntimeException(String.format(
                            "该记录与Excel第%d行重复",
                            excelProcessedKeys.size() + 1
                    ));
                } else {
                    CcdiStaffTransfer transfer = new CcdiStaffTransfer();
                    // 从addDTO复制，因为validateTransferData已经补全了部门名称
                    BeanUtils.copyProperties(addDTO, transfer);
                    transfer.setCreatedBy(userName);
                    transfer.setUpdatedBy(userName);
                    newRecords.add(transfer);
                    excelProcessedKeys.add(uniqueKey);
                }

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

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

                // 记录验证失败日志
                String keyData = String.format("员工ID=%s, 调动类型=%s, 调动日期=%s, 调动前部门ID=%s, 调动后部门ID=%s",
                        excel.getStaffId(), excel.getTransferType(), excel.getTransferDate(),
                        excel.getDeptIdBefore(), excel.getDeptIdAfter());
                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:staffTransfer:" + 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 excelList Excel数据列表
     * @return 已存在的唯一键集合
     */
    private Set<String> getExistingTransferKeys(List<CcdiStaffTransferExcel> excelList) {
        // 提取所有有效的唯一键
        Set<String> allKeys = excelList.stream()
                .filter(excel -> excel.getStaffId() != null
                        && excel.getDeptIdBefore() != null
                        && excel.getDeptIdAfter() != null
                        && excel.getTransferDate() != null)
                .map(excel -> buildUniqueKey(excel.getStaffId(), excel.getDeptIdBefore(),
                        excel.getDeptIdAfter(), excel.getTransferDate()))
                .collect(Collectors.toSet());

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

        // 查询数据库中已存在的记录
        LambdaQueryWrapper<CcdiStaffTransfer> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CcdiStaffTransfer::getStaffId,
                CcdiStaffTransfer::getDeptIdBefore,
                CcdiStaffTransfer::getDeptIdAfter,
                CcdiStaffTransfer::getTransferDate);

        List<CcdiStaffTransfer> existingTransfers = transferMapper.selectList(wrapper);

        // 构建已存在的唯一键集合
        return existingTransfers.stream()
                .map(t -> buildUniqueKey(t.getStaffId(), t.getDeptIdBefore(),
                        t.getDeptIdAfter(), t.getTransferDate()))
                .collect(Collectors.toSet());
    }

    /**
     * 构建唯一键
     *
     * @param staffId       员工ID
     * @param deptIdBefore  调动前部门ID
     * @param deptIdAfter   调动后部门ID
     * @param transferDate  调动日期
     * @return 唯一键字符串
     */
    private String buildUniqueKey(Long staffId, Long deptIdBefore, Long deptIdAfter, Date transferDate) {
        String dateStr = new java.text.SimpleDateFormat("yyyy-MM-dd").format(transferDate);
        return staffId + "_" + deptIdBefore + "_" + deptIdAfter + "_" + dateStr;
    }

    /**
     * 验证员工调动记录数据
     *
     * @param addDTO 新增DTO
     */
    private void validateTransferData(CcdiStaffTransferAddDTO addDTO) {
        // 验证必填字段
        if (addDTO.getStaffId() == null) {
            throw new RuntimeException("员工ID不能为空");
        }
        if (StringUtils.isEmpty(addDTO.getTransferType())) {
            throw new RuntimeException("调动类型不能为空");
        }
        if (addDTO.getTransferDate() == null) {
            throw new RuntimeException("调动日期不能为空");
        }

        // 验证调动前部门ID
        if (addDTO.getDeptIdBefore() == null) {
            throw new RuntimeException("调动前部门ID不能为空");
        }

        // 验证调动后部门ID
        if (addDTO.getDeptIdAfter() == null) {
            throw new RuntimeException("调动后部门ID不能为空");
        }

        // 将调动类型从中文转换为码值
        String transferTypeCode = DictUtils.getDictValue("ccdi_transfer_type", addDTO.getTransferType());
        if (StringUtils.isEmpty(transferTypeCode)) {
            throw new RuntimeException("调动类型[" + addDTO.getTransferType() + "]无效，请检查字典数据");
        }
        addDTO.setTransferType(transferTypeCode);

        // 验证部门ID是否存在并获取部门名称
        String deptNameBefore = getDeptNameById(addDTO.getDeptIdBefore());
        addDTO.setDeptNameBefore(deptNameBefore);

        String deptNameAfter = getDeptNameById(addDTO.getDeptIdAfter());
        addDTO.setDeptNameAfter(deptNameAfter);
    }

    /**
     * 根据部门ID查询部门名称
     *
     * @param deptId 部门ID
     * @return 部门名称
     * @throws RuntimeException 如果部门不存在
     */
    private String getDeptNameById(Long deptId) {
        if (deptId == null) {
            return null;
        }

        SysDept dept = deptMapper.selectDeptById(deptId);

        if (dept == null) {
            throw new RuntimeException("部门ID " + deptId + " 不存在，请检查部门信息");
        }

        return dept.getDeptName();
    }

    /**
     * 批量保存
     */
    private void saveBatch(List<CcdiStaffTransfer> list, int batchSize) {
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<CcdiStaffTransfer> subList = list.subList(i, end);
            transferMapper.insertBatch(subList);
        }
    }

    /**
     * 更新导入状态
     */
    private void updateImportStatus(String taskId, String status, ImportResult result) {
        String key = "import:staffTransfer:" + taskId;
        Map<String, Object> statusData = new HashMap<>();
        statusData.put("status", status);
        statusData.put("totalCount", result.getTotalCount());
        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 ImportStatusVO getImportStatus(String taskId) {
        String key = "import:staffTransfer:" + 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;
    }

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

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

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