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


function getStartAndEndTimeYearList(startTime, endTime) {
    let startYear = new Date(startTime).getFullYear();
    let endYear = new Date(endTime).getFullYear();
    let result = [];
    for (let i = endYear; i <= endYear; i++) {
        result.push(i);
    }
    return result;
}


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", "startTime", "endTime"], 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 面积变化Map = {};
    let thisYear = new Date().getFullYear();

    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);
            if (enterprise_leases[0].startTime && enterprise_leases[0].endTime ) {
                let leasesYearList = getStartAndEndTimeYearList(enterprise_leases[0].startTime , enterprise_leases[0].endTime);
                leasesYearList.forEach(itemYear => {
                    if (itemYear > thisYear) return;
                    if (!面积变化Map[itemYear] ) 面积变化Map[itemYear] = {key:itemYear, value:0};
                    面积变化Map[itemYear].value += 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 = {};
    let 融资企业变化趋势Map = {};
    rongZiList.forEach(info => {
        let { eId, investmentDate } = info;
        if (!rongZiMap[eId]) rongZiMap[eId] = 0;
        rongZiMap[eId] += 1;

        let itemYear = new Date(investmentDate).getFullYear();
        if (!融资企业变化趋势Map[itemYear]) 融资企业变化趋势Map[itemYear] = {};
        融资企业变化趋势Map[itemYear][eId] = 1;
    });
    let rongZiQiYeCount = Object.keys(rongZiMap).length;

    let 融资企业变化趋势 = [];
    for (let key in 融资企业变化趋势Map) {
        融资企业变化趋势.push({
            key,
            value:Object.keys(融资企业变化趋势Map[key]).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: "0㎡" },
        { key: "产值规模", value: "0亿元" },
        { key: "企业数量", value: `${在孵dbList.length}家` },
        { key: "企业数量", value: `0人` },
    ]; 
    let 在孵企业数据 = [
        { key: "在孵企业面积占比", value: "0%" },
        { key: "入驻", value: `${ruZhuCount}家` },
        { key: "迁出", value: `${qianChuCount}家` },
        { key: "到期退租", value: "0家" },
        { key: "违约退租", value: "0家" }
    ];
    let 孵化运营 = [
        { key: "孵化面积", value: `${areaCount}㎡` },
        { key: "在孵企业", value: `${在孵dbList.length}家` },
        { key: "毕业企业", value: `${biYeOutCount}家` },
        { key: "融资企业", value: `${rongZiQiYeCount}家` },

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

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

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


    //就业
    let jiuYeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.参保记录, {}, null);
    let 年度就业人数趋势分析Map = {};
    jiuYeList.forEach(info => {
        let {eId, annual} = info;
        let itemCount = 0;
        let itemYear = new Date(annual).getFullYear();
        if (info.zhuanKe) itemCount += info.zhuanKe;
        if (info.benKe) itemCount += info.benKe;
        if (info.shuoshi) itemCount += info.shuoshi;
        if (info.boShi) itemCount += info.boShi;
        if (info.boshiyishang) itemCount += info.boshiyishang;

        if (!年度就业人数趋势分析Map[itemYear]) 年度就业人数趋势分析Map[itemYear] = {key:itemYear, value:0};
        年度就业人数趋势分析Map[itemYear].value += itemCount;
    });
    let 年度就业人数趋势分析 = Object.values(年度就业人数趋势分析Map);

    //产业规模分析
    let jingYingList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, { annual:new Date().getFullYear() }, null);
    let 产业规模企业Map = {};
    jingYingList.forEach(info => {
        let {BI, eId} = info;
        if (!产业规模企业Map[eId]) 产业规模企业Map[eId] = 0;
        产业规模企业Map[eId] += BI;
    });
    let 产业规模分析List = [
        {num:400, key:"超400万", value:0},
        {num:300, key:"300-400万", value:0},
        {num:200, key:"200-300万", value:0},
        {num:100, key:"100-200万", value:0},
        {num:1, key:"<100万", value:0},
    ];
    for (let key in 产业规模企业Map) {
        let itemCount = 产业规模企业Map[key];
        for (let i = 0; i < 产业规模分析List.length; i++) {
            let {num} = 产业规模分析List[i];
            if (itemCount > num) {
                产业规模分析List[i] += itemCount;
                break;
            }
        }
    }
    let 在孵企业营收占比 = [];
    产业规模分析List.forEach(info => {
        let {key, value} = info;
        在孵企业营收占比.push({key, value});
    })


    let zhyy = {
        园区概况:{dataList:园区概况, title:["key", "value"]},
        在孵企业数据: { dataList: 在孵企业数据, titleList: ['key', 'value'] },
        在孵企业变化趋势: 在孵企业变化趋势,
        融资企业变化趋势:[{name:"融资企业变化趋势", data:融资企业变化趋势}],
        入驻企业变化趋势: [{ name: "入驻企业变化趋势", data: 入驻企业变化趋势 }],
        孵化面积变化趋势 :[{ name: "孵化面积变化趋势", data: Object.values(面积变化Map) }],
        入驻企业行业类型: { 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'] },
        年度就业人数趋势分析:[{name:"年度就业人数趋势分析", data:年度就业人数趋势分析}],
        在孵企业营收占比:{dataList:在孵企业营收占比, title:["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;
}



