/**
 * 在孵企业
 */

import moment = require("moment");
import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { operationalData, paginateArray, selectData, selectManyTableData } from "../data/operationalData";
import { changeAdd } from "../util/piecemeal";
import { changeEnumManyValue, changeEnumValue } from "../util/verificationEnum";
import * as enumConfig from "../config/enum/enum";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/enum/errorEnum";
import { getMySqlMs } from "../tools/system";
import { BUILDING } from "../config/enum/enum";


/**
 * 在孵企业列表
 * @param enterpriseName 
 * @param page 
 * @param logonStartTime 注册开始时间
 * @param logonEndTime 注册结束时间
 * @param startTime 租赁开始时间
 * @param endTime 租赁结束时间
 * @param building 园区楼号
 * @returns 
 */
 export async function enterpriseList(enterpriseName:string, page:number, logonStartTime:Number, logonEndTime:Number, startTime:Number, endTime:Number, building: number ) {
    let selectParam: any = {state: enumConfig.CHANGESTATE.已通过};
    if (enterpriseName) { 
        selectParam.enterpriseName = { "%like%": enterpriseName };
    }
    if (logonStartTime && logonEndTime) {
        selectParam.logonTime = {"%between%":[getMySqlMs(logonStartTime), getMySqlMs(logonEndTime)]}
    }

    // 主表字段过滤参数保持不变
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "logonAddress", "qiYeGuiMo"];
    let manyTableInfo: any = {};
    let rufuSelectParam = { state: { "%between%": [enumConfig.FUHUASTATE.实体孵化, enumConfig.FUHUASTATE.虚拟孵化] } };
    manyTableInfo[TABLENAME.企业孵化信息] = { column:["moveOutTime", "moveOutType", "startTime", "endTime"], where: rufuSelectParam};
    let resInfo = await selectManyTableData( OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo );
    
    /**查询租赁表信息 */
    let leaseWhere:any = {};
    if (startTime && endTime) {
        leaseWhere["%literal%"] = `(startTime BETWEEN '${getMySqlMs(startTime)}' and '${getMySqlMs(endTime)}' or endTime BETWEEN '${getMySqlMs(startTime)}' and '${getMySqlMs(endTime)}') `;
    }
    if (building) {
        if (!leaseWhere["%literal%"]) leaseWhere["%literal%"] = `building = ${building}`;
        else leaseWhere["%literal%"] += ` and building = ${building}`;
    }
    let zuLingList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.租赁信息, leaseWhere, ["eId", "area", "startTime", "endTime", "building", "roomNumber"]);
    let zaifuMap = {};
    if (zuLingList.length) {
        zuLingList.forEach(info => {
            zaifuMap[info.eId] = info;
        })
        
    } 
    let zaifuList = [];
    for (let info of resInfo) {
        let {
            eId,
            enterpriseName,
            uscc,
            logonTime,
            logonAddress,
            qiYeGuiMo,
            enterprise_fuhuas,
        } = info;

        if (Object.keys(zaifuMap).length) {
            if (!zaifuMap[eId]) continue; 
        }

        let leasesTime = '-';
        if (zaifuMap[eId]?.startTime) {
            leasesTime = `${moment(zaifuMap[eId].startTime).format("YYYY-MM-DD")}至${moment(zaifuMap[eId].endTime).format("YYYY-MM-DD")}`;
        }

        let fuhuaTime = '-';
        if (enterprise_fuhuas[0]?.startTime) {
            fuhuaTime = `${moment(enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`;
        }

        zaifuList.push({
            eId,
            enterpriseName, // 企业名称
            uscc, // 统一信用代码
            logonTime: moment(logonTime).format("YYYY-MM-DD"), // 注册日期
            logonAddress: changeAdd(JSON.parse(logonAddress)), // 注册地址
            qiYeGuiMo, // 企业规模
            fuhuaTime, // 孵化时间
            leasesTime, // 租赁时间
            area: zaifuMap[eId]?.area ? `${zaifuMap[eId].area}㎡` : '-',
            building: zaifuMap[eId]?.building || '-',
            // building:changeEnumValue(enumConfig.BUILDING, enterprise_leases[0].building),
            roomNumber: zaifuMap[eId]?.roomNumber || '-'
        });   
    }

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

    return {dataList, dataCount}; 
}


/**
 * 新增在孵企业迁出功能
 */
export async function enterpriseMoveOut(eId: string, moveOutType: number) {
    let filesList = ["eId", "moveOutTime", "state"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业孵化信息, { eId }, filesList);

    if (!resInfo || !resInfo.eId) throw new BizError(ERRORENUM.数据不存在);

    let addInfo = {
        state: enumConfig.FUHUASTATE.迁出,
        moveOutTime: getMySqlMs(),
        moveOutType
    };

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业孵化信息, addInfo, { eId });

    /**同步修改入孵企业面积 */
    
    /**在孵企业 当前时间小于孵化结束时间 */
    let 在孵面积 = 0;
    let araeParam = {column:["area", "unitPrice", "roomNumber", "rent"], where:{} };
    let zaifuTableInfo:any = {};
    zaifuTableInfo[TABLENAME.租赁信息] = araeParam;
    zaifuTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
    let zaifuResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过}, ["eId"], zaifuTableInfo );
    
    zaifuResList.forEach( info => {
        info.enterprise_leases.forEach( lease => {
            在孵面积 += parseFloat(lease.area);
        })
    })
    let yuyiList = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {}, []);
    if (在孵面积 != yuyiList.zaifuArea) await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.羽翼孵化器信息, {zaifuArea:在孵面积}, {yId:yuyiList.yId});

    return { isSuccess: true };
}


/**
 * 迁出企业列表
 * @param enterpriseName 
 * @param page 
 * @returns 
 */
export async function enterpriseMigrateList(enterpriseName:string, page:number) {
    let selectParam:any = {};
    if (enterpriseName) {
        selectParam.enterpriseName = {"%like%":enterpriseName}
    }

    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "logonAddress", "qiYeGuiMo"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.租赁信息] = {column:["area", "startTime", "endTime", "building", "roomNumber"], where:{} }; 
   
    // 关联企业孵化信息表，获取 moveOutTime 字段
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["moveOutTime","moveOutType", "startTime", "endTime"], where: { state:enumConfig.FUHUASTATE.迁出 } };
    
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo, page);

    let dataCount = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo);
    // let dataCount = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.企业基础信息表, selectParam, null);

    let dataList = [];
    resInfo.forEach(info => {
        let {eId, enterpriseName, uscc, logonTime, logonAddress, enterprise_fuhuas, qiYeGuiMo, enterprise_leases} = info;

        let formattedMoveOutTime = '-';
        if (enterprise_fuhuas[0].moveOutTime) {
            formattedMoveOutTime = moment(enterprise_fuhuas[0].moveOutTime).format("YYYY-MM-DD");
        } 
        
        let formattedMoveOutTypeName = '-';
        if (enterprise_fuhuas[0].moveOutType) {
            formattedMoveOutTypeName = changeEnumValue(enumConfig.EMIGRATIONTYPE, parseInt(String(enterprise_fuhuas[0].moveOutType)));
        }
        
        let leasesTime = '-'
        if (enterprise_leases[0].startTime){
            leasesTime = `${moment(enterprise_leases[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_leases[0].endTime).format("YYYY-MM-DD")}`;
        }

        let fuhuaTime = '-';
        if (enterprise_fuhuas[0].startTime){
            fuhuaTime = `${moment(enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`;
        }

        let dataInfo = {
            eId,
            enterpriseName, //企业名称
            uscc, //统一信用代码
            logonTime:moment(logonTime).format("YYYY-MM-DD"), //注册日期
            logonAddress:changeAdd(JSON.parse(logonAddress)), //注册地址
            moveOutTime:formattedMoveOutTime,//新增迁出时间
            moveOutType:formattedMoveOutTypeName,//新增迁出类型
            qiYeGuiMo,//企业规模
            leasesTime,//租赁时间
            fuhuaTime,//孵化时间
            area:enterprise_leases[0].area+"㎡",//租赁面积
            building:enterprise_leases[0].building,//楼号
            roomNumber:enterprise_leases[0].roomNumber,//室号
        };
        dataList.push(dataInfo);
        
    })
    
    return {dataList, dataCount:dataCount.length};
    
}

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

    let details = {
        enterprise: await enterpriseById(eId),
        manage: await enterpriseManageById(eId),
        financing: await enterpriseFinancingById(eId),
        honor: await enterpriseHonorById(eId),
        // talent: await enterpriseTalentById(eId),
        // service: await enterpriseServiceById(eId),
    }

    return details;
}


/**
 * 在孵企业详情 基础信息
 * @param eId 
 * @returns 
 */
export async function enterpriseById(eId:string) {
    let filesList = ["enterpriseName", "uscc", "logonTime", "logonAddress", "qiYeGuiMo"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.租赁信息] = {column:["area", "startTime", "endTime", "building","roomNumber"], where:{eId} };
    manyTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{eId} }; 

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

    let dataList = [];
    resInfo.forEach(info => {
        let {enterpriseName, uscc, logonTime, logonAddress, qiYeGuiMo, enterprise_leases, enterprise_fuhuas} = info;
        
        let fuhuasTime = '-'
        if (enterprise_fuhuas[0].startTime){
            fuhuasTime = `${moment(enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`;
        }
        let leasesTime = '-'
        if (enterprise_leases[0].startTime){
            leasesTime = `${moment(enterprise_leases[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_leases[0].endTime).format("YYYY-MM-DD")}`;
        }

        let dataInfo = [
            {
                key:"企业名称",
                value:enterpriseName
            },
            {
                key:"统一信用代码",
                value:uscc
            },
            {
                key:"注册日期",
                value:moment(logonTime).format("YYYY-MM-DD")
            },
            {
                key:"注册地址",
                value:changeAdd(JSON.parse(logonAddress))
            },
            {
                key:"企业规模",
                value:qiYeGuiMo
            },
            {
                key:"孵化时间",
                value:fuhuasTime
            },
            {
                key:"租赁时间",
                value:leasesTime
            },
            {
                key:"租赁面积",
                value:enterprise_leases[0].area+"㎡"
            },
            {
                key:"园区楼号",
                value:enterprise_leases[0].building
            },
            {
                key:"室号",
                value:enterprise_leases[0].roomNumber
            }
        ];
        dataList.push(dataInfo);
    })

    return dataList;
}


/**
 * 在孵企业详情 经营数据
 * @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","quarter"], manyTableInfo);
    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,quarterStr, enterprise} = info;
        info.annual = `${moment(info.annual).format("YYYY")}-${quarterStr}`; // 修改已有的 annual 变量

        let dataInfo = [
            {
                key:"企业名称",
                value:enterprise.enterpriseName
            },
            {
                key:"统一信用代码",
                value:enterprise.uscc
            },
            {
                key:"营收（万元）",
                value:BI
            },
            {
                key:"纳税（万元）",
                value:TXP
            },
            {
                key:"研发投入（万元）",
                value:RD
            },
            {
                key:"季度",
                value:info.annual
            },
            // {
            //     key:"季度",
            //     value:quarterStr
            // },
            // {
            //     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;
        if (enterprise_financings.length != 0) {
            enterprise_financings.forEach( item => {
                resData.push({enterpriseName, uscc, enterprise_financing:item, investmentDate:new Date(item.investmentDate).valueOf()});
            });
        }
    })
    
    resData.sort( (a, b) => {
        return b.investmentDate - a.investmentDate;
    })

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

    });

    return dataList;
}


/**
 * 在孵企业详情 荣誉奖项
 * @param eId 
 * @returns 
 */
 export async function enterpriseHonorById(eId:string) {
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName" ], where:{eId} };
    let filesList = ["awardName", "awardingUnit", "awardTime", "awardLevel"];
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业荣誉, {eId}, filesList, manyTableInfo);

    let dataList = [];
    resInfo.forEach(info => {
        let {awardName, awardingUnit, awardTime, awardLevel, enterprise} = info;

        let dataInfo = [
            {
                key:"企业名称",
                value:enterprise.enterpriseName
            },
            {
                key:"获奖名称",
                value:awardName
            },
            {
                key:"颁奖单位",
                value:awardingUnit
            },
            {
                key:"奖项等级",
                value:changeEnumValue(enumConfig.AWARDLEVEL, awardLevel)
            },
            {
                key:"奖项时间",
                value:awardTime ? moment(awardTime).format("YYYY") : "-"
            },
        ]

        dataList.push(dataInfo);
    });

    return dataList;
}


/**
 * 在孵企业详情 创始团队
 * @param eId 
 * @returns 
 */
export async function enterpriseTalentById(eId:string) {
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName" ], where:{eId} };
    let filesList = ["name", "sex", "birth", "degree", "graduationSchool"];
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.创业团队, {eId}, filesList, manyTableInfo);

    let dataList = [];
    resInfo.forEach(info => {
        let {name, sex, birth, degree, graduationSchool, enterprise} = info;

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

        dataList.push(dataInfo);
    });

    return dataList;
}


/**
 * 在孵企业详情 企业服务
 * @param eId 
 * @returns 
 */
export async function enterpriseServiceById(eId:string) {
    let filesList = ["esId", "needCategory", "applyTime", "followUpStatus", "resolveTime", "needContent"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["eId",  "enterpriseName"], where:{eId} };
    let resList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业服务表, {eId}, filesList, manyTableInfo );

    let resData = [];
    resList.forEach( info => {
        let {enterprise, needCategory, applyTime, followUpStatus, resolveTime, needContent} = info;
        resData.push({enterprise, needCategory, applyTime:new Date(applyTime).valueOf(), followUpStatus, resolveTime, needContent});
    })
    
    resData.sort( (a, b) => {
        return b.applyTime - a.applyTime;
    })

    let dataList = [];
    resData.forEach(info => {
        let dataInfo = [
            {
                key:"企业名称",
                value:info.enterprise.enterpriseName
            },
            {
                key:"需求类别",
                value:changeEnumValue(enumConfig.NEEDCATEGORY, info.needCategory)
            },
            {
                key:"申请时间",
                value:moment(info.applyTime).format("YYYY-MM-DD HH:mm")
            },
            {
                key:"跟进状态",
                value:changeEnumValue(enumConfig.FOLLOWUPSTATUS, info.followUpStatus)
            },
            {
                key:"解决时间",
                value:info.resolveTime ? moment(info.resolveTime).format("YYYY-MM-DD HH:mm") : '-'
            },
            {
                key:"需求内容",
                value:info.needContent
            },
        ]

        dataList.push(dataInfo);
    });

    return dataList;
}


/**
 * 加了注册时间，租赁时间，园区楼号筛选的
 */
export async function dwEnterpriseTable(enterpriseName:string, type:number, logonStartTime:number, logonEndTime:number, startTime:number, endTime:number, building: number ) {
    let files = [{key:"企业名称",value:"enterpriseName"},
                {key:"统一信用代码",value:"uscc"},
                {key:"注册时间",value:"logonTime"}, 
                {key:"注册地址",value:"logonAddress"}, 
                {key:"企业规模",value:"qiYeGuiMo"}, 
                {key:"孵化时间",value:"fuhuaStartTime"},//孵化时间
                {key:"租赁时间",value: "leaseStartTime"}, 
                {key:"租赁面积",value:"area",}, 
                {key:"楼号",value:"building"},//楼号
                {key:"室号",value:"roomNumber"},
                ];
    
    let selectParam: any = {state: enumConfig.CHANGESTATE.已通过};
    if (enterpriseName) { 
        selectParam.enterpriseName = { "%like%": enterpriseName };
    }
    if (logonStartTime && logonEndTime) {
        selectParam.logonTime = {"%between%":[getMySqlMs(logonStartTime), getMySqlMs(logonEndTime)]}
    }

    // 主表字段过滤参数保持不变
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "logonAddress", "qiYeGuiMo"];
    let manyTableInfo: any = {};
    let rufuSelectParam = { state: { "%between%": [enumConfig.FUHUASTATE.实体孵化, enumConfig.FUHUASTATE.虚拟孵化] } };
    manyTableInfo[TABLENAME.企业孵化信息] = { column:["moveOutTime", "moveOutType", "startTime", "endTime"], where: rufuSelectParam};
    let resInfo = await selectManyTableData( OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo );
    
    /**查询租赁表信息 */
    let leaseWhere:any = {};
    if (startTime && endTime) {
        leaseWhere["%literal%"] = `(startTime BETWEEN '${getMySqlMs(startTime)}' and '${getMySqlMs(endTime)}' or endTime BETWEEN '${getMySqlMs(startTime)}' and '${getMySqlMs(endTime)}') `;
    }
    if (building) {
        if (!leaseWhere["%literal%"]) leaseWhere["%literal%"] = `building = ${building}`;
        else leaseWhere["%literal%"] += ` and building = ${building}`;
    }
    let zuLingList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.租赁信息, leaseWhere, ["eId", "area", "startTime", "endTime", "building", "roomNumber"]);
    let zaifuMap = {};
    if (zuLingList.length) {
        zuLingList.forEach(info => {
            zaifuMap[info.eId] = info;
        })
        
    } 

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

    for (let info of resInfo) {
        let {
            eId,
            enterpriseName,
            uscc,
            logonTime,
            logonAddress,
            qiYeGuiMo,
            enterprise_fuhuas,
        } = info;

        if (Object.keys(zaifuMap).length) {
            if (!zaifuMap[eId]) continue; 
        }

        let leasesTime = '-';
        if (zaifuMap[eId]?.startTime) {
            leasesTime = `${moment(zaifuMap[eId].startTime).format("YYYY-MM-DD")}至${moment(zaifuMap[eId].endTime).format("YYYY-MM-DD")}`;
        }

        let fuhuaTime = '-';
        if (enterprise_fuhuas[0]?.startTime) {
            fuhuaTime = `${moment(enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`;
        }

        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterpriseName);//企业名称
            if (subInfo == "uscc") subList.push(uscc); //统一信用代码
            if (subInfo == "logonTime") subList.push(moment(logonTime).format("YYYY-MM-DD"));//注册日期
            if (subInfo == "logonAddress") subList.push(changeAdd(JSON.parse(logonAddress)));//注册地址
            if (subInfo == "qiYeGuiMo") subList.push(qiYeGuiMo);//企业规模
            if (subInfo == "fuhuaStartTime") subList.push(fuhuaTime);//孵化时间
            if (subInfo == "leaseStartTime") subList.push(leasesTime);//租赁时间
            if (subInfo == "area") subList.push(zaifuMap[eId]?.area ? `${zaifuMap[eId].area}㎡` : '-');//租赁面积
            if (subInfo == "building") subList.push(zaifuMap[eId]?.building || '-');//楼号
            if (subInfo == "roomNumber") subList.push(zaifuMap[eId]?.roomNumber || '-');//室号
        });

        dataList.push(subList); 
    }

    return {dataList};
}


export async function getAllDwOutPut(eId:string) {
    let details = {
        enterprise: await dwBasicInformation(eId),
        manage: await dwBusinessData(eId),
        financing: await dwFinancingSituatione(eId),
        honor: await dwHonorById(eId),
        // talent: await dwEnterpriseTeam(eId),
        // service: await dwEnterpriseService(eId),
    }

    return details;
}


/**
 * 下载单企业基础信息
 * @param eId 
 * @returns 
 */
export async function dwBasicInformation(eId:string) {
    let files = [{key:"企业名称",value:"enterpriseName"},
                {key:"统一信用代码",value:"uscc"},
                {key:"注册时间",value:"logonTime"}, 
                {key:"注册地址",value:"logonAddress"}, 
                {key:"企业规模",value:"qiYeGuiMo"}, 
                {key:"孵化时间",value:"fuhuaStartTime"},//孵化时间
                {key:"租赁时间",value: "leaseStartTime"}, 
                {key:"租赁面积",value:"area",}, 
                {key:"楼号",value:"building"},//楼号
                {key:"室号",value:"roomNumber"},
                ];
    let selectParam:any = {eId};
    
    let filesList = ["enterpriseName", "uscc", "logonTime", "logonAddress", "qiYeGuiMo"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.租赁信息] = {column:["area", "startTime", "endTime","building", "roomNumber"], where:{}}; 
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["startTime", "endTime"], where: { state:{"%ne%": enumConfig.FUHUASTATE.迁出} } };

    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, logonTime, logonAddress, qiYeGuiMo, enterprise_leases, enterprise_fuhuas} = info;
        let leasesTime = '-'
        if (enterprise_leases[0].startTime){
            leasesTime = `${moment(enterprise_leases[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_leases[0].endTime).format("YYYY-MM-DD")}`;
        }
        let fuhuasTime = '-';
        if (enterprise_fuhuas[0].startTime){
            fuhuasTime = `${moment(enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`;
        }
        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterpriseName);//企业名称
            if (subInfo == "uscc") subList.push(uscc); //统一信用代码
            if (subInfo == "logonTime") subList.push(moment(logonTime).format("YYYY-MM-DD"));//注册日期
            if (subInfo == "logonAddress") subList.push(changeAdd(JSON.parse(logonAddress)));//注册地址
            if (subInfo == "qiYeGuiMo") subList.push(qiYeGuiMo);//企业规模
            if (subInfo == "fuhuaStartTime") subList.push(fuhuasTime);//孵化时间
            if (subInfo == "leaseStartTime") subList.push(leasesTime);//租赁时间
            if (subInfo == "area") subList.push(enterprise_leases[0].area+"㎡");//租赁面积
            if (subInfo == "building") subList.push(enterprise_leases[0].building);//楼号
            if (subInfo == "roomNumber") subList.push(enterprise_leases[0].roomNumber);//室号
        });
       

        dataList.push(subList);
    })
    

    return {dataList};
    
}

/**
 * 下载单企业经营数据
 * @param eId 
 * @returns 
 */

export async function dwBusinessData(eId:string) {
    let files = [
        {key:"企业名称",value:"enterpriseName"},
        {key:"统一信用代码",value:"uscc"},
        {key:"营收（万元）",value:"BI"},
        {key:"纳税（万元）",value:"TXP"},
        {key:"研发投入（万元）",value:"RD"},
        {key:"季度",value:"annual"},
        // {key:"审核状态",value:"state"},
        // {key:"审核时间",value:"auditTime"}
    ];
    
    let filesList = ["enterpriseName", "uscc", "BI", "TXP", "RD", "annual","quarter"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column: ["enterpriseName", "uscc"], where:{eId} };
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业经营信息, {eId}, ["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 {enterprise, BI, TXP,RD, annual,quarter} = info;
        let quarterStr = "第一季度";
        if (quarter ) quarterStr = changeEnumValue(enumConfig.QUARTER, quarter);
       
        let subList = [];
        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(annual);//年度
            // if (subInfo == "annual") subList.push(new Date(annual).getFullYear()); // 年度，只保留年份
            if (subInfo == "annual") subList.push(`${moment(annual).format("YYYY")}-${quarterStr}`);
            // if (subInfo == "state") subList.push(state);//审核状态
        });
        dataList.push(subList);
    })
    
    return {dataList};
    
}

/**
 * 单企业融资情况todo
 * @param eId
 * @return
 */
export async function dwFinancingSituatione(eId: string) {

    let files = [{key:"企业名称",value:"enterpriseName"},
                {key:"统一信用代码",value:"uscc"},
                {key:"融资金额（万元）",value:"financingAmount"},
                {key:"融资轮次",value:"financingRounds"},
                {key:"获得投资时间",value:"investmentDate"},
                {key:"投资机构名称",value:"investmentInstitutionsName" },
            ];

    let selectParam:any = {eId};
   
    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, enterprise_financings} = info;
        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterpriseName);//企业名称
            if (subInfo == "uscc") subList.push(uscc); //统一信用代码
            if (subInfo == "financingAmount") subList.push(enterprise_financings[0].financingAmount);//融资金额
            if (subInfo == "financingRounds") subList.push(changeEnumValue(enumConfig.FINANCINGROUNDS, enterprise_financings[0].financingRounds));//融资轮次
            if (subInfo == "investmentDate") subList.push(moment(enterprise_financings[0].investmentDate).format("YYYY-MM-DD"));//获得投资时间 
            if (subInfo == "investmentInstitutionsName") subList.push(enterprise_financings[0].investmentInstitutionsName);//投资机构名称 
         });


        dataList.push(subList);
    })

    return {dataList};

}


/**
 * 下载单企业荣誉奖项
 * @param eId 
 * @returns 
 */
 export async function dwHonorById(eId:string) {
    let files = [
        {key:"企业名称",value:"enterpriseName"},
        {key:"获奖名称",value:"awardName"},
        {key:"颁奖单位",value:"awardingUnit"},
        {key:"奖项等级",value:"awardLevel"},
        {key:"奖项时间",value:"awardTime"},
    ];

    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName" ], where:{eId} };
    let filesList = ["awardName", "awardingUnit", "awardTime", "awardLevel"];
    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 {awardName, awardingUnit, awardTime, awardLevel, enterprise} = info;
        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterprise.enterpriseName);//企业名称
            if (subInfo == "awardName") subList.push(awardName);//获奖名称
            if (subInfo == "awardingUnit") subList.push(awardingUnit);//颁奖单位
            if (subInfo == "awardTime") subList.push(moment(awardTime).format("YYYY"));//奖项时间
            if (subInfo == "awardLevel") subList.push(changeEnumValue(enumConfig.AWARDLEVEL, awardLevel));//奖项等级
        });
        dataList.push(subList);
    })

    return {dataList};
}


/**
 * 下载单企业创始团队
 * @param name
 * @return
 */
export async function dwEnterpriseTeam(eId:string) {
    let files = [
        {key:"姓名",value:"name"},
        {key:"性别",value:"sex"},
        {key:"出生年月",value:"birth"},
        {key:"最高学历",value:"degree"},
        {key:"毕业学校",value:"graduationSchool"},
        {key:"企业名称",value:"enterpriseName"},
    ];
    
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["enterpriseName" ], where:{eId} };
    let filesList = ["name", "sex", "birth", "degree", "graduationSchool"];
    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 {name,sex,birth,degree,graduationSchool,enterprise} = info;
        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterprise.enterpriseName);//企业名称
            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);//毕业学校
        });
        dataList.push(subList);
    })

    return {dataList};

}

/**
 * 下载单企业企业服务
 * @param eId
 * @return
 */
export async function dwEnterpriseService(eId: string) {

    let files = [
        {key:"企业名称",value:"enterpriseName"},
        {key:"需求类别",value:"needCategory"},
        {key:"申请时间",value:"applyTime"},
        {key:"跟进状态",value:"followUpStatus"},
        {key:"解决时间",value:"resolveTime"},
        {key:"需求内容",value:"needContent"},
    ];

    let selectParam:any = {eId};


    let filesList = ["esId", "needCategory", "applyTime", "followUpStatus", "resolveTime","needContent"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column:["eId",  "enterpriseName"], where:{eId} };
    let resList = 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);
    resList.forEach(info => {
        let {enterprise,needCategory,applyTime,followUpStatus,resolveTime,needContent} = info;
        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterprise.enterpriseName);//公司名称
            if(subInfo == "needCategory") subList.push(needCategory);//需求类别
            if(subInfo == "applyTime") subList.push(applyTime);//申请时间
            if(subInfo == "followUpStatus") subList.push(followUpStatus);//跟进状态
            if(subInfo == "resolveTime") subList.push(resolveTime);//解决时间
            if(subInfo == "needContent") subList.push(needContent);//需求内容

        });
        dataList.push(subList);
    })

    return {dataList};

}


/**
 * 迁出企业下载
 * @params type:1(当前数据)，type:2(全部数据下载)
 */
export async function dwEnterpriseOutTable(enterpriseName: string, type: number, files) {
    let selectParam: any = {};
    if (type == 1) {
        if (enterpriseName) {
            selectParam.enterpriseName = { "%like%": enterpriseName }
        }
    }

    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "logonAddress", "qiYeGuiMo"];
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.租赁信息] = {column:["area", "startTime", "endTime","building", "roomNumber" ], where:{} }; 
   
    // 关联企业孵化信息表，获取 moveOutTime 字段
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["moveOutTime","moveOutType", "startTime", "endTime"], where: { state:enumConfig.FUHUASTATE.迁出 } };

    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 {eId, enterpriseName, uscc, logonTime, logonAddress, enterprise_fuhuas, qiYeGuiMo, enterprise_leases} = info;
        
        let formattedMoveOutTime = '-';
        if (enterprise_fuhuas[0].moveOutTime) {
            formattedMoveOutTime = moment(enterprise_fuhuas[0].moveOutTime).format("YYYY-MM-DD");
        } 
        
        let formattedMoveOutTypeName = '-';
        if (enterprise_fuhuas[0].moveOutType) {
            formattedMoveOutTypeName = changeEnumValue(enumConfig.EMIGRATIONTYPE, parseInt(String(enterprise_fuhuas[0].moveOutType)));
        }
        
        let leasesTime = '-'
        if (enterprise_leases[0].startTime){
            leasesTime = `${moment(enterprise_leases[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_leases[0].endTime).format("YYYY-MM-DD")}`;
        }
        let fuhuaTime = '-';
        if (enterprise_fuhuas[0].startTime){
            fuhuaTime = `${moment(enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`;
        }
        
        let subList = [];
        valueList.forEach(subInfo => {
            if (subInfo == "enterpriseName") subList.push(enterpriseName); //企业名称
            if (subInfo == "uscc") subList.push(uscc); //统一信用代码
            if (subInfo == "logonTime") subList.push(moment(logonTime).format("YYYY-MM-DD")); //注册日期
            if (subInfo == "logonAddress") subList.push(changeAdd(JSON.parse(logonAddress))); //注册地址
            if (subInfo == "qiYeGuiMo") subList.push(qiYeGuiMo); //企业规模
            if (subInfo == "startTime") subList.push(fuhuaTime);//孵化时间
            if (subInfo == "startTime") subList.push(leasesTime); //租赁时间
            if (subInfo == "area") subList.push(enterprise_leases[0].area + "㎡"); //租赁面积
            if (subInfo == "building") subList.push(enterprise_leases[0].building); //楼号
            if (subInfo == "roomNumber") subList.push(enterprise_leases[0].roomNumber); //室号
            if (subInfo == "moveOutTime") subList.push(formattedMoveOutTime); //迁出时间
            if (subInfo == "moveOutType") subList.push(formattedMoveOutTypeName); //迁出类型
        });

        dataList.push(subList);
    });

    return { dataList };
}

