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.CcdiBizIntermediary;
import com.ruoyi.info.collection.domain.excel.CcdiIntermediaryPersonExcel;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.IntermediaryPersonImportFailureVO;
import com.ruoyi.info.collection.mapper.CcdiBizIntermediaryMapper;
import com.ruoyi.info.collection.service.ICcdiIntermediaryPersonImportService;
import com.ruoyi.info.collection.utils.ImportLogUtils;
import com.ruoyi.common.utils.IdCardUtil;
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.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 中介信息异步导入实现
 */
@Service
@EnableAsync
public class CcdiIntermediaryPersonImportServiceImpl implements ICcdiIntermediaryPersonImportService {

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

    private static final String STATUS_KEY_PREFIX = "import:intermediary:";

    @Resource
    private CcdiBizIntermediaryMapper intermediaryMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void importPersonAsync(List<CcdiIntermediaryPersonExcel> excelList, String taskId, String userName) {
        long startTime = System.currentTimeMillis();
        ImportLogUtils.logImportStart(log, taskId, "中介信息", excelList.size(), userName);

        List<CcdiIntermediaryPersonExcel> ownerRows = new ArrayList<>();
        List<CcdiIntermediaryPersonExcel> relativeRows = new ArrayList<>();
        List<IntermediaryPersonImportFailureVO> failures = new ArrayList<>();

        for (int i = 0; i < excelList.size(); i++) {
            CcdiIntermediaryPersonExcel excel = excelList.get(i);
            try {
                validateCommonRow(excel);
                if (isOwnerRow(excel)) {
                    validateOwnerRow(excel);
                    ownerRows.add(excel);
                } else {
                    validateRelativeRow(excel);
                    relativeRows.add(excel);
                }
            } catch (Exception e) {
                failures.add(createFailureVO(excel, e.getMessage()));
                ImportLogUtils.logValidationError(log, taskId, i + 1, e.getMessage(),
                    String.format("姓名=%s, 证件号码=%s", excel.getName(), excel.getPersonId()));
            }
        }

        Set<String> existingOwnerPersonIds = getExistingOwnerPersonIds(ownerRows);
        Set<String> existingOwnerRefs = getExistingOwnerRefs(relativeRows);
        Set<String> existingRelativeCombinations = getExistingRelativeCombinations(relativeRows);

        List<CcdiBizIntermediary> successRecords = new ArrayList<>();
        Set<String> importedOwnerPersonIds = new HashSet<>();

        for (CcdiIntermediaryPersonExcel ownerExcel : ownerRows) {
            try {
                String ownerPersonId = ownerExcel.getPersonId();
                if (existingOwnerPersonIds.contains(ownerPersonId)) {
                    throw new RuntimeException(String.format("中介本人证件号码[%s]已存在，请勿重复导入", ownerPersonId));
                }
                if (!importedOwnerPersonIds.add(ownerPersonId)) {
                    throw new RuntimeException(String.format("中介本人证件号码[%s]在导入文件中重复", ownerPersonId));
                }
                successRecords.add(buildRecord(ownerExcel, userName, null));
            } catch (Exception e) {
                failures.add(createFailureVO(ownerExcel, e.getMessage()));
            }
        }

        Set<String> validOwnerRefs = new HashSet<>(existingOwnerRefs);
        validOwnerRefs.addAll(importedOwnerPersonIds);
        Set<String> processedRelativeCombinations = new HashSet<>();

        for (CcdiIntermediaryPersonExcel relativeExcel : relativeRows) {
            try {
                String ownerPersonId = relativeExcel.getRelatedNumId();
                String combination = ownerPersonId + "|" + relativeExcel.getPersonId();
                if (!validOwnerRefs.contains(ownerPersonId)) {
                    throw new RuntimeException(String.format("关联中介本人证件号码[%s]不存在", ownerPersonId));
                }
                if (existingRelativeCombinations.contains(combination)) {
                    throw new RuntimeException(String.format("同一中介本人名下证件号码[%s]的亲属已存在，请勿重复导入", relativeExcel.getPersonId()));
                }
                if (!processedRelativeCombinations.add(combination)) {
                    throw new RuntimeException(String.format("同一中介本人名下证件号码[%s]的亲属在导入文件中重复", relativeExcel.getPersonId()));
                }
                successRecords.add(buildRecord(relativeExcel, userName, ownerPersonId));
            } catch (Exception e) {
                failures.add(createFailureVO(relativeExcel, e.getMessage()));
            }
        }

        if (!successRecords.isEmpty()) {
            saveBatch(successRecords, 500);
        }

        if (!failures.isEmpty()) {
            redisTemplate.opsForValue().set(failureKey(taskId), failures, 7, TimeUnit.DAYS);
        }

        ImportResult result = new ImportResult();
        result.setTotalCount(excelList.size());
        result.setSuccessCount(successRecords.size());
        result.setFailureCount(failures.size());
        updateImportStatus(taskId, result);

        long duration = System.currentTimeMillis() - startTime;
        ImportLogUtils.logImportComplete(log, taskId, "中介信息",
            excelList.size(), result.getSuccessCount(), result.getFailureCount(), duration);
    }

    @Override
    public ImportStatusVO getImportStatus(String taskId) {
        String key = statusKey(taskId);
        if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
            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<IntermediaryPersonImportFailureVO> getImportFailures(String taskId) {
        Object failuresObj = redisTemplate.opsForValue().get(failureKey(taskId));
        if (failuresObj == null) {
            return Collections.emptyList();
        }
        return JSON.parseArray(JSON.toJSONString(failuresObj), IntermediaryPersonImportFailureVO.class);
    }

    private boolean isOwnerRow(CcdiIntermediaryPersonExcel excel) {
        return "本人".equals(excel.getPersonSubType());
    }

    private void validateCommonRow(CcdiIntermediaryPersonExcel excel) {
        if (StringUtils.isEmpty(excel.getName())) {
            throw new RuntimeException("姓名不能为空");
        }
        if (StringUtils.isEmpty(excel.getPersonSubType())) {
            throw new RuntimeException("人员子类型不能为空");
        }
        if (StringUtils.isEmpty(excel.getPersonId())) {
            throw new RuntimeException("证件号码不能为空");
        }
        String idCardError = IdCardUtil.getErrorMessage(excel.getPersonId());
        if (idCardError != null) {
            throw new RuntimeException("证件号码" + idCardError);
        }
    }

    private void validateOwnerRow(CcdiIntermediaryPersonExcel excel) {
        if (StringUtils.isNotEmpty(excel.getRelatedNumId())) {
            throw new RuntimeException("本人行关联中介本人证件号码必须为空");
        }
    }

    private void validateRelativeRow(CcdiIntermediaryPersonExcel excel) {
        if (StringUtils.isEmpty(excel.getRelatedNumId())) {
            throw new RuntimeException("亲属行必须填写关联中介本人证件号码");
        }
    }

    private Set<String> getExistingOwnerPersonIds(List<CcdiIntermediaryPersonExcel> ownerRows) {
        List<String> ownerPersonIds = ownerRows.stream()
            .map(CcdiIntermediaryPersonExcel::getPersonId)
            .filter(StringUtils::isNotEmpty)
            .distinct()
            .collect(Collectors.toList());
        if (ownerPersonIds.isEmpty()) {
            return Collections.emptySet();
        }

        LambdaQueryWrapper<CcdiBizIntermediary> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CcdiBizIntermediary::getPersonSubType, "本人")
            .in(CcdiBizIntermediary::getPersonId, ownerPersonIds);
        return intermediaryMapper.selectList(wrapper).stream()
            .map(CcdiBizIntermediary::getPersonId)
            .collect(Collectors.toSet());
    }

    private Set<String> getExistingOwnerRefs(List<CcdiIntermediaryPersonExcel> relativeRows) {
        List<String> ownerRefs = relativeRows.stream()
            .map(CcdiIntermediaryPersonExcel::getRelatedNumId)
            .filter(StringUtils::isNotEmpty)
            .distinct()
            .collect(Collectors.toList());
        if (ownerRefs.isEmpty()) {
            return Collections.emptySet();
        }

        LambdaQueryWrapper<CcdiBizIntermediary> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CcdiBizIntermediary::getPersonSubType, "本人")
            .in(CcdiBizIntermediary::getPersonId, ownerRefs);
        return intermediaryMapper.selectList(wrapper).stream()
            .map(CcdiBizIntermediary::getPersonId)
            .collect(Collectors.toSet());
    }

    private Set<String> getExistingRelativeCombinations(List<CcdiIntermediaryPersonExcel> relativeRows) {
        List<String> ownerRefs = relativeRows.stream()
            .map(CcdiIntermediaryPersonExcel::getRelatedNumId)
            .filter(StringUtils::isNotEmpty)
            .distinct()
            .collect(Collectors.toList());
        List<String> relativePersonIds = relativeRows.stream()
            .map(CcdiIntermediaryPersonExcel::getPersonId)
            .filter(StringUtils::isNotEmpty)
            .distinct()
            .collect(Collectors.toList());
        if (ownerRefs.isEmpty() || relativePersonIds.isEmpty()) {
            return Collections.emptySet();
        }

        LambdaQueryWrapper<CcdiBizIntermediary> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(CcdiBizIntermediary::getPersonSubType, "本人")
            .in(CcdiBizIntermediary::getRelatedNumId, ownerRefs)
            .in(CcdiBizIntermediary::getPersonId, relativePersonIds);
        return intermediaryMapper.selectList(wrapper).stream()
            .map(item -> item.getRelatedNumId() + "|" + item.getPersonId())
            .collect(Collectors.toSet());
    }

    private CcdiBizIntermediary buildRecord(CcdiIntermediaryPersonExcel excel, String userName, String ownerPersonId) {
        CcdiBizIntermediary intermediary = new CcdiBizIntermediary();
        BeanUtils.copyProperties(excel, intermediary);
        intermediary.setRelatedNumId(ownerPersonId);
        intermediary.setDataSource("IMPORT");
        intermediary.setCreatedBy(userName);
        intermediary.setUpdatedBy(userName);
        return intermediary;
    }

    private IntermediaryPersonImportFailureVO createFailureVO(CcdiIntermediaryPersonExcel excel, String errorMsg) {
        IntermediaryPersonImportFailureVO failure = new IntermediaryPersonImportFailureVO();
        BeanUtils.copyProperties(excel, failure);
        failure.setErrorMessage(errorMsg);
        return failure;
    }

    private void saveBatch(List<CcdiBizIntermediary> list, int batchSize) {
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            intermediaryMapper.insertBatch(list.subList(i, end));
        }
    }

    private void updateImportStatus(String taskId, ImportResult result) {
        Map<String, Object> statusData = new HashMap<>();
        statusData.put("status", result.getFailureCount() == 0 ? "SUCCESS" : "PARTIAL_SUCCESS");
        statusData.put("successCount", result.getSuccessCount());
        statusData.put("failureCount", result.getFailureCount());
        statusData.put("progress", 100);
        statusData.put("endTime", System.currentTimeMillis());
        statusData.put("message", result.getFailureCount() == 0
            ? "全部成功!共导入" + result.getTotalCount() + "条数据"
            : "成功" + result.getSuccessCount() + "条,失败" + result.getFailureCount() + "条");
        redisTemplate.opsForHash().putAll(statusKey(taskId), statusData);
    }

    private String statusKey(String taskId) {
        return STATUS_KEY_PREFIX + taskId;
    }

    private String failureKey(String taskId) {
        return statusKey(taskId) + ":failures";
    }
}
