import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { operationalData, selectData } from "../data/operationalData";
import { systemConfig } from "../config/serverConfig";
import { getQcc } from "../util/request";
import { getMySqlMs, getPinyinInitials, randomId } from "../tools/system";
import moment = require("moment");
import { FINANCINGROUNDS, STATE } from "../config/enum/enum";

const md5 = require("md5");


/**
 * 同步企查查数据
 * 逻辑：获取数据库所有企业uscc，进行企查查数据同步
 */
export async function updateQCCDataTask() {
    let enterpriseList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业基础信息表, {}, ["eId", "uscc", "enterpriseName"]);
    console.log(`开始同步企查查数据，${moment(new Date().valueOf()).format("YYYY-MM-DD HH:mm:ss")}：本次同步同${enterpriseList.length}家`);
    for (let i = 0; i < enterpriseList.length; i++) {
        let info = enterpriseList[i];
        
        await updateItemQCCData(info.uscc, info.eId);

        console.log(`下标 ${i} => eId：${info.eId}，uscc：${info.uscc}`);
    }
    console.log(`${enterpriseList.length}家企业同步成功`);
}


async function 数据是否存在(tableName, param, idKey) {
    let info = await selectData(OPERATIONALDATATYPE.查询单个, tableName, param, [idKey]);
    if (info && info[idKey]) {
        return true;
    }
    return false;
}



/**
 * 更新单个企业
 * @param uscc 
 * @param eId 
 */
export async function updateItemQCCData(uscc, eId) {
    await 工商信息(uscc, eId);
    await 知识产权(uscc, eId);
    await 主要人员(uscc, eId);
    await 空壳扫描(uscc, eId);
    await 准入尽职调查(uscc, eId);
    await 失信核查(uscc, eId);
    await 严重违法核查(uscc ,eId);
    await 科创分(uscc, eId);
    await 资质证书(uscc, eId);
    await 融资信息核查(uscc, eId);
    await 企业对外投资核查(uscc, eId);
}

/**
 * 封装了一个请求方法
 * @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:any = {};
    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};
}



/**
 * 同步工商信息数据
 * @param uscc 
 * @param eId 
 * @returns 
 */
async function 工商信息(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    
    let 工商信息:any = await getQcc('https://api.qichacha.com/ECIInfoVerify/GetInfo', query, header);//获取工商信息

    let khsfsb = getReqParam(uscc);
    let 客户身份识别:any = await getQcc('https://api.qichacha.com/CustomerDueDiligence/KYC', khsfsb.query, khsfsb.header);//获取工商信息

    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");

    if (工商信息.OperName) {
        let farenInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.法人信息表, {eId, name:工商信息.OperName}, ["legalId"] );
        if (!farenInfo || !farenInfo.legalId ) {
            await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.法人信息表, {}, {eId});
            let addfr = {
                legalId:randomId(TABLEID.法人信息表),
                eId,
                name:工商信息.OperName
            };
            await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.法人信息表, addfr, {});
        }
    }
    

    //企业基础信息
    let guanWang = "";
    if (工商信息.ContactInfo.WebSite && 工商信息.ContactInfo.WebSite[0]) {
        guanWang = 工商信息.ContactInfo.WebSite[0].Url || "";
    }
    let qiYeGuiMo = "";
     if (客户身份识别.Data && 客户身份识别.Data.Scale) {
        switch (客户身份识别.Data.Scale) {
            case "L": qiYeGuiMo = "大型"; break;
            case "M": qiYeGuiMo = "中型"; break;
            case "S": qiYeGuiMo = "小型"; break;
            case "XS": qiYeGuiMo = "微型"; break;
        }
    }

    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: 工商信息.ContactInfo.Email, //邮箱
        // isNaturalPersonHolding: 工商信息., //是否自然人控股
        // industry: 工商信息., //领域
        // moreMail: 工商信息., //更多邮箱
        // logonAddress: 工商信息.Address, //注册地址
        // tongXinDiZhi: 工商信息., //通信地址
        // liaison: 工商信息., //联系人
        liaisonPhone: 工商信息.ContactInfo.PhoneNumber, //联系电话
        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, eId});

    /**
     * 股权结构目前小程序没有做这块的更新，所以全部采用小程序的数据
     * 逻辑：检测到 股权人+比例 与原来的不一样（只要出现一个不一样），就会删除这个企业下所有的，并且重新写入企查查的这一块数据
     */
    if (工商信息.Partners) {
        
        let 出现不存在数据 = false;
        for (let i = 0; i < 工商信息.Partners.length; i++) { 
            let info = 工商信息.Partners[i];
            let findItemParam = {
                name:info.StockName,
                finalBenefitPercent:info.FinalBenefitPercent,
                stockPercent:info.StockPercent,
                stockType:info.StockType,
                realCapi:info.RealCapi,
            };
            if ( !await 数据是否存在(TABLENAME.股权结构, findItemParam, "owId") ) {
                出现不存在数据 = true;
            }
        }

        if (出现不存在数据) {
            //删除历史记录数据
            await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.股权结构, null, {eId});
            //同步最新记录
            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 operationalData(OPERATIONALDATATYPE.增加, TABLENAME.股权结构, ownershipList, null);
        }
        
    }

    /**
     * 企业标签表 ，已和项目经理确认同步需求：
     * 做全量更新，所有的以企查查的为准，企查查的标签数据全量同步到标签表和资质表，如果有用户自己填的，企查查没有的就使用用户填的【2025年5月28日 罗说明】 李欣鸣注
     * 逻辑说明：判断有和没有的标准是，是否存在标签或者资质名称。
     * 更新逻辑：1.企查查有，小程序没有，同步企查查的数据
     *          2.企查查没有，小程序有，用小程序的数据
     *          3.企查查有，小程序有，不覆盖
     *          4.企查查以前有现在没有，小程序没有，不删除之前的
     */
    if (工商信息.TagList) {
        for (let i = 0; i < 工商信息.TagList.length; i++) {
            let info = 工商信息.TagList[i];
            let {Type, Name} = info;
           
            let dbLabelItem = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业标签表, {labelName:info.Name, eId}, ["elId"]);
            if (!dbLabelItem || !dbLabelItem.elId) {
                //添加新的
                let addItemInfo = {
                    elId:randomId(TABLEID.企业标签表),
                    eId,
                    type:info.Type,
                    labelName:info.Name
                };
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业标签表, addItemInfo, {} )
            }

            //处理资质
            let isAdd = false;//库里是否不存在这个企业的数据
            let zzInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业资质, {eId}, ["qId"]);
            if (!zzInfo || !zzInfo.qId) {
                //不存在 直接添加
                zzInfo = {
                    qId : randomId(TABLEID.企业资质),
                    eId : eId,
                    xjrState:STATE.否,
                    kxState:STATE.否,
                    gxjsState:STATE.否,
                    zjtxState:STATE.否,
                    listedState:STATE.否,
                    xjrPyState:STATE.否,
                };
                isAdd = true;
            }
            switch (Name) {
                case "科技型中小企业": 
                    if (isAdd) {
                        zzInfo.kxState = STATE.是
                    } else {
                        if (!zzInfo.kxState) {
                            await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业资质, {kxState:STATE.是}, {eId});
                        }
                    }
                break;
                case "科技小巨人企业":
                    if (isAdd) {
                        zzInfo.xjrState = STATE.是
                    } else {
                        if (!zzInfo.xjrState) {
                            await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业资质, {xjrState:STATE.是}, {eId});
                        }
                    }    
                
                break;
                case "专精特新中小企业":
                    if (isAdd) {
                        zzInfo.zjtxState = STATE.是
                    } else {
                        if (!zzInfo.zjtxState) {
                            await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业资质, {zjtxState:STATE.是}, {eId});
                        }
                    }      
                break;
                case "高新技术企业":
                    if (isAdd) {
                        zzInfo.gxjsState = STATE.是
                    } else {
                        if (!zzInfo.gxjsState) {
                            await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业资质, {gxjsState:STATE.是}, {eId});
                        }
                    }       
                break;
                //如果后续有新的 标签 和 资质 关联，只需要在case里面加东西就好了
            }
            if (isAdd) {
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业资质, zzInfo, {})
            }

        }
        
    }

    /**
     * 行业领域目前没有用到，所以直接与企查查全量更新
     * 逻辑：先删除现有的，再重新添加
     */
    if (工商信息.Industry) {
        //删除历史记录数据
        await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.行业信息分类, null, {eId});
        //同步最新记录
        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 operationalData(OPERATIONALDATATYPE.增加, TABLENAME.行业信息分类, [industryInfo], null);
    }

    /**
     * 变更记录目前小程序没有涉及到这部分数据，所以直接与企查查全量更新
     * 逻辑：先删除现有的，再重新添加
     */
    if (工商信息.ChangeRecords && 工商信息.ChangeRecords.length) {
        //删除历史记录数据
        await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.变更信息表, null, {eId});
        //同步最新记录
        let infoupdateList = [];
        
        工商信息.ChangeRecords.forEach(info => {
            infoupdateList.push({
                updateId:randomId(TABLEID.变更信息表),
                eId,
                afterContent:info.AfterContent, //变更前
                beforeContent:info.BeforeContent, //变更后
                changeDate:getMySqlMs(info.ChangeDate),//变更时间
                projectName:info.ProjectName,//变更类型
            });
        });
        
        if (infoupdateList.length ) await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.变更信息表, infoupdateList, null);
    }
    
}

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;
}

/**
 * 更新知识产权
 * 包括：商标表，作品著作权表，软件著作权表，专利表
 * 数据来源：
 * 商标表：商标查询 【同步类型：IPRALLTYPE.商标信息】
 * 作品著作权表：作品著作查询 【同步类型：IPRALLTYPE.作品著作权】
 * 软件著作权表：软件著作查询 【同步类型：IPRALLTYPE.软件著作权】
 * 专利表：专利查询 【同步类型：IPRALLTYPE.外观设计专利， IPRALLTYPE.实用新型专利 IPRALLTYPE.发明专利】
 * 逻辑说明：判断有和没有的依据是，知识产权名称 + 知识产权时间
 * 更新逻辑：1.企查查有，小程序没填报，用企查查数据
 *          2.企查查没有，小程序填报了，用小程序的数据
 *          3.企查查有，小程序有，不覆盖
 * @param uscc 
 * @param eId 
 */
async function 知识产权(uscc, eId) {

    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 info = 商标查询[i];

            let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.商标, {qccId:info.ID}, ["qccId"]);
            if (!item || !item.qccId) {
                let qcc商标详情 = await 商标详情查询(uscc, info.ID);
                let imageUrl = [];
                if (info.ImageUrl) imageUrl.push(info.ImageUrl);
                //添加新的
                let addItemInfo:any = {
                    tmId:randomId(TABLEID.商标),
                    eId,
                    qccId:info.ID,
                    regNo:info.regNo,
                    name:info.Name,
                    categoryId:info.CategoryId,
                    category:info.Category,
                    person:info.Person,
                    imageUrl:JSON.stringify(imageUrl),
                    flowStatusDesc:info.FlowStatusDesc,
                };
                if (qcc商标详情.RegDate) addItemInfo.RegDate = getMySqlMs(qcc商标详情.RegDate)
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.商标, addItemInfo, {});
            }
        }

    }
    

    /**同步 作品著作 */
    let zpzzReqInfo = getReqParam(uscc);
    let 作品著作查询:any = await getQcc('https://api.qichacha.com/CopyRight/SearchCopyRight', zpzzReqInfo.query, zpzzReqInfo.header);
    if (Array.isArray(作品著作查询)) {

        for (let i = 0; i < 作品著作查询.length; i++) {
            let info = 作品著作查询[i];

            let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.作品著作权, {registerNo:info.RegisterNo}, ["registerNo"]);
            if (!item || !item.registerNo) { // 库里不存在就会添加新的
                let addItemInfo:any = {
                    crId:randomId(TABLEID.作品著作权),
                    eId,
                    owner:info.Owner,
                    category:info.Category,
                    name:info.Name,
                    registerNo:info.RegisterNo,
                };
                if (info.RegisterDate) addItemInfo.registerDate= getMySqlMs(info.RegisterDate);
                if (info.PublishDate) addItemInfo.publishDate= getMySqlMs(info.PublishDate);
                if (info.FinishDate) addItemInfo.finishDate= getMySqlMs(info.FinishDate);
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.作品著作权, addItemInfo, {});
            }
 
        }
        
        
    }

    /**同步 软件著作权 */
    let rjzzqReqInfo:any = getReqParam(uscc);
    rjzzqReqInfo.query.pageSize = 50;
    let 软件著作查询:any = await getQcc('https://api.qichacha.com/CopyRight/SearchSoftwareCr', rjzzqReqInfo.query, rjzzqReqInfo.header);
    if (Array.isArray(软件著作查询)) {
        for (let i = 0; i < 软件著作查询.length; i++) {
            let info = 软件著作查询[i];

            let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.软件著作权, {registerNo:info.RegisterNo}, ["registerNo"]);
            if (!item || !item.registerNo) { // 库里不存在就会添加新的
                let addItemInfo:any = {
                    scId:randomId(TABLEID.软件著作权),
                    eId,
                    category:info.Category,
                    versionNo:info.VersionNo,
                    registerNo:info.RegisterNo,
                    name:info.Name,
                    shortName:info.ShortName,
                    owner:info.Owner,
                };
                if (info.RegisterAperDate) addItemInfo.registerAperDate = getMySqlMs(info.RegisterAperDate);
                if (info.FinishDevelopDate) addItemInfo.finishDevelopDate = getMySqlMs(info.FinishDevelopDate);
                if (info.PublishDate) addItemInfo.publishDate = getMySqlMs(info.PublishDate);
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.软件著作权, addItemInfo, {});
            }
 
        }
        
        
    }

    /** IPRALLTYPE.外观设计专利， IPRALLTYPE.实用新型专利 IPRALLTYPE.发明专利 */
    let zlcxReqInfo:any = getReqParam(uscc);
    zlcxReqInfo.query.pageSize = 50;
    let 专利查询:any = await getQcc('https://api.qichacha.com/PatentV4/SearchMultiPatents', zlcxReqInfo.query, zlcxReqInfo.header);
    if (Array.isArray(专利查询)) {
        for (let i = 0; i < 专利查询.length; i++) {
            let info = 专利查询[i];

            let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.专利, {applicationNumber:info.ApplicationNumber}, ["applicationNumber"]);
            if (!item || !item.applicationNumber) { // 库里不存在就会添加新的
                let addItemInfo:any = {
                    patentId:randomId(TABLEID.专利),
                    eId,
                    category:info.Category,
                    kindcode:info.KindCode,
                    applicationNumber:info.ApplicationNumber,
                    
                    publicationNumber:info.PublicationNumber,
                  
                    legalStatusDesc:info.LegalStatusDesc,
                    title:info.Title,
                    agency:JSON.stringify(info.Agency || []),
                    kindCodeDesc:info.KindCodeDesc,
                    IPCDesc:JSON.stringify(info.IPCDesc || []),
                    inventorStringList:JSON.stringify(info.InventorStringList || []),
                    assigneestringList:JSON.stringify(info.AssigneestringList || []),
                };
                if (info.ApplicationDate) addItemInfo.applicationDate= getMySqlMs(info.ApplicationDate);
                if (info.PublicationDate) addItemInfo.publicationDate= getMySqlMs(info.PublicationDate);
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.专利, addItemInfo, {});
            }
 
        }
        
        
    }


}


/**
 * 主要人员
 * 逻辑：如果这个企业的人员和职位没有变动，就不更新，有的话就删除这个企业的所有，重新更新一遍
 * @param uscc 
 * @returns 
 */
async function 主要人员(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let 主要人员数据:any = await getQcc('https://api.qichacha.com/ECIEmployee/GetList', query, header);


    if (Array.isArray(主要人员数据)) {

        let employeesList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.主要人员, {eId}, ["job", "name"])
        let checkMap = {};
        employeesList.forEach(info => {
            checkMap[info.name] = info.job;
        });

        let isReSet = false;
        let reSetList = [];
        for (let i = 0; i < 主要人员数据.length; i++) {
            let info = 主要人员数据[i];
            reSetList.push({
                emId:randomId(TABLEID.主要人员),
                eId,
                job:info.Job,
                name:info.Name
            });
            if (!checkMap[info.name] || info.job != checkMap[info.name]) {
                isReSet = true;
                continue
            }
        }
        if (isReSet) {
            await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.主要人员, {}, {eId} );
            await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.主要人员, reSetList, {} );
        }
        
    }
    
}

/**
 * 空壳扫描
 * 逻辑：增量更新
 * @param uscc 
 * @returns 
 */
async function 空壳扫描(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ShellScan/GetList', query, header);

    if (qccselectdata.Data) {
        let addList = [];
        for (let i= 0; i < qccselectdata.Data.length; i++ ) {
            let info = qccselectdata.Data[i];

            let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.空壳扫描, {eId, title:info.Title}, ["emptyId"] );
            if (!item || !item.emptyId) {
                addList.push({
                    emptyId:randomId(TABLEID.空壳扫描),  
                    eId,
                    title:info.Title,
                    description:info.Description,
                });
            }
        }
        if (addList.length) await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.空壳扫描, addList, {});
    }
    
}


/**
 * 准入尽职调查
 * 逻辑：增量更新
 * @param uscc 
 * @returns 
 */
async function 准入尽职调查(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/AcctScan/GetInfo', query, header);

    if (qccselectdata.Data) {
        let addList = [];
        for (let i = 0; i < qccselectdata.Data.length; i++) {
            let info = qccselectdata.Data[i];
            
            let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.风险, {eId, title:info.Title}, ["riskId"] );
            if (!item || !item.riskId) {
                addList.push({
                    riskId:randomId(TABLEID.风险),  
                    eId,
                    title:info.Title,
                    description:info.Description,
                    passage:info.Passage,
                    riskType:info.RiskType,
                    typeCode:parseInt(info.TypeCode),
                });
            }   
        }
        if (addList.length) await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.风险, addList, {});
    }
    
}


/**
 * 失信核查
 * 逻辑：全量更新 删除之前所有的 再添加
 * @param uscc 
 * @returns 
 */
async function 失信核查(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ShixinCheck/GetList', query, header);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.失信核查, {}, {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 operationalData(OPERATIONALDATATYPE.增加, TABLENAME.失信核查, addList, {});
    }
    
}

/**
 * 严重违法核查
 * 逻辑：全量更新 删除之前所有的 再添加
 * @param uscc 
 * @returns 
 */
async function 严重违法核查(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/SeriousIllegalCheck/GetList', query, header);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.严重违法犯罪, {}, {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 operationalData(OPERATIONALDATATYPE.增加, TABLENAME.严重违法犯罪, addList, {});
    }
    
}

/**
 * 科创分
 * 有则更新，无则添加
 * @param uscc 
 * @returns 
 */
async function 科创分(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/TechScore/GetInfo', query, header);

    if (qccselectdata.Data) {
        let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.科创分, {eId}, ["stemId"] );
        if (!item || !item.stemId) {
            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 operationalData(OPERATIONALDATATYPE.增加, TABLENAME.科创分, addInfo, {});
        } else if (item.score != qccselectdata.Data.Score || item.industryRanking != qccselectdata.Data.IndustryRanking) {
            let updateInfo = {
                industry:qccselectdata.Data.Industry.Industry,
                subIndustry:qccselectdata.Data.Industry.SubIndustry,
                industryRanking:qccselectdata.Data.IndustryRanking,
                score:qccselectdata.Data.Score,
            };
            await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.科创分, updateInfo, {eId});
        }
        
    }
    
    return qccselectdata;
}


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


/**
 * 融资信息核查
 * 逻辑：增量更新，如果遇到未披露的融资金额，赋值0，【需求点：2025年5月28日 18:11分 于倩倩说明】李欣鸣注释
 * @param uscc 
 * @returns 
 */
async function 融资信息核查(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/CompanyFinancingSearch/GetList', query, header);
    if (qccselectdata.Data) {
        let addList = [];
        for (let i = 0; i < qccselectdata.Data.length; i++) {
            let info = qccselectdata.Data[i];

            let distinctParam = {eId,investmentDate:getMySqlMs(info.Date), investmentInstitutionsName:info.Investment };
            let disItem = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业融资, distinctParam, ["rId"]);
            if (!disItem || !disItem.rId) {
                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,
                });
            }

            
        }
        if (addList.length) await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业融资, addList, {});
    }
    
    return qccselectdata;
}


/**
 * 资质证书查询
 * 逻辑：增量更新
 * @param uscc 
 * @param eId 
 * @returns 
 */
async function 资质证书(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ECICertification/SearchCertification', query, header);

    if (Array.isArray(qccselectdata)) {
        let addList = [];
        for (let i = 0; i < qccselectdata.length; i++) {
            let info = qccselectdata[i];
            
            let distinctParam = {eId, type:info.Type, name:info.Name};
            let item = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.资质证书, distinctParam, ["cerId"] );

            if (!item || !item.cerId) {
                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);
            }

        }
        if (addList.length) await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.资质证书, addList, {});
    }
    
}


/**
 * 企业对外投资核查
 * 逻辑：删除当前企业的，再重新添加
 * @param uscc 
 * @returns 
 */
async function 企业对外投资核查(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/InvestmentCheck/GetList', query, header);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.对外投资, {}, {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 operationalData(OPERATIONALDATATYPE.增加, TABLENAME.对外投资, addList, {});
    }
    

}






