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.CcdiIntermediaryEnterpriseRelation;
import com.ruoyi.info.collection.domain.excel.CcdiIntermediaryEnterpriseRelationExcel;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.IntermediaryEnterpriseRelationImportFailureVO;
import com.ruoyi.info.collection.enums.DataSource;
import com.ruoyi.info.collection.enums.EnterpriseSource;
import com.ruoyi.info.collection.mapper.CcdiBizIntermediaryMapper;
import com.ruoyi.info.collection.mapper.CcdiIntermediaryEnterpriseRelationMapper;
import com.ruoyi.info.collection.service.ICcdiIntermediaryEnterpriseRelationImportService;
import com.ruoyi.info.collection.service.support.EnterpriseAutoFillService;
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 CcdiIntermediaryEnterpriseRelationImportServiceImpl implements ICcdiIntermediaryEnterpriseRelationImportService {

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

    private static final String STATUS_KEY_PREFIX = "import:intermediary-enterprise-relation:";

    @Resource
    private CcdiIntermediaryEnterpriseRelationMapper relationMapper;

    @Resource
    private CcdiBizIntermediaryMapper intermediaryMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private EnterpriseAutoFillService enterpriseAutoFillService;

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void importAsync(List<CcdiIntermediaryEnterpriseRelationExcel> excelList, String taskId, String userName) {
        long startTime = System.currentTimeMillis();
        ImportLogUtils.logImportStart(log, taskId, "中介实体关联关系", excelList.size(), userName);

        Map<String, String> ownerBizIdByPersonId = getOwnerBizIdByPersonId(excelList);
        Set<String> existingCombinations = getExistingRelationCombinations(ownerBizIdByPersonId, excelList);

        List<CcdiIntermediaryEnterpriseRelation> successRecords = new ArrayList<>();
        List<IntermediaryEnterpriseRelationImportFailureVO> failures = new ArrayList<>();
        Set<String> processedCombinations = new HashSet<>();

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

                String ownerPersonId = trim(excel.getOwnerPersonId());
                String socialCreditCode = trim(excel.getSocialCreditCode());
                String ownerBizId = ownerBizIdByPersonId.get(ownerPersonId);
                if (StringUtils.isEmpty(ownerBizId)) {
                    throw new RuntimeException("中介本人不存在，请先导入或维护中介本人信息");
                }

                String combination = ownerBizId + "|" + socialCreditCode;
                if (existingCombinations.contains(combination)) {
                    throw new RuntimeException("中介实体关联关系已存在，请勿重复导入");
                }
                if (!processedCombinations.add(combination)) {
                    throw new RuntimeException("同一中介本人与统一社会信用代码组合在导入文件中重复");
                }

                CcdiIntermediaryEnterpriseRelation relation = new CcdiIntermediaryEnterpriseRelation();
                BeanUtils.copyProperties(excel, relation);
                relation.setIntermediaryBizId(ownerBizId);
                relation.setSocialCreditCode(socialCreditCode);
                relation.setRelationPersonPost(trim(excel.getRelationPersonPost()));
                relation.setRemark(trim(excel.getRemark()));
                relation.setCreatedBy(userName);
                relation.setUpdatedBy(userName);
                successRecords.add(relation);
            } catch (Exception e) {
                failures.add(createFailureVO(excel, e.getMessage()));
                ImportLogUtils.logValidationError(log, taskId, i + 1, e.getMessage(),
                    String.format("中介本人证件号码=%s, 统一社会信用代码=%s", excel.getOwnerPersonId(), excel.getSocialCreditCode()));
            }
        }

        if (!successRecords.isEmpty()) {
            enterpriseAutoFillService.ensureExistsBatch(successRecords.stream()
                .map(item -> new EnterpriseAutoFillService.EnterpriseFillItem(
                    item.getSocialCreditCode(),
                    null,
                    EnterpriseSource.INTERMEDIARY.getCode(),
                    DataSource.IMPORT.getCode(),
                    userName
                ))
                .toList());
            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<IntermediaryEnterpriseRelationImportFailureVO> getImportFailures(String taskId) {
        Object failuresObj = redisTemplate.opsForValue().get(failureKey(taskId));
        if (failuresObj == null) {
            return Collections.emptyList();
        }
        return JSON.parseArray(JSON.toJSONString(failuresObj), IntermediaryEnterpriseRelationImportFailureVO.class);
    }

    private Map<String, String> getOwnerBizIdByPersonId(List<CcdiIntermediaryEnterpriseRelationExcel> excelList) {
        List<String> ownerPersonIds = excelList.stream()
            .map(CcdiIntermediaryEnterpriseRelationExcel::getOwnerPersonId)
            .map(this::trim)
            .filter(StringUtils::isNotEmpty)
            .distinct()
            .collect(Collectors.toList());
        if (ownerPersonIds.isEmpty()) {
            return Collections.emptyMap();
        }

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

    private Set<String> getExistingRelationCombinations(Map<String, String> ownerBizIdByPersonId,
                                                        List<CcdiIntermediaryEnterpriseRelationExcel> excelList) {
        List<String> combinations = excelList.stream()
            .map(excel -> {
                String ownerBizId = ownerBizIdByPersonId.get(trim(excel.getOwnerPersonId()));
                String socialCreditCode = trim(excel.getSocialCreditCode());
                if (StringUtils.isEmpty(ownerBizId) || StringUtils.isEmpty(socialCreditCode)) {
                    return null;
                }
                return ownerBizId + "|" + socialCreditCode;
            })
            .filter(StringUtils::isNotEmpty)
            .distinct()
            .collect(Collectors.toList());
        if (combinations.isEmpty()) {
            return Collections.emptySet();
        }
        return new HashSet<>(relationMapper.batchExistsByCombinations(combinations));
    }

    private void validateExcel(CcdiIntermediaryEnterpriseRelationExcel excel) {
        String ownerPersonId = trim(excel.getOwnerPersonId());
        String socialCreditCode = trim(excel.getSocialCreditCode());
        String relationPersonPost = trim(excel.getRelationPersonPost());
        String remark = trim(excel.getRemark());

        if (StringUtils.isEmpty(ownerPersonId)) {
            throw new RuntimeException("中介本人证件号码不能为空");
        }
        if (StringUtils.isEmpty(socialCreditCode)) {
            throw new RuntimeException("统一社会信用代码不能为空");
        }
        String ownerPersonIdError = IdCardUtil.getErrorMessage(ownerPersonId);
        if (ownerPersonIdError != null) {
            throw new RuntimeException("中介本人证件号码" + ownerPersonIdError);
        }
        if (StringUtils.isNotEmpty(relationPersonPost) && relationPersonPost.length() > 100) {
            throw new RuntimeException("关联职务长度不能超过100个字符");
        }
        if (StringUtils.isNotEmpty(remark) && remark.length() > 500) {
            throw new RuntimeException("备注长度不能超过500个字符");
        }
    }

    private String trim(String value) {
        return value == null ? null : value.trim();
    }

    private IntermediaryEnterpriseRelationImportFailureVO createFailureVO(CcdiIntermediaryEnterpriseRelationExcel excel,
                                                                          String errorMessage) {
        IntermediaryEnterpriseRelationImportFailureVO failure = new IntermediaryEnterpriseRelationImportFailureVO();
        BeanUtils.copyProperties(excel, failure);
        failure.setErrorMessage(errorMessage);
        return failure;
    }

    private void saveBatch(List<CcdiIntermediaryEnterpriseRelation> list, int batchSize) {
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            relationMapper.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";
    }
}
