/**
 * 企查查数据同步
 */

import moment from "moment";
import * as configEnum from "../config/enum";
import * as enterpriseData from "../data/enterprise";
import * as labelData from "../data/label";
import * as enterpriseRiskData from "../data/enterpriseRisk";
import * as dishonestPersonData from "../data/dishonestPerson";
import * as illegalityData from "../data/illegality";
import * as qualificationsData from "../data/qualifications";
import { systemConfig } from "../config/serverConfig";
import { getQcc } from "../util/request";
import { formatAddress, randomId } from "../tools/system";
import { TABLEID } from "../config/enum/dbEnum";
import { LABELGOAL, LABELTYPE } from "../config/enum/labelEnum";
const md5 = require("md5");


/**
 * 接口更新
 * 设置定时器，每天刷新一次数据
 */
export async function initApiDataStorage() {
    updateQCCDataTask();
    setInterval(async function () {
        updateQCCDataTask();
    }, 3600 * 1000 * 24);
}



/**
 * 同步企查查数据
 * 逻辑：获取数据库所有企业uscc，进行企查查数据同步
 */
export async function updateQCCDataTask() {
    let enterpriseList = await enterpriseData.findEnterpriseListByParam({isSettled: configEnum.STATE.是});
    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.name);

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


/**
 * 更新单个企业
 * @param uscc 
 * @param name 
 */
export async function updateItemQCCData(uscc, name) {
    await 工商信息(uscc);
    await 准入尽职调查(uscc);
    await 失信核查(uscc);
    await 严重违法核查(uscc);
    await 科创分(uscc);
    await 资质证书查询(uscc);
    //"91310114MA1GY5G71E"
}


/**
 * 封装了一个请求方法
 * @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: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) {
    let {header, query} = getReqParam(uscc);
    
    let 工商信息:any = await getQcc('https://api.qichacha.com/ECIInfoVerify/GetInfo', query, header);//获取工商信息
    if (Object.keys(工商信息).length) {
        let enterInfo = await enterpriseData.findEnterpriseByUscc(uscc);

        let khsfsb = getReqParam(uscc);
        let 客户身份识别:any = await getQcc('https://api.qichacha.com/CustomerDueDiligence/KYC', khsfsb.query, khsfsb.header);//获取工商信息
        let TermEnd = "无固定期限";
        if (工商信息.TermEnd) TermEnd = moment(工商信息.TermEnd).format("YYYY-MM-DD");
    
        if (工商信息.OperName) {
           enterInfo.legalPerson = 工商信息.OperName;
        }
        
        //企业基础信息
        let guanWang = "";
        if (工商信息.ContactInfo &&工商信息.ContactInfo.WebSite && 工商信息.ContactInfo.WebSite[0]) {
            enterInfo.guanWang = 工商信息.ContactInfo.WebSite[0].Url || "";
        }

        if (客户身份识别.Data && 客户身份识别.Data.Scale) {
            switch (客户身份识别.Data.Scale) {
                case "L":  enterInfo.qiYeGuiMo = configEnum.ENTERPRISESIZE.大型; break;
                case "M":  enterInfo.qiYeGuiMo = configEnum.ENTERPRISESIZE.中型; break;
                case "S":  enterInfo.qiYeGuiMo = configEnum.ENTERPRISESIZE.小型; break;
                case "XS":  enterInfo.qiYeGuiMo = configEnum.ENTERPRISESIZE.微型; break;
            }
        }
    
        if (工商信息.Address) {
            let logonAddressList = formatAddress(工商信息.Address); //解析注册地址
            enterInfo.logonAddress = logonAddressList;
        }

        enterInfo.zhuCeHao = 工商信息.No;
        enterInfo.zuZhiJiGouDaiMa = 工商信息.OrgNo;
        enterInfo.logonTime = new Date(工商信息.StartDate).valueOf();

        if (!enterInfo.jingYingFanWei) enterInfo.jingYingFanWei = 工商信息.Scope; //经营范围
            
        /**
         * 股权结构
         */
        if (工商信息.Partners) {
            let ownershipList = [];
            工商信息.Partners.forEach(info => {
                let addInfo:any = {
                    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);
            });
            enterInfo.guQuanJieGou = ownershipList;
        }
    

        /**
         * 企业标签表
         */
        if (工商信息.TagList) {
            for (let i = 0; i < 工商信息.TagList.length; i++) {
                let info = 工商信息.TagList[i];
                let {Type, Name} = info;
                if (Name == "曾用名") continue
                let labelInfo = await labelData.selectLabelOne({labelName:Name});
                if (!labelInfo || !labelInfo.id) {
                    //添加
                    labelInfo = {
                        id:LABELTYPE.自定义标签,
                        labelName:Name,
                        ctMs:new Date().valueOf(),
                        goal:LABELGOAL.企业,
                        labelType:LABELTYPE.自定义标签, //todo
                        state:false
                    };

                    await labelData.createOneLabel(labelInfo);
                }

                let thisEnterpriseHaveLabel = false;

                enterInfo.labels.forEach(itemLabelInfo => {
                    if (itemLabelInfo.labelId == labelInfo.id) thisEnterpriseHaveLabel = true;
                })
                if (!thisEnterpriseHaveLabel)  enterInfo.labels.push({labelId:labelInfo.id, labelType:LABELTYPE.自定义标签, state:true});
            }
            
        }

        await enterInfo.save();

    } else {
        console.log(`企查查获取不到该企业数据：${uscc}`);
    }
}


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

    if (qccselectdata.Data) {
        for (let i = 0; i < qccselectdata.Data.length; i++) {
            let info = qccselectdata.Data[i];
            
            let item = await enterpriseRiskData.findOnce({uscc, title:info.Title});
            if (!item || !item.id) {
                let addInfo:any = {
                    id:randomId(TABLEID.准入尽职调查),  
                    uscc,
                    enterpriseName:enterpriseInfo.name,
                    title:info.Title,
                    description:info.Description,
                    passage:info.Passage,
                    riskType:info.RiskType,
                };
                if (info.TypeCode) addInfo.typeCode = parseInt(info.TypeCode);
                await enterpriseRiskData.createDataByParam(addInfo);
            }   
        }
        
    }
    
}


/**
 * 失信核查
 * 逻辑：全量更新 删除之前所有的 再添加
 * @param uscc 
 * @returns 
 */
async function 失信核查(uscc) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ShixinCheck/GetList', query, header);

    await dishonestPersonData.removeMany({uscc});
    if (qccselectdata.Data) {
        let addList = [];
        qccselectdata.Data.forEach(info => {
            let addInfo:any = {
                id:randomId(TABLEID.失信核查),
                uscc,
                enterpriseName:enterpriseInfo.name,
                anno:info.Anno,
                executegov:info.Executegov,
                executestatus:info.Executestatus,
                executeno:info.Executeno,
                actionRemark:info.ActionRemark,
                amount:info.Amount,
            };

            addList.push(addInfo);
        });
        await dishonestPersonData.addMany(addList);
    }
    
}


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

    await illegalityData.removeMany({uscc});
    if (qccselectdata.Data) {
        let addList = [];
        qccselectdata.Data.forEach(info => {
            let addInfo:any = {
                id:randomId(TABLEID.严重违法核查),
                uscc,
                enterpriseName:enterpriseInfo.name,
                type:info.Type,
                addReason:info.AddReason,
                addOffice:info.AddOffice,
                removeReason:info.RemoveReason,
                removeOffice:info.RemoveOffice,
            };

            addList.push(addInfo);
        });
        await illegalityData.addMany(addList);
    }
    
}


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

    if (qccselectdata.Data) {
        let kcf = {
            industry:qccselectdata.Data.Industry.Industry,
            subIndustry:qccselectdata.Data.Industry.SubIndustry,
            industryRanking:qccselectdata.Data.IndustryRanking,
            score:qccselectdata.Data.Score,
        };

        enterpriseInfo.kcf = kcf;
    }
    
}


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


async function 资质证书查询(uscc) {
     let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    let {header, query} = getReqParam(uscc);
    let qccselectdata:any = await getQcc('https://api.qichacha.com/ECICertification/SearchCertification', query, header);

    await qualificationsData.removeMany({uscc});
    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 = {
                 uscc,
                enterpriseName:enterpriseInfo.name,
                id:randomId('qua'),
                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 = new Date(info.StartDate).valueOf();
            if (info.EndDate) addInfo.endDate = new Date(info.EndDate).valueOf();

            addList.push(addInfo);
        });
        await qualificationsData.addMany( addList);
    }
    
    return qccselectdata;
}
















