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

const md5 = require("md5");


/**
 * 获取数据库所有企业uscc，进行企查查数据同步
 */
export async function qccData() {
    let enterpriseList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业基础信息表, {}, ["eId", "uscc", "enterpriseName"]);
    for (let i = 0; i < enterpriseList.length; i++) {
        let info = enterpriseList[i];
        console.log("开始同步企查查数据");
        await awaitData(info.uscc, info.eId);

        console.log(`${info.enterpriseName} 同步成功, eId：${info.eId}，下标 ${i}`);
    }
}


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


async function awaitData(uscc, eId) {
    await 工商信息(uscc, eId);


    await 专利查询(uscc, eId);
    // await 软件著作(uscc);
    // await 主要人员(uscc);
    // await 分支机构(uscc);
    // await 行政许可核查(uscc);
    // await 空壳扫描(uscc);q
    // await 准入尽职调查(uscc);
    // await 融资信息核查(uscc);
    // await 国际专利(uscc);
    // await 科创分(uscc);
    // await 资质证书(uscc);
    // await 专利查询(uscc);
    // await 失信核查(uscc);
    // await 严重违法核查(uscc);
    // await 企业对外投资核查(uscc);

    console.log("企查查数据同步成功");

}

/**
 * 封装了一个请求方法
 * @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 == "qcc专利Id") {
        query = {
            key:systemConfig.qccKey,
            id:uscc,
        };
    } else {
        query = {
            key:systemConfig.qccKey,
            searchKey:uscc,
            // keyNo:"云合智网（上海）技术有限公司"
        };
    }
    return {header, query};
}


async function 工商信息(uscc, eId) {
    let {header, query} = getReqParam(uscc);
    
    let 工商信息:any = await getQcc('https://api.qichacha.com/ECIInfoVerify/GetInfo', query, 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");

    //企业基础信息
    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[0].Name, //企业规模 TagList
        RAS: 工商信息.Status, //登记状态
        guanWang: 工商信息.ContactInfo.WebSite[0].Url, //官网地址
        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 = 工商信息.Partner[i];
            let findItemParam = {
                name:info.StockName,
                finalBenefitPercent:info.FinalBenefitPercent,
                stockPercent:info.StockPercent,
                stockType:info.StockType,
                realCapi:info.RealCapi,
            };
            if (数据是否存在(TABLENAME.股权结构, findItemParam)) {}
        }
        //删除历史记录数据
        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);
    }

    //企业标签表
    if (工商信息.TagList) {
        //删除历史记录数据
        await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业标签表, null, {eId});
        //同步最新记录
        let enterpriseLabelList = [];
        工商信息.TagList.forEach(info => {
            enterpriseLabelList.push({
                elId:randomId(TABLEID.企业标签表),
                eId,
                type:info.Type,
                labelName:info.Name,
            });
        });
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业标签表, enterpriseLabelList, null);
    }

    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) {
        //删除历史记录数据
        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,//变更类型
            });
        });
        
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.变更信息表, infoupdateList, null);
    }
    return
}


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 著作权软著:any = await getQcc('https://api.qichacha.com/CopyRight/SearchCopyRight', 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 qccselectdata:any = await getQcc('https://api.qichacha.com/PatentV4/SearchMultiPatents', query, header);

    if (Array.isArray(qccselectdata)) {
        console.log();
        //todo 没有做
        let addList = [];
        for (let i = 0; i < qccselectdata.length; i++) {
            let info = qccselectdata[i];
            let qcc专利Id = info.Id;
            let 专利详情 = await 专利详情查询(uscc, qcc专利Id);

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

    }

    return qccselectdata;
}



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




