/**
 * 我的企业相关逻辑
 * 作者:lxm
 */

import * as eccFormParamConfig from "../../../config/eccParam/fuHuaQi";
import { ERRORENUM } from "../../../config/errorEnum";
import { BizError } from "../../../util/bizError";
import * as sysTools from "../../../tools/system";
import * as enterpriseData from "../../../data/enterprise/enterprise";
import * as splitResultConfig from "../../../config/splitResultConfig";
import * as configEnum from "../../../config/enum";
import { eccFormParam, eccReqParamater } from "../../../util/verificationParam";
import * as verificationEnumTools from "../../../util/verificationEnum";
import { checkChange, extractData } from "../../../util/piecemeal";
import * as scoreBiz from "../fuHuaQi/score";
import { ENTERPRISENODEENUM, FUHUAQINODEENUM } from "../../../config/pointConfig";
import { addEnterprisePoint, addFuHuaQiPoint } from "../../point";
import moment = require("moment");
import { addTeamData, findEnterpriseNewTeamData, findTeamByUsccAndTime } from "../../../data/enterprise/quarterTask/team";
import { EnterpriseTeamConfig } from "../../../config/splitResultConfig";
import { findBusinessDataByUsccAndYear } from "../../../data/enterprise/quarterTask/businessdata";
import { selectRepleishData } from "../../../data/enterprise/replenish";
import { enterpriseLabelEvent } from "../../label";
import { findFuHuaQiByUSCC } from "../../../data/fuHuaQi/fuhuaqi";
import * as leaseData from "../../../data/lease";
import { LABELEVENT } from "../../../config/enum/labelEnum";
import { EnterpriseQualificationUpdateConfig } from "../../../config/eccParam/enterprise";



/**
 * 我的企业列表
 * 小程序端 2.0
 * @param uscc 孵化器统一信用代码
 * @param state 孵化器状态 遵循 枚举FUHUASTATE
 * @param name 孵化器名称
 * @param page 当前页面
 */
export async function myEnterprise(uscc:string, state:number, name:string, page:number) {
    
    let result:any = {};

    let selectParam:any = { fuHuaQiUscc:uscc};
    if (name) selectParam.name = {"$regex":`${name}`};
    if (state == configEnum.INSIDESTATE.全部) {
        selectParam.state = {"$lt":4};
    } else {
        if (state == 5) selectParam.graduation = true;
        else selectParam.state = state;
    }
    
    let dataList = await enterpriseData.findEnterpriseListToPage(selectParam, (page-1)*10);

    /**当前条件数据量 */
    let dataCount = await enterpriseData.findEnterpriseCount(selectParam);
    /**当前条件页面数量 */
    result.dataCount = dataCount;
    result.pageCount = Math.ceil(dataCount/10);

    if (state != configEnum.FUHUASTATE.迁出) {
        /**查询所有的数据量 */
        let allCount = await enterpriseData.findEnterpriseCount({ fuHuaQiUscc:uscc });
        let virtualCount = 0;
        if (state == configEnum.FUHUASTATE.虚拟孵化) virtualCount = dataCount;
        else virtualCount = await enterpriseData.findEnterpriseCount({ fuHuaQiUscc:uscc, state:configEnum.FUHUASTATE.虚拟孵化 });


        /**拟毕业企业数量 */
        let graduate = await enterpriseData.findEnterpriseCount({ fuHuaQiUscc:uscc, graduation:true });

        result.dataNumberList = [
            {key:configEnum.INSIDESTATE.全部, value:`全部(${allCount})`},
            {key:configEnum.INSIDESTATE.实体孵化, value:`实体孵化(${allCount-virtualCount})`},
            {key:configEnum.INSIDESTATE.虚拟孵化, value:`虚拟孵化(${virtualCount})`},
            {key:5, value:`拟毕业企业(${graduate})`}
        ];

    }

    let enterpriseList = [];

    dataList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.MyEnterpriseDataConfig, info, false);
        if (state != configEnum.FUHUASTATE.迁出) {
            changeData.virtualCause = info.virtualCause || 0;
            changeData.virtualCauseDes = info.virtualCauseDes || "";
        }

        changeData.state = verificationEnumTools.changeEnumValue(configEnum.FUHUASTATE, changeData.state);
      
        enterpriseList.push(changeData);
    });

    result.enterpriseList = enterpriseList;
    
    return result;
}



/**
 * 我的企业列表
 * 小程序端 2.0
 * @param uscc 孵化器统一信用代码
 * @param state 孵化器状态 遵循 枚举FUHUASTATE
 * @param name 孵化器名称
 * @param page 当前页面
 */
export async function myEnterpriseJS(uscc:string, state:number, name:string, page:number) {
    let result:any = {};

    let selectParam:any = { fuHuaQiUscc:uscc, jiaSu:true};
    if (name) selectParam.name = {"$regex":`${name}`};
    if (state == configEnum.INSIDESTATE.全部) {
        selectParam.state = {"$lt":4};
    } else {
        if (state == 5) selectParam.graduation = true;
        else selectParam.state = state;
    }
    
    let dataList = await enterpriseData.findEnterpriseListToPage(selectParam, (page-1)*10);

    /**当前条件数据量 */
    let dataCount = await enterpriseData.findEnterpriseCount(selectParam);
    /**当前条件页面数量 */
    result.dataCount = dataCount;
    result.pageCount = Math.ceil(dataCount/10);

    if (state != configEnum.FUHUASTATE.迁出) {
        /**查询所有的数据量 */
        let allCount = await enterpriseData.findEnterpriseCount({ fuHuaQiUscc:uscc });
        let virtualCount = 0;
        if (state == configEnum.FUHUASTATE.虚拟孵化) virtualCount = dataCount;
        else virtualCount = await enterpriseData.findEnterpriseCount({ fuHuaQiUscc:uscc, state:configEnum.FUHUASTATE.虚拟孵化 });


        /**拟毕业企业数量 */
        let graduate = await enterpriseData.findEnterpriseCount({ fuHuaQiUscc:uscc, graduation:true });

        result.dataNumberList = [
            {key:configEnum.INSIDESTATE.全部, value:`全部(${allCount})`},
            {key:configEnum.INSIDESTATE.实体孵化, value:`实体孵化(${allCount-virtualCount})`},
            {key:configEnum.INSIDESTATE.虚拟孵化, value:`虚拟孵化(${virtualCount})`},
            {key:5, value:`拟毕业企业(${graduate})`}
        ];

    }

    let enterpriseList = [];

    dataList.forEach(info => {
        let changeData:any = extractData(splitResultConfig.MyEnterpriseDataConfig, info, false);
        if (state != configEnum.FUHUASTATE.迁出) {
            changeData.virtualCause = info.virtualCause || 0;
            changeData.virtualCauseDes = info.virtualCauseDes || "";
        }

        changeData.state = verificationEnumTools.changeEnumValue(configEnum.FUHUASTATE, changeData.state);
      
        changeData.follow = info.follow;
        changeData.jiaSuZiZhi = verificationEnumTools.changeEnumManyValue(configEnum.JIASUZIZHI, info.jiaSuZiZhi)
        enterpriseList.push(changeData);
    });

    result.enterpriseList = enterpriseList;
    
    return result;
}





/**
 * 修改企业孵化状态 修改为实体
 * 小程序端 2.0
 * @param fuHuaQiUscc 孵化器统一信用代码
 * @param uscc 企业统一信用代码
 * @param leasedArea 租赁面积
 * @returns {isSuccess:true/false}
 */
export async function updatePhysicalInfo(fuHuaQiUscc:string, uscc:string, leasedArea:number) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    if (!enterpriseInfo) throw new BizError(ERRORENUM.该企业不存在, "修改企业孵化状态 修改为实体",`孵化器 ${fuHuaQiUscc} -> 企业${uscc}`);

    if (enterpriseInfo.fuHuaQiUscc != fuHuaQiUscc) throw new BizError(ERRORENUM.无法操作其他孵化器的企业, "修改企业孵化状态 修改为实体",`孵化器 ${fuHuaQiUscc} -> 企业${uscc}`);

    let changeState = false;
    /** 区分修改状态和修改租赁面积 */
    if (enterpriseInfo.state == configEnum.FUHUASTATE.实体孵化) {
        //兼容什么都没有修改的情况，这种情况不需要更改数据库和埋点
        if (leasedArea != enterpriseInfo.leasedArea) {
            /**埋点 */
            addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.我的企业_占孵面积, enterpriseInfo.leasedArea || 0, leasedArea);
            /**修改数据 */
            enterpriseInfo.leasedArea = leasedArea;
        }
        
    } else {
        /**企业孵化状态埋点 */
        changeState = true;
        let oldData = {
            leasedArea: enterpriseInfo.leasedArea || 0,
            state: enterpriseInfo.state,
            virtualCause: enterpriseInfo.virtualCause
        };
        let newData = {
            leasedArea,
            state: configEnum.FUHUASTATE.实体孵化,
            virtualCause : null,//虚拟孵化模式
        };
        addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.我的企业_孵化状态, oldData, newData);
        /**修改数据 */
        enterpriseInfo.leasedArea = leasedArea;
        enterpriseInfo.state = configEnum.FUHUASTATE.实体孵化;

        /**修改为实体，需要把虚拟的和迁出的字段清空 */
        enterpriseInfo.virtualCause = null;//虚拟孵化模式
        enterpriseInfo.virtualCauseDes = "";//虚拟孵化原因
        enterpriseInfo.moveOutType = null;//迁出类型
        enterpriseInfo.moveOutCause = [];//迁出原因
        enterpriseInfo.moveOutTime = 0;
        
        /**标签*/
        let fuHuaQiInfo = await findFuHuaQiByUSCC(fuHuaQiUscc);
        await enterpriseLabelEvent(enterpriseInfo, LABELEVENT.孵化类型更新, fuHuaQiInfo.operationName);
    
    }

    await enterpriseInfo.save();

    if (changeState) {
        /**企业状态改变埋点 */
        let xn = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.虚拟孵化}) || 0; //虚拟孵化 
        let st = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.实体孵化}) || 0; //实体孵化
        let qc = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.迁出}) || 0; //迁出孵化
        addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.企业状态变化, {xn, st, qc}, {});
        
    }
    

    return {isUsccess:true};
}


/**
 * 修改企业孵化状态 修改为虚拟
 * 小程序端 2.0
 * @param fuHuaQiUscc 孵化器统一信用代码
 * @param uscc 企业统一信用代码
 * @param virtualCauseDes 虚拟孵化其他原因
 * @param virtualCause 虚拟孵化模式
 * @returns {isSuccess:true/false}
 */
export async function updateVirtualInfo(fuHuaQiUscc:string, uscc:string, virtualCauseDes:string, virtualCause:number) {
    verificationEnumTools.eccEnumValue('修改企业孵化状态', '修改为虚拟', configEnum.VIRTUALCAUSE, virtualCause);

    if (virtualCause == configEnum.VIRTUALCAUSE.其他 && !virtualCauseDes) {
        throw new BizError(ERRORENUM.请填入其他原因, "修改企业孵化状态 修改为虚拟", `virtualCause:${virtualCause}, virtualCauseDes:${virtualCauseDes}`);
    }

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterpriseInfo) throw new BizError(ERRORENUM.该企业不存在, "修改企业孵化状态 修改为实体",`孵化器 ${fuHuaQiUscc} -> 企业${uscc}`);
    /**埋点 -新值 */
    let oldData = {
        leasedArea: enterpriseInfo.leasedArea || 0,
        state: enterpriseInfo.state,
    };

    if (enterpriseInfo.fuHuaQiUscc != fuHuaQiUscc) throw new BizError(ERRORENUM.无法操作其他孵化器的企业, "修改企业孵化状态 修改为实体",`孵化器 ${fuHuaQiUscc} -> 企业${uscc}`);

    enterpriseInfo.virtualCause = virtualCause;
    if (virtualCauseDes)  enterpriseInfo.virtualCauseDes = virtualCauseDes;

    enterpriseInfo.state = configEnum.FUHUASTATE.虚拟孵化;

    /**修改为虚拟时，需要把实体的和迁出的字段清空 */
    enterpriseInfo.moveOutType = null;//迁出类型
    enterpriseInfo.moveOutCause = [];//迁出原因
    enterpriseInfo.leasedArea = 0;//租赁面积
    enterpriseInfo.moveOutTime = 0;

    /**埋点 -新值 */
    let newData = {
        leasedArea : 0,
        state: configEnum.FUHUASTATE.虚拟孵化,
    };
    addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.我的企业_孵化状态, oldData, newData );

    /**标签*/
    let fuHuaQiInfo = await findFuHuaQiByUSCC(fuHuaQiUscc);
    await enterpriseLabelEvent(enterpriseInfo, LABELEVENT.孵化类型更新, fuHuaQiInfo.operationName);


    await enterpriseInfo.save();

    /**企业状态改变埋点 */
    let xn = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.虚拟孵化}) || 0; //虚拟孵化 
    let st = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.实体孵化}) || 0; //实体孵化
    let qc = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.迁出}) || 0; //迁出孵化 
    addFuHuaQiPoint( fuHuaQiUscc, FUHUAQINODEENUM.企业状态变化, {xn, st, qc});

    return {isUsccess:true};
}


/**
 * 修改企业孵化状态 修改为迁出
 * 小程序端 2.0
 * @param fuHuaQiUscc 孵化器统一信用代码
 * @param uscc 企业统一信用代码
 * @param moveOutType 迁出类型
 * @param moveOutTrace 迁出去向 2.3新加字段
 * @param moveOutCause 迁出原因 多选
 * @returns {isSuccess:true/false}
 */
export async function updateMoveOutInfo(fuHuaQiUscc:string, uscc:string,  moveOutType:number, moveOutTrace:number, moveOutCause ) {
    /**校验参数 */
    verificationEnumTools.eccEnumValue('修改企业孵化状态', '修改为迁出', configEnum.MOVEOUTTYPE, moveOutType);
    if (moveOutType != configEnum.MOVEOUTTYPE.企业注销 ) {
        //选择了 非企业注销时 moveOutTrace 和 moveOutCause  为必选项
        await eccReqParamater({moveOutTrace:"Number", moveOutCause:"[Number]" }, {moveOutTrace, moveOutCause} );
        /**校验moveOutCause 和 moveOutTrace  是否符合规则*/
        verificationEnumTools.eccEnumValue('修改企业孵化状态', '迁出去向', configEnum.MOVEOUTTRACE, moveOutTrace);
        verificationEnumTools.eccEnumValue('修改企业孵化状态', '迁出原因', configEnum.MOVEOUTCAUSE, moveOutCause);
        /**根据 不同的迁出类型 校验不同的迁出原因枚举 */
        if (moveOutType == configEnum.MOVEOUTTYPE.毕业迁出) {
            moveOutCause = [moveOutCause[0]];//非毕业迁出是单选
            verificationEnumTools.eccEnumValue('修改企业孵化状态', '修改为迁出', configEnum.MOVEOUTCAUSECLIENT, moveOutCause);
        }
        if (moveOutType == configEnum.MOVEOUTTYPE.非毕业迁出) {
            verificationEnumTools.eccEnumValue('修改企业孵化状态', '修改为迁出', configEnum.MOVEOUTCAUSENOTCLIENT, moveOutCause);
        }
    } else {
        /**如果是选择了企业注销 这里的两个参数要为空 */
        moveOutTrace = 0;
        moveOutCause = [];
    }
    

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterpriseInfo) throw new BizError(ERRORENUM.该企业不存在, "修改企业孵化状态 修改为实体",`孵化器 ${fuHuaQiUscc} -> 企业${uscc}`);

    /**埋点 -旧值 */
    let oldData = {
        leasedArea: enterpriseInfo.leasedArea || 0,
        state: enterpriseInfo.state,
        virtualCause : null,//虚拟孵化模式
        virtualCauseDes : "",//虚拟孵化原因
    };

    if (enterpriseInfo.fuHuaQiUscc != fuHuaQiUscc) throw new BizError(ERRORENUM.无法操作其他孵化器的企业, "修改企业孵化状态 修改为实体",`孵化器 ${fuHuaQiUscc} -> 企业${uscc}`);

    enterpriseInfo.moveOutType = moveOutType;
    enterpriseInfo.moveOutCause = moveOutCause;
    enterpriseInfo.moveOutTrace = moveOutTrace;
    enterpriseInfo.moveOutTime = new Date().valueOf();

    enterpriseInfo.state = configEnum.FUHUASTATE.迁出;

    /**修改为迁出时，需要把实体的和虚拟的字段清空 */
    enterpriseInfo.virtualCause = null;//虚拟孵化模式
    enterpriseInfo.virtualCauseDes = "";//虚拟孵化原因
    enterpriseInfo.leasedArea = 0;//租赁面积


    /**埋点 -新值*/
    let newData = {
        leasedArea : 0,
        state: configEnum.FUHUASTATE.迁出,
        moveOutType: moveOutType,
        moveOutCause: moveOutCause,
        moveOutTrace: moveOutTrace,
        moveOutTime: new Date().valueOf(),
        graduation: await enterpriseData.findEnterpriseCount({ fuHuaQiUscc, graduation:true })
    };
    
    addFuHuaQiPoint( fuHuaQiUscc, FUHUAQINODEENUM.我的企业_孵化状态, oldData, newData );

    /**标签 */
    let fuHuaQiInfo = await findFuHuaQiByUSCC(fuHuaQiUscc);
    await enterpriseLabelEvent(enterpriseInfo, LABELEVENT.迁出, fuHuaQiInfo.operationName);

    await enterpriseInfo.save();

    /**企业状态改变埋点 */
    let xn = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.虚拟孵化}) || 0; //虚拟孵化 
    let st = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.实体孵化}) || 0; //实体孵化
    let qc = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.迁出}) || 0; //迁出孵化
    addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.企业状态变化, {xn, st, qc});

    return {isUsccess:true};
}



/**
 * 企业基本信息 回显
 * 小程序端 2.0
 * @param fuHuaQiUscc 孵化器统一信用代码
 * @param uscc 企业统一信用代码
 */
export async function getMyEnterpriseBaseInfo(fuHuaQiUscc:string, uscc:string) {
    
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    if (!enterpriseInfo) throw new BizError(ERRORENUM.该企业不存在, `我的企业 回显企业信息 ${uscc}`);
    if ( enterpriseInfo.fuHuaQiUscc != fuHuaQiUscc) throw new BizError(ERRORENUM.无法操作其他孵化器的企业, '企业基本信息回显', `孵化器:${fuHuaQiUscc} 企业:${uscc}`);

    let changeData = extractData(splitResultConfig.MyEnterpriseBaseDataConfig, enterpriseInfo, false);

    return {enterpriseInfo:changeData};
}


/**
 * 修改我的企业基本信息
 * 小程序端 2.0
 * @param fuHuaQiUscc 孵化器统一信用代码 
 * @param param 表单
 */
export async function updateMyEnterpriseBaseInfo(fuHuaQiUscc:string, param) {
    
    eccFormParam("修改我的企业基本信息", eccFormParamConfig.UpdateMyEnterpriseBaseDataConfig, param );
    verificationEnumTools.eccEnumValue('修改新注册企业', 'industry', configEnum.INDUSTRY, param.industry);
    if ( !sysTools.eccUscc(param.uscc) ) throw new BizError(ERRORENUM.统一社会信用代码不合法);

    const Uscc = param.uscc;
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(Uscc);

    if (!enterpriseInfo) throw new BizError(ERRORENUM.该企业不存在, `我的企业 修改我的企业基本信息 ${Uscc}`);
    if ( enterpriseInfo.fuHuaQiUscc != fuHuaQiUscc) throw new BizError(ERRORENUM.无法操作其他孵化器的企业, '修改我的企业基本信息', `孵化器:${fuHuaQiUscc} 企业:${Uscc}`);

    /**修改字段 */
    let changeList = checkChange(param, enterpriseInfo);
    if ( !changeList.length ) throw new BizError(ERRORENUM.数据无更新, `${param.uscc}数据无更新`);
    changeList.forEach(key => {
        enterpriseInfo[key] = param[key];
    });

    /**埋点 */
    let oldPointInfo = {};
    for (let key in param) {
        oldPointInfo[key] = enterpriseInfo[key] || '';
    }
    addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.我的企业_基本信息, oldPointInfo, param );

    await enterpriseInfo.save();

    /**更新分数 */
    await scoreBiz.updateScore(fuHuaQiUscc, configEnum.SCOREWAYS.我的企业数据, false);

    return {isSuccess:true};
}



/**
 * 补录新迁入企业信息
 * 小程序端 2.0
 * @param fuHuaQiUscc 孵化器统一信用代码 
 * @param param 表单
 */
export async function replenishMyEnterpriseInPutInfo(fuHuaQiUscc:string, param) {
    eccFormParam("补录新迁入企业信息", eccFormParamConfig.ReplenishMyEnterpriseInPutDataConfig, param );
    let now = new Date().valueOf();
    if ( param.logonTime > now || param.firstIncubationTime > now || param.timeOfImmigration > now) throw new BizError(ERRORENUM.不可选择未来时间);
    verificationEnumTools.eccEnumValue('补录新迁入企业信息', 'industry', configEnum.INDUSTRY, param.industry);
    if ( !sysTools.eccUscc(param.uscc) ) throw new BizError(ERRORENUM.统一社会信用代码不合法);

    /**不能出现重复的统一社会信用代码 草稿的也不行 */
    let dataBaseInfo = await enterpriseData.findEnterpriseByUscc(param.uscc);
    if ( dataBaseInfo && dataBaseInfo.uscc && dataBaseInfo.state != configEnum.FUHUASTATE.迁出)  throw new BizError(ERRORENUM.该企业已存在, `${param.uscc}已经在库中存在`);

     if (param.jiaSu == 1 || param.jiaSu == 2) {
        //判断
        if (param.jiaSu == 1 && !param.jiaSuZiZhi) {
            throw new BizError(ERRORENUM.参数错误, "加速企业缺失加速资质");
        } else if (param.jiaSu == 1 && param.jiaSuZiZhi.indexOf(configEnum.JIASUZIZHI.其他) > -1  && !param.jiaSuZiZhiDesc) {
            throw new BizError(ERRORENUM.参数错误, "加速企业的加速资质选了其他但是没填写内容");
        }
    } else throw new BizError(ERRORENUM.参数错误, "加速企业不符合1或2", param.jiaSu);

    param.jiaSu = param.jiaSu == 1;

    /**添加新注册企业标识 */
    if ( dataBaseInfo && dataBaseInfo.state && dataBaseInfo.state == configEnum.FUHUASTATE.迁出) {
        dataBaseInfo.fuHuaQiUscc = fuHuaQiUscc;
        dataBaseInfo.state = configEnum.FUHUASTATE.实体孵化;
        dataBaseInfo.isCreate = false;
        dataBaseInfo.virtualCause = 0;
        dataBaseInfo.virtualCauseDes = '';
        dataBaseInfo.moveOutType = 0;
        dataBaseInfo.moveOutTrace = 0;
        dataBaseInfo.moveOutCause = [];
        dataBaseInfo.moveOutTime = 0;
        for (let key in eccFormParamConfig.MoveInEnterpriseParamConfig) {
            dataBaseInfo[key] = param[key];
        }
        

    } else {
        /**添加新注册企业标识 */
        param.isCreate = false;//标识此次操作是否是迁入企业并不是新注册企业
        
        param.state = configEnum.FUHUASTATE.实体孵化;//默认就是实体孵化

        await enterpriseData.replenishEnterpriseData(fuHuaQiUscc, param);  
    }


    addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.我的企业_补录企业, param.uscc, '新迁入' );

    /**企业状态改变埋点 */
    let xn = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.虚拟孵化}) || 0; //虚拟孵化 
    let st = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.实体孵化}) || 0; //实体孵化
    let qc = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.迁出}) || 0; //迁出孵化
    addFuHuaQiPoint( fuHuaQiUscc, FUHUAQINODEENUM.企业状态变化, {xn, st, qc});

    /**标签 */
    let fuHuaQiInfo = await findFuHuaQiByUSCC(fuHuaQiUscc);
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(param.uscc);
    await enterpriseLabelEvent(enterpriseInfo, LABELEVENT.入孵, fuHuaQiInfo.operationName);


     //2025新加内容
    let leaseInfo = await leaseData.findOnceData({uscc:param.uscc});
    if (leaseInfo && leaseInfo.uscc) { //
        leaseInfo.enterpriseName = param.name;
        leaseInfo.contractStartTime = param.contractStartTime;
        leaseInfo.contractEndTime = param.contractEndTime;
        leaseInfo.price = param.price;//单价
        leaseInfo.area = param.leasedArea;//租赁面积
        leaseInfo.address = param.leaseAddress;
        leaseInfo.areaUnit = param.areaUnit;
        leaseInfo.rentPayment = [
            {
                payStartTime:param.payStartTime,
                payLong:param.payLong
            }
        ];
        await leaseInfo.save();
    } else {
        let addLease = {
            uscc:param.uscc,
            enterpriseName:param.name,
            contractStartTime:param.contractStartTime,
            contractEndTime:param.contractEndTime,
            price:param.price,//单价
            area:param.leasedArea,//租赁面积
            areaUnit : param.areaUnit,
            rentPayment : [
                {
                payStartTime:param.payStartTime,
                payLong:param.payLong
                }
            ],
            address:param.leaseAddress,//地址

        };
        await leaseData.createData(addLease);
    }

    return {isSuccess:true};
}


/**
 * 补录新注册企业信息
 * 小程序端 2.0
 * @param fuHuaQiUscc 孵化器统一信用代码 
 * @param param 表单
 */
export async function replenishMyEnterpriseCreateInfo(fuHuaQiUscc:string, param) {
    
    eccFormParam("补录新迁入企业信息", eccFormParamConfig.ReplenishMyEnterpriseCreateDataConfig, param );
    let now = new Date().valueOf();
    if ( param.logonTime > now || param.firstIncubationTime > now) throw new BizError(ERRORENUM.不可选择未来时间);

    verificationEnumTools.eccEnumValue('补录新迁入企业信息', 'industry', configEnum.INDUSTRY, param.industry);
    if ( !sysTools.eccUscc(param.uscc) ) throw new BizError(ERRORENUM.统一社会信用代码不合法);

    /**不能出现重复的统一社会信用代码 草稿的也不行 */
    let dataBaseInfo = await enterpriseData.findEnterpriseByUscc(param.uscc);
    if ( dataBaseInfo && dataBaseInfo.uscc)  throw new BizError(ERRORENUM.该企业已存在, `${param.uscc}已经在库中存在`);

    /**添加新注册企业标识 */
    param.isCreate = true;//标识此次操作是否是迁入企业并不是新注册企业
    param.state = configEnum.FUHUASTATE.实体孵化;

    if (param.jiaSu == 1 || param.jiaSu == 2) {
        //判断
        if (param.jiaSu == 1 && !param.jiaSuZiZhi) {
            throw new BizError(ERRORENUM.参数错误, "加速企业缺失加速资质");
         } else if (param.jiaSu == 1 && param.jiaSuZiZhi.indexOf(configEnum.JIASUZIZHI.其他) > -1  && !param.jiaSuZiZhiDesc) {
            throw new BizError(ERRORENUM.参数错误, "加速企业的加速资质选了其他但是没填写内容");
        }
    } else throw new BizError(ERRORENUM.参数错误, "加速企业不符合1或2", param.jiaSu);

    param.jiaSu = param.jiaSu == 1;
    
    await enterpriseData.replenishEnterpriseData(fuHuaQiUscc, param);

    addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.我的企业_补录企业, param.uscc, '新注册' );

    /**企业状态改变埋点 */
    let xn = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.虚拟孵化, draftLock:true}) || 0; //虚拟孵化 
    let st = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.实体孵化, draftLock:true}) || 0; //实体孵化
    let qc = await enterpriseData.findEnterpriseCount({fuHuaQiUscc, state:configEnum.FUHUASTATE.迁出, draftLock:true}) || 0; //迁出孵化 
    addFuHuaQiPoint(fuHuaQiUscc, FUHUAQINODEENUM.企业状态变化, {xn, st, qc});

    /**标签 */
    let fuHuaQiInfo = await findFuHuaQiByUSCC(fuHuaQiUscc);
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(param.uscc);
    await enterpriseLabelEvent(enterpriseInfo, LABELEVENT.入孵, fuHuaQiInfo.operationName);

    //2025新加内容
        let leaseInfo = await leaseData.findOnceData({uscc:param.uscc});
        if (leaseInfo && leaseInfo.uscc) { //
            leaseInfo.enterpriseName = param.name;
            leaseInfo.contractStartTime = param.contractStartTime;
            leaseInfo.contractEndTime = param.contractEndTime;
            leaseInfo.price = param.price;//单价
            leaseInfo.area = param.leasedArea;//租赁面积
            leaseInfo.address = param.leaseAddress;
            leaseInfo.areaUnit = param.areaUnit;
            leaseInfo.rentPayment = [
                {
                   payStartTime:param.payStartTime,
                   payLong:param.payLong
                }
            ];
            await leaseInfo.save();
        } else {
            let addLease = {
                uscc:param.uscc,
                enterpriseName:param.name,
                contractStartTime:param.contractStartTime,
                contractEndTime:param.contractEndTime,
                price:param.price,//单价
                area:param.leasedArea,//租赁面积
                areaUnit : param.areaUnit,
                rentPayment : [
                    {
                    payStartTime:param.payStartTime,
                    payLong:param.payLong
                    }
                ],
                address:param.leaseAddress,//地址
    
            };
            await leaseData.createData(addLease);
        }

    return {isSuccess:true};
}


/**
 * 我的企业入口查看企业资质
 * @param uscc 企业统一信用代码
 */
export async function getMyEnterpriseQualification(uscc:string) {
    let dataBaseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    let qualificationParam = {
        isHighTech:false,
        highTechMs:0,//高新技术
        isZjtx:false,
        zjtxMs:0,//专精特新
        isXjrpy:false,
        xjrpyMs:0,//小巨人培育
        isXjr:false,
        xjrMs:0,//小巨人
        isBeOnTheMarket:false,//是否上市
        beOnTheMarket:[],
    };

    let qualification = dataBaseInfo.qualification;
    if (qualification) {
        if (qualification.isHighTech) {
            qualificationParam.isHighTech = true;
            qualificationParam.highTechMs = qualification.highTechMs;
        }
        if (qualification.isZjtx) {
            qualificationParam.isZjtx = true;
            qualificationParam.zjtxMs = qualification.zjtxMs;
        }
        if (qualification.isXjrpy) {
            qualificationParam.isXjrpy = true;
            qualificationParam.xjrpyMs = qualification.xjrpyMs;
        }
        if (qualification.isXjr) {
            qualificationParam.isXjr = true;
            qualificationParam.xjrMs = qualification.xjrMs;
        }
        if (qualification.isBeOnTheMarket) {
            qualificationParam.isBeOnTheMarket = true;
            qualificationParam.beOnTheMarket =  qualification.beOnTheMarket;
        }
    }


    let intellectualPropertyParam = {
        alienPatent:0,
        classIPatent:0,
        secondClassPatent:0,
    };
    let intellectualProperty = dataBaseInfo.intellectualProperty;
    if (intellectualProperty) {
        intellectualPropertyParam.alienPatent = intellectualProperty.alienPatent;//海外专利
        intellectualPropertyParam.classIPatent = intellectualProperty.classIPatent;//一类专利
        intellectualPropertyParam.secondClassPatent = intellectualProperty.secondClassPatent;//二类专利
    }

    
    return { qualificationParam, intellectualPropertyParam };
}



/**
 * 修改企业资质
 * @param uscc 企业统一信用代码
 * @returns 
 */
export async function updateQualification(uscc:string, intellectualPropertyParam, qualificationParam) {
    eccFormParam("修改企业资质", eccFormParamConfig.MyEnterpriseQualificationUpdateConfig, qualificationParam);

    if (qualificationParam.isBeOnTheMarket) {
        if (!qualificationParam.beOnTheMarket.length) throw new BizError(ERRORENUM.参数错误, '修改企业资质', '缺失 beOnTheMarket  ')
        verificationEnumTools.eccEnumValue("修改企业资质", "beOnTheMarket", configEnum.LISTINGSITUATION, qualificationParam.beOnTheMarket );
    } else qualificationParam.beOnTheMarket = [];

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    /**埋点 */
    let oldQualification = enterpriseInfo.qualification || {};

    let oldHighTechData = {highTechMs:oldQualification.highTechMs, isHighTech:oldQualification.isHighTech};
    let newHighTechData = {highTechMs:qualificationParam.highTechMs, isHighTech:qualificationParam.isHighTech};
    addEnterprisePoint( uscc, ENTERPRISENODEENUM.企业资质_高新技术,oldHighTechData, newHighTechData );

    let oldIsZjtxData = {isZjtx:oldQualification.isZjtx, zjtxMs:oldQualification.zjtxMs};
    let newIsZjtxData = {isZjtx:qualificationParam.isZjtx, zjtxMs:qualificationParam.zjtxMs};
    addEnterprisePoint( uscc, ENTERPRISENODEENUM.企业资质_专精特新,oldIsZjtxData, newIsZjtxData );

    let oldIsXjrpyData = {isXjrpy:oldQualification.isXjrpy, xjrpyMs:oldQualification.xjrpyMs};
    let newIsXjrpyData = {isXjrpy:qualificationParam.isXjrpy, xjrpyMs:qualificationParam.xjrpyMs};
    addEnterprisePoint( uscc, ENTERPRISENODEENUM.企业资质_小巨人培育,oldIsXjrpyData, newIsXjrpyData );

    let oldIsXjrData = {isXjr:oldQualification.isXjr, xjrMs:oldQualification.xjrMs};
    let newIsXjrData = {isXjr:qualificationParam.isXjr, xjrMs:qualificationParam.xjrMs};
    addEnterprisePoint( uscc, ENTERPRISENODEENUM.企业资质_小巨人,oldIsXjrData, newIsXjrData );

    let oldMarketData = {
        beOnTheMarket:oldQualification.beOnTheMarket ? JSON.stringify(oldQualification.beOnTheMarket) : '[]', 
        isBeOnTheMarket:oldQualification.isBeOnTheMarket
    };
    let newMarketData = {
        beOnTheMarket:qualificationParam.beOnTheMarket ? JSON.stringify(qualificationParam.beOnTheMarket) : '[]', 
        isBeOnTheMarket:qualificationParam.isBeOnTheMarket
    };
    addEnterprisePoint(uscc, ENTERPRISENODEENUM.企业资质_上市情况,oldMarketData, newMarketData );
    
    enterpriseInfo.qualification = JSON.parse(JSON.stringify(qualificationParam) );

    /**标签 */
    await enterpriseLabelEvent(enterpriseInfo, LABELEVENT.资质更新, '企业登记');

    eccFormParam("修改企业资质", eccFormParamConfig.MyEnterpriseIntellectualPropertyUpdateConfig, intellectualPropertyParam);

    if (enterpriseInfo.alienPatent != intellectualPropertyParam.alienPatent) {
        addEnterprisePoint( uscc, ENTERPRISENODEENUM.知识产权_海外专利, enterpriseInfo.alienPatent || 0, intellectualPropertyParam.alienPatent);
    } 
    if (enterpriseInfo.classIPatent != intellectualPropertyParam.classIPatent) {
        addEnterprisePoint( uscc, ENTERPRISENODEENUM.知识产权_一类专利, enterpriseInfo.classIPatent || 0, intellectualPropertyParam.classIPatent);
    } 
    if (enterpriseInfo.secondClassPatent != intellectualPropertyParam.secondClassPatent) {
        addEnterprisePoint( uscc, ENTERPRISENODEENUM.知识产权_二类专利, enterpriseInfo.secondClassPatent || 0, intellectualPropertyParam.secondClassPatent);
    }
    
    enterpriseInfo.intellectualProperty = {
        alienPatent:intellectualPropertyParam.alienPatent, 
        classIPatent:intellectualPropertyParam.classIPatent, 
        secondClassPatent:intellectualPropertyParam.secondClassPatent
    };
        
    await enterpriseInfo.save();
    
    return {isSuccess:true};
}

/**
 * 我的企业入口查看企业团队信息
 * 这里使用和 /enterprise/team/info 接口一样的逻辑
 * @param uscc 企业统一信用代码
 */
export async function getMyEnterpriseTeamInfo(uscc:string, declarationYear, declarationQuarter) {

    let teamInfo = await findTeamByUsccAndTime(uscc, declarationYear, declarationQuarter);
    // let teamInfo = await findEnterpriseNewTeamData(uscc);
    if (!teamInfo || !teamInfo.year) {
        teamInfo = { 
            doctor:0, master:0, undergraduate:0, juniorCollege:0,
            other:0, studyAbroad:0, graduates:0,
        }
    }

    let result:any = extractData(EnterpriseTeamConfig, teamInfo, false);

    result.count = result.doctor +result.master +result.undergraduate +result.juniorCollege +result.other;

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);


    result.cycsrbj = enterpriseInfo.cycsrbj;

    return result;
}

export async function updateMyEnterpriseTeamInfo(uscc:string, quarter, year, cycsrbj, param) {

    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);

    eccFormParam("孵化器修改团队信息", eccFormParamConfig.FuHuaQiReplenishEnterpriseTeamDataConfig, param);

    let teamInfo = await findTeamByUsccAndTime(uscc, year, quarter);
    if (!teamInfo || !teamInfo.uscc) {
        //添加新的
        let addInfo = {
            uscc, 
            fuHuaQiUscc:enterpriseInfo.fuHuaQiUscc,
            name:enterpriseInfo.name,//企业名称
            year:year,
            quarter:quarter,
            doctor:param.doctor,
            master:param.master,
            undergraduate:param.undergraduate,
            juniorCollege:param.juniorCollege,
            other:param.other,
            studyAbroad:param.studyAbroad,
            graduates:param.graduates,
            createMs:new Date().valueOf(),
            isUpdate:true,
            isSubmit:true,
            fhqIsSubmit:true

        };
        await addTeamData(addInfo);
    } else {
        for (let key in param) {
            teamInfo[key] = param[key];
        }
        teamInfo.isUpdate = true;
        teamInfo.isSubmit = true;
        teamInfo.fhqIsSubmit = true;
        await teamInfo.save();
    }

    enterpriseInfo.cycsrbj = cycsrbj;
    await enterpriseInfo.save();

    return {isSuccess:true};
}




/**
 * 我的企业入口查看经济状况
 * @param uscc 
 */
export async function getMyEnterpriseBusinessData(uscc:string, yearMs:number) {
    let year = new Date(yearMs).getFullYear();
    /**找任务填报数据 */
    let thisYearData = await findBusinessDataByUsccAndYear(uscc, year);

    let checkKeyList = ["RD", "BI", "TXP"];
    let thisYearBusinessData = {};//结构 {"季度":{RD:0, BI:0, TXP:0} }
    for (let i= 1; i <= 4; i++) {
        thisYearBusinessData[i] = {RD:0, BI:0, TXP:0};
    }
    thisYearData.forEach(info => {
        let quarter = info.quarter;
        checkKeyList.forEach(key => {
            thisYearBusinessData[quarter][key] = info[key] || 0;
        });
    });
    
    /**找补录数据 */
    let thisYearRepleishData = await selectRepleishData(uscc, year);

    thisYearRepleishData.forEach(info => {
        let {quarter, type, value} = info;
        let key = "";
        switch(type) {
            case configEnum.BUSINESSDATATYPE.研发投入: key = "RD";
            case configEnum.BUSINESSDATATYPE.纳税: key = "TXP";
            case configEnum.BUSINESSDATATYPE.营业收入: key = "BI";
        } 
        if (thisYearBusinessData[quarter] && thisYearBusinessData[quarter][key] == 0 ) {
            thisYearBusinessData[quarter][key] = value;
        }
    });
    
    let result = {
        "RD":0,
        "TXP":0,
        "BI":0,
        quarterDataList:[]
    }; 

    for (let quarter in thisYearBusinessData) {
        let {RD, BI, TXP} = thisYearBusinessData[quarter];
        result.BI += BI;
        result.TXP += TXP;
        result.RD += RD;
        result.quarterDataList.push({quarter, RD, BI, TXP});
    }

    return result;
}

/**
 * 关注
 * @param uscc 
 */
export async function guanZhu(uscc:string) {
    let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterpriseInfo) throw new BizError(ERRORENUM.该企业不存在);

    

}


/**
 * 取消关注
 * @param uscc 
 */
export async function quXiaoGuanZhu(uscc:string) {

}