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

import { extractData } from "../../../util/piecemeal";
import * as enterpriseData from "../../../data/enterprise/enterprise";
import * as leaseData from "../../../data/lease";
import * as splitResultConfig from "../../../config/splitResultConfig";
import * as fuHuaQiData from "../../../data/fuHuaQi/fuhuaqi";
import * as demandData from "../../../data/fuHuaQi/demand";
import * as configEnum from "../../../config/enum";
import * as verificationEnumTools from "../../../util/verificationEnum";
import * as businessData from "../../../data/enterprise/quarterTask/businessdata";
import * as  initialTeamData from "../../../data/enterprise/initialTeam";
import moment = require("moment");
import { findEnterpriseNewTeamData } from "../../../data/enterprise/quarterTask/team";
import { changeAddToString, getRandomId } from "../../../tools/system";
import { JiaSuEnterpriseConfig, ZuLinEnterpriseConfig } from "../../../config/eccParam/admin";
import { eccFormParam } from "../../../util/verificationParam";
import { BizError } from "../../../util/bizError";
import { ERRORENUM } from "../../../config/errorEnum";
import * as dynamicsData from "../../../data/enterprise/dynamics";

/**
 * 获取在孵企业信息列表
 * @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.虚拟孵化;
    } else {
        selectParam.state = {"$ne":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.findFuHuaQiOperationNameMapByParam({});//用于将孵化器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.taskId || info.enterpriseIsInPut) {
            if (info.enterpriseIsInPut) changeData.isCreate = "底库数据";
            else {
                changeData.isCreate =  (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);

        if (!changeAddToString(info.oldLogonAddress)) {
            changeData.oldLogonAddress = "-";
        }
        if (!changeAddToString(info.logonAddress)) {
            changeData.logonAddress = "-";
        }
        if (!changeAddToString(info.operatingAddress)) {
            changeData.operatingAddress = "-";
        }

        /**将枚举值转为字符 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        changeData.cycxfx = verificationEnumTools.changeEnumValue(configEnum.CYCXFX, changeData.cycxfx) || "未选择";
        changeData.cycsrbj = verificationEnumTools.changeEnumValue(configEnum.CYCSRBJ, changeData.cycsrbj) || "未选择";

        let intellectualProperty = changeData.intellectualProperty || {}
        changeData.alienPatent =  intellectualProperty.alienPatent || 0;
        changeData.classIPatent =  intellectualProperty.classIPatent || 0;
        changeData.secondClassPatent =  intellectualProperty.secondClassPatent || 0;

        if (changeData.qualification) {
            let onceData = changeData.qualification;
            let beOnTheMarket = "无上市";
            if (changeData.qualification.beOnTheMarket){
                beOnTheMarket = verificationEnumTools.changeEnumValue( configEnum.FINANCINGROUNDS, onceData.beOnTheMarket)
            }

            let qualificationList = [{
                beOnTheMarket,
                highTechMs: onceData.highTechMs ? new Date(onceData.highTechMs).getFullYear() : '未认证',//高新技术
                zjtxMs: onceData.zjtxMs ? new Date(onceData.zjtxMs).getFullYear() : '未认证',//专精特新
                xjrpyMs: onceData.xjrpyMs ? new Date(onceData.xjrpyMs).getFullYear() : '未认证',//小巨人培育
                xjrMs: onceData.xjrMs ? new Date(onceData.xjrMs).getFullYear() : '未认证',//小巨人
            }];

            changeData.qualification = qualificationList;
        } else {
            changeData.qualification = [{
                beOnTheMarket:"无上市",
                highTechMs: '未认证',//高新技术
                zjtxMs: '未认证',//专精特新
                xjrpyMs: '未认证',//小巨人培育
                xjrMs: '未认证',//小巨人
            }]
        }
        
        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, isFuHuaQi:boolean) {
    /**拼接查询条件 */
    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.虚拟孵化;
        } else {
            selectParam.state = {"$ne":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}]}] ; //未提交的企业不能查看
    if (isFuHuaQi) {
        selectParam.fuHuaQiUscc = fuHuaQiUscc;
    }

    /**查询内容 */
    let usccMap = await fuHuaQiData.findFuHuaQiOperationNameMapByParam({});//用于将孵化器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","cycxfx","cycsrbj",
        "alienPatent", "classIPatent", "secondClassPatent",
        "beOnTheMarket", "highTechMs", "zjtxMs", "xjrpyMs", "xjrMs"
    ];//表头对应的字段顺序
    let dataList = [TitleList];
    
    dataBaseList.forEach( info => {
        /**截取返回结果 */
        let changeData:any = extractData(splitResultConfig.EnterpriseListConfig, info, true);

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

        if (!changeAddToString(info.oldLogonAddress)) {
            changeData.oldLogonAddress = "-";
        }
        if (!changeAddToString(info.logonAddress)) {
            changeData.logonAddress = "-";
        }
        if (!changeAddToString(info.operatingAddress)) {
            changeData.operatingAddress = "-";
        }

        changeData.cycxfx = verificationEnumTools.changeEnumValue(configEnum.CYCXFX, changeData.cycxfx) || "未选择";
        changeData.cycsrbj = verificationEnumTools.changeEnumValue(configEnum.CYCSRBJ, changeData.cycsrbj) || "未选择";

        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);
        
        /**- */
        let intellectualProperty = changeData.intellectualProperty || {}
        changeData.alienPatent =  intellectualProperty.alienPatent || 0;
        changeData.classIPatent =  intellectualProperty.classIPatent || 0;
        changeData.secondClassPatent =  intellectualProperty.secondClassPatent || 0;

        if (changeData.qualification) {
            let onceData = changeData.qualification;
            let beOnTheMarket = "无上市";
            if (onceData.beOnTheMarket){
                beOnTheMarket = verificationEnumTools.changeEnumValue( configEnum.FINANCINGROUNDS, onceData.beOnTheMarket) || "无上市"
            }

            changeData.beOnTheMarket = beOnTheMarket;
            changeData.highTechMs = onceData.highTechMs ? new Date(onceData.highTechMs).getFullYear() : '未认证';//高新技术
            changeData.zjtxMs = onceData.zjtxMs ? new Date(onceData.zjtxMs).getFullYear() : '未认证';//专精特新
            changeData.xjrpyMs = onceData.xjrpyMs ? new Date(onceData.xjrpyMs).getFullYear() : '未认证';//小巨人培育
            changeData.xjrMs = onceData.xjrMs ? new Date(onceData.xjrMs).getFullYear() : '未认证';//小巨人

        } else {
            changeData.beOnTheMarket = "无上市";//是否上市
            changeData.highTechMs =  '未认证';//高新技术
            changeData.zjtxMs =  '未认证';//专精特新
            changeData.xjrpyMs =  '未认证';//小巨人培育
            changeData.xjrMs =  '未认证';//小巨人
        }
        
        /**根据表头与key的顺序 生成小数组 */
        let subList = [];
        KeyList.forEach( keyStr => {
            let value = changeData[keyStr];
            if (value == null || value == undefined) value = "-"
            subList.push( value );
        });
        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.findFuHuaQiOperationNameMapByParam({});//用于将孵化器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) || "-";
        
        changeData.moveOutCause = verificationEnumTools.changeEnumValue(configEnum.MOVEOUTCAUSE, changeData.moveOutCause);
        changeData.moveOutTrace = verificationEnumTools.changeEnumValue(configEnum.MOVEOUTTRACE, changeData.moveOutTrace);
        changeData.moveOutType = verificationEnumTools.changeEnumValue(configEnum.MOVEOUTTYPE, changeData.moveOutType);

        changeData.logonAdd = changeAddToString(changeData.logonAddress) || "-";
        changeData.operatingAdd = changeAddToString(changeData.operatingAddress) || "-";
        changeData.oldLogonAdd = changeAddToString(changeData.oldLogonAddress) || "-";
        changeData.mainBusiness = changeData.mainBusiness || "-";

        changeData.leasedArea = 0;

        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, isFuHuaQi:boolean) {
    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 = "当前数据";
    }
    if (isFuHuaQi) selectParam.fuHuaQiUscc = fuHuaQiUscc;
    

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

    let keyList = [ "name", "moveOutTime", "moveOutType", "moveOutTrace","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) || "-";

        changeData.moveOutCause = verificationEnumTools.changeEnumValue(configEnum.MOVEOUTCAUSE, changeData.moveOutCause);
        changeData.moveOutType = verificationEnumTools.changeEnumValue(configEnum.MOVEOUTTYPE, changeData.moveOutType);
        changeData.moveOutTrace = verificationEnumTools.changeEnumValue(configEnum.MOVEOUTTRACE, changeData.moveOutTrace);

        changeData.logonAdd = changeAddToString(changeData.logonAddress) || "-";
        changeData.operatingAdd = changeAddToString(changeData.operatingAddress) || "-";
        changeData.oldLogonAdd = changeAddToString(changeData.oldLogonAddress) || "-";
        changeData.mainBusiness = changeData.mainBusiness || "-";

        changeData.leasedArea = 0;
        
        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, fuHuaQiUscc?) {

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

    let dataBaseList = await businessData.findBusinessDataByParamsToPage(selectParam, (page-1)*10);
    let dataCount = await businessData.findBusinessDataCountByParams(selectParam);
    let dataList = [];
    dataBaseList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.EnterpriseBusinessDataConfig, info, true);
        if (!info.isUpdate) {
            changeData.BI = "-";
            changeData.RD = "-";
            changeData.TXP = "-";
        }
        dataList.push(changeData);
    });

    return { dataList, count:dataCount, pageCount:Math.ceil(dataCount/10) };
}


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

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

    if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;

    let dataBaseList = await businessData.findBusinessDataByParams(selectParam);

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

    let dataList = [titleList];
    dataBaseList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.EnterpriseBusinessDataConfig, info, true);
        if (!info.isUpdate) {
            changeData.BI = "-";
            changeData.RD = "-";
            changeData.TXP = "-";
        }
        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, fuHuaQiUscc?) {
    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;
    }
    if (fuHuaQiUscc) {
        let idList = [];
        let thisFHQEnterpriseList = await enterpriseData.findEnterpriseList({state:{"$ne":configEnum.FUHUASTATE.迁出}, fuHuaQiUscc:fuHuaQiUscc});
        thisFHQEnterpriseList.forEach(info => {
            let {uscc} = info;
            idList.push(uscc);
        });
        selectParam.uscc = {"$in":idList};
    }

    let dataBaseList = await initialTeamData.findEnterpriseInitialTeamsByParamToPage(selectParam, (page-1)*10 );
    let count = await initialTeamData.findEnterpriseInitialTeamsCountByParamToPage(selectParam);
    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, count, pageCount:Math.ceil(count/10) };
}


/**
 * 导出企业创始团队列表
 * @param name 
 * @param member 
 * @param memberType 
 * @param type 
 * @returns 
 */
export async function outPutInitialTeamList(name:string, member:string, memberType:number, type:number, fuHuaQiUscc) {
    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 = "当前数据";
    }
    if (fuHuaQiUscc) {
        let idList = [];
        let thisFHQEnterpriseList = await enterpriseData.findEnterpriseList({state:{"$ne":configEnum.FUHUASTATE.迁出}, fuHuaQiUscc:fuHuaQiUscc});
        thisFHQEnterpriseList.forEach(info => {
            let {uscc} = info;
            idList.push(uscc);
        });
        selectParam.uscc = {"$in":idList};
    }
   

    let dataBaseList = await initialTeamData.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
}

export async function getEnterpriseTeamInfoList(uscc:string) {
    let teamInfo = await findEnterpriseNewTeamData(uscc);
    let onceInfo;
    if (!teamInfo) {
        onceInfo = {
            doctor:"未填报",//博士
            master:"未填报",//硕士
            undergraduate:"未填报",//本科
            juniorCollege:"未填报",//专科
            other:"未填报",//其他
            count:"未填报",
            studyAbroad:"未填报",//留学人数
            graduates:"未填报",//应届毕业生
        };
    } else {
        onceInfo = {
            doctor:teamInfo.doctor || 0, 
            master:teamInfo.master || 0, 
            undergraduate:teamInfo.undergraduate || 0, 
            juniorCollege:teamInfo.juniorCollege || 0, 
            other:teamInfo.other || 0, 
            studyAbroad:teamInfo.studyAbroad || 0, 
            graduates:teamInfo.graduates || 0
        };
        onceInfo.count = teamInfo.doctor + teamInfo.master + teamInfo.undergraduate + teamInfo.juniorCollege + teamInfo.other;
    }
    let dataList = [onceInfo];
    return {dataList};
}


/**
 * 企业信息回显
 * @param uscc 
 */
export async function enterpriseInfomation(uscc:string) {
    //暂时回显名称
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let dataInfo = {
        name:enterpriseInfo.name
    }
    return {dataInfo};
}


export async function updateEnterpriseInfomation(uscc:string, name:string) {
    //暂时回显名称
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    enterpriseInfo.name = name;

    await enterpriseInfo.save();

    return {isSuccess:true}
}

export async function jiasuEnterprise(name, industry, jiaSuZiZhi, isNaturalPersonHolding, page) {
    let selectParam:any = {};//{jiaSu:true};

    if (name) selectParam.name = {"$regex":name};
    if (industry && industry.length) selectParam.industry = {"$in":industry};
    if (jiaSuZiZhi && jiaSuZiZhi.length) selectParam.jiaSuZiZhi = {"$in":jiaSuZiZhi};
    if (isNaturalPersonHolding > 1) {
        if (isNaturalPersonHolding == 2) selectParam.isNaturalPersonHolding = true;
        else selectParam.isNaturalPersonHolding = false;
    }

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

    let dataList = [];

    dataBaseList.forEach(info => {
         /**截取返回数据 */ 
        let changeData:any = extractData(splitResultConfig.JiasuEnterpriseListConfig, info, true);

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

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

        
        
        dataList.push(changeData);
    })

    return {dataList, count}
}


export async function jsqInfo(uscc:string) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    let leaseInfo = await leaseData.findOnceData({uscc});

    if (!leaseInfo || !leaseInfo.id) leaseInfo.area = 0;
    let dataInfo = {
        name:enterpriseInfo.name,
        uscc:enterpriseInfo.uscc,
        mainBusiness:enterpriseInfo.mainBusiness,
        logonTime:enterpriseInfo.logonTime,
        firstIncubationTime:enterpriseInfo.firstIncubationTime,
        industry:enterpriseInfo.industry,
        jiaSuZiZhi:enterpriseInfo.jiaSuZiZhi,
        isNaturalPersonHolding:enterpriseInfo.isNaturalPersonHolding,
        leaseAddress:enterpriseInfo.leaseAddress,
        leasedArea:leaseInfo.area
    }
    return {dataInfo};
}



export async function jsqyUpdate(uscc:string, param) {
    eccFormParam("管理后台修改加速企业", JiaSuEnterpriseConfig, param);
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    enterpriseInfo.name = param.name;
    enterpriseInfo.mainBusiness = param.mainBusiness;
    enterpriseInfo.logonTime = param.logonTime;
    enterpriseInfo.firstIncubationTime = param.firstIncubationTime;
    enterpriseInfo.industry = param.industry;
    enterpriseInfo.jiaSuZiZhi = param.jiaSuZiZhi;
    enterpriseInfo.isNaturalPersonHolding = param.isNaturalPersonHolding;
    enterpriseInfo.leaseAddress = param.leaseAddress;

    let leaseInfo = await leaseData.findOnceData({uscc});
    leaseInfo.area = param.leasedArea;

    await enterpriseInfo.save();
    await leaseInfo.save();

    return {isSuccess:true}
}



export async function zlqyList( name, contractState, state, page) {
    let selectParam:any = {};//{jiaSu:true};

    if (name) selectParam.name = {"$regex":name};
    if (state) selectParam.state = state;

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

    const Now = new Date().valueOf();
    let dataList = [];

    for (let i = 0; i < dataBaseList.length; i++) {
        let {uscc} = dataBaseList[i];
        let info = dataBaseList[i];

        let leaseInfo = await leaseData.findOnceData({uscc});

        let payLong = 0;
        let contractStartTime = "";
        let contractEndTime = "";
        let rentDay = 0;
        let contractState = "";//合同状态
        let rentRecent = "";
        let rentNext = "";
        if (leaseInfo && leaseInfo.uscc) {
            leaseInfo.rentPayment.forEach(item => {
                payLong += item.payLong;
            });
            if (leaseInfo.rentPayment.length) {
                rentRecent = leaseInfo.rentPayment[ leaseInfo.rentPayment.length - 1].payStartTime;
                if (rentRecent) rentRecent = moment(rentRecent).format("YYYY-MM");
            } 
           
            
        }
        if (info.leaseInfo) {
            contractStartTime = moment(info.leaseInfo.contractStartTime).format("YYYY-MM-DD");
            contractEndTime = moment(info.leaseInfo.contractEndTime).format("YYYY-MM-DD");

            if (info.leaseInfo.rentEndTime) {
                rentDay = moment().diff(moment(info.leaseInfo.rentEndTime));
                if (!rentDay) rentDay = rentDay < 0 ? 0 : rentDay;
            }

            if (!leaseInfo || !leaseInfo.contractStartTime) {
                contractState = "到期未签"
            } else {
                if ((leaseInfo.contractEndTime - Now) < 0) {
                    contractState = "到期未签";
                } else {
                    contractState = "签约企业";
                }
            }

            rentNext = moment(info.leaseInfo.rentEndTime).format("YYYY-MM-DD");
        } 
       
        let changeData = {
            name:info.name,
            uscc:info.uscc,
            payLong,
            contractStartTime,
            contractEndTime,
            rentDay,
            contractState,
            rentRecent,
            rentNext,
            leaseAddress:info.leaseAddress || ""
        };
        dataList.push(changeData);
    }

    return {dataList, count}
}



export async function zlqyInfo(uscc:string) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    let leaseInfo = await leaseData.findOnceData({uscc});

    let Now = new Date().valueOf();

    let contractState = "到期未签";
     let rentRecent = "";
    if (!leaseInfo || !leaseInfo.id) leaseInfo = {};
    else {
        if (!leaseInfo || !leaseInfo.contractStartTime) {
            contractState = "到期未签"
        } else {
            if ((leaseInfo.contractEndTime - Now) < 0) {
                contractState = "到期未签";
            } else {
                contractState = "签约企业";
            }
        }
        if (leaseInfo.rentPayment.length) {
            rentRecent = leaseInfo.rentPayment[ leaseInfo.rentPayment.length - 1].payStartTime;
            if (rentRecent) rentRecent = moment(rentRecent).format("YYYY-MM");
        }
        
    }

    let dataInfo = {
        name:enterpriseInfo.name,
        contractLong:leaseInfo.contractLong || 0,
        contractStartTime:leaseInfo.contractStartTime || null,
        contractEndTime:leaseInfo.contractEndTime|| null,
        contractState,
        price:leaseInfo.price || 0,
        rentRecent,
        area:leaseInfo.area || 0,
        areaUnit:leaseInfo.areaUnit || 1,
        address:leaseInfo.address || ""
    }
    return {dataInfo};
}

export async function zlqyUpdate(uscc:string, param) {
    eccFormParam("管理后台修改租赁信息", ZuLinEnterpriseConfig, param);
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    if (enterpriseInfo.leaseInfo && enterpriseInfo.leaseInfo.contractStartTime) {
        enterpriseInfo.leaseInfo.contractStartTime = param.contractStartTime;
        enterpriseInfo.leaseInfo.contractEndTime = param.contractEndTime;
        enterpriseInfo.leaseAddress = param.address;
    }

    let leaseInfo = await leaseData.findOnceData({uscc});
    if (!leaseInfo) {
        let addInfo = {
            uscc,
            enterpriseName:enterpriseInfo.enterpriseName,
            rentPayment:[],
            contractLong : param.contractLong,
            contractStartTime : param.contractStartTime,
            contractEndTime : param.contractEndTime,
            price : param.price,
            area : param.area,
            areaUnit : param.areaUnit,
            address : param.address,
        }
        await leaseData.createData(addInfo);
    } else {
        leaseInfo.contractLong = param.contractLong;
        leaseInfo.contractStartTime = param.contractStartTime;
        leaseInfo.contractEndTime = param.contractEndTime;
        leaseInfo.price = param.price;
        leaseInfo.area = param.area;
        leaseInfo.areaUnit = param.areaUnit;
        leaseInfo.address = param.address;
        await leaseInfo.save();
    }
    

    await enterpriseInfo.save();
    

    return {isSuccess:true}
}


export async function zlqyrentPaymentList(uscc) {
    let leaseInfo = await leaseData.findOnceData({uscc});

    let dataList = [];
    if (leaseInfo && leaseInfo.uscc) {
        leaseInfo.rentPayment.forEach(info => {
            dataList.push({
                payStartTime:info.payStartTime,
                payLong:info.payLong
            });
        })
    }

    return {dataList}
}

export async function zlqyrentPaymentUpdate(uscc, rentPayment) {
    let leaseInfo = await leaseData.findOnceData({uscc});

    if (!leaseInfo || !leaseInfo.uscc) {
        let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
        let addInfo = {
            uscc:enterpriseInfo.uscc,
            enterpriseName:enterpriseInfo.name,
            rentPayment:rentPayment
        };

        await leaseData.createData(addInfo);
    } else {
        leaseInfo.rentPayment = rentPayment;
        await leaseInfo.save();
    }

    return {isSuccess:true};
}



export async function demandList(name:string, demand, page) {
    let param:any = {};
    if (name) param.enterpriseName = name;
    if (demand) param.demand = {"$in":[demand]};

    let dbList = await demandData.findEnterpriseListToPage(param, page);
    let dataCount = await demandData.findCountByParam(param);

    let dataList = [];
    dbList.forEach(info => {
        let demandList = [];
        info.demand.forEach(item => {
            demandList.push({
                key:item,
                value:configEnum.VISITDEMAND[item]
            })
        })

        dataList.push({
            uscc:info.uscc,
            name:info.enterpriseName,
            demand:demandList
        });
    })

    return {dataCount, dataList}
}


export async function demandLabel(uscc:string, demand) {
    let param:any = {uscc};
    param.demand = {"$in":[demand]};

    let dbInfo = await demandData.findOne(param);

    let dataInfo = {
        demand:verificationEnumTools.changeEnumManyValue(configEnum.VISITDEMAND, dbInfo.demand),
        demandDesc:dbInfo
    };

    return {dataInfo}
}


export async function demandInfo(uscc:string) {
    let param:any = {uscc};
    let dbInfoList = await demandData.findByParam(param);

    let dataList = [];
    dbInfoList.forEach(info => {
        dataList.push({
            id:info.id,
            demand:verificationEnumTools.changeEnumManyValue(configEnum.VISITDEMAND, info.demand),
            demandDesc:info.demandDesc,
            createTime:moment(info.createTime).format("YYYY-MM-DD")
        });
    });

    return {dataList}
}


export async function removeDemand(id) {
    let param:any = {id};
    let demandInfo = await demandData.findOne(param);

    if (!demandInfo) throw new BizError(ERRORENUM.目标数据不存在);
    
    await demandData.removeOneData(id);

    return {isSuccess:true}
}


export async function demandCreate(uscc, demand, demandDesc) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let demandInfo = {
        id:getRandomId("deman"),
        fuHuaQiUscc:enterpriseInfo.fuHuaQiUscc,
        uscc,
        enterpriseName:enterpriseInfo.name,
        createTime:new Date().valueOf(),
        enterpriseType:configEnum.VISITENTERPRISETYPE.主动申报需求企业,
        demand,
        demandDesc
    };

    await demandData.createDataByParam(demandInfo);

    return {isSuccess:true}
}

export async function demandUpdate(id, demand) {
    // let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    let demandInfo = await demandData.findOne({id});

    demandInfo.demand = demand;
    await demandInfo.save();

    return {isSuccess:true}
}


export async function enterpriseNameList(name:string) {
    let param:any = {};
    if (name) param.name = {"$regex":name};

    let dbList = await enterpriseData.findEnterpriseList(param);

    let dataList = [];
    dbList.forEach(info => {
        dataList.push({
            value:info.uscc,
            key:info.name
        });
    })

    return {dataList}
}


export async function keynoteList(name, type, page ) {
    let param:any = {follow:true};
    if (name) param.name = {"$regex":name};
    if (type) {
        param.keynote = {"$in":[type]}
    }

    let dbList = await enterpriseData.findEnterpriseListToPage(param, (page-1)*10);
    let dataCount = await enterpriseData.findEnterpriseCount(param);

    let dataList = [];
    dbList.forEach(info => {
        let label = [];
        let keynote = info.keynote || [];
        keynote.forEach(item => {
            label.push(verificationEnumTools.changeEnumValue(configEnum.ZHONGDIANQIYE, item) );
        })
        dataList.push({
            uscc:info.uscc,
            label,
            haveActivity:true,
            name:info.name
        });
    })

    return {dataList, count:dataCount}
}

export async function keynoteActivityList(uscc) {
    let dbList = await dynamicsData.findByParam({uscc});

    let dataList = [];
    dbList.forEach(info => {
        dataList.push({
            time:moment(info.createTime).format("YYYY.MM.DD"),
            contentBefore:info.oldContent,
            content:info.content
        });
    });

    return {dataList};
}

export async function addKeynote(uscc, label) {

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    enterpriseInfo.keynote = label;

    await enterpriseInfo.save();

    return {isSuccess:true};
}

export async function delKeynote(uscc) {

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    enterpriseInfo.keynote = [];

    await enterpriseInfo.save();

    return {isSuccess:true};
}