/**
 * 绩效管理驾驶仓
 */

import moment = require("moment")
import { FUHUASTATE, INDUSTRY, MOVEOUTTYPE, OPERATIONALDATATYPE, TABLENAME, FINANCINGROUNDS, ENTERPRISETEAM } from "../../config/enum";
import { selectData, selectManyTableData } from "./operationalData";
import { keyValuePackage } from "../../dataPackage/inFrontOut";
import { info } from "console";
import { getChart, getKeyValue, getYearList } from "./out";


export async function getJxgljsc() {
    let jxgljsc = {
        产业结构: { dataList: [], titleList: ['key', 'value'] },//产业结构
        人才引进: { dataList: [], titleList: ['key', 'value'] },//人才引进
        孵化器汇总数据: { 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 nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
    let fhColumn = ["fId", "eId", "startTime", "endTime", "state", "virtualCause", "virtualCauseDes", "moveOutType",
        "moveOutTrace", "moveOutCause", "moveOutTime", "graduationTime"];
    //获取在孵企业
    // let 在孵dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, { "endTime": { "%gt%": nowTime } }, fhColumn);
    let 在孵dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {}, fhColumn);

    //获取在孵企业租赁信息
    let 租赁Column = ["eId", "year", "alienPatent", "classIPatent", "secondClassPatent", "thirdPentent"];
    let 在孵租赁联查includeConf = {};
    在孵租赁联查includeConf[TABLENAME.企业孵化信息] = {cloum:fhColumn, where:{"endTime": { "%gt%": nowTime }}};
    在孵租赁联查includeConf[TABLENAME.租赁信息] = {cloum:租赁Column, where:{}}
    let 在孵租赁联查dbList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {}, ["enterpriseName"], 在孵租赁联查includeConf);

    //获取羽翼孵化器
    let 羽翼孵化器dbList = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器, {}, []);

    jxgljsc.产业结构.dataList = await cyjg();//产业结构
    
    jxgljsc.人才引进.dataList = await rcyj();//人才引进

    let fhqhzsjInfo = await fhqhzsj(羽翼孵化器dbList, 在孵dbList);
    jxgljsc.孵化器汇总数据.dataList = getKeyValue(fhqhzsjInfo);//孵化器汇总数据

    let qydtInfo = await qydt(在孵dbList);
    jxgljsc.企业动态.dataList = getKeyValue(qydtInfo);//企业动态

    jxgljsc.在孵企业变化趋势 = await zfqybhqs(在孵dbList);//在孵企业变化趋势

    let zysjeList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {}, null);
    let zysjeInfo = await zysje(zysjeList);
    jxgljsc.总营收金额.dataList = getKeyValue(zysjeInfo);//总营收金额

    let zfqyzysInfo = await zfqyzys(在孵dbList);
    jxgljsc.在孵企业总营收.dataList = getKeyValue(zfqyzysInfo);//在孵企业总营收

    // jxgljsc.tzlx.dataList = await tzlx();//投资类型

    jxgljsc.在孵企业融资情况.dataList = await zfqyrzqk();//在孵企业融资情况

    let 资质Column = ["qId", "eId", "kxTime", "zjtxTime", "xjrTime", "xjrPyTime", "goPublicTime", "gaoXinJiShuTime", "goPublicSector"];
    let 企业资质联查includeConf = {};
    企业资质联查includeConf[TABLENAME.企业资质] = {cloum:资质Column, where:{}}
    let 企业资质信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {}, [], 企业资质联查includeConf);
    let qyfhsInfo = await qyfhs(企业资质信息);
    jxgljsc.企业孵化数.dataList = getKeyValue(qyfhsInfo)//企业孵化数

    return jxgljsc;
}


//产业结构
async function cyjg() {
    let result = [];

    for (let key in INDUSTRY) {
        let anyKey: any = key;
        if (isNaN(anyKey)) {
            let keyStr = key;
            let industry = INDUSTRY[key];
            let count = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.企业基础信息表, { industry }, null);
            result.push({ key: keyStr, value: count })
        }
    }

    return result;
}

//人才引进

async function rcyj() {
    let result = [];

    // 分别获取不同表的数据并合并处理
    // let 创业团队List = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.创业团队, {}, null);
    for (let key in ENTERPRISETEAM) {
        let anyKey: any = key;
        if (isNaN(anyKey)) {
            let keyStr = key;
            let talentType = ENTERPRISETEAM[key];
            let count = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.创业团队, { talentType }, null);
            result.push({ key: keyStr, value: count })
        }
    }

    return result;
}



//孵化器汇总数据
async function fhqhzsj(data, zfData) {
    let fhqhzsj = {
        孵化器总面积:data.totalArea + "㎡",
        在孵企业: zfData.length,
        在孵面积: data.zaifuArea + "㎡"
    }

    return fhqhzsj;
}

//企业动态---------
async function qydt(data) {

    let result = [];
    let qydt = {
        "本月新加入在孵企业": 0,
        "同比上月": "",
        "环比去年": ""
    }

    //本月新加入在孵企业
    let nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
    let monthAgo = moment().format('YYYY-MM-01 00:00:00');
    //同比上月
    let monthAgo2 = moment().subtract(1, 'month').format('YYYY-MM-01 00:00:00');
    let monthAgo2End = moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD 00:00:00');
    //环比去年
    let thisYear = moment().format('YYYY-01-01 00:00:00');
    let yearAgo = moment().subtract(1, 'year').format('YYYY-01-01 00:00:00');
    let yearAgoEnd = moment().subtract(1, 'year').format('YYYY-12-31 00:00:00');
    
    
    let 上月 = 0;
    let 今年 = 0;
    let 去年 = 0;
    data.forEach( info => {
        if (moment( info.startTime) > moment(monthAgo) && moment(info.startTime) < moment(nowTime)) {
            qydt.本月新加入在孵企业 += 1;
        }
        if (moment( info.startTime) > moment(monthAgo2) && moment(info.startTime) < moment(monthAgo2End)) {
            上月 += 1;
        }
        if (moment( info.startTime) > moment(thisYear) && moment(info.startTime) < moment(nowTime)) {
            今年 += 1;
        }
        if (moment( info.startTime) > moment(yearAgo) && moment(info.startTime) < moment(yearAgoEnd)) {
            去年 += 1;
        }
    })

    let 同比 = ((qydt.本月新加入在孵企业 - 上月) / 上月) * 100;
    qydt.同比上月 = 同比.toFixed(2) + "%";

    let 环比 = ((今年 - 去年) / 去年) * 100;
    qydt.环比去年 = 环比.toFixed(2) + "%";

    return result;
}


function zfqybhqs(data){
    let year = getYearList();
    let zhqy = {
        "在孵企业":[]
    }
    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;
        })
        zhqy.在孵企业.push({key:year[i], value:count});
    }

    let zhqybhqs = getChart(zhqy);

    return zhqybhqs;
}



//总营收金额
async function zysje(data) {
    //获取总营收金额
    let zysje = {
        总营收金额:0
    };
    data.forEach(item => {
        zysje.总营收金额 += parseFloat(item.BI);
    });

    return zysje;
}

//在孵企业总营收
async function zfqyzys(data) {
    let zfqyzys = {
        "500万以下":0,
        "500万-1000万":0,
        "1000万-2000万":0,
        "2000万以上":0
    }

    for (let i = 0; i < data.length; i++) {
        //获取在孵企业经营数据
        let 经营信息dbList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {eId:data[i].eId}, null);
        经营信息dbList.forEach( info => { //BI（单位万元）
            if (info.BI < 500) zfqyzys["500万以下"] += 1;
            else if (info.BI >= 500 && info.BI < 1000) zfqyzys["500万-1000万"] += 1;
            else if (info.BI >= 1000 && info.BI < 2000) zfqyzys["1000万-2000万"] += 1;
            else zfqyzys["2000万以上"] += 1;
        })
    }

    return zfqyzys
}


//在孵企业融资情况
async function zfqyrzqk() {
    let result = [];

    for (let key in FINANCINGROUNDS) {
        let anyKey: any = key;
        if (isNaN(anyKey)) {
            let financingRounds = FINANCINGROUNDS[key];
            let count = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.企业融资, {financingRounds}, null);
            result.push({ key: key, value: count })
        }
    }

    return result;
}


//企业孵化率
async function qyfhl() {
    let result = [];
    let qyfhlList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业孵化信息, {}, null);

    //获取企业孵化率
    let qyfhl = {
        "企业毕业率": 0,
        "环比去年孵化率": 0
    };
    let nowYear = new Date().getFullYear();
    let lastYear = nowYear - 1;

    for (let i = 0; i < qyfhlList.length; i++) {
        let item = qyfhlList[i];
        let endTime = new Date(item.endTime).getFullYear();
        let startTime = new Date(item.startTime).getFullYear();

        if (endTime === nowYear) {
            qyfhl.企业毕业率 += 1;
            if (startTime <= lastYear && endTime >= lastYear) {
                qyfhl.环比去年孵化率 += 1;
            }
        }
    }

    result.push({ key: "企业孵化率", value: qyfhl.企业毕业率 });
    result.push({ key: "环比去年孵化率", value: qyfhl.环比去年孵化率 });

    return result;
}

//企业孵化数
async function qyfhs(data) {
    //获取企业孵化数
    let qyfhs = {
        "科小":0,//新增"科小"
        "小巨人": 0,
        "高新企业": 0,
        "专精特新": 0,
        "小巨人培育": 0,
    };

    data.forEach( info => {
        let {enterprise_qualifications} = info;
        enterprise_qualifications.forEach( item => {
            // if (item.xjrTime) qyfhs.小巨人 += 1;
            if (item.kexiaoTime) qyfhs.科小 += 1;//新增"科小"
            else if (item.xjrTime) qyfhs.小巨人 += 1;
            else if (item.gaoXinJiShuTime) qyfhs.高新企业 += 1;
            else if (item.zjtxTime) qyfhs.专精特新 += 1;
            else if (item.xjrPyTime) qyfhs.小巨人培育 += 1;
        })
    })

    return qyfhs;
}


