/**
 * 管理后台 企业融资相关接口
 * 作者:lxm
 */

import { ERRORENUM } from "../../../config/errorEnum";
import * as financingData from "../../../data/fuHuaQi/monthTask/financing";
import * as splitResultConfig from "../../../config/splitResultConfig";
import { BizError } from "../../../util/bizError";
import * as fuhuaqiData from "../../../data/fuHuaQi/fuhuaqi";
import moment = require("moment");
import * as configEnum from "../../../config/enum";
import { changeEnumValue } from "../../../util/verificationEnum";
import { extractData } from "../../../util/piecemeal";
import { selectFinancingListByParams, selectFinancingListByParamsToPage } from "../../../data/enterprise/financingInfo";


/**
 * 融资企业信息列表
 * @param monthData 数据月份 目前数据库没有该字段
 * @param fuHuaQiName 所属孵化器 这里前端传的是孵化器的统一信用代码
 * @param industry 行业领域
 * @param fuHuaQiInvestment 孵化器是否参与投资
 * @param page 页数 
 * @returns {data, count} data:数据列表  count:符合条件的数据量 
 */
export async function financingList(monthData:string, fuHuaQiName:string, industry, fuHuaQiInvestment:number, page:number) { 
    /**拼接查询条件 */
    let selectParam:any = {};
    if (fuHuaQiName.length > 0) {
        let fuHuaQiInfo = await fuhuaqiData.findFuHuaQiByUSCC(fuHuaQiName);
        if(!fuHuaQiInfo) throw new BizError(ERRORENUM.未找到数据, `管理后台查询融资列表时 ${fuHuaQiName}不存在`);
        selectParam.fuHuaQiUscc = fuHuaQiInfo.uscc;
    }
    if ( monthData.length > 0 ) {
        let startT = moment(monthData).startOf('month').valueOf();
        let endT = moment(monthData).endOf('month').valueOf();
        selectParam.createTime = {'$gt':startT, '$lt':endT};
    }
    if (industry.length >0 ) selectParam.industry = industry;
    if (fuHuaQiInvestment == 2 || fuHuaQiInvestment == 3) {
        selectParam.fuHuaQiInvestment = fuHuaQiInvestment == 2 ? true : false;
    }

    /**查数据 */
    let dataBaseList = await financingData.findFinancingListToPage(selectParam, (page-1)*10 );
    let count = await financingData.findFinancingCount(selectParam);
    let usccMap = await fuhuaqiData.findAllFuHuaQiOperationNameMap();//用于转换所属孵化器名称
    
    /**拼接返回值 */
    let dataList = [];
    dataBaseList.forEach( info => {
        /**截取返回字段 */
        let changeData:any = extractData(splitResultConfig.FinancingListConfig, info, true);

        /** 字段的特化处理 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        changeData.industry = changeEnumValue(configEnum.INDUSTRY, info.industry);
        changeData.financingRounds = changeEnumValue(configEnum.FINANCINGROUNDS, info.financingRounds);
        changeData.fuHuaQiInvestmentStyle = changeEnumValue(configEnum.FUHUAQILNVESTMENTSTYLE, info.fuHuaQiInvestmentStyle);
        dataList.push(changeData);
    });

    return {count, dataList};
}



/**
 * 导出融资企业信息列表
 * @param monthData 数据月份 目前数据库没有该字段
 * @param fuHuaQiName 所属孵化器 
 * @param industry 行业领域
 * @param fuHuaQiInvestment 孵化器是否参与投资
 * @param type 页数 
 * @returns 
 */
export async function outPutFinancingList(monthData:string, fuHuaQiName:string, industry, fuHuaQiInvestment:number, type:number) {
    let selectParam:any = {};
    if (type == configEnum.OUTPUTTYPE.当前数据 ) { 
        /**如果选择当前数据 则拼接查询条件 */
        if (fuHuaQiName.length > 0) {
            let fuHuaQiInfo = await fuhuaqiData.findFuHuaQiByName(fuHuaQiName);
            if(!fuHuaQiInfo) throw new BizError(ERRORENUM.未找到数据, `管理后台查询融资列表时 ${fuHuaQiName}不存在`);
            selectParam.fuHuaQiUscc = fuHuaQiInfo.uscc;
        }
        
        if ( monthData.length > 0 ) {
            let startT = moment(monthData).startOf('month').valueOf();
            let endT = moment(monthData).endOf('month').valueOf();
            selectParam.createTime = {'$gt':startT, '$lt':endT};
        }
        if (industry.length >0 ) selectParam.industry = industry;
        if (fuHuaQiInvestment == 2 || fuHuaQiInvestment == 3) {
            selectParam.fuHuaQiInvestment = fuHuaQiInvestment == 2 ? true : false;
        }
    }

    /**主要查询 */
    let dataBaseList = await financingData.findFinancingList(selectParam );
    let usccMap = await fuhuaqiData.findAllFuHuaQiOperationNameMap();
    
    /**拼接返回 需要注意的是 keyList要和titleList一一对应 */
    let keyList = [
        "name", "uscc", "fuhuaqiUscc","logonAddress", "logonTime", "industry", "financingRounds", "operatingAddress", "financingAmount","investmentInstitutionsName",
        "timeToObtainInvestment", "fuHuaQiInvestment", "fuHuaQiInvestmentAmount", "fuHuaQiInvestmentStyle", "createTime"
    ];
    let titleList = [
        "企业名称", "信用代码", "所属孵化器","注册地址","注册时间", "行业领域", "融资轮次", "经营地址","融资金额(万元)","投资机构名称","获得投资时间",
        "孵化器是否投资","孵化器投资金额(万元)","孵化器投资方式","录入时间",
    ];
    
    let result = [titleList];
    dataBaseList.forEach( info => {
        /**截取返回字段 */
        let changeData:any = extractData(splitResultConfig.FinancingListConfig, info, true);
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        changeData.industry = changeEnumValue(configEnum.INDUSTRY, info.industry);
        changeData.financingRounds = changeEnumValue(configEnum.FINANCINGROUNDS, info.financingRounds);
        changeData.fuHuaQiInvestmentStyle = changeEnumValue(configEnum.FUHUAQILNVESTMENTSTYLE, info.fuHuaQiInvestmentStyle);

        /**根据keyList的顺序生成小数组 */
        let subList = [];
        keyList.forEach(keyStr => {
            subList.push(changeData[keyStr] || '');
        });
        result.push(subList);
    });

    return result;
}


/**
 * 获取 企业填报的融资数据
 * @param name 企业名称
 * @param financingRounds 融资轮次 
 * @param fuHuaQiInvestment 孵化器是否参与投资
 * @param page 页面
 */
export async function getEnterpriseFinancing(name:string, financingRounds:number, fuHuaQiInvestment:number, page:number) {

    let selectParam:any = {};
    if (name) selectParam.name = {"$regex":`${name}`};
    if (financingRounds) selectParam.financingRounds = financingRounds;
    if (fuHuaQiInvestment == 2 || fuHuaQiInvestment == 3) {
        selectParam.fuHuaQiInvestment = fuHuaQiInvestment == 2 ? true : false;
    }

    let dataBaseList = await selectFinancingListByParamsToPage(selectParam, page);

    let dataList = [];
    dataBaseList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.EnterpriseFinancingDataConfig, info, true);
        changeData.financingRounds = changeEnumValue(configEnum.FINANCINGROUNDS, changeData.financingRounds);
        changeData.fuHuaQiInvestment = changeData.fuHuaQiInvestment ? "是" : "否";
        changeData.fuHuaQiInvestmentStyle = changeEnumValue(configEnum.FUHUAQILNVESTMENTSTYLE, changeData.fuHuaQiInvestmentStyle);

        dataList.push(changeData);
    });

    return { dataList };
}


/**
 * 导出 企业填报的融资数据
 * @param name 
 * @param financingRounds 
 * @param fuHuaQiInvestment 
 * @param type 
 */
export async function outPutEnterpriseFinancing(name:string, financingRounds:number, fuHuaQiInvestment:number, type:number) {
    let selectParam:any = {};
    let fileName = "全部";
    if (type == configEnum.OUTPUTTYPE.当前数据 ) { 
        /**如果选择当前数据 则拼接查询条件 */
        if (name) selectParam.name = {"$regex":`${name}`};
        if (financingRounds) selectParam.financingRounds = financingRounds;
        if (fuHuaQiInvestment == 2 || fuHuaQiInvestment == 3) {
            selectParam.fuHuaQiInvestment = fuHuaQiInvestment == 2 ? true : false;
        }
        fileName = "当前数据";
    }

    let dataBaseList = await selectFinancingListByParams(selectParam);

    let keyList = [
        "name", "financingRounds", "financingAmount","investmentInstitutionsName", "timeToObtainInvestment", 
        "fuHuaQiInvestment", "fuHuaQiInvestmentAmount", "fuHuaQiInvestmentStyle"
    ];
    let titleList = [
        "企业名称", "融资轮次", "融资金额(万元)","投资机构名称","获得投资时间", "孵化器是否投资", "孵化器投资金额(万元)", "孵化器投资方式"
    ];

    let dataList = [titleList];
    dataBaseList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.EnterpriseFinancingDataConfig, info, true);
        changeData.fuHuaQiInvestment = changeData.fuHuaQiInvestment ? "是" : "否";

        let subList = [];
        for (let i = 0; i < keyList.length; i++) {
            let value = changeData[keyList[i]]
            subList.push(value);
        } 
        dataList.push(subList);
    });

    return { dataList, fileName };
}