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

import { checkChange, extractData } from "../../../util/piecemeal";
import * as enterpriseData from "../../../data/enterprise/enterprise";
import * as splitResultConfig from "../../../config/splitResultConfig";
import * as fuHuaQiData from "../../../data/fuHuaQi/fuhuaqi";
import * as configEnum from "../../../config/enum";
import * as verificationEnumTools from "../../../util/verificationEnum";
import moment = require("moment");
import { findBusinessDataByParams, findBusinessDataByParamsToPage } from "../../../data/enterprise/quarterTask/businessdata";
import { findEnterpriseInitialTeamsByParam, findEnterpriseInitialTeamsByParamToPage } from "../../../data/enterprise/initialTeam";


/**
 * 获取在孵企业信息列表
 * @param createType 新注册/迁入  1:全选 2:新注册 3:迁入   以前是时间  2/23日修改为类型
 * @param fuHuaQiUscc 所属孵化器 
 * @param industry 行业领域
 * @param isNaturalPersonHolding 自然人控股
 * @param state 孵化状态2.0
 * @param createTime 入库时间 
 * @param page 页数
 * @returns dataList:[], count:0  dataList=数据列表  count:条件筛选下的数据总数
 */
export async function enterpriseList(createType:number, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, state:number, createTime:number, name:string, page:number) {
    /**拼接查询条件 */
    let selectParam:any = {};
    if (createType == 2 || createType == 3) {
        selectParam.isCreate = createType == 2 ? true : false;
    }
    if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
    if (industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台获取在孵企业信息列表', 'industry', configEnum.INDUSTRY, industry);
        selectParam.industry = industry;
    }
    if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
        selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
    }
    if (state != configEnum.INSIDESTATE.全部) {
        if (state == configEnum.INSIDESTATE.实体孵化) selectParam.state = configEnum.FUHUASTATE.实体孵化;
        if (state == configEnum.INSIDESTATE.虚拟孵化) selectParam.state = configEnum.FUHUASTATE.虚拟孵化;
    }
    if (createTime) {
        let startT = createTime;
        let endT = moment(createTime).endOf('month').valueOf();
        selectParam.createTime = {"$gt":startT, "$lt":endT};
    }
    if (name) {
        selectParam.name = {"$regex":`${name}`};
    }
    selectParam["$or"] = [{"$and":[{"draftLock":true}, {"taskId":{"$ne":null}}]}, {"$and":[{"draftLock":false}, {"taskId":null}]}] ; //未提交的企业不能查看

    /**需要用到的查询数据 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseListToPage(selectParam, (page-1)*10 );
    let count = await enterpriseData.findEnterpriseCount(selectParam);//符合查询条件的数据总数

    /**组合返回结果 */
    let dataList = [];
    dataBaseList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.EnterpriseListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";

        /** 返回的isCreate字段为字符串 当为导入数据时这里显示为空字符  */
        if (info.enterpriseIsInPut) changeData.isCreate = "";
        else changeData.isCreate = (changeData.isCreate) ? "新注册" : "新迁入";

        changeData.state = verificationEnumTools.changeEnumValue(configEnum.FUHUASTATE, changeData.state);
        changeData.virtualCause = !changeData.virtualCause ? '-' : verificationEnumTools.changeEnumValue(configEnum.VIRTUALCAUSE, changeData.virtualCause);

        /**将枚举值转为字符 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        
        dataList.push(changeData);
    });

    return {count, dataList};
}


/**
 * 导出在孵企业信息列表
 * @param createType 新注册时间/迁入时间
 * @param fuHuaQiUscc 所属孵化器 
 * @param industry 行业领域 数组
 * @param isNaturalPersonHolding 自然人控股
 * @returns 二维数组
 */
export async function outPutEnterpriseData(createType:number, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, state:number, createTime:number, name:string, type:number) {
    /**拼接查询条件 */
    let selectParam:any = {};
    if (type == configEnum.OUTPUTTYPE.当前数据) {
        if (createType == 2 || createType == 3) {
            selectParam.isCreate = createType == 2 ? true : false;
        }
        if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
        if (industry && industry.length > 0) selectParam.industry = industry;
        if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
            selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
        }
        if (state != configEnum.INSIDESTATE.全部) {
            if (state == configEnum.INSIDESTATE.实体孵化) selectParam.state = configEnum.FUHUASTATE.实体孵化;
            if (state == configEnum.INSIDESTATE.虚拟孵化) selectParam.state = configEnum.FUHUASTATE.虚拟孵化;
        }
        if (createTime) {
            let startT = createTime;
            let endT = moment(createTime).endOf('month').valueOf();
            selectParam.createTime = {"$gt":startT, "$lt":endT};
        }
        if (name) {
            selectParam.name = {"$regex":`${name}`};
        }
    }
    selectParam["$or"] = [{"$and":[{"draftLock":true}, {"taskId":{"$ne":null}}]}, {"$and":[{"draftLock":false}, {"taskId":null}]}] ; //未提交的企业不能查看

    /**查询内容 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseList(selectParam );

    /**组合二维数组  titleList 与 keyList 要一一对应 */ 
    const TitleList = [
        "企业名称", "入库时间", "所属孵化器", "新注册/新迁入", "孵化状态", "虚拟孵化服务模式", "统一信用代码", "行业领域","主营业务",
        "注册时间", "首次入孵时间", "迁入时间", "是否自然人控股", "迁入前注册地址",
        "注册地址", "经营地址", "租赁面积（平方米）"
    ];//表头顺序  如果这里修改了 下面的keyList也要修改
    const KeyList = [
        "name", "createTime", "fuhuaqiUscc", "isCreate",  "state", "virtualCause", "uscc", "industry", "mainBusiness", "logonTime",
        "firstIncubationTime", "timeOfImmigration", "isNaturalPersonHolding", "oldLogonAddress",
        "logonAddress", "operatingAddress", "leasedArea"
    ];//表头对应的字段顺序
    let dataList = [TitleList];
    
    dataBaseList.forEach( info => {
        /**截取返回结果 */
        let changeData:any = extractData(splitResultConfig.EnterpriseListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        if (info.enterpriseIsInPut) changeData.isCreate = "";
        else changeData.isCreate = (changeData.isCreate) ? "新注册" : "新迁入";

        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**修改枚举值 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        changeData.state = verificationEnumTools.changeEnumValue(configEnum.FUHUASTATE, changeData.state);
        changeData.virtualCause = verificationEnumTools.changeEnumValue(configEnum.VIRTUALCAUSE, changeData.virtualCause);
        // dataList.push(changeData);
        /**根据表头与key的顺序 生成小数组 */
        let subList = [];
        KeyList.forEach( keyStr => {
            subList.push(changeData[keyStr] || '');
        });
        dataList.push(subList);
    });

    return dataList;
}


/**
 * 在孵企业页面的所属孵化器 下拉框
 * 只返回有入孵企业的孵化器
 * @returns result result类型为数组对象 对象内容为{name, uscc}
 */
export async function getAffiliationFuHuaQi() {
    /**获取已有入孵企业的孵化器统一信用代码列表 */
    let bindList = await enterpriseData.findAllBindFuHuaQiUsccList();

    /**限制为 非禁用状态下的孵化器 */
    let notDisabledList = await fuHuaQiData.findAllNotDisabledFuHuaQi();

    let distinctMap = {}; //去重用的map对象 格式为:{uscc:name}
    notDisabledList.forEach(info => {
        distinctMap[info.uscc] = info.operationName;
    });

    let result = [];
    bindList.forEach(fuHuaQiUscc => {
        let fuHuaQiName = distinctMap[fuHuaQiUscc];
        if ( fuHuaQiName ) {
            result.push({
                name:fuHuaQiName,
                uscc:fuHuaQiUscc
            });
        }
    });

    return {result}
}


/**
 * 企业迁出列表
 * @param name 企业名称
 * @param fuHuaQiUscc 所属孵化器统一信用代码
 * @param industry 领域多选
 * @param isNaturalPersonHolding  是否自然人控股
 * @param page 页面
 * @returns 
 */
export async function enterpriseMoveOutList(name:string, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, page:number) {
    /**拼接查询条件 */
    let selectParam:any = {state:configEnum.FUHUASTATE.迁出};
    if (name) {
        selectParam.name = {"$regex":`${name}`};
    }
    if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
    if (industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台获取在孵企业信息列表', 'industry', configEnum.INDUSTRY, industry);
        selectParam.industry = industry;
    }
    if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
        selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
    }
    selectParam.draftLock = true; //未提交的企业不能查看

    /**需要用到的查询数据 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseListToPage(selectParam, (page-1)*10 );
    let count = await enterpriseData.findEnterpriseCount(selectParam);//符合查询条件的数据总数

    /**组合返回结果 */
    let dataList = [];
    dataBaseList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.EnterpriseMoveOutListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**将枚举值转为字符 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        
        dataList.push(changeData);
    });

    return {count, dataList};
}


/**
 * 导出 企业迁出列表
 * @param name 企业名称
 * @param fuHuaQiUscc 所属孵化器统一信用代码
 * @param industry 领域多选
 * @param isNaturalPersonHolding  是否自然人控股
 * @param type 页面
 * @returns 
 */
export async function outPutEnterpriseMoveOutList(name:string, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, type:number) {
    let fileName = "全部";
    /**拼接查询条件 */
    let selectParam:any = {state:configEnum.FUHUASTATE.迁出};
    if (type == configEnum.OUTPUTTYPE.当前数据) {
        if (name) {
            selectParam.name = {"$regex":`${name}`};
        }
        if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
        if (industry.length > 0) {
            verificationEnumTools.eccEnumValue('管理后台获取在孵企业信息列表', 'industry', configEnum.INDUSTRY, industry);
            selectParam.industry = industry;
        }
        if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
            selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
        }
        selectParam.draftLock = true; //未提交的企业不能查看
        fileName = "当前数据";
    }
    

    /**需要用到的查询数据 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseList(selectParam);

    let keyList = [ "name", "moveOutTime", "moveOutType", "moveOutCause", "fuHuaQiUscc", "industry",
        "createTime","uscc","mainBusiness","logonTime","timeOfImmigration","oldLogonAdd","firstIncubationTime",
        "isNaturalPersonHolding","logonAdd","operatingAdd","leasedArea"];
    let titleList = ["企业名称"," 迁出时间"," 迁出类型"," 迁出原因"," 前所属孵化器"," 行业领域",
        "入库时间", "统一信用代码", "主营业务", "注册时间", "迁入时间", "迁入前注册地址",
        "首次入孵时间","是否自然人控股","注册地址","经营地址","租赁面积（平方米）"];
    /**组合返回结果 */
    let dataList = [titleList];
    dataBaseList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.EnterpriseMoveOutListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**将枚举值转为字符 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        
        let subList = [];
        
        for (let i = 0; i < keyList.length; i++) {
            let value = changeData[keyList[i]]
            subList.push(value);
        }
        dataList.push(subList);
    });

    return { fileName, dataList };
}


/**
 * 获取企业经营数据列表
 * @param name 企业名称
 * @param year 年份
 * @param quarter 季度
 * @param page 页面
 */
export async function getBusinessDataList(name:string, year:number, quarter:number, page:number) {

    let selectParam:any = {};
    if (name) selectParam.name = {"$regex":`${name}`};
    if (year) {
        selectParam.year = year;
        if (quarter) selectParam.quarter = quarter;
    }

    let dataBaseList = await findBusinessDataByParamsToPage(selectParam, (page-1)*10);

    let dataList = [];
    dataBaseList.forEach(info => {
        let changeData = extractData(splitResultConfig.EnterpriseBusinessDataConfig, info, true);
        dataList.push(changeData);
    });

    return { dataList };
}


/**
 * 导出企业经营数据列表
 * @param name 企业名称
 * @param year 年份
 * @param quarter 季度
 */
export async function outPutBusinessDataList(name:string, year:number, quarter:number, type:number) {

    let fileName = "全部";
    /**拼接查询条件 */
    let selectParam:any = {state:configEnum.FUHUASTATE.迁出};
    if (type == configEnum.OUTPUTTYPE.当前数据) {
        if (name) {
            selectParam.name = {"$regex":`${name}`};
        }
        if (year) {
            selectParam.year = year;
            if (quarter) selectParam.quarter = quarter;
        }
        
        fileName = "当前数据";
    }

    let dataBaseList = await findBusinessDataByParams(selectParam);

    let keyList = [ "name", "year", "quarter", "BI", "RD", "TXP"];
    let titleList = ["企业名称"," 季度"," 年度"," 营业收入"," 研发投入"," 纳税"];

    let dataList = [titleList];
    dataBaseList.forEach(info => {
        let changeData = extractData(splitResultConfig.EnterpriseBusinessDataConfig, info, true);
        let subList = [];
        for (let i = 0; i < keyList.length; i++) {
            let value = changeData[keyList[i]]
            subList.push(value);
        } 
        dataList.push(subList);
    });

    return { dataList, fileName };
}


/**
 * 创始团队列表
 * @param name 企业名称
 * @param member 成员名称
 * @param type 人才类型
 * @param page 页面
 */
export async function getInitialTeamList(name:string, member:string, type:number, page:number) {
    let selectParam:any = {};
    if (name) selectParam.name = {"$regex":`${name}`};
    if (member) selectParam.memberName = member;
    if (type) {
        verificationEnumTools.eccEnumValue("企业创始团队列表", "type", configEnum.ENTERPRISETEAM, type );
        selectParam.type = type;
    }

    let dataBaseList = await findEnterpriseInitialTeamsByParamToPage(selectParam, (page-1)*10 );

    let dataList = [];
    dataBaseList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.EnterpriseInitialTeamDataListConfig, info, true);
        changeData.memberDEGREE = verificationEnumTools.changeEnumValue(configEnum.DEGREE, changeData.memberDEGREE);
        changeData.type = verificationEnumTools.changeEnumValue(configEnum.ENTERPRISETEAM, changeData.type);
        changeData.memberSex = verificationEnumTools.changeEnumValue(configEnum.SEX, changeData.memberSex);

        dataList.push(changeData);
    });

    return { dataList };
}


/**
 * 导出企业创始团队列表
 * @param name 
 * @param member 
 * @param memberType 
 * @param type 
 * @returns 
 */
export async function outPutInitialTeamList(name:string, member:string, memberType:number, type:number) {
    let fileName = "全部";
    /**拼接查询条件 */
    let selectParam:any = {};
    if (type == configEnum.OUTPUTTYPE.当前数据) {
        if (name) selectParam.name = {"$regex":`${name}`};
        if (member) selectParam.memberName = member;
        if (memberType){
            verificationEnumTools.eccEnumValue("导出企业创始团队列表", "memberType", configEnum.ENTERPRISETEAM, memberType );
            selectParam.type = memberType;
        }

        fileName = "当前数据";
    }
   

    let dataBaseList = await findEnterpriseInitialTeamsByParam(selectParam );

    let keyList = [ "name", "type", "memberName", "memberSex", "memberAge", "memberDEGREE", "memberSchool", "des"];
    let titleList = ["企业名称", "创始团队人才类型", "成员姓名", "成员性别", "成员出生年月", "成员最高学历", "毕业学校", "履历描述"];
    
    let dataList = [titleList];
    dataBaseList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.EnterpriseInitialTeamDataListConfig, info, true);

        /**将枚举值转为字符 */
        changeData.type = verificationEnumTools.changeEnumValue(configEnum.ENTERPRISETEAM, changeData.type);
        changeData.memberDEGREE = verificationEnumTools.changeEnumValue(configEnum.DEGREE, changeData.memberDEGREE);
        changeData.memberSex = verificationEnumTools.changeEnumValue(configEnum.SEX, changeData.memberSex);
         
        let subList = [];
        
        for (let i = 0; i < keyList.length; i++) {
            let value = changeData[keyList[i]]
            subList.push(value);
        }
        dataList.push(subList);
    });

    return { dataList, fileName };//todo
}