package com.zksy.basicData.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zksy.basicData.mapper.*;
import com.zksy.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class InformationService {
    @Resource
    private XcrEBaseinfoMapper xcrEBaseinfoMapper;//企业基本信息
    @Resource
    private XcrEnterpriseAnnualReportShareholderMapper xcrEnterpriseAnnualReportShareholderMapper;//企业年报股东及出资信息
    @Resource
    private XcrChangeFilingMapper xcrChangeFilingMapper;//变更备案信息
    @Resource
    private XcrBranchOfficesInfoMapper xcrBranchOfficesInfoMapper;//分支机构

    @Resource
    private XcrAnnualReportExternalInvestmentMapper xcrAnnualReportExternalInvestmentMapper;//企业年报对外投资信息
    @Resource
    private XcrAdministrativeLicensingMapper xcrAdministrativeLicensingMapper;//行政许可
    //资质证书
    //企业认证信息
    //企业商标
    //专利
    //软件著作权
    //社会荣誉
    //行业信用评价结果
    //第三方信用评价结果
    //企业社会责任（大类）
    @Resource
    private XcrAnnualReportBaseInfoMapper xcrAnnualReportBaseInfoMapper;//企业年报
    //招投标中标信息
    //项目业绩
    //抽查结果信息
    @Resource
    private XcrInspectionResultsMapper xcrInspectionResultsMapper;//抽查结果信息
    //纳税缴交信息
    @Resource
    private XcrOtherInfo36Mapper xcrOtherInfo36Mapper;//行政奖励，水费，电费，燃气费，行政监督检查，行政强制，严重失信主体名单信息
    @Resource
    private XcrAbnormalBusinessOperationsMapper xcrAbnormalBusinessOperationsMapper;//经营异常名录信息
    @Resource
    private XcrAdministrativePenaltyMapper xcrAdministrativePenaltyMapper;//行政处罚
    @Resource
    private XcrSeriousIllegalDishonestEnterprisesMapper xcrSeriousIllegalDishonestEnterprisesMapper;//严重违法失信企业名单
    //司法拍卖
    //被执行人
    //失信被执行人
    //限制消费
    //破产公告
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    private List<BaseMapper<?>> mappers;
    @PostConstruct
    public void init() {
        this.mappers = Arrays.asList(xcrEBaseinfoMapper,xcrEnterpriseAnnualReportShareholderMapper,xcrChangeFilingMapper,
                xcrBranchOfficesInfoMapper,xcrAnnualReportExternalInvestmentMapper,xcrAdministrativeLicensingMapper,
                xcrAnnualReportBaseInfoMapper,xcrInspectionResultsMapper,xcrOtherInfo36Mapper, xcrAbnormalBusinessOperationsMapper,
                xcrAdministrativePenaltyMapper,xcrSeriousIllegalDishonestEnterprisesMapper);
    }
    public AjaxResult queryByCreditCode(String creditCode) {
        Map<String, List<?>> resultMap = new ConcurrentHashMap<>();

        List<CompletableFuture<Void>> futures = mappers.stream()
                .map(mapper -> CompletableFuture.runAsync(() -> {
                    try {
                        List<?> result = queryFromMapper(mapper, creditCode);
                            String mapperName = getOriginalClassName(mapper);
                            resultMap.put(mapperName, result);

                    } catch (Exception e) {
                        // 记录异常日志
                        log.error("查询失败: " + mapper.getClass().getName(), e);
                    }
                }, taskExecutor))
                .collect(Collectors.toList());

        // 等待所有异步任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        return AjaxResult.success("查询成功", resultMap);
    }

    private <T> List<T> queryFromMapper(BaseMapper<T> mapper, String creditCode) {
        try {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uni_code", creditCode);
            List<T> ts = mapper.selectList(queryWrapper);
            return ts;
        } catch (Exception e) {
            // 记录异常日志
            log.error("查询失败: " + mapper.getClass().getName(), e);
            return null;
        }
    }
    private String getOriginalClassName(Object obj) {
        Class<?>[] interfaces = obj.getClass().getInterfaces();
        for (Class<?> iface : interfaces) {
            String className = iface.getSimpleName();
            // 去掉前缀 "Xcr" 和后缀 "Mapper"
            if (className.startsWith("Xcr") && className.endsWith("Mapper")) {
                return className.substring(3, className.length() - 6);
            }
        }
        return obj.getClass().getSimpleName();
    }


}