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

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.collection.domain.CcdiAssetInfo;
import com.ruoyi.info.collection.domain.excel.CcdiBaseStaffAssetInfoExcel;
import com.ruoyi.info.collection.domain.vo.BaseStaffAssetImportFailureVO;
import com.ruoyi.info.collection.domain.vo.ImportResult;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.mapper.CcdiAssetInfoMapper;
import com.ruoyi.info.collection.service.ICcdiBaseStaffAssetImportService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
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.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 员工资产信息异步导入服务层处理
 *
 * @author ruoyi
 * @date 2026-03-13
 */
@Service
@EnableAsync
public class CcdiBaseStaffAssetImportServiceImpl implements ICcdiBaseStaffAssetImportService {

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

    @Resource
    private CcdiAssetInfoMapper assetInfoMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Lazy
    @Resource
    private ICcdiBaseStaffAssetImportService baseStaffAssetImportService;

    @Override
    @Transactional
    public String importAssetInfo(List<CcdiBaseStaffAssetInfoExcel> excelList) {
        if (excelList == null || excelList.isEmpty()) {
            throw new RuntimeException("至少需要一条数据");
        }

        String taskId = UUID.randomUUID().toString();
        Map<String, Object> statusData = new HashMap<>();
        statusData.put("taskId", taskId);
        statusData.put("status", "PROCESSING");
        statusData.put("totalCount", excelList.size());
        statusData.put("successCount", 0);
        statusData.put("failureCount", 0);
        statusData.put("progress", 0);
        statusData.put("startTime", System.currentTimeMillis());
        statusData.put("message", "正在处理...");

        String statusKey = STATUS_KEY_PREFIX + taskId;
        redisTemplate.opsForHash().putAll(statusKey, statusData);
        redisTemplate.expire(statusKey, 7, TimeUnit.DAYS);

        baseStaffAssetImportService.importAssetInfoAsync(excelList, taskId, currentUserName());
        return taskId;
    }

    @Override
    @Async
    @Transactional
    public void importAssetInfoAsync(List<CcdiBaseStaffAssetInfoExcel> excelList, String taskId, String userName) {
        importAssetInfoSync(excelList, taskId, userName, Map.of());
    }

    @Override
    @Transactional
    public void importAssetInfoSync(List<CcdiBaseStaffAssetInfoExcel> excelList,
                                    String taskId,
                                    String userName,
                                    Map<String, Set<String>> extraOwnerMappings) {
        List<CcdiAssetInfo> successList = new ArrayList<>();
        List<BaseStaffAssetImportFailureVO> failures = new ArrayList<>();

        List<String> personIds = excelList.stream()
                .map(CcdiBaseStaffAssetInfoExcel::getPersonId)
                .filter(StringUtils::isNotEmpty)
                .distinct()
                .toList();

        Map<String, Set<String>> ownerMap = buildOwnerMap(personIds);
        mergeOwnerMappings(ownerMap, extraOwnerMappings);
        Set<String> existingAssetKeys = buildExistingAssetKeys(personIds);
        Set<String> importedAssetKeys = new java.util.LinkedHashSet<>();

        for (int i = 0; i < excelList.size(); i++) {
            CcdiBaseStaffAssetInfoExcel excel = excelList.get(i);
            try {
                validateExcel(excel);
                Set<String> familyIds = ownerMap.get(excel.getPersonId());
                if (familyIds == null || familyIds.isEmpty()) {
                    throw new RuntimeException("员工资产导入仅支持员工本人证件号");
                }
                String assetKey = buildAssetKey(excel.getPersonId(), excel.getAssetMainType(), excel.getAssetSubType(), excel.getAssetName());
                if (existingAssetKeys.contains(assetKey)) {
                    throw new RuntimeException("资产记录已存在");
                }
                if (!importedAssetKeys.add(assetKey)) {
                    throw new RuntimeException("资产记录在导入文件中重复");
                }

                CcdiAssetInfo assetInfo = new CcdiAssetInfo();
                BeanUtils.copyProperties(excel, assetInfo);
                assetInfo.setFamilyId(excel.getPersonId());
                assetInfo.setPersonId(excel.getPersonId());
                assetInfo.setCreateBy(userName);
                assetInfo.setUpdateBy(userName);
                successList.add(assetInfo);
            } catch (Exception e) {
                BaseStaffAssetImportFailureVO failureVO = new BaseStaffAssetImportFailureVO();
                BeanUtils.copyProperties(excel, failureVO);
                failureVO.setSheetName("员工资产信息");
                failureVO.setRowNum(i + 2);
                failureVO.setErrorMessage(e.getMessage());
                failures.add(failureVO);
            }
        }

        if (!successList.isEmpty()) {
            assetInfoMapper.insertBatch(successList);
        }

        if (!failures.isEmpty()) {
            redisTemplate.opsForValue().set(STATUS_KEY_PREFIX + taskId + ":failures", failures, 7, TimeUnit.DAYS);
        }

        ImportResult result = new ImportResult();
        result.setTotalCount(excelList.size());
        result.setSuccessCount(successList.size());
        result.setFailureCount(failures.size());
        updateImportStatus(taskId, failures.isEmpty() ? "SUCCESS" : "PARTIAL_SUCCESS", result);
    }

    @Override
    public ImportStatusVO getImportStatus(String taskId) {
        String key = STATUS_KEY_PREFIX + 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<BaseStaffAssetImportFailureVO> getImportFailures(String taskId) {
        Object failuresObj = redisTemplate.opsForValue().get(STATUS_KEY_PREFIX + taskId + ":failures");
        if (failuresObj == null) {
            return List.of();
        }
        return JSON.parseArray(JSON.toJSONString(failuresObj), BaseStaffAssetImportFailureVO.class);
    }

    private Map<String, Set<String>> buildOwnerMap(List<String> personIds) {
        Map<String, Set<String>> result = new LinkedHashMap<>();
        if (personIds == null || personIds.isEmpty()) {
            return result;
        }
        mergeOwnerMappings(result, assetInfoMapper.selectOwnerCandidatesByBaseStaffIdCards(personIds));
        return result;
    }

    private Set<String> buildExistingAssetKeys(List<String> personIds) {
        if (personIds == null || personIds.isEmpty()) {
            return Set.of();
        }
        LambdaQueryWrapper<CcdiAssetInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CcdiAssetInfo::getPersonId, personIds);
        return assetInfoMapper.selectList(wrapper).stream()
                .filter(asset -> StringUtils.equals(asset.getFamilyId(), asset.getPersonId()))
                .map(asset -> buildAssetKey(asset.getPersonId(), asset.getAssetMainType(), asset.getAssetSubType(), asset.getAssetName()))
                .collect(java.util.stream.Collectors.toCollection(java.util.LinkedHashSet::new));
    }

    private void mergeOwnerMappings(Map<String, Set<String>> result, List<Map<String, String>> mappings) {
        if (mappings == null) {
            return;
        }
        for (Map<String, String> mapping : mappings) {
            String personId = mapping.get("personId");
            String familyId = mapping.get("familyId");
            if (StringUtils.isEmpty(personId) || StringUtils.isEmpty(familyId)) {
                continue;
            }
            result.computeIfAbsent(personId, key -> new java.util.LinkedHashSet<>()).add(familyId);
        }
    }

    private void mergeOwnerMappings(Map<String, Set<String>> result, Map<String, Set<String>> mappings) {
        if (mappings == null || mappings.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Set<String>> entry : mappings.entrySet()) {
            if (StringUtils.isEmpty(entry.getKey()) || entry.getValue() == null || entry.getValue().isEmpty()) {
                continue;
            }
            result.computeIfAbsent(entry.getKey(), key -> new java.util.LinkedHashSet<>()).addAll(entry.getValue());
        }
    }

    private void validateExcel(CcdiBaseStaffAssetInfoExcel excel) {
        if (StringUtils.isEmpty(excel.getPersonId())) {
            throw new RuntimeException("员工身份证号不能为空");
        }
        if (StringUtils.isEmpty(excel.getAssetMainType())) {
            throw new RuntimeException("资产大类不能为空");
        }
        if (StringUtils.isEmpty(excel.getAssetSubType())) {
            throw new RuntimeException("资产小类不能为空");
        }
        if (StringUtils.isEmpty(excel.getAssetName())) {
            throw new RuntimeException("资产名称不能为空");
        }
        if (excel.getCurrentValue() == null) {
            throw new RuntimeException("当前估值不能为空");
        }
        if (StringUtils.isEmpty(excel.getAssetStatus())) {
            throw new RuntimeException("资产状态不能为空");
        }
    }

    private String buildAssetKey(String personId, String assetMainType, String assetSubType, String assetName) {
        return String.join("|",
                StringUtils.nvl(personId, ""),
                StringUtils.nvl(assetMainType, ""),
                StringUtils.nvl(assetSubType, ""),
                StringUtils.nvl(assetName, ""));
    }

    private void updateImportStatus(String taskId, String status, ImportResult result) {
        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());
        statusData.put("message", "SUCCESS".equals(status)
                ? "全部成功!共导入" + result.getTotalCount() + "条数据"
                : "成功" + result.getSuccessCount() + "条,失败" + result.getFailureCount() + "条");
        redisTemplate.opsForHash().putAll(STATUS_KEY_PREFIX + taskId, statusData);
    }

    private String currentUserName() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            return "system";
        }
    }
}
