/**
 * 企业信息
 * 汇总
 * */
 
import { ApplyForUpdateConfig, GardenNoticeUpdateConfig, PolicyUpdateConfig, RegisterUpdateConfig, SettleInForUpdateConfig } from "../config/eccParam/enterprise";
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import * as enumConfig from "../config/enum/enum";
import { operationalData, paginateArray, selectData, selectManyTableData } from "../data/operationalData";
import { BizError } from "../util/bizError";
import { eccFormParam } from "../util/verificationParam";
import { ERRORENUM } from "../config/enum/errorEnum";
import { getMySqlMs, getToken, md5PwdStr, randomCode, randomId } from "../tools/system";
import moment = require("moment");
import { changeAdd, extractData } from "../util/piecemeal";
import { EnterpriseApplyForConfig } from "../config/splitResult/enterprise";
import { changeEnumValue } from "../util/verificationEnum";
import { on } from "process";
import { systemConfig } from "../config/serverConfig";

export async function allEnterpriseNameList() {
    let listList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过}, ["enterpriseName", "eId"]);

    let dataList = [];
    listList.forEach(info => {
        dataList.push({
            key:info.enterpriseName,
            value:info.eId
        })
    });

    return {dataList}
}


//企业申请上传资料
export async function enterpriseApplyFor(eId:string) {
    let filesList = ["eId", "uscc", "enterpriseName", "logonAddress", "logonTime"];
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);
    if (!enterpriseUserInfo || !enterpriseUserInfo.eId) {
        throw new BizError(ERRORENUM.请先申请入孵);
    }
    // let leaseFilesList = ["leaseId", "startTime", "endTime", "area", "leaseContract", "entryPlan", "businessLicense", "agreement", "tripartiteAgreement"];
    let leaseFilesList = ["leaseId", "startTime", "endTime", "area", 
    "sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong", "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua", "yaJinZhiFu", "cardCopy"];
    let leaseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.租赁信息, {eId}, leaseFilesList);
    enterpriseUserInfo.logonAddress = JSON.parse(enterpriseUserInfo.logonAddress);
    let dataInfo:any = extractData(EnterpriseApplyForConfig, enterpriseUserInfo);

    dataInfo.logonTime = moment(enterpriseUserInfo.logonTime).format("YYYY-MM-DD");
    // dataInfo.leaseTime = `${moment(leaseInfo.startTime).format("YYYY-MM-DD")}至${moment(leaseInfo.endTime).format("YYYY-MM-DD")}`;
    dataInfo.area = leaseInfo.area;

    dataInfo.sanFangXieYi = leaseInfo.sanFangXieYi;
    dataInfo.fuHuaXieYi = leaseInfo.fuHuaXieYi;
    dataInfo.fangWuZuLing = leaseInfo.fangWuZuLing;
    dataInfo.fuHuaXieYiBuChong = leaseInfo.fuHuaXieYiBuChong;
    dataInfo.chengXinChengNuoHan = leaseInfo.chengXinChengNuoHan;
    dataInfo.yingYeZhiZhao = leaseInfo.yingYeZhiZhao;
    dataInfo.ruFuZiLiao = leaseInfo.ruFuZiLiao;
    dataInfo.ruZhuJiHua = leaseInfo.ruZhuJiHua;
    dataInfo.yaJinZhiFu = leaseInfo.yaJinZhiFu;
    dataInfo.cardCopy = leaseInfo.cardCopy;

    /**下载用：模板 */
    dataInfo.sanFangXieYiModelUrl = "/yuyi/files/三方协议.docx"
    dataInfo.fuHuaXieYiModelUrl = "/yuyi/files/孵化协议最新版.docx"
    // dataInfo.fangWuZuLingModelUrl = ""
    dataInfo.fuHuaXieYiBuChongModelUrl = "/yuyi/files/孵化协议补充协议书.docx"
    dataInfo.chengXinChengNuoHanModelUrl = "/yuyi/files/诚信承诺函.docx"
    // dataInfo.yingYeZhiZhaoModelUrl = ""
    dataInfo.ruFuZiLiaoModelUrl = "/yuyi/files/入孵资料明细.xls"
    dataInfo.ruZhuJiHuaModelUrl = "/yuyi/files/孵化企业入驻计划.xlsx"
    // dataInfo.yaJinZhiFuModelUrl = ""
    // dataInfo.cardCopyModelUrl = ""

    // dataInfo.leaseContractModelUrl = "/yuyi/files/孵化协议模板.docx";
    // dataInfo.entryPlanModelUrl = "/yuyi/files/孵化企业入驻计划.xlsx";
    // dataInfo.tripartiteModelUrl = "/yuyi/files/三方协议.docx";

    return {dataInfo};
}

export async function updateEnterpriseApplyFor(eId:string, param) {
    const FuncName = "企业修改入驻信息";
    eccFormParam(FuncName, ApplyForUpdateConfig, param );
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);
    if (!resInfo || !resInfo.eId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    // 去掉审核状态的检查和更新逻辑
    // if (resInfo.state == 2) {
    //     throw new BizError(ERRORENUM.已审核请前往小程序登录)
    // } 

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.租赁信息, param, {eId});

    return {isSuccess:true};
}


/**
 * 经营数据列表
 * @param year 
 * @param enterpriseName 
 * @param page 
 * @returns 
 */
export async function enterpriseExamineList(year:number, enterpriseName:string, page:number) {
    // let selectParam:any = {isSubmit:enumConfig.STATE.是};
    let selectParam:any = {};
    if (year) selectParam = {annual:getMySqlMs(year)};

    let filesList = [ "mId", "annual", "quarter",  "BI", "TXP", "RD", "state"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName"], where:{} };
    if (enterpriseName) {
        manyTableInfo[TABLENAME.企业基础信息表].where["enterpriseName"] = {"%like%":enterpriseName}
    }

    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业经营信息, selectParam, filesList, manyTableInfo, page);
    let dataCount = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.企业经营信息, selectParam, null);

    let dataList = [];
    resInfo.forEach(info => {
        let dataInfo = {
            enterpriseName:info.enterprise.enterpriseName,
            mId:info.mId,
            annual:moment(info.annual).format("YYYY"),
            quarter: changeEnumValue(enumConfig.QUARTER, info.quarter),
            BI:info.BI,
            TXP:info.TXP,
            RD:info.RD,
            state:info.state
        };
        dataList.push(dataInfo);
    })
    
    dataList.sort( (a, b) => {
        return b.annual - a.annual;
    })

    return {dataList, dataCount};
}


export async function enterpriseExamineInfo(mId:string) {
    let filesList = [ "mId", "annual",  "BI", "TXP", "RD"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {mId}, filesList);
    if (!resInfo || !resInfo.mId) {
        throw new BizError(ERRORENUM.数据不存在);
    }

    let dataInfo = {
        mId:resInfo.mId,
        BI:resInfo.BI,
        TXP:resInfo.TXP,
        RD:resInfo.RD
    }

    return {dataInfo};
}

export async function enterpriseExamineUpdate( mId, param) {
    let filesList = [ "eId", "annual",  "BI", "TXP", "RD"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {mId}, filesList);
    if (!resInfo || !resInfo.eId) {
        throw new BizError(ERRORENUM.数据不存在);
    }

    let dataInfo = {
        BI:param.BI,
        TXP:param.TXP,
        RD:param.RD
    }

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业经营信息, dataInfo, {mId});

    return {dataInfo};
}

//企业审核通过
// export async function enterpriseExaminePass(mId) {
//     let filesList = [ "eId", "annual",  "BI", "TXP", "RD"];
//     let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {mId}, filesList);
//     if (!resInfo || !resInfo.eId) {
//         throw new BizError(ERRORENUM.数据不存在);
//     }

//     let dataInfo = {
//         state:enumConfig.STATE.是
//     }

//     await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业经营信息, dataInfo, {mId});

//     return {dataInfo};
// }


// --------------------------------------经营数据
export async function enterpriseManageList(enterpriseName:string, year:number, page:number) {
    let selectParam:any = {isSubmit:enumConfig.STATE.是};
    if (year) selectParam.annual = `${moment(year).format("YYYY")}-01-01 00:00:00`;

    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column: ["enterpriseName", "uscc", "eId"], where:{} };

    if (enterpriseName) {
        manyTableInfo[TABLENAME.企业基础信息表].where["enterpriseName"] = {"%like%":enterpriseName}
    }
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业经营信息, selectParam, ["mId", "BI", "TXP", "RD", "annual", "quarter"], manyTableInfo, page);
    let dataCountList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业经营信息, selectParam, ["eId"], manyTableInfo);
    let dataCount = dataCountList.length;

    let resData = [];
    resInfo.forEach( info => {
        let {BI, mId, TXP, RD, annual, quarter, enterprise} = info;
        let quarterStr = "第一季度";
        if (quarter) quarterStr = changeEnumValue(enumConfig.QUARTER, quarter);  
        let year = moment(annual).format("YYYY");
        resData.push({BI, mId, TXP, RD, annual:year, quarter, enterprise, quarterStr});
    })
    
    resData.sort( (a, b) => {
        return b.annual - a.annual || b.quarter - a.quarter;
    })

    let dataList = [];
    resData.forEach(info => {
        let {BI, mId, TXP, RD, annual, quarter, enterprise, quarterStr} = info;
        
        let dataInfo = {
            eId:enterprise.eId, //企业id
            enterpriseName:enterprise.enterpriseName, //企业名称
            uscc:enterprise.uscc, //统一信用代码
            BI, //营收（万元）
            TXP:TXP, //纳税（万元）
            RD:RD,//研发投入（万元）
            annual:`${moment(annual).format("YYYY")}-${quarterStr}`,//年度
            mId:mId
        };
        dataList.push(dataInfo);
    });

    return {dataList, dataCount};
}


export async function outPutEnterpriseManageList(enterpriseName:string, year:number, type:number, files) {
    let selectParam:any = {isSubmit:enumConfig.STATE.是};
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column: ["enterpriseName", "uscc", "eId"], where:{} };

    if (type == 1) {
        if (year) selectParam.annual = `${moment(year).format("YYYY")}-01-01 00:00:00`;
        if (enterpriseName) {
            manyTableInfo[TABLENAME.企业基础信息表].where["enterpriseName"] = {"%like%":enterpriseName}
        }
    }

    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业经营信息, selectParam, ["mId", "BI", "TXP", "RD", "annual", "quarter"], manyTableInfo);

    let dataList = [];
    let titleList = []
    let valueList = [];
    files.forEach(item => {
        titleList.push(item.key);
        valueList.push(item.value);
    });
    dataList.push(titleList);

    let resData = [];
    resInfo.forEach( info => {
        let {BI, mId, TXP, RD, annual, quarter, enterprise} = info;
        let quarterStr = "第一季度";
        if (quarter) quarterStr = changeEnumValue(enumConfig.QUARTER, quarter);  

        let year = moment(annual).format("YYYY");
        resData.push({BI, mId, TXP, RD, annual:year, quarter, enterprise, quarterStr});
    })
    
    resData.sort( (a, b) => {
        return b.annual - a.annual || b.quarter - a.quarter;
    })

    resData.forEach(info => {
        let subList = [];
        let {BI, mId, TXP, RD, annual, quarter, enterprise, quarterStr} = info;
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterprise.enterpriseName);
            if (subInfo == "uscc") subList.push(enterprise.uscc);
            if (subInfo == "BI") subList.push(BI);
            if (subInfo == "TXP") subList.push(TXP);
            if (subInfo == "RD") subList.push(RD);
            if (subInfo == "annual") subList.push(`${moment(annual).format("YYYY")}-${quarterStr}`);
        });
        dataList.push(subList);
    });

    return {dataList};
}


/**
 * 经营数据-编辑
 * @param mId 
 * @param BI 营收（万元）
 * @param TXP 纳税（万元）
 * @param RD 研发投入（万元）
 * @returns 
 */
export async function updateManage(mId:string, BI:string, TXP:string, RD:string) {
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {mId}, ["mId", "BI", "TXP", "RD", "annual", "quarter"]);
    if (!resInfo || !resInfo.mId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业经营信息, {BI, TXP, RD}, {mId});

    return {isSuccess:true};
}



//===融资
export async function enterpriseFinancingList(enterpriseName:string, year:number, page:number) {
    // let selectParam:any = {state:enumConfig.STATE.是};
    let selectParam:any = {};
    if (enterpriseName) {
        selectParam.enterpriseName = {"%like%":enterpriseName}
    }
   
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业融资] = {
        column:["rId", "financingAmount", "financingRounds", "investmentDate", "investmentInstitutionsName" ], 
        where:{}
    };
    let filesList = ["enterpriseName", "uscc", "eId"];

    if (year) {
        let selectStartTime = getMySqlMs(year);
        let selectEndTime = getMySqlMs(moment(year).endOf('year').valueOf());
        manyTableInfo[TABLENAME.企业融资].where = {"investmentDate": {"%gt%":selectStartTime, "%lt%":selectEndTime}};
    }

    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo, page);
    // let dataCountList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo);
    
    let dataList = [];
    resInfo.forEach(info => {
        let {eId, enterpriseName, uscc, enterprise_financings} = info;
        if (enterprise_financings.length > 0) {
            enterprise_financings.forEach( item => {
                let dataInfo = {
                    eId,//企业id
                    enterpriseName, //企业名称
                    uscc, //统一信用代码
                    financingAmount:item.financingAmount, //融资金额（万元）
                    financingRounds:changeEnumValue(enumConfig.FINANCINGROUNDS, item.financingRounds), //融资轮次
                    investmentDate:moment(item.investmentDate).format("YYYY-MM-DD"),//获得投资时间
                    investmentInstitutionsName:item.investmentInstitutionsName,//投资机构名称
                };
                dataList.push(dataInfo);
            })
        }
        
    });

    dataList.sort( (a, b) => {
        return new Date(b.investmentDate).valueOf() - new Date(a.investmentDate).valueOf();
    })

    return {dataList, dataCount:dataList.length};
}


/**
 * 融资情况 查询企业下所有融资信息
 * @param eId 
 * @returns 
 */
export async function enterpriseFinancingAllYear(eId:string) {
    let filesList = ["eId","rId", "financingAmount", "financingRounds", "investmentDate", "investmentInstitutionsName" ];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业融资, {eId}, filesList);

    let dataList = [];
    resInfo.forEach(info => {
        let dataInfo = {
            eId,//企业id
            investmentDate:moment(info.investmentDate).format("YYYY-MM-DD"),//获得投资时间
            financingAmount:info.financingAmount, //融资金额（万元）
            financingRounds:changeEnumValue(enumConfig.FINANCINGROUNDS, info.financingRounds), //融资轮次
            investmentInstitutionsName:info.investmentInstitutionsName,//投资机构名称
        };
        dataList.push(dataInfo);
    });

    return {dataList};
}


/**
 * 融资情况当前数据下载
 * @param enterpriseName 
 * @param year 
 * @param type 
 * @param files 
 * @returns 
 */
export async function outPutEnterpriseFinancingList(enterpriseName:string, year:number, type:number, files) {
    let selectParam:any = {};
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业融资] = {
        column:["rId", "financingAmount", "financingRounds", "investmentDate", "investmentInstitutionsName" ], 
        where:{}
    };
    let filesList = ["enterpriseName", "uscc", "eId"];
    if (type == 1) {
        if (enterpriseName) {
            selectParam.enterpriseName = {"%like%":enterpriseName}
        }
        if (year) {
            let selectStartTime = getMySqlMs(year);
            let selectEndTime = getMySqlMs(moment(year).endOf('year').valueOf());
            manyTableInfo[TABLENAME.企业融资].where = {"investmentDate": {"%gt%":selectStartTime, "%lt%":selectEndTime}};
        }
    }

    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo);

    let dataList = [];
    let titleList = [];
    let valueList = [];
    files.forEach(item => {
        titleList.push(item.key);
        valueList.push(item.value);
    });
    dataList.push(titleList);

    resInfo.forEach(info => {
        let {enterpriseName, uscc, enterprise_financings} = info;
        let subList = [];
        if (enterprise_financings.length > 0) {
            enterprise_financings.forEach( item => {
                valueList.forEach(subInfo => {
                    if (subInfo == "enterpriseName") subList.push(enterpriseName);
                    if (subInfo == "uscc") subList.push(uscc);
                    if (subInfo == "financingAmount") subList.push(item.financingAmount);
                    if (subInfo == "financingRounds") subList.push(changeEnumValue(enumConfig.FINANCINGROUNDS, item.financingRounds));
                    if (subInfo == "investmentDate") subList.push(moment(item.investmentDate).format("YYYY-MM-DD"));
                    if (subInfo == "investmentInstitutionsName") subList.push(item.investmentInstitutionsName);
                })
                dataList.push(subList);
            });
        }
    });
    return {dataList};
}


export async function enterpriseTalentList(enterpriseName:string, page:number) {
    let selectParam:any = {};

    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName" ], where:{} };
    if (enterpriseName) {
        manyTableInfo[TABLENAME.企业基础信息表].where['enterpriseName'] = {"%like%":enterpriseName};
    }
    let filesList = ["name", "sex", "birth", "degree", "graduationSchool"];
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.创业团队, selectParam, filesList, manyTableInfo, page);

    let dataList = [];
    resInfo.forEach(info => {
        let {name, sex, birth, degree, graduationSchool, enterprise} = info;
        let dataInfo = {
            name, //姓名
            sex:changeEnumValue(enumConfig.SEX, sex), //性别
            birth:moment(birth).format("YYYY-MM-DD"), //出生年月
            degree:changeEnumValue(enumConfig.DEGREE, degree), //最高学历
            graduationSchool,//毕业学校
            enterpriseName:enterprise.enterpriseName,//企业名称
        };
        dataList.push(dataInfo);
    });

    return {dataList, dataCount:dataList.length};
}


export async function outPutEnterpriseTalentList(enterpriseName:string, type:number, files) {
    let selectParam:any = {};

    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName" ], where:{} };
    if (type == 1) {
        if (enterpriseName) {
            manyTableInfo[TABLENAME.企业基础信息表].where = {"enterpriseName": {"%like%":enterpriseName}};
        }
    }
    let filesList = ["name", "sex", "birth", "degree", "graduationSchool"];
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.创业团队, selectParam, filesList, manyTableInfo);

    let dataList = [];
    let titleList = [];
    let valueList = [];
    files.forEach(item => {
        titleList.push(item.key);
        valueList.push(item.value);
    });
    dataList.push(titleList);
    resInfo.forEach(info => {
        let {name, sex, birth, degree, graduationSchool, enterprise} = info;
        let subList = [];
      
        valueList.forEach(subInfo => {
            if (subInfo == "name") subList.push(name);
            if (subInfo == "sex") subList.push(changeEnumValue(enumConfig.SEX, sex));
            if (subInfo == "birth") subList.push(moment(birth).format("YYYY-MM-DD"));
            if (subInfo == "degree") subList.push(changeEnumValue(enumConfig.DEGREE, degree));
            if (subInfo == "graduationSchool") subList.push(graduationSchool);
            if (subInfo == "enterpriseName") subList.push(enterprise.enterpriseName);
        });
        dataList.push(subList);
    });

    return {dataList};
}



// export async function iprList(enterpriseName, page) {
//     let selectParam:any = {};
//     if (enterpriseName) {
//         selectParam.enterpriseName = {"%like%":enterpriseName};
//     }
//     let manyTableInfo:any = {};
//     manyTableInfo[TABLENAME.企业专利表] = {column:["year", "alienPatent", "classIPatent", "secondClassPatent", "thirdPentent"], where:{} };
//     manyTableInfo[TABLENAME.知识产权] = {column:["number"], where:{}};

//     let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业基础信息表, selectParam, ["enterpriseName", "uscc"], manyTableInfo, page);
//     let allDataList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["enterpriseName", "uscc"], manyTableInfo);
    
//     let dataList = [];
//     resInfo.forEach(info => {
//         let {uscc, enterpriseName, enterprise_iprs, enterprise_patents} = info;
//         let addItem = {
//             uscc, 
//             enterpriseName, 
//             alienPatent:undefined, 
//             classIPatent:undefined, 
//             secondClassPatent:undefined, 
//             thirdPentent:undefined,
//             count:undefined
//         };
//         for (let i = 0; i < enterprise_patents.length; i++) {
//             let item = enterprise_patents[i];
//             if (item.alienPatent) {
//                 if (addItem.alienPatent == undefined) addItem.alienPatent = 0;
//                 addItem.alienPatent += item.alienPatent;
//             } 
//             if (item.classIPatent) {
//                 if (addItem.classIPatent == undefined) addItem.classIPatent = 0;
//                 addItem.classIPatent += item.classIPatent;
//             } 
//             if (item.secondClassPatent) {
//                 if (addItem.secondClassPatent == undefined) addItem.secondClassPatent = 0;
//                 addItem.secondClassPatent += item.secondClassPatent;
//             } 
//             if (item.thirdPentent) {
//                 if (addItem.thirdPentent == undefined) addItem.thirdPentent = 0;
//                 addItem.thirdPentent += item.thirdPentent;
//             }
//         }
//         for (let i = 0; i < enterprise_iprs.length; i++) {
//             let item = enterprise_iprs[i];
//             if (item.number) {
//                 if (addItem.count == undefined) addItem.count = 0;
//                 addItem.count += item.number;
//             } 
//         }

//         for (let key in addItem) {
//             if (addItem[key] == undefined) addItem[key] = "-";
//         }
//         dataList.push(addItem);
//     });

    

//     return {dataList, dataCount:allDataList.length}; 
// }

/**
 * 知识产权及专利列表
 * @param enterpriseName 
 * @param page 
 * @returns 
 */
export async function iprList(enterpriseName, page) {
    let 商标 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.商标, {}, ["tmId", "eId", "qccId", "regNo", "name", "categoryId", "category", "person", "imageUrl", "flowStatusDesc", "RegDate"]);
    let 作品著作权 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.作品著作权, {}, ["crId", "eId", "owner", "category", "name", "registerNo", "registerDate", "publishDate", "finishDate"]);
    let 软件著作权 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.软件著作权, {}, ["scId", "eId", "category", "publishDate", "versionNo", "registerNo", "registerAperDate", "name", "shortName", "owner", "finishDevelopDate"]);
    let 专利 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.专利, {}, ["patentId", "eId", "category", "kindcode", "applicationNumber", "applicationDate", "publicationNumber", "publicationDate", "legalStatusDesc", "title", "agency", "kindCodeDesc", "IPCDesc", "inventorStringList", "assigneestringList"]);

    let 知识产权Map:any = {};
    if (商标.length) {
        商标.forEach( info => {
            if (!知识产权Map[info.eId]) 知识产权Map[info.eId] = {};
            if (!知识产权Map[info.eId][enumConfig.IPRALLTYPE.商标信息]) 知识产权Map[info.eId][enumConfig.IPRALLTYPE.商标信息] = [];
            知识产权Map[info.eId][enumConfig.IPRALLTYPE.商标信息].push(info)
        })
    }

    if (作品著作权.length) {
        作品著作权.forEach( info => {
            if (!知识产权Map[info.eId]) 知识产权Map[info.eId] = {};
            if (!知识产权Map[info.eId][enumConfig.IPRALLTYPE.作品著作权]) 知识产权Map[info.eId][enumConfig.IPRALLTYPE.作品著作权] = [];
            知识产权Map[info.eId][enumConfig.IPRALLTYPE.作品著作权].push(info)
        })
    }

    if (软件著作权.length) {
        软件著作权.forEach( info => {
            if (!知识产权Map[info.eId]) 知识产权Map[info.eId] = {};
            if (!知识产权Map[info.eId][enumConfig.IPRALLTYPE.软件著作权]) 知识产权Map[info.eId][enumConfig.IPRALLTYPE.软件著作权] = [];
            知识产权Map[info.eId][enumConfig.IPRALLTYPE.软件著作权].push(info)
        })
    }

    if (专利.length) {
        //1.发明公布，2.发明授权，3.实用新型，4.外观设计
        专利.forEach( info => {
            if (!知识产权Map[info.eId]) 知识产权Map[info.eId] = {};
            if (!知识产权Map[info.eId][enumConfig.IPRALLTYPE.发明专利]) 知识产权Map[info.eId][enumConfig.IPRALLTYPE.发明专利] = [];
            if (!知识产权Map[info.eId][enumConfig.IPRALLTYPE.实用新型专利]) 知识产权Map[info.eId][enumConfig.IPRALLTYPE.实用新型专利] = [];
            if (!知识产权Map[info.eId][enumConfig.IPRALLTYPE.外观设计专利]) 知识产权Map[info.eId][enumConfig.IPRALLTYPE.外观设计专利] = [];

            let {kindcode} = info;
            if (kindcode == enumConfig.KUNDCODE.发明公布) {
                知识产权Map[info.eId][enumConfig.IPRALLTYPE.发明专利].push(info);
            } else if (kindcode == enumConfig.KUNDCODE.发明授权) {
                知识产权Map[info.eId][enumConfig.IPRALLTYPE.发明专利].push(info);
            } else if (kindcode == enumConfig.KUNDCODE.实用新型) {
                知识产权Map[info.eId][enumConfig.IPRALLTYPE.实用新型专利].push(info);
            } else if (kindcode == enumConfig.KUNDCODE.外观设计) {
                知识产权Map[info.eId][enumConfig.IPRALLTYPE.外观设计专利].push(info);
            }
        })
    }

    let eIdConf = [];
    for (let key in 知识产权Map) {
        eIdConf.push(key)
    }

    let selectParam:any = {};
    if (enterpriseName) {
        selectParam.enterpriseName = {"%like%":enterpriseName};
    }
    if (eIdConf.length) {
        selectParam.eId = {"%in%":eIdConf};
    }
    let resInfo = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业基础信息表, selectParam, []);
    let resData = [];
    resInfo.forEach(info => {
        let 知识产权数量 = {
            商标信息 : 0,
            作品著作权 : 0,
            软件著作权 : 0,
            外观设计专利 : 0,
            实用新型专利 : 0,
            发明专利 : 0,
        };

        let count = 0;
        if (Object.keys(知识产权Map).length) {
            if (Object.keys(知识产权Map[info.eId]).length) {
                if (知识产权Map[info.eId][enumConfig.IPRALLTYPE.商标信息]) 知识产权数量.商标信息 = 知识产权Map[info.eId][enumConfig.IPRALLTYPE.商标信息].length;
                if (知识产权Map[info.eId][enumConfig.IPRALLTYPE.作品著作权]) 知识产权数量.作品著作权 = 知识产权Map[info.eId][enumConfig.IPRALLTYPE.作品著作权].length;
                if (知识产权Map[info.eId][enumConfig.IPRALLTYPE.软件著作权]) 知识产权数量.软件著作权 = 知识产权Map[info.eId][enumConfig.IPRALLTYPE.软件著作权].length;
                if (知识产权Map[info.eId][enumConfig.IPRALLTYPE.外观设计专利]) 知识产权数量.外观设计专利 = 知识产权Map[info.eId][enumConfig.IPRALLTYPE.外观设计专利].length;
                if (知识产权Map[info.eId][enumConfig.IPRALLTYPE.实用新型专利]) 知识产权数量.实用新型专利 = 知识产权Map[info.eId][enumConfig.IPRALLTYPE.实用新型专利].length;
                if (知识产权Map[info.eId][enumConfig.IPRALLTYPE.发明专利]) 知识产权数量.发明专利 = 知识产权Map[info.eId][enumConfig.IPRALLTYPE.发明专利].length;
            
                count = 知识产权数量.商标信息 + 知识产权数量.作品著作权 + 知识产权数量.软件著作权 + 知识产权数量.外观设计专利 + 知识产权数量.实用新型专利 + 知识产权数量.发明专利;

                let addInfo = {
                    eId:info.eId,
                    enterpriseName:info.enterpriseName,
                    count, //知识产权总数
                    shangbiao:知识产权数量.商标信息,//商标信息
                    zuopingzhuzuo:知识产权数量.作品著作权,//作品著作权
                    ruanjianzhuzuo:知识产权数量.软件著作权,//软件著作权
                    waiguansheji:知识产权数量.外观设计专利,//外观设计专利
                    shiyongxinxing:知识产权数量.实用新型专利,//实用新型专利
                    faming:知识产权数量.发明专利,//发明专利
                }

                resData.push(addInfo)
            }
        }
    })

    let paginatedData = await paginateArray(resData, page);
    let dataList = paginatedData.data;
    let dataCount = paginatedData.meta.totalItems;

    return {dataList, dataCount}; 
}

/**
 * 知识产权及专利列表详情
 * @param eId 
 * @returns
 */
export async function getiprDetails(eId:string) {
    let 商标 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.商标, {eId}, ["tmId", "eId", "qccId", "regNo", "name", "categoryId", "category", "person", "imageUrl", "flowStatusDesc", "RegDate"]);
    let 作品著作权 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.作品著作权, {eId}, ["crId", "eId", "owner", "category", "name", "registerNo", "registerDate", "publishDate", "finishDate", "iprUrl"]);
    let 软件著作权 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.软件著作权, {eId}, ["scId", "eId", "category", "publishDate", "versionNo", "registerNo", "registerAperDate", "name", "shortName", "owner", "finishDevelopDate", "iprUrl"]);
    let 专利 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.专利, {eId}, ["patentId", "eId", "category", "kindcode", "applicationNumber", "applicationDate", "publicationNumber", "publicationDate", "legalStatusDesc", "title", "agency", "kindCodeDesc", "IPCDesc", "inventorStringList", "assigneestringList", "iprUrl"]);

    let 知识产权Map:any = {};
    if (商标.length) {
        商标.forEach( info => {
            if (!知识产权Map[enumConfig.IPRALLTYPE.商标信息]) 知识产权Map[enumConfig.IPRALLTYPE.商标信息] = [];
            知识产权Map[enumConfig.IPRALLTYPE.商标信息].push(info)
        })
    }

    if (作品著作权.length) {
        作品著作权.forEach( info => {
            if (!知识产权Map[enumConfig.IPRALLTYPE.作品著作权]) 知识产权Map[enumConfig.IPRALLTYPE.作品著作权] = [];
            知识产权Map[enumConfig.IPRALLTYPE.作品著作权].push(info)
        })
    }

    if (软件著作权.length) {
        软件著作权.forEach( info => {
            if (!知识产权Map[enumConfig.IPRALLTYPE.软件著作权]) 知识产权Map[enumConfig.IPRALLTYPE.软件著作权] = [];
            知识产权Map[enumConfig.IPRALLTYPE.软件著作权].push(info)
        })
    }

    if (专利.length) {
        //1.发明公布，2.发明授权，3.实用新型，4.外观设计
        专利.forEach( info => {
            if (!知识产权Map[enumConfig.IPRALLTYPE.发明专利]) 知识产权Map[enumConfig.IPRALLTYPE.发明专利] = [];
            if (!知识产权Map[enumConfig.IPRALLTYPE.实用新型专利]) 知识产权Map[enumConfig.IPRALLTYPE.实用新型专利] = [];
            if (!知识产权Map[enumConfig.IPRALLTYPE.外观设计专利]) 知识产权Map[enumConfig.IPRALLTYPE.外观设计专利] = [];

            let {kindcode} = info;
            if (kindcode == enumConfig.KUNDCODE.发明公布) {
                知识产权Map[enumConfig.IPRALLTYPE.发明专利].push(info);
            } else if (kindcode == enumConfig.KUNDCODE.发明授权) {
                知识产权Map[enumConfig.IPRALLTYPE.发明专利].push(info);
            } else if (kindcode == enumConfig.KUNDCODE.实用新型) {
                知识产权Map[enumConfig.IPRALLTYPE.实用新型专利].push(info);
            } else if (kindcode == enumConfig.KUNDCODE.外观设计) {
                知识产权Map[enumConfig.IPRALLTYPE.外观设计专利].push(info);
            }
        })
    }

    let iprTypeInfo = {};
    let iprConf = [];
    for (let key in 知识产权Map) {
        let dataList:any = [];
        let iprType = parseInt(key);
        if (iprType == enumConfig.IPRALLTYPE.商标信息) {
            iprConf = ["tmId", "name", "RegDate", "imageUrl"]
        }
    
        if (iprType == enumConfig.IPRALLTYPE.作品著作权) {
            iprConf = ["crId", "name", "registerDate", "iprUrl"]
        }
    
        if (iprType == enumConfig.IPRALLTYPE.软件著作权) {
            iprConf = ["scId", "name", "registerAperDate", "iprUrl"]
        }
    
        if (iprType == enumConfig.IPRALLTYPE.外观设计专利) {
            iprConf = ["patentId", "title", "publicationDate", "iprUrl"]
        }
    
        if (iprType == enumConfig.IPRALLTYPE.实用新型专利) {
            iprConf = ["patentId", "title", "publicationDate", "iprUrl"]
        }
    
        if (iprType == enumConfig.IPRALLTYPE.发明专利) {
            iprConf = ["patentId", "title", "publicationDate", "iprUrl"]
        }

        知识产权Map[key].forEach( info => {
            let iprUrl = [];
            let iprUrlList = [];
            if (info[iprConf[3]]) iprUrlList = JSON.parse(info[iprConf[3]]);
            for (let i = 0; i < iprUrlList.length; i++) {
                let url = ``;
                if (iprUrlList[i].indexOf("http") > -1) {
                    url = `${iprUrlList[i]}`;
                } else url =`${systemConfig.imgFileUrl}${iprUrlList[i]}`;
                
                iprUrl.push(url);
            }

            let iprTime = "";
            if (info[iprConf[2]]) iprTime = moment(info[iprConf[2]]).format("YYYY-MM-DD");

            dataList.push({
                iprId:info[iprConf[0]],
                iprName:info[iprConf[1]],
                iprTime,
                iprUrl,
                timeNumber:new Date(info[iprConf[2]]).valueOf()
            })
        })

        //倒序
        dataList.sort(function(a, b) {
            return b.timeNumber - a.timeNumber;
        });

        iprTypeInfo[key] = dataList;
    }

    return iprTypeInfo;
}
           

/**
 * 资质认证列表
 * @param enterpriseName 
 * @param page 
 * @returns 
 */
export async function qiyeRenZheng(enterpriseName, page) {
    let selectParam:any = {state:enumConfig.CHANGESTATE.已通过};
    if (enterpriseName) {
        selectParam.enterpriseName = {"%like%":enterpriseName};
    }
    let manyTableInfo:any = {};
    let manyTableColumn = ["qId", "kxState","kxTime","kxNumber","kxImg", "zjtxState","zjtxTime","zjtxImg",
        "xjrPyState", "xjrPyTime","xjrPyImg", "gxjsState", "cxTime", "cxImg", "cxState" ,"gaoXinJiShuTime","gaoXinJiShuImg"];
    manyTableInfo[TABLENAME.企业资质] = {column:manyTableColumn, where:{} };
    manyTableInfo[TABLENAME.企业孵化信息] = {column:["fId", "eId"], where:{state: { "%between%": [enumConfig.FUHUASTATE.实体孵化, enumConfig.FUHUASTATE.虚拟孵化] }} };

    // let manyTableInfo:any = {};
    // let manyTableColumn = ["qId", "kxState","kxTime","kxNumber","kxImg", "zjtxState","zjtxTime","zjtxImg",
    //     "xjrState", "xjrTime","xjrImg","xjrPyState", "xjrPyTime","xjrPyImg",
    //     "gxjsState","gaoXinJiShuTime","gaoXinJiShuImg","listedState", "goPublicTime", "goPublicSector","other"];
    // manyTableInfo[TABLENAME.企业资质] = {column:manyTableColumn, where:{} };

    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业基础信息表, selectParam, ["enterpriseName", "uscc", "eId"], manyTableInfo, page);
    let allDataList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["enterpriseName", "uscc"], manyTableInfo);
    
    let dataList = [];
    for (let res = 0; res < resInfo.length; res++) {
        let {uscc, enterpriseName, enterprise_qualifications} = resInfo[res];
        let addItem:any = {
            uscc, 
            enterpriseName, 
            kxTime:"-",
            kxImg:[],
            kxState:"否",
            kxNumber:"-",
            zjtxTime:"-",
            zjtxState:"否",
            zjtxImg:[],
            // xjrState:"否",
            // xjrTime:"-",
            // xjrImg:[],
            xjrPyTime:"-",
            xjrPyImg:[],
            xjrPyState:"否",
            gxjsState:"否",
            // goPublicTime:"-",
            gaoXinJiShuImg:[],
            gaoXinJiShuTime:"-",
            cxTime:"-",
            cxState:"否",
            cxImg:[],
            // listedState:"否",
            // other:"",
            // goPublicSector:"",
        };

        let imgConf = ["kxImg", "zjtxImg", "xjrPyImg", "gaoXinJiShuImg", "cxImg"];

        let updateInfo:any = {};
        for (let i = 0; i < enterprise_qualifications.length; i++) {
            let item = enterprise_qualifications[i];
            /**状态与时间逻辑不对的话，修改状态 时间有数据，但状态为否，自动修改状态为是 */
            if (item.kxTime && item.kxState != enumConfig.STATE.是) {
                updateInfo.kxState = enumConfig.STATE.是;
                item.kxState = enumConfig.STATE.是;
            }
            if (item.zjtxTime && item.zjtxState != enumConfig.STATE.是) {
                updateInfo.zjtxState = enumConfig.STATE.是;
                item.zjtxState = enumConfig.STATE.是;
            }
            // if (item.xjrTime && item.xjrState != enumConfig.STATE.是) {
            //     updateInfo.xjrState = enumConfig.STATE.是; 
            //     item.xjrState = enumConfig.STATE.是; 
            // }
            if (item.xjrPyTime && item.xjrPyState != enumConfig.STATE.是) {
                updateInfo.xjrPyState = enumConfig.STATE.是; 
                item.xjrPyState = enumConfig.STATE.是; 
            }
            // if (item.goPublicTime && item.listedState != enumConfig.STATE.是) {
            //     updateInfo.listedState = enumConfig.STATE.是; 
            //     item.listedState = enumConfig.STATE.是; 
            // }
            if (item.gaoXinJiShuTime && item.gxjsState != enumConfig.STATE.是) {
                updateInfo.gxjsState = enumConfig.STATE.是; 
                item.gxjsState = enumConfig.STATE.是; 
            }
            if (item.cxTime && item.cxState != enumConfig.STATE.是) {
                updateInfo.cxState = enumConfig.STATE.是; 
                item.cxState = enumConfig.STATE.是; 
            }
            if(Object.keys(updateInfo).length > 0) await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业资质, updateInfo, {qId:item.qId});

            if (item.kxTime) addItem.kxTime = moment(item.kxTime).format("YYYY");
            if (item.kxState) addItem.kxState = changeEnumValue(enumConfig.STATE, item.kxState);
            // if (item.kxImg) addItem.kxImg = JSON.parse(item.kxImg);

            if (item.zjtxTime) addItem.zjtxTime = moment(item.zjtxTime).format("YYYY");
            if (item.zjtxState) addItem.zjtxState = changeEnumValue(enumConfig.STATE, item.zjtxState);
            // if (item.zjtxImg) addItem.zjtxImg = JSON.parse(item.zjtxImg);

            // if (item.xjrTime) addItem.xjrTime = moment(item.xjrTime).format("YYYY");
            // if (item.xjrState) addItem.xjrState = changeEnumValue(enumConfig.STATE, item.xjrState);
            // if (item.xjrImg) addItem.xjrImg = JSON.parse(item.xjrImg);

            if (item.xjrPyTime) addItem.xjrPyTime = moment(item.xjrPyTime).format("YYYY");
            if (item.xjrPyState) addItem.xjrPyState = changeEnumValue(enumConfig.STATE, item.xjrPyState);
            // if (item.xjrPyImg) addItem.xjrPyImg = JSON.parse(item.xjrPyImg);
            
            if (item.goPublicTime) addItem.goPublicTime = moment(item.goPublicTime).format("YYYY");
            if (item.listedState) addItem.listedState = changeEnumValue(enumConfig.STATE, item.listedState);

            if (item.gxjsState) addItem.gxjsState =changeEnumValue(enumConfig.STATE, item.gxjsState) ;
            if (item.gaoXinJiShuTime) addItem.gaoXinJiShuTime = moment(item.gaoXinJiShuTime).format("YYYY");
            // if (item.gaoXinJiShuImg) addItem.gaoXinJiShuImg = JSON.parse(item.gaoXinJiShuImg);

            if (item.cxTime) addItem.cxTime = moment(item.cxTime).format("YYYY");
            if (item.cxState) addItem.cxState = changeEnumValue(enumConfig.STATE, item.cxState);
            if (item.cxImg) addItem.cxImg = JSON.parse(item.cxImg);

            if (item.goPublicSector && item.goPublicSector != "[]") {
                // if (!addItem.goPublicSector) addItem.goPublicSector = [];
                addItem.goPublicSector = changeEnumValue(enumConfig.LISTINGSITUATION, JSON.parse(item.goPublicSector));
            }
            if (item.other) addItem.other = item.other;
            if (item.kxNumber) addItem.kxNumber = item.kxNumber;

            for (let j = 0; j < imgConf.length; j++) {
                let imgKey = imgConf[j];
                if (item[imgKey]) {
                    let imgArr = JSON.parse(item[imgKey]);
                    for (let k = 0; k < imgArr.length; k++) {
                        addItem[imgKey].push(`${systemConfig.imgFileUrl}${imgArr[k]}`);
                    }
                }
            }

            dataList.push(addItem);
        }
    };

    return {dataList, dataCount:allDataList.length};
}



export async function enterpriseHonor(enterpriseName, page) {
    let selectParam:any = {};
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName", "uscc"], where:{} };

    if (enterpriseName) {
        manyTableInfo[TABLENAME.企业基础信息表].where["enterpriseName"] = {"%like%":enterpriseName};
    }

    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业荣誉, selectParam, ["awardName", "awardingUnit", "awardTime", "awardLevel", "awardImg"], manyTableInfo, page);
    let allDataList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业荣誉, selectParam, ["awardName", "awardingUnit", "awardTime", "awardLevel", "awardImg"], manyTableInfo);
    
    let dataList = [];
    resInfo.forEach(info => {
        let {enterprise, awardName, awardingUnit, awardTime, awardLevel, awardImg} = info;

        let addItem = {
            uscc:enterprise.uscc, 
            enterpriseName:enterprise.enterpriseName,
            awardName, awardingUnit, 
            awardTime:moment(awardTime).format("YYYY"), 
            awardLevel:changeEnumValue(enumConfig.AWARDLEVEL,awardLevel),
            awardImg:JSON.parse(awardImg),
            // awardImg:JSON.parse(JSON.parse(awardImg)),
        };
        
        dataList.push(addItem);
    });

    return {dataList, dataCount:allDataList.length}; 
}




/**
 * 经营数据详情
 * @param eId 
 */
export async function getDetails(eId:string) {
    if (!eId) throw new BizError(ERRORENUM.参数错误, `经营数据详细信息缺失eId`)

    let details = {
        manage: await enterpriseManageById(eId),
        financing: await enterpriseFinancingById(eId),
        
    }

    return details;
}



/**
 * 详情 经营数据
 * @param eId 
 * @returns 
 */
export async function enterpriseManageById(eId:string) {
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column: ["enterpriseName", "uscc"], where:{eId} };
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业经营信息, {eId}, ["mId", "BI", "TXP", "RD", "annual", "state"], manyTableInfo);
    let resData = [];
    resInfo.forEach( info => {
        let {BI, mId, TXP,RD,state,annual, enterprise} = info;
        resData.push({BI, mId, TXP,RD,state,annual:moment(annual).format("YYYY"), enterprise});
    })
    
    resData.sort( (a, b) => {
        return b.annual - a.annual;
    })

    let dataList = [];
    resData.forEach(info => {
        let {BI, mId, TXP,RD,state,annual, enterprise} = info;

        let dataInfo = [
            {
                key:"企业名称",
                value:enterprise.enterpriseName
            },
            {
                key:"统一信用代码",
                value:enterprise.uscc
            },
            {
                key:"营收（万元）",
                value:BI
            },
            {
                key:"纳税（万元）",
                value:TXP
            },
            {
                key:"研发投入（万元）",
                value:RD
            },
            {
                key:"年度",
                value:annual
            },
            {
                key:"审核状态",
                value:state ? "已审核" : "未审核"
            }
        ]
        dataList.push(dataInfo);
    });

    return dataList;
}


/**
 * 详情 融资情况
 * @param eId 
 * @returns 
 */
export async function enterpriseFinancingById(eId:string) {
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业融资] = {column:["financingAmount", "financingRounds", "investmentDate", "investmentInstitutionsName" ], where:{eId} };
    let filesList = ["enterpriseName", "uscc"];
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {eId}, filesList, manyTableInfo);
    
    let resData = [];
    resInfo.forEach( info => {
        let {enterpriseName, uscc, enterprise_financings} = info;
        resData.push({enterpriseName, uscc, enterprise_financings, investmentDate:new Date(enterprise_financings[0].investmentDate).valueOf()});
    })
    
    resData.sort( (a, b) => {
        return b.investmentDate - a.investmentDate;
    })

    let dataList = [];
    resData.forEach(info => {
        let {enterpriseName, uscc, enterprise_financings} = info;

        let dataInfo = [
            {
                key:"企业名称",
                value:enterpriseName
            },
            {
                key:"统一信用代码",
                value:uscc
            },
            {
                key:"融资金额（万元）",
                value:enterprise_financings[0].financingAmount
            },
            {
                key:"融资轮次",
                value:changeEnumValue(enumConfig.FINANCINGROUNDS, enterprise_financings[0].financingRounds)
            },
            {
                key:"获得投资时间",
                value:moment(enterprise_financings[0].investmentDate).format("YYYY-MM-DD")
            },
            {
                key:"投资机构名称",
                value:enterprise_financings[0].investmentInstitutionsName
            },
        ]
        dataList.push(dataInfo);
    });

    return dataList;
}


//经营数据下载
export async function dwEnterpriseTable(eId: string, enterpriseName:string, type:number, files) {
    
    let selectParam:any = {};
    if (type ==1) {
        if (enterpriseName) {
            selectParam.enterpriseName = {"%like%":enterpriseName}
        }
    }
    
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column: ["enterpriseName", "uscc"], where:{eId} };
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业经营信息, {eId}, ["mId", "BI", "TXP", "RD", "annual", "state"], manyTableInfo);
    
    let dataList = [];
    let titleList = []
    let valueList = [];
    files.forEach(item => {
        titleList.push(item.key);
        valueList.push(item.value);
    });
    dataList.push(titleList);
    resInfo.forEach(info => {
        let {enterpriseName, uscc, BI, TXP, RD, annual, state} = info;

        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterpriseName);//企业名称
            if (subInfo == "uscc") subList.push(uscc); //统一信用代码
            if (subInfo == "BI") subList.push(BI);//营收
            if (subInfo == "TXP") subList.push(TXP);//纳税
            if (subInfo == "RD") subList.push(RD);//研发投入
            if (subInfo == "annual") subList.push(annual);//年度
            if (subInfo == "state") subList.push(state);//审核状态
        });
        dataList.push(subList);
    })

    return {dataList};
}

/**融资情况下载 */
export async function dwFinancingTable(eId: string, enterpriseName:string, type:number, files) {
    let selectParam:any = {};
    if (type ==1) {
        if (enterpriseName) {
            selectParam.enterpriseName = {"%like%":enterpriseName}
        }
    }
    
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业融资] = {column:["financingAmount", "financingRounds", "investmentDate", "investmentInstitutionsName" ], where:{eId} };
    let filesList = ["enterpriseName", "uscc"];
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {eId}, filesList, manyTableInfo);
    
    let dataList = [];
    let titleList = []
    let valueList = [];
    files.forEach(item => {
        titleList.push(item.key);
        valueList.push(item.value);
    });
    dataList.push(titleList);
    resInfo.forEach(info => {
        let {enterpriseName, uscc, financingAmount, financingRounds, investmentDate, investmentInstitutionsName} = info;
        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterpriseName);//企业名称
            if (subInfo == "uscc") subList.push(uscc); //统一信用代码
            if (subInfo == "financingAmount") subList.push(financingAmount);//融资金额
            if (subInfo == "financingRounds") subList.push(changeEnumValue(enumConfig.FINANCINGROUNDS, financingRounds));//融资轮次
            if (subInfo == "investmentDate") subList.push(moment(investmentDate).format("YYYY-MM-DD"));//获得投资时间
            if (subInfo == "investmentInstitutionsName") subList.push(investmentInstitutionsName);//投资机构名称
        });
        dataList.push(subList);
    })

    return {dataList};

}