/**
 * 孵化器看板
 */

import moment = require("moment");
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { BUILDING, CHANGETYPE, EMIGRATIONTYPE, FUHUASTATE, INCOME, INDUSTRY, OFFLINEPROMOTION, ONLINEPROMOTION, PROMOTIONTYPE, STATE } from "../config/enum/enum";
import { operationalData, selectData, selectManyTableData } from "../data/operationalData";
import { getMySqlMs, randomId } from "../tools/system";
import { changeEnumValue } from "../util/verificationEnum";
import { eccFormParam } from "../util/verificationParam";
import { AdminRegisterAddConfig, AdminRegisterUpdateConfig, YuYiBaseDataUpdateConfig } from "../config/eccParam/enterprise";
import { ERRORENUM } from "../config/enum/errorEnum";
import { BizError } from "../util/bizError";
import { extractData } from "../util/piecemeal";
import { EnterpriseApplyForConfig, 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 filesList = ["eId", "enterpriseName", "uscc", "logonTime"];
    let selectParam = {state:STATE.是};

    /**在孵企业 当前时间小于孵化结束时间 */
    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 => {
            // 确认租赁时间在有效范围内
            if (nowTime >= lease.startTime && nowTime <= lease.endTime) {
                baseData.fuhuaData["在孵面积"] += parseFloat(lease.area);
            }
        });
    });
    // baseData.fuhuaData["在孵面积占比"] = ((baseData.fuhuaData["在孵面积(㎡)"] / baseData.fuhuaData["总面积(㎡)"])*100).toFixed(2) + "%";

    /**迁出企业 */
    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.毕业迁出}, {});
    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`]);
    baseData.entryInfo = {"1":{"入驻率":"", "入驻企业":""}, "3":{"入驻率":"", "入驻企业":""}, "4":{"入驻率":"", "入驻企业":""}};

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

    /**
     * 运营推广(次数)
     */
    let promotionList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.运营推广信息表,{}, ["opId","promotionType", "promotionApp", "promotionNum"]);
    baseData.promotionInfo = {"线上推广": {},  "线下推广": {}};
    if (promotionList.length) {
        promotionList.forEach( info => {
            let appStr = "";
            if (info.promotionType == PROMOTIONTYPE.线上推广) {
                appStr = changeEnumValue(ONLINEPROMOTION, info.promotionApp);
                baseData.promotionInfo["线上推广"][appStr] = info.promotionNum;
            } else if (info.promotionType == PROMOTIONTYPE.线下推广) {
                appStr = changeEnumValue(OFFLINEPROMOTION, info.promotionApp);
                baseData.promotionInfo["线下推广"][appStr] = info.promotionNum;
            }
        })
    }

    return {baseData};
}


/**
 * 运营分析
 * 出租率变化趋势暂未接入数据库数据
 * 孵化器收入暂未接入数据库数据
 */
// export async function getOperateData(year) {
//     // let yearTime = moment(year).format("YYYY-MM-DD");
//     // console.log(yearTime);
//     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 qushiConf = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

//     /**在孵企业 */
//     // let zaifuParam = {state:{"%notIn%":FUHUASTATE.迁出}};
//     let zaifuParam = {startTime:{"%lt%":yearTime}, endTime:{"%gt%":yearTime}, state:{"%notIn%":FUHUASTATE.迁出}};
//     console.log("zaifuParam:", zaifuParam);

//     let zaifuList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, zaifuParam, {});
//     console.log("zaifuList length:", zaifuList.length);

//     operateData.当前在孵企业数 = zaifuList.length;
//     let zaifuStateInfo = {
//         "实体孵化":qushiConf, 
//         "虚拟孵化":qushiConf
//     };
//     zaifuList.forEach( info => {
//         let state = changeEnumValue(FUHUASTATE, info.state);
//         let time = moment(info.endTime).format("YYYY-MM");
//         let year = moment(info.endTime).format("YYYY");
//         let month = moment(info.endTime).format("MM");
//         if (!zaifuStateInfo[state]) zaifuStateInfo[state] = {};
//         // if (year == yearTime) {
//         if (year === moment(yearTime).format("YYYY")) {
//             zaifuStateInfo[state][month] += 1;
//         }
//     })

//     for (let key in zaifuStateInfo["实体孵化"]) {
//         operateData.在孵企业数变化趋势.实体孵化.push({key, value:zaifuStateInfo["实体孵化"][key].toString()});
//     }
//     //X轴排序
//     operateData.在孵企业数变化趋势.实体孵化.sort( (a, b) => {
//         return a.key - b.key;
//     })

//     for (let key in zaifuStateInfo["虚拟孵化"]) {
//         operateData.在孵企业数变化趋势.虚拟孵化.push({key, value:zaifuStateInfo["虚拟孵化"][key].toString()});
//     }
//     //X轴排序
//     operateData.在孵企业数变化趋势.虚拟孵化.sort( (a, b) => {
//         return a.key - b.key;
//     })


//     /**毕业企业 */
//     let biyeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {graduationTime:{"%ne%":null}}, {});//state:{"%ne%":0}
//     let biyeInfo = qushiConf;
//     biyeList.forEach( info => {
//         let year = moment(info.graduationTime).format("YYYY");
//         let month = moment(info.graduationTime).format("MM");
//         // if (year == yearTime) {
//         if (year === moment(yearTime).format("YYYY")) {
//             biyeInfo[month] += 1;
//         }
//     })
    

//     for(let key in biyeInfo) {
//         operateData.毕业企业数变化趋势.毕业企业.push({key, value:biyeInfo[key].toString()});
//     }
//     //X轴排序
//     operateData.毕业企业数变化趋势.毕业企业.sort( (a, b) => {
//         return a.key - b.key;
//     })


//     /**出租率 */
//     let chuzulvParam = {startTime:{"%lt%":yearTime}, endTime:{"%gt%":yearTime}};
//     // let chuzulvList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME., chuzulvParam);
//     let chuzulvInfo = qushiConf;
//     for(let key in chuzulvInfo) {
//         operateData.出租率变化趋势.push({key, value:chuzulvInfo[key].toString()});
//     }
//     //X轴排序
//     operateData.出租率变化趋势.sort( (a, b) => {
//         return a.key - b.key;
//     })


//     /**在孵企业行业领域 */
//     /**在孵企业 当前时间小于孵化结束时间 */
//     let araeParam = {column:["area", "unitPrice", "roomNumber", "rent"], where:{} };
//     let zaifuTableInfo:any = {};
//     zaifuTableInfo[TABLENAME.租赁信息] = araeParam;
//     zaifuTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{startTime:{"%lt%":yearTime}, endTime:{"%gt%":yearTime}, state:{"%notIn%":FUHUASTATE.迁出}} };
//     // let zaifuList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {endTime:{"%lt%":nowTime}}, {});
//     let zaifuResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {}, ["eId", "industry"], zaifuTableInfo );
    
//     for (let key in INDUSTRY) {
//         let industryData:any = {};
//         let anyKey:any = key;
//         if (isNaN(anyKey)) {
//             const EnumValue = parseInt(INDUSTRY[key])
//             industryData = {key:anyKey, value:0};
//             zaifuResList.forEach( info => {
//                 if (info.industry == EnumValue) {
//                     industryData.value += 1;
//                 }
//             })
//             operateData.在孵企业行业领域.push(industryData);
//         }
//     }


//     /**孵化器收入 */
//     for (let key in INCOME) {
//         let anyKey:any = key;
//         if (isNaN(anyKey)) {
//             operateData.孵化器收入.push({key:anyKey, value:0});
//         }
//     }

//     return {operateData};
// }
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 zaifuParam = {
        startTime: { "%lt%": yearTime },
        endTime: { "%gt%": yearTime },
        state: { "%notIn%": [FUHUASTATE.迁出] }
    };
    

    let zaifuList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, zaifuParam, {});

    operateData.当前在孵企业数 = zaifuList.length;

    // 新增：统一统计每个月的数据
    let trendInfo = { ...qushiConf }; // 初始化每月数据为0

    zaifuList.forEach(info => {
        let year = moment(info.endTime).format("YYYY");
        let month = moment(info.endTime).format("MM");

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

    // 转换为数组并排序
    for (let key in trendInfo) {
        operateData.在孵企业数变化趋势.在孵企业.push({ key, value: trendInfo[key].toString() });
    }

    operateData.在孵企业数变化趋势.在孵企业.sort((a, b) => a.key - b.key);

    /**毕业企业 */
    let biyeList = await selectData(
        OPERATIONALDATATYPE.查询多个,
        TABLENAME.企业孵化信息,
        { 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));

    /**出租率 */
    let chuzulvParam = {startTime:{"%lt%":yearTime}, endTime:{"%gt%":yearTime}};
    // let chuzulvList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME., chuzulvParam);
    let chuzulvInfo = qushiConf;
    for(let key in chuzulvInfo) {
        operateData.出租率变化趋势.push({key, value:chuzulvInfo[key].toString()});
    }
    //X轴排序
    operateData.出租率变化趋势.sort( (a, b) => {
        return a.key - b.key;
    })


    /**在孵企业行业领域 */
    // let araeParam = { column: ["area", "unitPrice", "roomNumber", "rent"], where: {} };
    let araeParam = { column: ["area", "building", "roomNumber", "rent"], where: {} };
    let zaifuTableInfo: any = {};
    zaifuTableInfo[TABLENAME.租赁信息] = araeParam;
    zaifuTableInfo[TABLENAME.企业孵化信息] = {
        column: ["state", "startTime", "endTime"],
        where: { startTime: { "%lt%": yearTime }, endTime: { "%gt%": yearTime }, state: { "%notIn%": FUHUASTATE.迁出 } },
    };
    let zaifuResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {}, ["eId", "industry"], zaifuTableInfo);
    // console.log("zaifuResList:", zaifuResList);
    
    //将 industry 字符串转换为数组
    zaifuResList.forEach(info => {
        if (typeof info.industry === 'string') {
            try {
                info.industry = JSON.parse(info.industry);
            } catch (e) {
                console.error("Failed to parse industry:", e);
                info.industry = []; // 如果解析失败，设置为默认空数组
            }
        }
    });

    for (let key in INDUSTRY) {
        let industryData: any = {};
        let anyKey: any = key;
        if (isNaN(anyKey)) {
            const EnumValue = parseInt(INDUSTRY[key]);
            industryData = { key: anyKey, value: 0 };
            zaifuResList.forEach(info => {
                if (info.industry == EnumValue) {
                    industryData.value += 1;
                }
            });
            
            operateData.在孵企业行业领域.push(industryData);
        }
        
    }

    // /**孵化器收入 */
    // for (let key in INCOME) {
    //     let anyKey: any = key;
    //     if (isNaN(anyKey)) {
    //         operateData.孵化器收入.push({ key: anyKey, value: 0 });
    //     }
    // }


    return { operateData };
}


/**
 * 风险预警
 * 暂未接入数据库数据
 */
// export async function getRiskData() {
//     let riskData = [
//         {
//             key:"出租率异常",
//             value:0
//         },
//         {
//             key:"办公地址冲突",
//             value:0
//         },
//         {
//             key:"连续未填报",
//             value:0
//         },
//     ]

//     return riskData;
// }
export async function getRiskData() {
    let riskData = [
        {
            key: "迁出异常",
            value: 0
        },
        {
            key: "办公地址冲突",
            value: 0
        },
        {
            key: "连续未填报",
            value: 0
        },
    ];

    // 1. 获取所有迁出记录（state 为迁出）
    let zaifuList = await selectManyTableData(OPERATIONALDATATYPE.多表联查,TABLENAME.企业基础信息表,{},["eId", "enterpriseName"],
        {
            [TABLENAME.企业孵化信息]: {
                column: ["state", "moveOutTime", "moveOutType", "endTime"],
                where: { state: FUHUASTATE.迁出 }
            }
        }
    );

    let abnormalCount = 0;

    for (const info of zaifuList) {
        const incubationInfo = info.enterprise_fuhuas[0]; // 关联的孵化信息
        if (!incubationInfo || !incubationInfo.moveOutTime) continue;
    
        let moveOutTime = new Date(incubationInfo.moveOutTime);
        let endTime = info.enterprise_fuhuas[0].endTime ? new Date(info.enterprise_fuhuas[0].endTime) : null;
    
        // 1. 违约迁出
        let isBreachExit = incubationInfo.moveOutType === EMIGRATIONTYPE.违约退租;
        
        // 2. 未到期迁出（迁出早于孵化结束）
        let isEarlyExit = endTime && moveOutTime < endTime;
    
        // 如果满足任一异常条件，计为异常
        if (isBreachExit || isEarlyExit) {
            abnormalCount++;
        }
    }
    
    riskData[0].value = abnormalCount;

    // 2. 办公地址冲突（楼号 + 室号 + 时间段冲突）
    let leaseList = await selectData(OPERATIONALDATATYPE.查询多个,TABLENAME.租赁信息,{},["eId", "building", "roomNumber", "startTime", "endTime"]);

    // 构建一个 map，key 是 building_roomNumber，值是租赁时间段列表
    let addressMap = new Map<string, Array<{ eId: number; start: Date; end: Date }>>();

    for (const lease of leaseList) {
        const key = `${lease.building}_${lease.roomNumber}`;
        const timeRange = {
            eId: lease.eId,
            start: new Date(lease.startTime),
            end: new Date(lease.endTime)
        };

        if (!addressMap.has(key)) {
            addressMap.set(key, []);
        }
        addressMap.get(key)?.push(timeRange);
    }

    let conflictCount = 0;

    // 遍历每个地址组合，检查时间段是否有重叠
    for (const [key, ranges] of addressMap.entries()) {
        for (let i = 0; i < ranges.length; i++) {
            for (let j = i + 1; j < ranges.length; j++) {
                const a = ranges[i];
                const b = ranges[j];

                // 判断时间段是否重叠
                if (a.start < b.end && b.start < a.end) {
                    conflictCount++;
                    break; // 当前地址组合已冲突，跳出循环
                }
            }
        }
    }

    riskData[1].value = conflictCount;

    // 3. 连续未填报（改进：在孵企业中没有任何经营数据）
    let selectParam = {state:STATE.是};

    /**在孵企业 当前时间小于孵化结束时间 */
    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 allIncubatingEnterprises = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["eId"], zaifuTableInfo );
    
    // 收集所有有填报记录的企业
    let reportedEnterprises = await selectData(OPERATIONALDATATYPE.查询多个,TABLENAME.企业经营信息,{},["eId"]);

    let reportedEIds = new Set(reportedEnterprises.map(e => e.eId));

    // 找出没有填报的在孵企业
    let continuousUnreported = new Set<number>();

    allIncubatingEnterprises.forEach(ent => {
        if (!reportedEIds.has(ent.eId)) {
            continuousUnreported.add(ent.eId);
        }
    });

    riskData[2].value = continuousUnreported.size;

    return riskData;
}

/**
 * 价值分析
 */
export async function getWorthDate() {
    let worthData = {
        // "countData":[
        //     {
        //         key:"国际合作/大企业合作机构",
        //         value:0
        //     },
        //     {
        //         key:"大学/科研院合作机构",
        //         value:0
        //     }
        // ],
        "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 nashuiData = {};
    nashuiList.forEach( info => {
        let year = moment(info.annual).format("YYYY");
        if (!nashuiData[year]) nashuiData[year] = 0;
        nashuiData[year] += parseFloat(info.TXP);
    })
    for (let key in nashuiData) {
        worthData.TXP.push({key, value:nashuiData[key].toString()});
    }
    //X轴排序
    worthData.TXP.sort( (a, b) => {
        return a.key - b.key;
    })


    /**融资企业数量趋势 */
    let rongziList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业融资, {}, {});
    let yearTime = moment(new Date()).format("YYYY");
    let rongziInfo = qushiConf;
    rongziList.forEach( info => {
        let year = moment(info.graduationTime).format("YYYY");
        let month = moment(info.graduationTime).format("MM");
        if (year == yearTime) {
            rongziInfo[month] += 1;
        }
    })
    for(let key in rongziInfo) {
        worthData.financing.push({key, value:rongziInfo[key].toString()});
    }
    //X轴排序
    worthData.financing.sort( (a, b) => {
        return a.key - b.key;
    })


    /**就业人数趋势 */
    let jiuyeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.参保记录, {}, {});
    let jiuyeInfo = {};
    jiuyeList.forEach( info => {
        let year = moment(info.annual).format("YYYY");
        if (!jiuyeInfo[year]) jiuyeInfo[year] = 0;
        jiuyeInfo[year] += 1;
    })
    for(let key in jiuyeInfo) {
        worthData.jiuye.push({key, value:jiuyeInfo[key].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 entryInfo = {"1": {"入驻率": "", "入驻企业": ""}, "3": {"入驻率": "", "入驻企业": ""}, "4": {"入驻率": "", "入驻企业": ""}};

    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].入驻企业 = info.enteredEnterprises;
        });
    }

    // 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 = {promotionType:key, promotionApp:app}
            await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.入驻信息表, updateInfo, updateParam);
        }
    }
    // await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.入驻信息表, param, {info_enterId:yuyiInfo.info_enterId});
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.运营推广信息表, param, {opId:yuyiInfo.opId});

    return {isSuccess:true};
}







