import moment = require("moment");
import { AWARDLEVEL, FOLLOWUPSTATUS, FUHUASTATE, INDUSTRY, MOVEOUTTYPE, NEEDCATEGORY, OPERATIONALDATATYPE, TABLENAME } from "../../config/enum";
import { selectData, selectManyTableData } from "./operationalData";
import { changeEnumValue } from "../../tools/eccEnum";
import { getChart, getYearList } from "./out";



export async function getZhyy() {
    // let zhyy = {
    //     在孵企业数据:{dataList:[], titleList:['key', 'value']},
    //     入驻企业变化趋势:[],
    //     入驻企业行业类型:{dataList:[], titleList:['key', 'value']},
    //     孵化运营:{dataList:[], titleList:['key', 'value']},
    //     智慧运营汇总数据:{dataList:[], titleList:['key', 'value']},
    //     企业服务:{dataList:[], titleList:['key', 'value']},
    //     企业服务类型:{dataList:[], titleList:['key', 'value']},
    // };

    let fhColumn = ["industry", "eId"];
    //获取所有企业孵化信息

    let manyTableInfo: any = {}
    // manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: { state: FUHUASTATE.实体孵化 } };
    manyTableInfo[TABLENAME.企业孵化信息] = { column: ["fId", "eId", "startTime", "endTime", "state"], where: {} };
    manyTableInfo[TABLENAME.租赁信息] = { column: ["area"], where: {} };
    let fhdbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {}, fhColumn, manyTableInfo);
    let 在孵dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {}, ["fId", "eId", "startTime", "endTime", "state", "virtualCause", 
    "virtualCauseDes", "moveOutType", "moveOutTrace", "moveOutCause", "moveOutTime", "graduationTime"]);

    //入驻企业变化趋势
    let industryMap = {};
    let ruZhuMap = {};
    let ruZhuCount = 0;
    let areaCount = 0;
    let enterpriseCount = 0;

    let firstDayMsOfMonth = moment().startOf('month').valueOf();
    let checlTimeMs = moment(firstDayMsOfMonth).subtract(8, 'months').valueOf();
    fhdbList.forEach(info => {
        let { industry, enterprise_fuhuas, enterprise_leases } = info;
        let startTime = enterprise_fuhuas[0].startTime;
        if (!startTime) return;

        let startTimeMs = new Date(startTime).valueOf();
        if (startTimeMs >= checlTimeMs) {
            let timeStr = moment(startTime).format("YY/MM");
            if (!ruZhuMap[timeStr]) ruZhuMap[timeStr] = 0;
            ruZhuMap[timeStr] += 1;
            // ruZhuCount += 1;
        }
        ruZhuCount += 1;

        //行业领域分布
        if (industry) {
            let industryStr = changeEnumValue(INDUSTRY, JSON.parse(industry)[0]);
            if (!industryMap[industryStr]) industryMap[industryStr] = 0;
            industryMap[industryStr] += 1;
        }

        let area = enterprise_leases[0].area || 0;
        if (area) areaCount += parseFloat(area);

        enterpriseCount += 1;

    });
    let 入驻企业变化趋势 = [];
    for (let key in ruZhuMap) {
        入驻企业变化趋势.push({ key, value: ruZhuMap[key] });
    }
    // 入驻企业变化趋势.sort((a, b) => { return parseInt(a.key) - parseInt(b.key) });
    入驻企业变化趋势.sort((a, b) => {
        const dateA = moment(a.key, "YY/MM");
        const dateB = moment(b.key, "YY/MM");
        return dateA.diff(dateB);
    });


    //行业领域
    let 行业领域 = [];
    for (let key in industryMap) {
        行业领域.push({ key, value: industryMap[key] });
    }

    let biYeOutCount = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.企业孵化信息, { state: FUHUASTATE.迁出, moveOutType: MOVEOUTTYPE.毕业迁出 }, null);
    let qianChuCount = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.企业孵化信息, { state: FUHUASTATE.迁出 }, null);
    let rongZiList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业融资, {}, null);
    let rongZiMap = {};
    rongZiList.forEach(info => {
        let { eId } = info;
        if (!rongZiMap[eId]) rongZiMap[eId] = 0;
        rongZiMap[eId] += 1;
    });
    let rongZiQiYeCount = Object.keys(rongZiMap).length;

    let fuWuCount = 0;//服务数
    let fuWuQiYeCountMap = {};//服务覆盖企业
    let fuWuQiYeTypeMap = {};//
    let fuWuList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业服务表, {}, null);

    fuWuList.forEach(info => {
        let { followUpStatus, eId, needCategory } = info;
        if (followUpStatus == FOLLOWUPSTATUS.已完成) {
            fuWuCount += 1;

            if (!fuWuQiYeCountMap[eId]) {
                fuWuQiYeCountMap[eId] = 0;
            }
            fuWuQiYeCountMap[eId] += 1;

            let needCategoryStr = changeEnumValue(NEEDCATEGORY, needCategory)

            if (!fuWuQiYeTypeMap[needCategoryStr]) fuWuQiYeTypeMap[needCategoryStr] = 0;
            fuWuQiYeTypeMap[needCategoryStr] += 1;
        }
    });
    let fuWuQiYeCount = Object.keys(fuWuQiYeCountMap).length;//服务覆盖企业

    let fuWuQiYeTypeList = [];
    
    // 遍历 NEEDCATEGORY 枚举
    // const allNeedCategories = Object.values(NEEDCATEGORY);
    // allNeedCategories.forEach(needCategory => {
    //     let needCategoryStr = changeEnumValue(NEEDCATEGORY, needCategory);
    //     let value = fuWuQiYeTypeMap[needCategoryStr] || 0;
    //     fuWuQiYeTypeList.push({
    //         key: needCategoryStr,
    //         value: value
    //     });

    // for (let key in NEEDCATEGORY) {
    //     let keyAny:any = NEEDCATEGORY[key];
    //     if (isNaN(keyAny)) {
    //         //toupdate 这里继续完善  有点小bug
    //     }
    // }

    for (let key in NEEDCATEGORY) {
        let enumValue = NEEDCATEGORY[key];
        // 跳过未显式赋值的枚举成员（如果有的话，它们默认为枚举前一个成员的值加1）
        if (isNaN(Number(key))) { // 这里检查 key 是否可以被转换为数字，以识别枚举成员名称
            let needCategoryStr = changeEnumValue(NEEDCATEGORY, enumValue);
            let value = fuWuQiYeTypeMap[needCategoryStr] || 0;
            fuWuQiYeTypeList.push({
                key: needCategoryStr,
                value: value
            });
        }
    }
    // for (let key in NEEDCATEGORY) {
    //     let keyAny:any = NEEDCATEGORY[key];
    //     if (isNaN(keyAny)) {
    //         //toupdate 这里继续完善  有点小bug
    //         let keyStr = key;
    //         let serviceType = NEEDCATEGORY[key];
    //         let value = fuWuQiYeTypeMap[keyStr] || 0;
    //         fuWuQiYeTypeList.push({
    //             key: keyStr,
    //             value: value
    //         });
    //     }
    // }

     //荣誉资质统计
     let guojiaJiCount = 0;
     let shengJiCount = 0;
     let shiJiCount = 0;
     let awardList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业荣誉, {}, null);
     awardList.forEach(info => {
         let { awardLevel } = info;
         if (awardLevel == AWARDLEVEL.国家级) {
             guojiaJiCount += 1;
         } else if (awardLevel == AWARDLEVEL.省级) {
             shengJiCount += 1;
         } else if (awardLevel == AWARDLEVEL.市级) {
             shiJiCount += 1;
         }
     });

    let 在孵企业数据 = [
        { key: "在孵企业面积占比", value: "3%" },
        { key: "入驻", value: `${ruZhuCount}家` },
        { key: "迁出", value: `${qianChuCount}家` },
        { key: "到期退租", value: "3家" },
        { key: "违约退租", value: "10家" }
    ];
    let 孵化运营 = [
        { key: "孵化面积", value: `${areaCount}㎡` },
        { key: "在孵企业", value: `${在孵dbList.length}家` },
        { key: "毕业企业", value: `${biYeOutCount}家` },
        { key: "融资企业", value: `${rongZiQiYeCount}家` },

    ];
    let 智慧运营汇总数据 = [
        { key: "配套服务", value: `3项` },
        { key: "第三方供应商", value: `3家` },
        { key: "累计服务企业", value: `${fuWuQiYeCount}次` },
    ];
    let 企业服务 = [
        { key: "服务数", value: fuWuCount },
        { key: "服务覆盖企业", value: fuWuQiYeCount },

    ];
    let 荣誉资质 = [
        { key: "国家级", value:`${guojiaJiCount}项` },
        { key: "省级", value: `${shengJiCount}项` },
        { key: "市级", value: `${shiJiCount}项`},
    ];

    /**在孵企业变化趋势 */
    let 在孵企业变化趋势 = getZfqy(在孵dbList);


    let zhyy = {
        在孵企业数据: { dataList: 在孵企业数据, titleList: ['key', 'value'] },
        在孵企业变化趋势: 在孵企业变化趋势,
        入驻企业变化趋势: [{ name: "入驻企业变化趋势", data: 入驻企业变化趋势 }],
        入驻企业行业类型: { dataList: 行业领域, titleList: ['key', 'value'] },
        孵化运营: { dataList: 孵化运营, titleList: ['key', 'value'] },
        智慧运营汇总数据: { dataList: 智慧运营汇总数据, titleList: ['key', 'value'] },
        企业服务: { dataList: 企业服务, titleList: ['key', 'value'] },
        企业服务类型: { dataList: fuWuQiYeTypeList, titleList: ['key', 'value'] },
        荣誉资质:{ dataList:荣誉资质, titleList: ['key', 'value'] }
    }

    return zhyy;
}





/**
 * 在孵企业——变化趋势
 */
 function getZfqy(data) {
    let year = getYearList();
    let hbqs = {
        "企业数": []
    }
    for (let i = 0; i < year.length; i++) {
        let count = 0;
        data.forEach(info => {
            let startTimeYear = moment(info.startTime).year(); //获取入孵开始时间
            let thisYear = parseInt(year[i]);
            if (startTimeYear === thisYear) count += 1;
        })
        hbqs.企业数.push({ key: year[i], value: count });
    }

    let qybhqkbhqs = getChart(hbqs);

    return qybhqkbhqs;
}



