/**
 * 孵化器看板
 */

import moment = require("moment");
import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { BUILDING, CHANGESTATE, EMIGRATIONTYPE, FUHUASTATE, INDUSTRY, OFFLINEPROMOTION, ONLINEPROMOTION, PROMOTIONTYPE, STATE } from "../config/enum/enum";
import { operationalData, selectData, selectManyTableData } from "../data/operationalData";
import { getIntervalYear, getMySqlMs, randomId } from "../tools/system";
import { changeEnumValue } from "../util/verificationEnum";
import { eccFormParam } from "../util/verificationParam";
import { YuYiBaseDataUpdateConfig } from "../config/eccParam/enterprise";
import { ERRORENUM } from "../config/enum/errorEnum";
import { BizError } from "../util/bizError";
import { extractData } from "../util/piecemeal";
import { YuYiBaseDataConfig } from "../config/splitResult/enterprise";


/**
 * 基本信息
 * @returns 
 */
export async function getBaseData() {
    let nowTime = getMySqlMs(new Date());

    let baseData = {
        fuhuaData:{ //孵化器数据
            // "总面积":0, //没有
            "孵化器总面积":0,
            "在孵面积":0,
            // "自用面积":0,
            "在孵企业":0,
            "迁出企业":0,
            "毕业企业":0,
            // "出租率": "", // 添加出租率字段
            // "园区面积":0,//新增
            // "产业规模": 0,
            // "总资产投入金额": 0,
            // "引入机构数量": 0,
            // "引入机构投资": 0,
        },
        fuhuaPinfen:0, //孵化器评分 没有该字段
        fuhuaInfo:{ //孵化器信息   
        },
        entryInfo: [], // 孵化器入驻信息
        promotionInfo: {} // 运营推广信息
    };

    let selectParam = { state:CHANGESTATE.已通过 };
    let araeParam = {column:["area", "unitPrice", "roomNumber", "rent", "startTime", "endTime"], where:{} };
    let zaifuTableInfo:any = {};
    zaifuTableInfo[TABLENAME.租赁信息] = araeParam;
    zaifuTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{state:{"%ne%":FUHUASTATE.迁出}} };
    let zaifuResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["eId"], zaifuTableInfo );
    
    if (zaifuResList) baseData.fuhuaData["在孵企业"] = zaifuResList.length;
    // zaifuResList.forEach( info => {
    //     info.enterprise_leases.forEach( lease => {
    //         baseData.fuhuaData["在孵面积"] += parseFloat(lease.area);
    //     })
    // })
    // 累加在孵面积（考虑租赁时间）
    // zaifuResList.forEach(info => {
    //     info.enterprise_leases.forEach(lease => {
    //         // 确认租赁时间在有效范围内
    //             baseData.fuhuaData["在孵面积"] += parseFloat(lease.area);
    //         // if (nowTime >= lease.startTime && nowTime <= lease.endTime) {
    //         //     baseData.fuhuaData["在孵面积"] += parseFloat(lease.area);
    //         // }
    //     });
    // });
    // baseData.fuhuaData["在孵面积占比"] = ((baseData.fuhuaData["在孵面积(㎡)"] / baseData.fuhuaData["总面积(㎡)"])*100).toFixed(2) + "%";
    /**在孵企业面积 */
    let {孵化器总面积, 在孵企业面积, 在孵企业面积占比, 各楼栋在孵企业面积} = await get在孵企业面积();
    baseData.fuhuaData["在孵面积"] = 在孵企业面积;

    /**迁出企业 */
    let qianchuList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {state:FUHUASTATE.迁出}, {});
    if (qianchuList) baseData.fuhuaData["迁出企业"] = qianchuList.length;

    /**毕业企业 */
    // let biyeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {graduationTime:{"%ne%":null}}, {});
    // let biyeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {moveOutType:EMIGRATIONTYPE.毕业迁出}, {});
    let biyeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {"%or%":[{moveOutType:EMIGRATIONTYPE.毕业迁出}, {moveOutType:EMIGRATIONTYPE.毕业未迁出}]}, {});
    if (biyeList) baseData.fuhuaData["毕业企业"] = biyeList.length;
    
    /**孵化器信息 */
    let yuyiList = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {}, []);
    if (baseData.fuhuaData["在孵面积"] != yuyiList.zaifuArea) await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.羽翼孵化器信息, {zaifuArea:baseData.fuhuaData["在孵面积"]}, {yId:yuyiList.yId});
    
    if (yuyiList) {
        // baseData.fuhuaData["总面积"] = yuyiList.totalArea;
        baseData.fuhuaData["孵化器总面积"] = yuyiList.totalArea;
        // baseData.fuhuaData["在孵面积"] = yuyiList.zaifuArea;
        // baseData.fuhuaData["自用面积"] = yuyiList.ziyonArea;   
        // baseData.fuhuaData["园区面积"] = yuyiList.parkArea;//新增
        // baseData.fuhuaData["产业规模"] = yuyiList.industrialScale;
        // baseData.fuhuaData["总资产投入金额"] = yuyiList.totalAssetInvestmentAmount;
        // baseData.fuhuaData["引入机构数量"] = yuyiList.numberOfInstitutionsIntroduced;
        // baseData.fuhuaData["引入机构投资"] = yuyiList.introduceInstitutionalInvestment;
        // baseData.fuhuaData["出租率"] = yuyiList.rentRate;//出租率

        baseData.fuhuaInfo = {
            "运营名称":yuyiList.operateName,
            "孵化器名称":yuyiList.name,
            "统一社会信用代码":yuyiList.uscc,
            "注册时间":yuyiList.registerTime,
            "孵化级别":yuyiList.incubateLv,
            "孵化器认定时间":yuyiList.incubateTime,
            "孵化领域":yuyiList.incubateField,
            "机构性质":yuyiList.natureInstitution,
            "是否成立投资基金":yuyiList.fundedReserve,//
            "联系人":yuyiList.contacts,
            "负责人":yuyiList.personCharge,
            "手机号码":yuyiList.phone,
            "孵化器简介":yuyiList.synopsis,
        }
    }

    /**
     * 孵化器入驻信息
     */
    let entryList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.入驻信息表, {}, [`info_enterId`, `building`, `occupancyRate`, `enteredEnterprises`]);
    let 入驻企业 = await get入驻企业列表();
    let 备案孵化面积 = {
        "1":4800,
        "3":6200,
        "4":13200
    }

    let 入孵率占比 = {
        "1":"",
        "3":"",
        "4":""
    }
    //这栋楼的在孵企业总面积 / 这栋楼的备案面积
    let 入孵率1 = (各楼栋在孵企业面积["1"] / 备案孵化面积["1"]) * 100;
    let 入孵率3 = (各楼栋在孵企业面积["3"] / 备案孵化面积["3"]) * 100;
    let 入孵率4 = (各楼栋在孵企业面积["4"] / 备案孵化面积["4"]) * 100;

    入孵率占比["1"] = 入孵率1.toFixed(2) + "%";
    入孵率占比["3"] = 入孵率3.toFixed(2) + "%";
    入孵率占比["4"] = 入孵率4.toFixed(2) + "%";
    if (入孵率1 > 100) 入孵率占比["1"] = "100%";
    if (入孵率3 > 100) 入孵率占比["3"] = "100%";
    if (入孵率4 > 100) 入孵率占比["4"] = "100%";

    let entryInfo = {
        "1":{"入孵率":入孵率占比["1"], "入驻企业":入驻企业[BUILDING["1号楼"]].length}, 
        "3":{"入孵率":入孵率占比["3"], "入驻企业":入驻企业[BUILDING["3号楼"]].length}, 
        "4":{"入孵率":入孵率占比["4"], "入驻企业":入驻企业[BUILDING["4号楼"]].length}
    };

    for (let key in entryInfo) {
        let 入驻信息updateInfo = {occupancyRate:entryInfo[key].入孵率, enteredEnterprises:entryInfo[key].入驻企业};
        let updateParam = {building:key}
        await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.入驻信息表, 入驻信息updateInfo, updateParam);
    }
    
    if (entryList.length) {
        entryList.forEach( info => {
            // let  = changeEnumValue(BUILDING, info.building);
            let building = info.building;
            if (!entryInfo[building]) {
                entryInfo[building] = { "入孵率": "", "入驻企业": "" };
            }
            // entryInfo[building].入孵率 = info.occupancyRate;
            entryInfo[building].入驻企业 = 入驻企业[building].length;
        })
    }

    baseData.entryInfo = [];
    for (let key in entryInfo) {
        let dataList = [];
        for (let name in entryInfo[key]) {
            dataList.push({key:name, value:entryInfo[key][name]});
        }
        baseData.entryInfo.push({name:changeEnumValue(BUILDING, parseInt(key)), dataList});
    }

    /**
     * 运营推广(次数)
     */
    let promotionList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.运营推广信息表,{}, ["opId","promotionType", "promotionApp", "promotionNum"]);
    let promotionInfo = {"线上推广": {"视频号":0, "抖音":0, "小红书":0},  "线下推广": {"活动宣讲":0, "三方机构合作":0}};
    if (promotionList.length) {
        promotionList.forEach( info => {
            let appStr = "";
            if (info.promotionType == PROMOTIONTYPE.线上推广) {
                appStr = changeEnumValue(ONLINEPROMOTION, info.promotionApp);
                promotionInfo["线上推广"][appStr] = info.promotionNum;
            } else if (info.promotionType == PROMOTIONTYPE.线下推广) {
                appStr = changeEnumValue(OFFLINEPROMOTION, info.promotionApp);
                promotionInfo["线下推广"][appStr] = info.promotionNum;
            }
        })
    }

    baseData.promotionInfo = {"线上推广": [],  "线下推广": []};
    for (let key in promotionInfo) {
        let infoData = promotionInfo[key];
        for (let name in infoData) {
            baseData.promotionInfo[key].push({key:name, value:infoData[name]});
        }
    }

    return {baseData};
}



/**
 * 获取各个楼栋的企业列表
 * @returns 
 */
export async function get入驻企业列表() {
    // 获取当前时间
    let nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
    let fhColumn = ["fId", "eId", "startTime", "endTime", "state", "virtualCause", "virtualCauseDes", "moveOutType",
    "moveOutTrace", "moveOutCause", "moveOutTime", "graduationTime", ];
    let 租赁Column = ["eId", "year", "alienPatent", "classIPatent", "secondClassPatent", "thirdPentent"];
    let 在孵租赁联查includeConf = {};
    在孵租赁联查includeConf[TABLENAME.企业孵化信息] = { cloum: fhColumn, where: { state: { "%between%": [FUHUASTATE.实体孵化, FUHUASTATE.虚拟孵化] } } };
    在孵租赁联查includeConf[TABLENAME.租赁信息] = { cloum: 租赁Column, where: {} }
    let 在孵租赁联查dbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { state: CHANGESTATE.已通过 }, ["enterpriseName", "industry", "qiYeGuiMo"], 在孵租赁联查includeConf);

    let 楼栋Map = {};
    在孵租赁联查dbList.forEach( info => {
        let {enterprise_fuhuas, enterprise_leases, enterpriseName, industry, qiYeGuiMo} = info;
        // let building = changeEnumValue(BUILDING, parseInt(enterprise_leases[0].building))
        let building = enterprise_leases[0].building;
        if (!楼栋Map[building]) 楼栋Map[building] = [];
        // let intervalYear = getIntervalYear(new Date(enterprise_fuhuas[0].startTime), new Date(enterprise_fuhuas[0].endTime));
        let intervalYear = getIntervalYear(new Date(enterprise_fuhuas[0].startTime), new Date());
        let industryStr = changeEnumValue(INDUSTRY, industry) || "-";
        楼栋Map[building].push([enterpriseName, moment(enterprise_fuhuas[0].startTime).format("YY/MM/DD"), intervalYear, industryStr, qiYeGuiMo]);
    })

    return 楼栋Map;
}


export async function getOperateData(year) {
    let yearTime = moment(year, "YYYY").startOf('year').format("YYYY-MM-DD");
    console.log("yearTime:", yearTime);

    let operateData = {
        "当前在孵企业数": 0,
        // "在孵企业数变化趋势": [], // 修改：不再区分实体/虚拟
        "在孵企业数变化趋势": {
            "在孵企业": []
        },
        "毕业企业数变化趋势": {
            "毕业企业": []
        },
        "企业需求新增趋势": [],
        "在孵企业行业领域": [],
    };
    let qushiConf = { "01": 0, "02": 0, "03": 0, "04": 0, "05": 0, "06": 0, "07": 0, "08": 0, "09": 0, "10": 0, "11": 0, "12": 0 };

    /**在孵企业 */
    let fhColumn = ["fId", "eId", "startTime", "endTime", "state", "virtualCause", "virtualCauseDes", "moveOutType",
        "moveOutTrace", "moveOutCause", "moveOutTime", "graduationTime", ];
    let 在孵dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {state: { "%between%": [FUHUASTATE.实体孵化, FUHUASTATE.虚拟孵化] }}, fhColumn);
    // 新增：统一统计每个月的数据
    let zaifuInfo = { ...qushiConf }; // 初始化每月数据为0
    在孵dbList.forEach(info => {
        let year = moment(info.startTime).format("YYYY");
        let month = moment(info.startTime).format("MM");

        if (year === moment(yearTime).format("YYYY")) {
            operateData.当前在孵企业数 += 1;
            zaifuInfo[month] += 1;
        }
    })

    operateData.在孵企业数变化趋势.在孵企业 = Object.keys(zaifuInfo)
        .map(key => ({ key, value: zaifuInfo[key].toString() }))
        .sort((a, b) => parseInt(a.key) - parseInt(b.key));


    /**毕业企业 */
    let biyeList = await selectData(
        OPERATIONALDATATYPE.查询多个,
        TABLENAME.企业孵化信息,
        {"%or%":[{ moveOutType:EMIGRATIONTYPE.毕业迁出 }, { moveOutType:EMIGRATIONTYPE.毕业未迁出 }]}, {}); // 只查毕业迁出的企业

    let biyeInfo = { ...qushiConf }; // 每月初始化为0

    biyeList.forEach(info => {
        let graduationTime = info.graduationTime || info.moveOutTime; // 如果graduationTime不存在用moveOutTime代替
        if (!graduationTime) return;

        let year = moment(graduationTime).format("YYYY");
        let month = moment(graduationTime).format("MM");

        if (year === moment(yearTime).format("YYYY")) {
            biyeInfo[month] += 1;
        }
    });

    operateData.毕业企业数变化趋势.毕业企业 = Object.keys(biyeInfo)
        .map(key => ({ key, value: biyeInfo[key].toString() }))
        // .sort((a, b) => a.key - b.key);
        .sort((a, b) => parseInt(a.key) - parseInt(b.key));
    
    //将 industry 字符串转换为数组
    let manyTableInfo: any = {}
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: {state: { "%between%": [FUHUASTATE.实体孵化, FUHUASTATE.虚拟孵化] }} };
    manyTableInfo[TABLENAME.租赁信息] = { column: ["area", "startTime", "endTime"], where: {} };
    let fhdbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { state: CHANGESTATE.已通过 }, ["industry", "eId"], manyTableInfo);
    
    let industryMap = {};
    fhdbList.forEach(info => {
        let { industry, enterprise_fuhuas } = info;
        let startYear = moment(enterprise_fuhuas[0].startTime).format("YYYY");
        let endYear = moment(enterprise_fuhuas[0].endTime).format("YYYY");
        if (moment(startYear).format("YYYY") <= year && moment(endYear).format("YYYY") >= year) {
            //行业领域分布
            if (industry) {
                let industryList = JSON.parse(industry);
                for (let i = 0; i < industryList.length; i++) {
                    let industryStr = changeEnumValue(INDUSTRY, industryList[i]);
                    if (!industryMap[industryStr]) industryMap[industryStr] = 0;
                    industryMap[industryStr] += 1;
                }
            }
        }
        
    })
    for (let key in INDUSTRY) {
        let anyKey: any = key;
        if (isNaN(anyKey)) {
            let keyStr = key;
            operateData.在孵企业行业领域.push({ key: keyStr, value: industryMap[keyStr] || 0 });
        }
    }
    
    /**企业需求新增趋势 */
    //获取所有企业服务表联查企业信息表 applyTime:申请服务时间
    let 企业服务dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业服务表, {applyTime: { "%gt%": yearTime }}, null);

    // 新增：统一统计每个月的数据
    let xuqiuInfo = { ...qushiConf }; // 初始化每月数据为0
    企业服务dbList.forEach(info => {
        let applyTime = info.applyTime;
        if (!applyTime) return;

        let year = moment(applyTime).format("YYYY");
        let month = moment(applyTime).format("MM");

        if (year === moment(yearTime).format("YYYY")) {
            xuqiuInfo[month] += 1;
        }
    });

    operateData.企业需求新增趋势 = Object.keys(xuqiuInfo)
        .map(key => ({ key, value: xuqiuInfo[key].toString() }))
        .sort((a, b) => parseInt(a.key) - parseInt(b.key));

    return { operateData };
}


/**
 * 根据传入的年份生成当前年份与目标年份之间的所有年份列表
 * @param targetYear 传入的年份
 * @returns 
 */
export function getYearList(targetYear) {
    const currentYear = new Date().getFullYear();
  
    // 生成目标年份与当前年份之间的年份列表
    const startYear = Math.min(targetYear, currentYear);
    const endYear = Math.max(targetYear, currentYear);
    let years = [];
    for (let year = startYear; year <= endYear; year++) {
        years.push(year);
    }

    // 如果结果不足5年，返回近5年列表
    if (years.length < 5) {
        years = [];
        for (let year = currentYear - 4; year <= currentYear; year++) {
        years.push(year);
        }
    }

    // 确保输出顺序始终为时间正序
    years.sort((a, b) => {
        return a - b;
    })

    return years;
}


export async function getRiskData() {
    let yj = {
        高风险: 0,
        中低风险: 0,
        关注: 0
    }
    let riskEnterprises:any[] = [];
    let fhColumn = ["enterpriseName", "industry", "eId", "shijiaoziben"];
    //获取所有企业孵化信息
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "moveOutTime", "moveOutType", "state"], where: {} };
    let fhdbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {state: CHANGESTATE.已通过}, fhColumn, manyTableInfo);

    let manageList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {isSubmit:STATE.是}, ["annual", "eId"]);

    let map = {};
    manageList.forEach(info => {
        map[info.eId] = 1;
    });

    fhdbList.forEach(info => {
        let riskLevel = "";
        if (info.enterprise_fuhuas[0].moveOutType == EMIGRATIONTYPE.违约退租) {
            yj.高风险 += 1;
            riskLevel = "高风险";
            riskEnterprises.push([info.enterpriseName, riskLevel]);
        } else if (info.enterprise_fuhuas[0].moveOutType == EMIGRATIONTYPE.到期退租) {
            yj.关注 += 1;
            riskLevel = "关注";
            riskEnterprises.push([info.enterpriseName, riskLevel]);
        } else if (info.enterprise_fuhuas[0].state != FUHUASTATE.迁出 && !map[info.eId]) {
            yj.中低风险 += 1;
            riskLevel = "中低风险";
            riskEnterprises.push([info.enterpriseName, riskLevel]);
        }
    });
    
    let yujiData = [];
    for (let key in yj) {
        yujiData.push({key, value:yj[key]});
    }

    return {
        yujiData,
        riskEnterprises
    };
}


// export async function getRiskData() {
//     let yj = {
//         高风险: 0,
//         中低风险: 0,
//         关注: 0
//     }
//     let riskEnterprises: any[] = [];
//     let fhColumn = ["enterpriseName", "industry", "eId", "shijiaoziben"];
//     //获取所有企业孵化信息
//     let manyTableInfo: any = {}
//     // manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: { state: FUHUASTATE.实体孵化 } };
//     manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "moveOutTime", "moveOutType"], where: {} };
//     // manyTableInfo[TABLENAME.企业经营信息] = { column: ["annual"], where: {} };
//     let fhdbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {state: CHANGESTATE.已通过}, fhColumn, manyTableInfo);

//     let manageList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {}, ["annual", "eId"]);

//     let map = {};
//     manageList.forEach(info => {
//         map[info.eId] = 1;
//     });

//     fhdbList.forEach(info => {
//         let riskLevel = "";
//         if (info.enterprise_fuhuas[0].moveOutType == EMIGRATIONTYPE.违约退租) {
//             yj.高风险 += 1;
//             riskLevel = "高风险";
//             riskEnterprises.push([info.enterpriseName, riskLevel]);
//         } else if (!map[info.eId]) {
//             yj.中低风险 += 1;
//             riskLevel = "中低风险";
//             riskEnterprises.push([info.enterpriseName, riskLevel]);
//         } else if (info.enterprise_fuhuas[0].moveOutType == EMIGRATIONTYPE.到期退租) {
//             yj.关注 += 1;
//             riskLevel = "关注";
//             riskEnterprises.push([info.enterpriseName, riskLevel]);
//         } 
//     });

//     let yujiData = [];
//     for (let key in yj) {
//         yujiData.push({key, value:yj[key]});
//     }

//     return {
//         yujiData,
//         riskEnterprises
//     };
// }


/**
 * 价值分析
 */
export async function getWorthDate() {
    let worthData = {
        "TXP":[], //纳税趋势(万元)
        "financing":[], //融资金额趋势
        "jiuye":[] //就业人数趋势
    }
    let qushiConf = {"01":0, "02":0, "03":0, "04":0, "05":0, "06":0, "07":0, "08":0, "09":0, "10":0, "11":0, "12":0};

    /**纳税趋势 */
    let nashuiList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {}, {});
    let minNaShuiYear = Math.min( ...nashuiList.map(item => new Date(item.investmentDate).getFullYear()) );
    if (!nashuiList.length) minNaShuiYear = new Date().getFullYear();
    let nashuiYear = getYearList(minNaShuiYear);

    for(let i = 0; i < nashuiYear.length; i++) {
        let nashui = 0;
        nashuiList.forEach( info => {
            let parsedStartTime = moment(info.annual);
            if (parsedStartTime.isValid() && parsedStartTime.year() === nashuiYear[i]) {
                nashui += parseFloat(info.TXP);
            }
        })

        worthData.TXP.push({key:nashuiYear[i], value:nashui.toString()});
    }

    //X轴排序
    worthData.TXP.sort( (a, b) => {
        return a.key - b.key;
    })


    /**融资额趋势分析 */
    let 融资情况 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业融资, {}, []);
    let minYear = Math.min( ...融资情况.map(item => new Date(item.investmentDate).getFullYear()) );
    if (!融资情况.length) minYear = new Date().getFullYear();
    let year = getYearList(minYear);
    for(let i = 0; i < year.length; i++) {
        let 融资金额 = 0;
        融资情况.forEach(info => {
            let 融资日期 = moment(info.investmentDate);
            if (融资日期.isValid() && 融资日期.year() === year[i]) {
                融资金额 += parseFloat(info.financingAmount || 0);
            }
        });
        worthData.financing.push({key:year[i], value:融资金额});
    }

    /**就业人数趋势 */
    let 参保记录 = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.参保记录, {}, {});
    let minJiuyeYear = Math.min( ...参保记录.map(item => new Date(item.investmentDate).getFullYear()) );
    if (!参保记录.length) minJiuyeYear = new Date().getFullYear();
    let jiuyeyear = getYearList(minJiuyeYear);
    for(let i = 0; i < jiuyeyear.length; i++) {
        let 就业人数 = 0;
        参保记录.forEach(info => {
            let 参保日期 = moment(info.annual);
            if (参保日期.isValid() && 参保日期.year() === jiuyeyear[i]) {
                if (info.zhuanKe) {
                    就业人数 += parseInt(info.zhuanKe);
                }
                if (info.benKe) {
                    就业人数 += parseInt(info.benKe);
                }
                if (info.shuoshi) {
                    就业人数 += parseInt(info.shuoshi);
                }
                if (info.boShi) {
                    就业人数 += parseInt(info.boShi);
                }
                if (info.boshiyishang) {
                    就业人数 += parseInt(info.boshiyishang);
                }
                if (info.qiTa) {
                    就业人数 += parseInt(info.qiTa);
                }
            }
        });
        worthData.jiuye.push({key:jiuyeyear[i], value:就业人数.toString()});
    }

    //X轴排序
    worthData.jiuye.sort( (a, b) => {
        return a.key - b.key;
    })

    return worthData;
}




// ============================== 管理后台操作 ======================================
/**
 * 雨艺孵化器数据回显
 */
// export async function getYuYiFuHua() {
//     let yuyiInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {uscc:"91310115069312504K"}, []);
//     let dataInfo:any = extractData(YuYiBaseDataConfig, yuyiInfo);
//     //兼容一下唯一一个number
//     // dataInfo.enterpriseNum = dataInfo.enterpriseNum || 0;

//     return {dataInfo};
// }
export async function getYuYiFuHua() {
    // 1. 获取羽翼孵化器基本信息
    let yuyiInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {uscc: "91310115069312504K"}, []);
    let dataInfo: any = extractData(YuYiBaseDataConfig, yuyiInfo);

    // 2. 获取孵化器入驻信息
    let entryList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.入驻信息表, {}, [`info_enterId`, `building`, `occupancyRate`, `enteredEnterprises`]);
    let 入驻企业 = await get入驻企业列表();
    let entryInfo = {
        "1":{"入孵率":"", "入驻企业":入驻企业[BUILDING["1号楼"]].length}, 
        "3":{"入孵率":"", "入驻企业":入驻企业[BUILDING["3号楼"]].length}, 
        "4":{"入孵率":"", "入驻企业":入驻企业[BUILDING["4号楼"]].length}};

    if (entryList.length) {
        entryList.forEach(info => {
            // let building = changeEnumValue(BUILDING, info.building);
            let building = info.building;
            if (!entryInfo[building]) {
                entryInfo[building] = { "入孵率": "", "入驻企业": "" };
            }
            entryInfo[building].入孵率 = info.occupancyRate;
            entryInfo[building].入驻企业 = 入驻企业[building].length;
        });
    }

    // 3. 获取运营推广（次数）信息
    let promotionList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.运营推广信息表, {}, ["opId", "promotionType", "promotionApp", "promotionNum"]);
    let promotionInfo = {"线上推广": {}, "线下推广": {}};

    if (promotionList.length) {
        promotionList.forEach(info => {
            let appStr = "";
            if (info.promotionType == PROMOTIONTYPE.线上推广) {
                appStr = changeEnumValue(ONLINEPROMOTION, info.promotionApp);
                promotionInfo["线上推广"][appStr] = info.promotionNum;
            } else if (info.promotionType == PROMOTIONTYPE.线下推广) {
                appStr = changeEnumValue(OFFLINEPROMOTION, info.promotionApp);
                promotionInfo["线下推广"][appStr] = info.promotionNum;
            }
        });
    }

    // 4. 将 entryInfo 和 promotionInfo 可以合并到 dataInfo 中
    // dataInfo.entryInfo = entryInfo;
    // dataInfo.promotionInfo = promotionInfo;

    // 4. 组装返回数据
    return {
        dataInfo,
        entryInfo,
        promotionInfo
    };
}

/**
 * 雨艺孵化器基本信息修改
 * @param yId 
 * @param entryInfo {"1号楼":{入孵率:"", 入驻企业:""}, ......}
 * @param promotionInfo {"线上推广":{"活动宣讲":0, "三方机构合作":0}, "线下推广":{"活动宣讲":0, "三方机构合作":0}}
 */
export async function updateYuYi(yId, param) {
    const FuncName = "雨艺孵化器基本信息修改";
    eccFormParam(FuncName, YuYiBaseDataUpdateConfig, param);
    let yuyiInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {yId}, []);
    if (!yuyiInfo || !yuyiInfo.yId) {
        throw new BizError(ERRORENUM.数据不存在);
    }

    let enterInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.入驻信息表, {info_enterId:yuyiInfo.info_enterId}, [`info_enterId`, `building`, `occupancyRate`, `enteredEnterprises`]);
    if (!enterInfo || !enterInfo.info_enterId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    // let promotiondbInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.运营推广信息表, {opId:yuyiInfo.opId}, ["opId", "promotionType", "promotionApp", "promotionNum"]);
    // if (!promotiondbInfo || !promotiondbInfo.opId) {
    //     throw new BizError(ERRORENUM.数据不存在);
    // }

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.羽翼孵化器信息, param, {yId});
    
    let  entryInfo = param.entryInfo;
    for (let key in entryInfo) {
        let 入驻信息updateInfo = {occupancyRate:entryInfo[key].入孵率, enteredEnterprises:entryInfo[key].入驻企业};
        let updateParam = {building:key}
        await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.入驻信息表, 入驻信息updateInfo, updateParam);
    }
    let promotionInfo = param.promotionInfo
    for (let key in promotionInfo) {
        for (let app in promotionInfo[key]) {
            let updateInfo = {promotionNum:promotionInfo[key][app]};
            let updateParam:any = {promotionType:PROMOTIONTYPE[key]}
            if (PROMOTIONTYPE[key] == PROMOTIONTYPE.线上推广) {
                updateParam.promotionApp = ONLINEPROMOTION[app];
            } else if (PROMOTIONTYPE[key] == PROMOTIONTYPE.线下推广) {
                updateParam.promotionApp = OFFLINEPROMOTION[app];
            }
            let 运营推广dbInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.运营推广信息表, updateParam, ["opId", "promotionType", "promotionApp", "promotionNum"]); 
            if (!Object.keys(运营推广dbInfo).length) {
                if (updateInfo.promotionNum) {
                    let addInfo = {
                        opId:randomId(TABLENAME.运营推广信息表),
                        promotionType:updateParam.promotionType,
                        promotionApp:updateParam.promotionApp,
                        promotionNum:updateInfo.promotionNum || ""
                    };
                    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.运营推广信息表, addInfo, {});
                }
            } else {
                await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.运营推广信息表, {promotionNum:promotionInfo[key][app]}, updateParam);
            }
        }
    }

    return {isSuccess:true};
}




export async function get在孵企业面积() {
    // 获取当前时间
    // let nowTime = new Date( moment().format("YYYY-01-01") ).valueOf();
    let nowTime = new Date().valueOf();
    let zlColumn = ["eId", "area", "unitPrice", "isDeposit", "startTime", "endTime", "rentFreeStart", "rentFreeEnd", "roomNumber",
    "rent", "notes", "building", 
    "sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong", "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua", "yaJinZhiFu", "cardCopy"];
    // "rent", "notes", "leaseContract", "entryPlan", "businessLicense", "agreement"];

    // let manyTableInfo: any = {}
    // manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: {state: { "%between%": [FUHUASTATE.实体孵化, FUHUASTATE.虚拟孵化] }} };
    // manyTableInfo[TABLENAME.租赁信息] = { column: zlColumn, where: {"startTime": {"%lt%": nowTime}, "endTime": { "%gt%": nowTime }} }; //租赁开始时间小于当前时间、租赁结束时间大于当前时间
    // let zldbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {}, ["industry", "eId"], manyTableInfo);

    /**2025.06.05 罗总开会确认去掉租赁时间，在孵面积计算只用判断是否在孵企业 */
    let manyTableInfo: any = {}
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: {state: { "%between%": [FUHUASTATE.实体孵化, FUHUASTATE.虚拟孵化] }} };
    manyTableInfo[TABLENAME.租赁信息] = { column: zlColumn, where: {} }; //租赁开始时间小于当前时间、租赁结束时间大于当前时间
    let zldbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {state: CHANGESTATE.已通过}, ["industry", "eId"], manyTableInfo);

    let 在孵企业面积 = 0;
    let 各楼栋在孵企业面积 = {
        "1":0,
        "3":0,
        "4":0
    }
    zldbList.forEach( info => {
        let {enterprise_fuhuas, enterprise_leases} = info;
        // if (nowTime <= new Date(enterprise_fuhuas[0].endTime).valueOf()) {
        //     enterprise_leases.forEach( leases => {
        //         if (leases.area) 在孵企业面积 += parseFloat(leases.area);
        //     })
        // }

        enterprise_leases.forEach( leases => {
            if (leases.building) {
                if (leases.area) 各楼栋在孵企业面积[leases.building] += parseFloat(leases.area);
            }
            if (leases.area) 在孵企业面积 += parseFloat(leases.area);
        })
    });

    let 雨艺孵化器dbList = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {}, []);
    let 孵化器总面积 = parseFloat(雨艺孵化器dbList.totalArea);

    let zfqymjzb = ((在孵企业面积 / 孵化器总面积) * 100);
    let 在孵企业面积占比 = "0%";
    if (zfqymjzb >= 100) 在孵企业面积占比 = "100%";
    else 在孵企业面积占比 = zfqymjzb.toFixed(2) + "%";

    return {孵化器总面积, 在孵企业面积, 在孵企业面积占比, 各楼栋在孵企业面积};
}



