import moment = require("moment");
import { AWARDLEVEL, DEGREE, FINANCINGROUNDS, IPRTYPECLIENT, NEEDCATEGORY, OPERATIONALDATATYPE, TABLENAME } from "../../config/enum";
import { selectData, selectManyTableData } from "./operationalData";
import { getChart, getKeyValue, getYearList } from "./out";
import { changeEnumValue } from "../../tools/eccEnum";



export async function getQyszhx(eId) {
    let qyszhx = {
        企业基本情况: { 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'] },
        营收变化趋势: [],
        企业动态: { bodyList: [], headerList: [['企业照片', '获奖名称', '获奖时间', '颁奖单位', '奖项等级']] },
        服务需求: { dataList: [], titleList: ['key', 'value'] },
        活动变化趋势分析: [],
        服务记录_空间服务: { bodyList: [], headerList: [['服务名称', '服务时间', '服务内容']] },
        服务记录_工商服务: { bodyList: [], headerList: [['服务名称', '服务时间', '服务内容']] },
        服务记录_融资服务: { bodyList: [], headerList: [['服务名称', '服务时间', '服务内容']] },
        服务记录: { dataList: [], titleList: ['key', 'value'] },
    }

    /**数据库查询 */
    let 企业基础信息 = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, { eId }, null);

    // let column = ["eId", "enterpriseName", "uscc", "", "", "", "", "", "", "", "", "", "", "", ""];
    let 孵化Column = ["fId", "eId", "startTime", "endTime", "state", "virtualCause", "virtualCauseDes", "moveOutType", "moveOutTrace", "moveOutCause", "moveOutTime",
        "graduationTime", "jiShuHeTongJiaoYi"];

    let 企业孵化联查includeConf = {};
    企业孵化联查includeConf[TABLENAME.企业孵化信息] = { cloum: 孵化Column, where: {} }
    let 企业孵化信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { eId }, [], 企业孵化联查includeConf);

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

    let 专利Column = ["pId", "eId", "year", "alienPatent", "classIPatent", "secondClassPatent", "thirdPentent"];
    let 企业专利联查includeConf = {};
    企业专利联查includeConf[TABLENAME.企业专利表] = { cloum: 专利Column, where: {} }
    let 企业专利信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { eId }, [], 企业专利联查includeConf);

    let 创业团队Column = ["tId", "eId", "name", "sex", "birth", "degree", "graduationSchool", "talentType", "des"];
    let 创业团队联查includeConf = {};
    创业团队联查includeConf[TABLENAME.创业团队] = { cloum: 创业团队Column, where: {} }
    let 创业团队信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { eId }, [], 创业团队联查includeConf);

    let 企业经营Column = ["mId", "eId", "annual", "BI", "TXP", "RD", "createTime", "state"];
    let 企业经营联查includeConf = {};
    企业经营联查includeConf[TABLENAME.企业经营信息] = { cloum: 企业经营Column, where: {} }
    let 企业经营信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { eId }, [], 企业经营联查includeConf);

    let 企业荣誉Column = ["hId", "eId", "awardName", "awardingUnit", "awardTime", "awardLevel", "awardImg"];
    let 企业荣誉联查includeConf = {};
    企业荣誉联查includeConf[TABLENAME.企业荣誉] = { cloum: 企业荣誉Column, where: {} }
    let 企业荣誉信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { eId }, [], 企业荣誉联查includeConf);

    let 企业融资Column = ["rId", "eId", "financingAmount", "financingRounds", "fuHuaQiInvestment", "fuHuaQiInvestmentStyle",
        "fuHuaQiInvestmentAmount", "investmentDate", "investmentInstitutionsName", "valuation"];
    let 企业融资联查includeConf = {};
    企业融资联查includeConf[TABLENAME.企业融资] = { cloum: 企业融资Column, where: {} }
    let 企业融资信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { eId }, [], 企业融资联查includeConf);

    let 企业服务Column = ["esId", "eId", "needCategory", "needContent", "applyTime", "followUpStatus", "resolveTime", "fangKui",
        "shouLiTime", "outcome", "desc"];
    let 企业服务联查includeConf = {};
    企业服务联查includeConf[TABLENAME.企业服务表] = { cloum: 企业服务Column, where: {} }
    let 企业服务信息 = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, { eId }, [], 企业服务联查includeConf);

    //企业基本情况
    let qyjbqk = {
        企业介绍: 企业基础信息.jianJie,
        企业图片: "企业照片占位图.png",
    };

    //企业基本数据
    qyszhx.企业基本情况.dataList = getKeyValue(qyjbqk);
    let qyjbsj = {
        注册时间: "-",
        迁入时间: "-",
        首次入孵时间: "-",
    };
    if (企业基础信息.logonTime) qyjbsj.注册时间 = moment(企业基础信息.logonTime).format("YYYY-MM-DD")
    if (企业孵化信息[0].enterprise_fuhuas.startTime) qyjbsj.首次入孵时间 = moment(企业孵化信息[0].enterprise_fuhuas.startTime).format("YYYY-MM-DD")
    qyszhx.企业基本数据.dataList = getKeyValue(qyjbsj);

    //企业标签 todo
    let qybq = get企业标签(企业资质信息);
    qyszhx.企业标签.dataList = qybq;

    //知识产权
    let zscq = get知识产权(企业专利信息);
    qyszhx.知识产权.dataList = getKeyValue(zscq);

    //企业员工画像
    let qyyghx = await get企业员工画像(创业团队信息);
    qyszhx.企业员工画像.dataList = getKeyValue(qyyghx);

    //企业汇总数据
    let qyhzsj = {
        // 企业认证:0, //todo 
        资质认证: 0,
        一级专利: zscq.一级专利,
    }
    qyszhx.企业汇总数据.dataList = getKeyValue(qyhzsj);

    //营收情况
    let { ysqk, ysbhqs } = get营收情况(企业经营信息);
    qyszhx.营收情况.dataList = getKeyValue(ysqk);

    //营收变化趋势
    qyszhx.营收变化趋势 = ysbhqs;

    //企业动态
    let qydt = get企业动态(企业荣誉信息);
    qyszhx.企业动态.bodyList = qydt;

    //服务需求
    let fwxq = get服务需求(企业融资信息);
    qyszhx.服务需求.dataList = getKeyValue(fwxq);

    //活动变化趋势分析
    let hdbhqsfx = get活动变化趋势分析(企业融资信息);
    qyszhx.活动变化趋势分析 = hdbhqsfx;

    //服务记录_空间服务
    let fwjlxx = get服务记录(企业服务信息);
    // qyszhx.服务记录_空间服务.bodyList = fwjlxx.空间服务;
    qyszhx.服务记录_工商服务.bodyList = fwjlxx.工商服务;
    qyszhx.服务记录_融资服务.bodyList = fwjlxx.融资服务;

    //服务记录
    let fwjl = {
        // 空间服务次数: fwjlxx.空间服务.length,
        工商服务次数: fwjlxx.工商服务.length,
        融资服务次数: fwjlxx.融资服务.length,
    }
    qyszhx.服务记录.dataList = getKeyValue(fwjl);

    return qyszhx;
}


function get企业标签(data) {
    let qybqData = [];

    data.forEach(info => {
        let { enterprise_qualifications } = info;
        enterprise_qualifications.forEach(item => {
            if (item.xjrTime) qybqData.push("小巨人");
            else if (item.gaoXinJiShuTime) qybqData.push("高新企业");
            else if (item.zjtxTime) qybqData.push("专精特新");
            else if (item.xjrPyTime) qybqData.push("小巨人培育");
        })
    })

    let qybq = [];
    qybqData.push(item => {
        qybq.push({ key: "文本", value: item });
    })

    return qybq;
}


function get知识产权(data) {
    let zscq:any = {
        软件著作:0,
        发明专利:0,
        海外专利:0,
        植物新品种:0,
        集成电路布图:0,
    }
    
    data.forEach(info => {
        let { enterprise_patents } = info;
        enterprise_patents.forEach(patents => {
            if (patents.iprType) {
                let iprTypeStr = changeEnumValue(IPRTYPECLIENT, patents.iprType);
                if (!zscq[iprTypeStr]) zscq[iprTypeStr] = 0;
                zscq[iprTypeStr] += 1;
            }
        })
        
    })
    
    // data.forEach(info => {
    //     let { enterprise_patents } = info;
    //     enterprise_patents.forEach(patents => {
    //         zscq.一级专利 += patents.classIPatent;
    //         zscq.二级专利 += patents.secondClassPatent
    //         zscq.三级专利 += patents.thirdPentent;
    //         zscq.海外专利 += patents.alienPatent;
    //     })
    // })

    return zscq;
}


async function get企业员工画像(data) {
    let qyyghx = {};

    for (let key in DEGREE) {
        let anyKey: any = key;
        if (isNaN(anyKey)) {
            let keyStr = key;
            if (!qyyghx[keyStr]) qyyghx[keyStr] = 0;
            let degree = DEGREE[key];
            data.forEach(info => {
                let { enterprise_teams } = info;
                if (enterprise_teams && Array.isArray(enterprise_teams)) {
                    enterprise_teams.forEach(team => {
                        if (degree == team.degree) {
                            qyyghx[keyStr] += 1;
                        }
                    })
                }

            })
        }
    }

    return qyyghx;
}


function get营收情况(data) {
    let ysqk = {
        累计营收: 0,
        累计研发投入: 0,
        累计纳税: 0
    }

    let ysbhqsInfo = {
        营业收入: [],
        研发投入: [],
        纳税金额: [],
    }

    let year = getYearList();

    data.forEach(info => {
        let { enterprise_manages } = info;
        enterprise_manages.forEach(manage => {
            ysqk.累计营收 += parseFloat(manage.BI);
            ysqk.累计研发投入 += parseFloat(manage.RD);
            ysqk.累计纳税 += parseFloat(manage.TXP);

        })
    })

    for (let i = 0; i < year.length; i++) {
        let 营业收入 = 0;
        let 研发投入 = 0;
        let 纳税金额 = 0;
        data.forEach(info => {
            let { enterprise_manages } = info;
            enterprise_manages.forEach(manage => {
                let thisAnnual = moment(manage.annual).year();
                let thisYear = parseInt(year[i]);
                if (thisAnnual === thisYear) {
                    营业收入 += parseFloat(manage.BI);
                    研发投入 += parseFloat(manage.RD);
                    纳税金额 += parseFloat(manage.TXP);
                }

            })
        })
        ysbhqsInfo.营业收入.push({ key: year[i], value: 营业收入 });
        ysbhqsInfo.研发投入.push({ key: year[i], value: 研发投入 });
        ysbhqsInfo.纳税金额.push({ key: year[i], value: 纳税金额 });
    }

    let ysbhqs = getChart(ysbhqsInfo);

    return { ysqk, ysbhqs };
}


function get企业动态(data) {
    let qydt = [];
    data.forEach(info => {
        let { enterprise_honors } = info;
        enterprise_honors.forEach(honors => {
            let awardLevel = changeEnumValue(AWARDLEVEL, honors.awardLevel);
            let awardImg = JSON.parse(JSON.parse(honors.awardImg));
            let awardTime = moment(honors.awardTime).format("YYYY-MM-DD");
            qydt.push([awardImg[0], honors.awardName, awardTime, honors.awardingUnit, awardLevel]);
        })
    })

    return qydt;
}


function get服务需求(data) {
    let newestFinancing: any = {};
    data.forEach(info => {
        let { enterprise_financings } = info;
        let enterprise_financingsData = [];

        enterprise_financings.forEach(financings => {
            enterprise_financingsData.push({
                financingAmount: financings.financingAmount,
                financingRounds: financings.financingRounds,
                investmentDate: new Date(financings.investmentDate).valueOf(),
                investmentInstitutionsName: financings.investmentInstitutionsName
            })
        })
        //获取最新时间的融资信息
        enterprise_financingsData.sort((a, b) => {
            return b.investmentDate - a.investmentDate;
        })
        newestFinancing = enterprise_financingsData[0];
    })

    let fwxq = {
        融资金额: newestFinancing.financingAmount,
        融资轮次: changeEnumValue(FINANCINGROUNDS, newestFinancing.financingRounds),
        融资时间: "-",
        投资机构: newestFinancing.investmentInstitutionsName
    };

    if (newestFinancing.investmentDate) fwxq.融资时间 = moment(newestFinancing.investmentDate).format("YYYY-MM-DD");

    return fwxq;
}


function get活动变化趋势分析(data) {
    let hdbhqsfxInfo = {
        融资额: [],
        融资事件: [],
    }
    let year = getYearList();
    for (let i = 0; i < year.length; i++) {
        let 融资额 = 0;
        let 融资事件 = 0;
        data.forEach(info => {
            let { enterprise_financings } = info;
            enterprise_financings.forEach(financings => {
                let thisAnnual = moment(financings.investmentDate).year();
                let thisYear = parseInt(year[i]);
                if (thisAnnual === thisYear) {
                    融资额 += parseFloat(financings.financingAmount);
                    融资事件 += 1;
                }

            })

        })
        hdbhqsfxInfo.融资额.push({ key: year[i], value: 融资额 });
        hdbhqsfxInfo.融资事件.push({ key: year[i], value: 融资事件 });
    }

    let hdbhqsfx = getChart(hdbhqsfxInfo);

    return hdbhqsfx;
}


function get服务记录(data) {
    let fwjl = {
        // 空间服务: [],
        工商服务: [],
        融资服务: []
    };

    data.forEach(info => {
        let { enterprise_services } = info;
        enterprise_services.forEach(service => {
            let needCategory = changeEnumValue(NEEDCATEGORY, service.needCategory);
            // if ( service.needCategory == NEEDCATEGORY.空间服务) {
            //     fwjl.空间服务.push([needCategory, service.resolveTime, service.needContent])
            // } else 
            if (service.needCategory == NEEDCATEGORY.工商服务) {
                fwjl.工商服务.push([needCategory, service.resolveTime, service.needContent])
            } else if (service.needCategory == NEEDCATEGORY.融资服务) {
                fwjl.融资服务.push([needCategory, service.resolveTime, service.needContent])
            }
        })
    })

    return fwjl;
}









