/**
 * 企业信息
 * 汇总
 * */
 
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, 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:1}, ["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"];
    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.leaseContract = leaseInfo.leaseContract;
    dataInfo.entryPlan = leaseInfo.entryPlan;
    dataInfo.businessLicense = leaseInfo.businessLicense;
    dataInfo.agreement = leaseInfo.agreement;

    dataInfo.leaseContractModelUrl = "/yuyi/files/孵化协议模板.docx";
    dataInfo.entryPlanModelUrl = "/yuyi/files/孵化企业入驻计划.xlsx";
    dataInfo.agreementModelUrl = "/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 == 1) {
    //     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",  "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"),
            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.是};

    // let selectParam:any = {};
    // if (year) {
    //     selectParam.annual = getMySqlMs(year);
    // }
    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, quarterStr, enterprise, yearStr:`${year}${quarter}`});
    })
    
    resData.sort( (a, b) => {
        return b.yearStr - a.yearStr;
    })

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

    return {dataList, dataCount};
}


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

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

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

    resInfo.forEach(info => {
        let {BI, mId, TXP, RD,  annual, quarter,  enterprise} = info;
        let quarterStr = "第一季度";
        if (quarter ) quarterStr = changeEnumValue(enumConfig.QUARTER, quarter);
    
        let subList = [];
        // let stateStr = state ? "已审核" : "未审核";
        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}`);
            // if (subInfo == "annual") subList.push(moment(annual).format("YYYY"));
            // if (subInfo == "state") subList.push(stateStr);
        });
        dataList.push(subList);
    });

    return {dataList};
}

//企业审核通过
// export async function enterpriseManagePass(mId:string) {
//     let info = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {mId}, ["mId"]);

//     if (!info || !info.mId) throw new BizError(ERRORENUM.当前数据不存在);

//     await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业经营信息, {state:1}, {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};
}


export async function outPutEnterpriseFinancingList(enterpriseName:string,year:number, type:number, files) {
    // let selectParam:any = {state:enumConfig.STATE.是};
    let selectParam:any = {};
    if (type == 1) {
        if (enterpriseName) {
            selectParam.enterpriseName = {"%like%":enterpriseName}
        }
        if (year) {
            //selectParam.annual = getMySqlMs(year);
            selectParam.investmentDate = {">=": `${year}-01-01`, "<=": `${year}-12-31`};
        }
    }

    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业融资] = {column:["financingAmount", "financingRounds", "investmentDate", "investmentInstitutionsName" ], where:{} };
    let filesList = ["enterpriseName", "uscc","eId"];
    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 selectParam:any = {};
    if (enterpriseName) {
        selectParam.enterpriseName = {"%like%":enterpriseName};
    }
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.知识产权] = {column:["eId","number","iprType"], where:{}};

    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业基础信息表, selectParam, [], manyTableInfo, page);
    let allDataList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["enterpriseName", "uscc"], manyTableInfo);
    
    let dataList = [];
    resInfo.forEach(info => {
        let {eId,uscc, enterpriseName, enterprise_iprs} = info;
        let addItem = {
            eId,
            uscc, 
            enterpriseName,
            count:0,
            softwareCopyrightCount: 0,//软件著作权
            inventionPatentCount: 0,
            overseasPatentCount: 0,
            plantVarietyCount: 0,
            icLayoutCount: 0
        };
        for (let i = 0; i < enterprise_iprs.length; i++) {
            let item = enterprise_iprs[i];
            if (item.number) {
                addItem.count += item.number;
            }


            if (item.iprType === enumConfig.IPRALLTYPE.软件著作权) {
                addItem.softwareCopyrightCount += item.number;
            }else if (item.iprType === enumConfig.IPRALLTYPE.发明专利){
                addItem.inventionPatentCount += item.number;
            } else if (item.iprType === enumConfig.IPRALLTYPE.海外专利){
                addItem.overseasPatentCount += item.number;
            } else if (item.iprType === enumConfig.IPRALLTYPE.植物新品种){
                addItem.plantVarietyCount += item.number;
            } else if (item.iprType === enumConfig.IPRALLTYPE.集成电路布图){
                addItem.icLayoutCount += item.number;
            }
        }

         // 确保 count 是所有专利类型的总和
         addItem.count = addItem.softwareCopyrightCount
          + addItem.inventionPatentCount + addItem.overseasPatentCount
         + addItem.plantVarietyCount + addItem.icLayoutCount;

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

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

/**
 * 知识产权及专利列表详情
 * @param eId 
 * @returns
 */
export async function getiprDetails(eId: string) {
    let selectParam:any = {eId };
    
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.知识产权] = {column:["eId","iprName","year","iprUrl", "iprType"], where:{}};
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["enterpriseName", "uscc"], manyTableInfo);
    

     // 检查 resInfo 是否为空或 undefined
     if (!resInfo || resInfo.length === 0) {
        return {}; // 或者返回其他合适的默认值
    }

    let iprTypeInfo = {};

    let fileConfig =  {};
    fileConfig[enumConfig.IPRALLTYPE.软件著作权] = "softwareCopyright";
    fileConfig[enumConfig.IPRALLTYPE.发明专利] = "inventionPatent";
    fileConfig[enumConfig.IPRALLTYPE.海外专利] = "overseasPatent";
    fileConfig[enumConfig.IPRALLTYPE.植物新品种] = "plantVariety";
    fileConfig[enumConfig.IPRALLTYPE.集成电路布图] = "icLayout";

    resInfo[0].enterprise_iprs.forEach(info => {
        let {iprName, year, iprUrl, iprType} = info;
        let typeStr = fileConfig[iprType];
        let yearStr = moment(year).format("YYYY");
        if(!iprTypeInfo[typeStr]) iprTypeInfo[typeStr] = [];
        let iprUrlStr = [];
        //遍历iprUrl
        if (iprUrl) {
            let iprUrlArr = JSON.parse(iprUrl);
            for (let i = 0; i < iprUrlArr.length; i++) {
                iprUrlStr.push(`${systemConfig.imgFileUrl}${iprUrlArr[i]}`);
            }
        }
        iprTypeInfo[typeStr].push([
            {
                key:"著作名称",
                value: iprName
            },
            {
                key:"认定时间",
                value: `${yearStr}年`, 
            },
            {
                key:"证明材料",
                // value:iprUrl ? JSON.parse(iprUrl) : []
                value:iprUrlStr
            }
        ])
    });

    return iprTypeInfo;
}
           

/**
 * 资质认证列表
 * @param enterpriseName 
 * @param page 
 * @returns 
 */
export async function qiyeRenZheng(enterpriseName, page) {
    let selectParam:any = {};
    if (enterpriseName) {
        selectParam.enterpriseName = {"%like%":enterpriseName};
    }
    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:"-",
            listedState:"否",
            other:"",
            goPublicSector:"",
        };

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

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

}