//初始化企查查数据

import { systemConfig } from "../config/serverConfig";
import { onceSheetBecomeOfblockData } from "../util/analysisExcel";
const md5 = require("md5");
import moment = require("moment");
import { getQcc } from "../util/request";
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { operationalData, selectData } from "../data/operationalData";
import { getMySqlMs, getPinyinInitials, getPwdMd5, randomId } from "../tools/system";
import { FINANCINGROUNDS } from "../config/enum/enum";
const xlsx = require('node-xlsx');
const path = require('path');
const fs = require('fs');


/**
 * 迁移所有企业用户的密码为加密格式
 */
export async function migrateEnterpriseUserPasswords() {
    try {
        // 获取所有企业用户
        const enterpriseUsers = await selectData(
            OPERATIONALDATATYPE.查询多个,
            TABLENAME.企业用户表,
            {},
            ["uId", "uscc", "pwd", "userName"]
        );

        if (!enterpriseUsers || enterpriseUsers.length === 0) {
            console.log("没有找到需要迁移的企业用户");
            return { success: true, migrated: 0 };
        }

        let migratedCount = 0;
        
        // 遍历所有用户并更新密码
        for (const user of enterpriseUsers) {
            // 跳过已经加密的密码（假设加密后的密码长度为32位）
            if (user.pwd && user.pwd.length === 32) {
                console.log(`用户 ${user.uscc} 的密码已经加密，跳过`);
                continue;
            }
            
            // 使用uId作为盐值进行加密
            const encryptedPwd = getPwdMd5(user.uId, user.pwd);
            
            // 更新数据库中的密码
            await operationalData(
                OPERATIONALDATATYPE.修改,
                TABLENAME.企业用户表,
                { pwd: encryptedPwd },
                { uId: user.uId }
            );
            
            migratedCount++;
            console.log(`已迁移用户 ${user.userName} 的密码`);
        }
        
        console.log(`企业用户密码迁移完成，共迁移了 ${migratedCount} 个用户`);
        return { success: true, migrated: migratedCount };
    } catch (error) {
        console.error("企业用户密码迁移过程中发生错误:", error);
        return { success: false, error: error.message };
    }
}


/**
 * 迁移所有企业用户的密码为加密格式
 */
 export async function migrateAdminPasswords() {
    try {
        // 获取所有企业用户
        const enterpriseUsers = await selectData(
            OPERATIONALDATATYPE.查询多个,
            TABLENAME.管理后台用户,
            {},
            ["aId", "loginId", "pwd", "name"]
        );

        if (!enterpriseUsers || enterpriseUsers.length === 0) {
            console.log("没有找到需要迁移的企业用户");
            return { success: true, migrated: 0 };
        }

        let migratedCount = 0;
        
        // 遍历所有用户并更新密码
        for (const user of enterpriseUsers) {
            // 跳过已经加密的密码（假设加密后的密码长度为32位）
            if (user.pwd && user.pwd.length === 32) {
                console.log(`用户 ${user.loginId} 的密码已经加密，跳过`);
                continue;
            }
            
            // 使用aId作为盐值进行加密
            const encryptedPwd = getPwdMd5(user.aId, user.pwd);
            
            // 更新数据库中的密码
            await operationalData(
                OPERATIONALDATATYPE.修改,
                TABLENAME.管理后台用户,
                { pwd: encryptedPwd },
                { aId: user.aId }
            );
            
            migratedCount++;
            console.log(`已迁移用户 ${user.name} 的密码`);
        }
        
        console.log(`企业用户密码迁移完成，共迁移了 ${migratedCount} 个用户`);
        return { success: true, migrated: migratedCount };
    } catch (error) {
        console.error("企业用户密码迁移过程中发生错误:", error);
        return { success: false, error: error.message };
    }
}


/**
 * 获取当个excel文件数据
 * @param filePath 
 * @returns 
 */
function getExcel(filePath) {
    const workSheetsFromFile = xlsx.parse(filePath);
    let sheetMap = {};
    let sheetList = [];

    for (let i = 0; i < workSheetsFromFile.length; i++) {
        let sheetInfo = workSheetsFromFile[i];
        sheetMap[sheetInfo.name] = sheetInfo.data;
        sheetList.push(sheetInfo);
    }

    return {sheetMap, sheetList}  
}

/**
 * 用于统计当前所有企业的企查查数据完整度
 */
export async function 统计() {
    let iMap = 领域补充();
    let fuhuaqiExcelData = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '在孵企业导入_孵化器提供1210.xlsx' ));
    let data2List = fuhuaqiExcelData.sheetMap['雨艺孵化器孵化企业明细'];
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '在孵企业导入1210.xlsx' ));
    let dataList = sheetMap['Sheet1'];

    let usccMap = {};
    dataList.forEach(subList => {
        usccMap[subList[0]] = subList[6];
    })

    let dataMap = {};
    for (let i = 0; i < data2List.length; i++) {
        let subList= data2List[i];
        if (!i) continue;
        let uscc = usccMap[subList[1]];
        let industry = iMap[uscc];
        let 室号 = subList[3];
        let 楼栋 = 室号.substring(0, 室号.indexOf("-"));
        if (industry) {
            if (industry.indexOf(",") > -1) industry = industry.substring(0, industry.indexOf(","));
            else industry = industry;
            
        } else {
            industry = "";
            console.log(楼栋, subList[1])
        }

        let 规模 = await 获取规模(uscc);
        
        if (!dataMap[楼栋]) dataMap[楼栋] = {};
        if (!dataMap[楼栋][industry]) dataMap[楼栋][industry] = {};
        if (!dataMap[楼栋][industry][规模]) dataMap[楼栋][industry][规模] = 0;
        dataMap[楼栋][industry][规模] += 1;
        console.log();
    }
   
    console.log();
}


/**
 * 测试用
 */
export async function test() {
    let uscc = "91310115MADM8EA654";
    await 工商信息(uscc);
    await 软件著作查询(uscc);
    await 国际专利(uscc);
    await 专利查询(uscc);
    await 融资信息核查(uscc);
    console.log();
}

export async function 获取规模(uscc) {
    let {header, query} = getReqParam(uscc);
    
    let 工商信息:any = await getQcc('https://api.qichacha.com/CustomerDueDiligence/KYC', query, header);//获取工商信息
    
    return 工商信息.Data.Scale;
}

export async function qccData() {
    let iMap = await 领域补充();
    let 企业名单 = onceSheetBecomeOfblockData('在孵企业导入1210.xlsx', "Sheet1");
    let dataList = 企业名单[0].blockData;
    let titleList = ["企业名称", "注册时间", "注册地址", "注册资本", "实缴资本", "上市类型", "投资人", "联系方式", "行业分类", "标签", "软著", "风险提示", "专利数", "失信核查", "资质数量", "融资信息"];
  
    for (let i =1; i < dataList.length; i++) {

        let uscc = dataList[i][6];
        if (!iMap[uscc]) {
            console.log(dataList[i][0]);
            continue
        }

        await awaitData(uscc);
        console.log(`${dataList[i][1]} 同步成功, 下标 ${i}`);
    }
    let enterpriseList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业基础信息表, {}, ["eId", "uscc", "enterpriseName"]);

    //导出成excel表格

}

/**
 * 封装了一个请求方法
 * @param uscc 
 * @returns 
 */
function getReqParam(uscc, isKeyNo?) {
    const TimeSpan = Math.round(new Date().valueOf()/ 1000);
    let header = {
        Token:md5(`${systemConfig.qccKey}${TimeSpan}${systemConfig.qccSecretKey}`).toUpperCase(),
        TimeSpan
    };
    let query = {};
    if (isKeyNo == "isKeyNo") {
        query = {
            key:systemConfig.qccKey,
            keyNo:uscc,
        };
    } else if (isKeyNo == "Id") {
        query = {
            key:systemConfig.qccKey,
            id:uscc,
        };
    } else if (isKeyNo == "certId") {
        query = {
            key:systemConfig.qccKey,
            certId:uscc,
        };
    } else if (isKeyNo == "企业名称") {
        query = {
            key:systemConfig.qccKey,
            keyword:uscc,
        }
    } else {
        query = {
            key:systemConfig.qccKey,
            searchKey:uscc,
            // keyNo:"云合智网（上海）技术有限公司"
        };
    }
    return {header, query};
}


async function addManyData(tableName, dataList) {
    for (let i= 0; i < dataList.length; i++) {
        let info = dataList[i];

        await operationalData(OPERATIONALDATATYPE.增加, tableName, info, null); 

    }
    console.log(tableName, "写入成功");
}

export async function awaitData(uscc:string) {
    let 商标查询Data = await 商标查询(uscc);
    let 专利查询Data = await 专利查询(uscc);
    let 作品著作查询Data = await 作品著作查询(uscc);
    let 软件著作Data = await 软件著作查询(uscc);
    let 备案网站Data = await 备案网站查询(uscc);
    let 资质证书Data = await 资质证书查询(uscc);
    // let 工商信息Data = await 工商信息(uscc);
    // let 软件著作Data = await 软件著作(uscc);
    // let 主要人员Data = await 主要人员(uscc);
    // let 分支机构Data = await 分支机构(uscc);
    // let 行政许可核查Data = await 行政许可核查(uscc);
    // let 空壳扫描Data = await 空壳扫描(uscc);
    // let 准入尽职调查Data = await 准入尽职调查(uscc);
    // let 融资信息核查Data = await 融资信息核查(uscc);
    // let 国际专利Data = await 国际专利(uscc);
    // let 科创分Data = await 科创分(uscc);
    // let 资质证书Data = await 资质证书(uscc);
    // let 失信核查Data = await 失信核查(uscc);
    // let 严重违法核查Data = await 严重违法核查(uscc);
    // let 企业对外投资核查Data = await 企业对外投资核查(uscc);
    // let 企业年报信息Data = await 企业年报信息(uscc);

    let initData = {
        // 工商信息Data, 
        // 软件著作Data, 
        // 主要人员Data, 
        // 分支机构Data, 
        // 行政许可核查Data, 
        // 空壳扫描Data, 
        // 准入尽职调查Data, 
        // 融资信息核查Data, 
        // 国际专利Data, 
        // 科创分Data, 
        // 资质证书Data, 
        商标查询Data,
        专利查询Data, 
        作品著作查询Data, 
        软件著作Data, 
        备案网站Data, 
        资质证书Data, 
        // 失信核查Data, 
        // 严重违法核查Data, 
        // 企业对外投资核查Data, 
        // 企业年报信息Data, 
    }
    console.log("企查查数据同步成功");

    return initData;
}


async function 商标查询(uscc) {
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId", "enterpriseName"]);
    let enterpriseName = enterpriseInfo.enterpriseName;
    let {header, query} = getReqParam(enterpriseName, "企业名称");

    let 商标查询:any = await getQcc('https://api.qichacha.com/tm/SearchByApplicant', query, header);
    if (Array.isArray(商标查询)) {
        for (let i = 0; i < 商标查询.length; i++) {
            let Id = 商标查询[i].ID;
            let qcc商标详情= await 商标详情查询(uscc, Id);
            商标查询[i]["qcc商标详情"] = qcc商标详情;
        }
    }

    return 商标查询;
}


async function 商标详情查询(uscc, id) {
    let {header, query} = getReqParam(id, "Id");
    let qccselectdata:any = await getQcc('https://api.qichacha.com/tm/GetDetails', query, header);
    
    return qccselectdata;
}


async function 专利查询(uscc) {
    // let {header, query} = getReqParam(uscc);
    // let qccselectdata:any = await getQcc('https://api.qichacha.com/PatentV4/SearchMultiPatents', query, header);

    // if (Array.isArray(qccselectdata)) {
    //     let addList = [];
    //     for (let i = 0; i < qccselectdata.length; i++) {
    //         let qcc专利详情 = {};
    //         let info = qccselectdata[i];
    //         let qcc专利Id = info.Id;
    //         qccselectdata[i]["qcc专利详情"] = await 专利详情查询(qcc专利Id);

    //         addList.push({
    //             iprId:randomId(TABLEID.知识产权),
    //         });
    //     }

    // }

    // return qccselectdata;
}


async function 专利详情查询(id) {
    let {header, query} = getReqParam(id, "Id");
    let qccselectdata:any = await getQcc('https://api.qichacha.com/PatentV4/GetDetails', query, header);
    
    return qccselectdata;
}


async function 作品著作查询(uscc) {
    let {header, query} = getReqParam(uscc);

    let 作品著作查询:any = await getQcc('https://api.qichacha.com/CopyRight/SearchCopyRight', query, header);
    if (Array.isArray(作品著作查询)) {
        let addList = [];
        
    }

    return 作品著作查询;
}


async function 软件著作查询(uscc) {
    let {header, query} = getReqParam(uscc);

    let 软件著作查询:any = await getQcc('https://api.qichacha.com/CopyRight/SearchSoftwareCr', query, header);
    // let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    // let eId = enterpriseInfo.eId;

    if (Array.isArray(软件著作查询)) {
        let addList = [];
    //     著作权软著.forEach(info => {
    //         addList.push({
    //             iprId:randomId(TABLEID.知识产权),
    //             eId,
    //             year:getMySqlMs(info.RegisterDate),
    //             number:1,
    //             iprType:IPRALLTYPE.软件著作权,
    //             iprName:info.Name,
    //             category:info.Category,
    //         });
    //     });

    //     await addManyData(TABLENAME.知识产权, addList);
    }

    return 软件著作查询;
}


async function 备案网站查询(uscc) {
    let {header, query} = getReqParam(uscc);

    let 备案网站查询:any = await getQcc('https://api.qichacha.com/WebSiteV4/GetCompanyWebSite', query, header);
    if (Array.isArray(备案网站查询)) {
        let addList = [];
        
    }

    return 备案网站查询;
}


async function 资质证书查询(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ECICertification/SearchCertification', query, header);
    // let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    // let eId = enterpriseInfo.eId;

    if (Array.isArray(qccselectdata)) {
        let addList = [];
        for (let i = 0; i < qccselectdata.length; i++) {
            let qcc资质证书详情 = {};
            let info = qccselectdata[i];
            let qcc资质证书Id = info.Id;
            qccselectdata[i]["qcc资质证书详情"] = await 资质证书详情查询(qcc资质证书Id);

        }


    //     qccselectdata.forEach(info => {
    //         let addInfo:any = {
    //             cerId:randomId(TABLEID.资质证书),
    //             eId,
    //             name:info.Name,
    //             type:info.Type,
    //             no:info.No,
    //             typeDesc:info.TypeDesc,
    //             institutionList:info.InstitutionList ? info.InstitutionList[0] :"",
    //             status:info.Status,
    //         };

    //         if (info.StartDate) addInfo.startDate = getMySqlMs(info.StartDate)
    //         if (info.EndDate) addInfo.endDate = getMySqlMs(info.EndDate)

    //         addList.push(addInfo);
    //     });
    //     await addManyData(TABLENAME.资质证书, addList);
    }
    
    return qccselectdata;
}


async function 资质证书详情查询(id) {
    let {header, query} = getReqParam(id, "certId");
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ECICertification/GetCertificationDetailById', query, header);
    
    return qccselectdata;
}

function 领域补充() {
    let 企业名单 = onceSheetBecomeOfblockData('科学城在孵企业.xlsx', "Sheet1");
    let dataList = 企业名单[0].blockData;

    let map = {};
    dataList.forEach((sub, index) => {
        if (!index) return;
        map[sub[6]] = sub[7];
    });

    return map;
}

async function 工商信息(uscc) {
    let {header, query} = getReqParam(uscc);
    
    let 工商信息:any = await getQcc('https://api.qichacha.com/ECIInfoVerify/GetInfo', query, header);//获取工商信息

    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;
    let pinyinName = getPinyinInitials(工商信息.Name);
    let industryList = []; //Industry
    let TermStart = moment(工商信息.TermStart).format("YYYY-MM-DD");
    let TermEnd = "无固定期限";
    if (工商信息.TermEnd) TermEnd = moment(工商信息.TermEnd).format("YYYY-MM-DD");

    //企业基础信息
    let baseInfo = {
        enterpriseName: 工商信息.Name,
        pinyinName,
        uscc: 工商信息.CreditCode,
        zhuCeHao: 工商信息.No, //EntType = 0/1/4/6/7/9/10/11/-1 中国境内企业时：该字段返回工商注册号；EntType = 3 中国香港企业时：该字段返回企业编号；EntType = 5 中国台湾企业时：该字段返回企业编号
        zuZhiJiGouDaiMa: 工商信息.OrgNo,
        // gengDuoDianHua: 工商信息., //更多电话
        // mainBusiness: 工商信息., //主营业务
        logonTime: getMySqlMs(工商信息.StartDate), //成立日期
        // mail: 工商信息., //邮箱
        // isNaturalPersonHolding: 工商信息., //是否自然人控股
        // industry: 工商信息., //领域
        // moreMail: 工商信息., //更多邮箱
        // logonAddress: 工商信息.Address, //注册地址
        // tongXinDiZhi: 工商信息., //通信地址
        // liaison: 工商信息., //联系人
        // liaisonPhone: 工商信息., //联系电话
        dengJiJiGuan: 工商信息.BelongOrg, //登机机关
        // qiYeGuiMo: 工商信息., //企业规模 TagList
        RAS: 工商信息.Status, //登记状态
        // guanWang: 工商信息., //官网地址
        yingYeQiXian: `${TermStart} 至${TermEnd}`, //营业期限 TermStart至TermEnd
        logOffMS: 工商信息.EndDate || null, //注销时间
        shijiaoziben: 工商信息.RecCap, //实缴资本
        // enterpriseType: 工商信息., //企业机构类型
        // jianJie: 工商信息., //简介
        zhuceziben: 工商信息.RegistCapi, //注册资本
        // naShuiRenZiZhi: 工商信息., //纳税人资质
        // operatingAddress: 工商信息., //经营地址
        // oldLogonAddress: 工商信息., //迁入前注册地址
        // shuiHao: 工商信息., //税号
        // shuiWuJu: 工商信息., //税务员
        jingYingFanWei: 工商信息.Scope, //经营范围
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, baseInfo, {uscc});

    // //股权结构
    // if (工商信息.Partners) {
    //     let ownershipList = [];
        
    //     工商信息.Partners.forEach(info => {
    //         let addInfo:any = {
    //             owId:randomId(TABLEID.股权结构),
    //             eId,
    //             name:info.StockName,
    //             finalBenefitPercent:info.FinalBenefitPercent,
    //             stockPercent:info.StockPercent,
    //             stockType:info.StockType,
    //             realCapi:info.RealCapi,
    //             paidUpCapitalUnit:info.PaidUpCapitalUnit,
    //             subscribedCapital:info.SubscribedCapital,
    //             subscribedCapitalUnit:info.SubscribedCapitalUnit,
    //         };
    //         if (info.CapiDate) addInfo.capiDate = getMySqlMs(info.CapiDate);
    //         if (info.ShoudDate) addInfo.shoudDate = getMySqlMs(info.ShoudDate);

    //         ownershipList.push(addInfo);
    //     });
        
    //     await addManyData(TABLENAME.股权结构, ownershipList);
    // }

    // if (工商信息.TagList) {
    //     let enterpriseLabelList = [];
        
    //     工商信息.TagList.forEach(info => {
    //         enterpriseLabelList.push({
    //             elId:randomId(TABLEID.企业标签表),
    //             eId,
    //             type:info.Type,
    //             labelName:info.Name,
    //         });
    //     });
        
    //     await addManyData(TABLENAME.企业标签表, enterpriseLabelList);
    // }

    // if (工商信息.Industry) {
    //     let industryInfo = {
    //         eiId:randomId(TABLEID.行业信息分类),
    //         eId,
    //         industryCode:工商信息.Industry.IndustryCode ,//行业门类code
    //         industry:工商信息.Industry.Industry ,//行业门类描述
    //         subIndustryCode:工商信息.Industry.SubIndustryCode ,//行业大类code
    //         subIndustry:工商信息.Industry.SubIndustry ,//行业大类描述
    //         middleCategoryCode:工商信息.Industry.MiddleCategoryCode ,//行业中类code
    //         middleCategory:工商信息.Industry.MiddleCategory ,//行业中类描述
    //         smallCategoryCode:工商信息.Industry.SmallCategoryCode ,//行业小类code
    //         smallCategory:工商信息.Industry.SmallCategory ,//行业小类描述
    //     };
        
    //     await addManyData(TABLENAME.行业信息分类, [industryInfo]);
    // }

    // if (工商信息.ChangeRecords) {
    //     let infoupdateList = [];
        
    //     工商信息.ChangeRecords.forEach(info => {
    //         infoupdateList.push({
    //             updateId:randomId(TABLEID.变更信息表),
    //             eId,
    //             afterContent:info.AfterContent, //变更前
    //             beforeContent:info.BeforeContent, //变更后
    //             changeDate:getMySqlMs(info.ChangeDate),//变更时间
    //             projectName:info.ProjectName,//变更类型
    //         });
    //     });
        
    //     await addManyData(TABLENAME.变更信息表, infoupdateList);
    // }
    return 工商信息;
}

async function 主要人员(uscc) {
    let {header, query} = getReqParam(uscc);
    let 主要人员数据:any = await getQcc('https://api.qichacha.com/ECIEmployee/GetList', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (Array.isArray(主要人员数据)) {
        let addList = [];
        主要人员数据.forEach(info => {
            addList.push({
                emId:randomId(TABLEID.主要人员),
                eId,
                job:info.Job,
                name:info.Name
            });
        });
        await addManyData(TABLENAME.主要人员, addList);
    }
    
    return 主要人员数据;
}


async function 分支机构(uscc) {
    let {header, query} = getReqParam(uscc);
    let 分支机构数据:any = await getQcc('https://api.qichacha.com/ECIBranch/GetList', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (Array.isArray(分支机构数据)) {
        let addList = [];
        分支机构数据.forEach(info => {
            addList.push({
                brId:randomId(TABLEID.分支机构),
                eId,
                name:info.Name,
                status:info.Status,
                employeesName:info.OperInfo.Name
            });
        });
        await addManyData(TABLENAME.分支机构, addList);
    }
    
    return 分支机构数据;
}


async function 行政许可核查(uscc) {
    let {header, query} = getReqParam(uscc);
    let 行政许可核查数据:any = await getQcc('https://api.qichacha.com/AdminLicenseCheck/GetList', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (行政许可核查数据.Data) {
        let addList = [];
        行政许可核查数据.Data.forEach(info => {
            let addInfo:any = {
                liId:randomId(TABLEID.行政许可核查),  
                eId,
                source:info.Source,
                licenseNo:info.LicenseNo,
                licenseName:info.LicenseName,
                licensOffice:info.LicensOffice,
                licensContent:info.LicensContent,
                documentNo:info.DocumentNo,
                permissionNo:info.PermissionNo,
            };
            if (info.ValidityFrom) addInfo.validityFrom = getMySqlMs(info.ValidityFrom);
            if (info.ValidityTo) addInfo.validityTo = getMySqlMs(info.ValidityTo);

            addList.push(addInfo);
        });

        await addManyData(TABLENAME.行政许可核查, addList);
    }
    
    return 行政许可核查数据;
}

async function 空壳扫描(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ShellScan/GetList', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (qccselectdata.Data) {
        let addList = [];
        qccselectdata.Data.forEach(info => {
            addList.push({
                emptyId:randomId(TABLEID.空壳扫描),  
                eId,
                title:info.Title,
                description:info.Description,
           });
        });
        await addManyData(TABLENAME.空壳扫描, addList);
    }
    
    return qccselectdata;
}

async function 准入尽职调查(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/AcctScan/GetInfo', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (qccselectdata.Data) {
        let addList = [];
        qccselectdata.Data.forEach(info => {
            addList.push({
                riskId:randomId(TABLEID.风险),  
                eId,
                title:info.Title,
                description:info.Description,
                passage:info.Passage,
                riskType:info.RiskType,
                typeCode:parseInt(info.TypeCode),
           });
        });
        await addManyData(TABLENAME.风险, addList);
    }
    
    return qccselectdata;
}


function getFinancingRounds(str) {
    if (str.indexOf("天使")) return FINANCINGROUNDS.天使投资;
    if (str.indexOf("种子")) return FINANCINGROUNDS.种子轮;
    if (str.indexOf("A")) return FINANCINGROUNDS.A轮;
    if (str.indexOf("B")) return FINANCINGROUNDS.B轮;
    if (str.indexOf("C")) return FINANCINGROUNDS.C轮;
    if (str.indexOf("以上")) return FINANCINGROUNDS.C轮以上;
    return FINANCINGROUNDS.天使投资;
}

async function 融资信息核查(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/CompanyFinancingSearch/GetList', query, header);
    // let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    // let eId = enterpriseInfo.eId;

    // if (qccselectdata.Data) {
    //     let addList = [];
    //     qccselectdata.Data.forEach(info => {
    //         addList.push({
    //             rId:randomId(TABLEID.企业融资),  
    //             eId,
    //             financingAmount:isNaN(info.Amoun) ? 0 : parseFloat(info.Amount),
    //             financingRounds:getFinancingRounds(info.Round),
    //             investmentDate:getMySqlMs(info.Date),
    //             investmentInstitutionsName:info.Investment,
    //        });
    //     });
    //     await addManyData(TABLENAME.企业融资, addList);
    // }
    
    return qccselectdata;
}

async function 国际专利(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/InternationalPatentCheck/GetList', query, header);
    // let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    // let eId = enterpriseInfo.eId;

    // if (qccselectdata.Data) {
    //     let addList = [];
    //     qccselectdata.Data.forEach(info => {
    //         addList.push({
    //             iprId:randomId(TABLEID.知识产权),
    //             eId,
    //             year:getMySqlMs(info.PublicationDate),
    //             number:1,
    //             iprType:IPRALLTYPE.海外专利,
    //             iprName:info.Title,
    //         });
    //     });
    //     await addManyData(TABLENAME.知识产权, addList);
    // }
    
    return qccselectdata;
}


async function 科创分(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/TechScore/GetInfo', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (qccselectdata.Data) {
        let addInfo = {
            stemId:randomId(TABLEID.科创分),
            eId,
            industry:qccselectdata.Data.Industry.Industry,
            subIndustry:qccselectdata.Data.Industry.SubIndustry,
            industryRanking:qccselectdata.Data.IndustryRanking,
            score:qccselectdata.Data.Score,
        };
        await addManyData(TABLENAME.科创分, [addInfo]);
    }
    
    return qccselectdata;
}


// async function 专利查询(uscc) {
//     let {header, query} = getReqParam(uscc);
//     let qccselectdata:any = await getQcc('https://api.qichacha.com/PatentV4/Search', query, header);
//     let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
//     let eId = enterpriseInfo.eId;

//     if (Array.isArray(qccselectdata)) {
//         console.log();
//         //todo 没有做
//         let addList = [];
//         qccselectdata.forEach(info => {
//             addList.push({
//                 iprId:randomId(TABLEID.知识产权),
               
//             });
//         });

//     }

//     return qccselectdata;
// }


async function 失信核查(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ShixinCheck/GetList', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (qccselectdata.Data) {
        let addList = [];
        qccselectdata.Data.forEach(info => {
            let addInfo:any = {
                disId:randomId(TABLEID.失信核查),
                eId,   
                anno:info.Anno,
                executegov:info.Executegov,
                executestatus:info.Executestatus,
                executeno:info.Executeno,
                actionRemark:info.ActionRemark,
                amount:info.Amount,
            };

            if (info.Liandate) addInfo.liandate = getMySqlMs(info.Liandate);
            if (info.Publicdate) addInfo.publicdate = getMySqlMs(info.Publicdate);

            addList.push(addInfo);
        });
        await addManyData(TABLENAME.失信核查, addList);
    }
    
    return qccselectdata;
}


async function 严重违法核查(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/SeriousIllegalCheck/GetList', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (qccselectdata.Data) {
        let addList = [];
        qccselectdata.Data.forEach(info => {
            let addInfo:any = {
                stemId:randomId(TABLEID.严重违法犯罪),
                eId,
                type:info.Type,
                addReason:info.AddReason,
                addOffice:info.AddOffice,
                removeReason:info.RemoveReason,
                removeOffice:info.RemoveOffice,
            };
            if (info.AddDate) addInfo.addDate = getMySqlMs(info.AddDate);
            if (info.RemoveDate) addInfo.removeDate = getMySqlMs(info.RemoveDate);

            addList.push(addInfo);
        });
        await addManyData(TABLENAME.严重违法犯罪, addList);
    }
    
    return qccselectdata;
}


async function 企业对外投资核查(uscc) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/InvestmentCheck/GetList', query, header);
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    let eId = enterpriseInfo.eId;

    if (qccselectdata.Data) {
        let addList = [];
        qccselectdata.Data.forEach(info => {
            let addInfo:any = {
                oilId:randomId(TABLENAME.对外投资),
                eId,
                name:info.Name,
                registCapi:info.RegistCapi,
                registeredCapital:info.RegisteredCapital,
                registeredCapitalUnit:info.RegisteredCapitalUnit,
                registeredCapitalCCY:info.RegisteredCapitalCCY,
                fundedRatio:info.FundedRatio,
                shouldCapi:info.ShouldCapi,
                subscribedCapital:info.SubscribedCapital,
                subscribedCapitalUnit:info.SubscribedCapitalUnit,
                subscribedCapitalCCY:info.SubscribedCapitalCCY,
                status:info.Status,
                operName:info.Oper.Name
            };
            if (info.StartDate) addInfo.StartDate = getMySqlMs(addInfo.StartDate);
            if (info.investDate) addInfo.InvestDate = getMySqlMs(addInfo.InvestDate);

            addList.push(addInfo);
        });
        await addManyData(TABLENAME.对外投资, addList);
    }
    
    return qccselectdata;
}


async function 企业年报信息(uscc) {
    let {header, query} = getReqParam(uscc, "isKeyNo");
    let 企业年报信息:any = await getQcc('https://api.qichacha.com/AR/GetAnnualReport', query, header);
    // let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, ["eId"]);
    // let eId = enterpriseInfo.eId;

    // if (企业年报信息.Data) {
    //     let addList = [];
    //     企业年报信息.Data.forEach(info => {
    //         addList.push({
    //             stemId:randomId(TABLENAME.知识产权),
    //             eId,
    //             industry:info.Industry,
    //             subIndustry:info.SubIndustry,
    //             industryRanking:info.IndustryRanking,
    //             score:info.Score,
    //         });
    //     });

    // }
    
    return 企业年报信息;
}









async function 企查查数据集(uscc) {
    
    const TimeSpan = Math.round(new Date().valueOf()/ 1000);
    let header = {
        Token:md5(`${systemConfig.qccKey}${TimeSpan}${systemConfig.qccSecretKey}`).toUpperCase(),
        TimeSpan
    };
    let query = {
        key:systemConfig.qccKey,
        searchKey:uscc,
        // keyNo:"云合智网（上海）技术有限公司"
    };
    let 工商信息:any = await getQcc('https://api.qichacha.com/ECIInfoVerify/GetInfo', query, header);//获取工商信息
    
    let keyList = ["Name", "StartDate", "Address", "RegistCapi", "RecCap", "StockType"];

    let dataList = [];
    keyList.forEach(str => {
        dataList.push(工商信息[str] || "-");
    });
    let PartnersStr = "";//投资人
    if (工商信息.Partners) {
        工商信息.Partners.forEach(item => {
            PartnersStr += `${item.StockName}:${item.StockPercent};`
        });
    }
    dataList.push(PartnersStr);
    dataList.push(工商信息.ContactInfo.PhoneNumber||"-");
    dataList.push(工商信息.Industry.Industry||"-");
    //联系信息
    let TagListStr = "";//企业标签
    if (工商信息.TagList) {
        工商信息.TagList.forEach(item => {
            TagListStr += `${item.Name};`
        });
    }
    dataList.push(TagListStr);
   
    let 著作权软著:any = await getQcc('https://api.qichacha.com/CopyRight/SearchCopyRight', query, header);

    let 著作权软著Str = "";
    if(Object.keys(著作权软著).length) {
        著作权软著.forEach(item => {
            著作权软著Str += item.Name;
        });
    }
    dataList.push(著作权软著Str);

    let 准入尽职调查:any = await getQcc('https://api.qichacha.com/AcctScan/GetInfo', query, header);
    let 风险 = "";
    if (准入尽职调查.Data) {
        准入尽职调查.Data.forEach(item => {
            风险 += item.Title;
        });
    }
    dataList.push(风险);

    let 专利查询:any = await getQcc('https://api.qichacha.com/PatentV4/Search', query, header);
    let 专利查询Str = 0;
    if (Object.keys(专利查询).length) {
        专利查询.forEach(item=> {
            专利查询Str += item.items.length;
        })
    }
    dataList.push(专利查询Str);

    let 失信核查:any = await getQcc('https://api.qichacha.com/ShixinCheck/GetList', query, header);
    let 失信核查Str = 失信核查.VerifyResult ?? "-";
    dataList.push(失信核查Str);

    let 资质证书:any = await getQcc('https://api.qichacha.com/ECICertification/SearchCertification', query, header);
    let 资质证书Str = 0;
    if (Object.keys(资质证书).length) {
        资质证书Str = 资质证书.length;
    }
    dataList.push(资质证书Str);

    let 融资信息:any = await getQcc('https://api.qichacha.com/CompanyFinancingSearch/GetList', query, header);
    
    let 融资信息Str = "";
    if (融资信息.Data) {
        融资信息.Data.forEach(item => {
            融资信息Str += `${item.Amount};` 
        })
    }
    dataList.push(融资信息Str);

    return dataList;
}