/**
 * 孵化器基础数据相关逻辑
 * 作者: 李欣鸣
 * 孵化器相关逻辑 包括孵化器的增删改查
 * 
 */
import * as eccFormParamConfig from "../../../config/eccFormParamConfig";
import { findEnterpriseCount, findEnterpriseCountByFuHuaQiUscc, groupFindEnterpriseCount } from "../../../data/enterprise/enterprise";
import * as fuhuaqiData from "../../../data/fuHuaQi/fuhuaqi";
import * as splitResultConfig from "../../../config/splitResultConfig";
import * as configEnum from "../../../config/enum";
import { checkChange, extractData } from "../../../util/piecemeal";
import { BizError } from "../../../util/bizError";
import { ERRORENUM } from "../../../config/errorEnum";
import { eccFormParam } from "../../../util/verificationParam";
import { changeEnumValue, eccEnumValue } from "../../../util/verificationEnum";
import * as scoreBiz from "./score";


/**
 * 主界面基础数据
 * 小程序端  首页的基础数据
 * 评分数据还没有
 * @param uscc 孵化器统一信用代码
 * @returns {} "incubatedAcreage", "acreageTotal", "acreagePersonalUse", "name", "lv", "institutionalNature"
 */
export async function homeData(uscc:string) {
    /** 这里中间件已经验证过uscc的可靠性了，不需要做多余的验证*/
    let dataBaseInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);

    /**根据配置截取返回的字段 */
    let data:any = extractData(splitResultConfig.FuHuaQiHomeDataConfig, dataBaseInfo, false);
    data.enterpriseCount  = await findEnterpriseCountByFuHuaQiUscc(uscc) || 0;
    data.lv = changeEnumValue(configEnum.FUHUAQILV, dataBaseInfo.lv);
    data.institutionalNature = changeEnumValue(configEnum.INSTITUTIONALNATURE, dataBaseInfo.institutionalNature);
    /**截取小数位 */
    data.incubatedAcreage = parseInt(data.incubatedAcreage);
    data.acreageTotal = parseInt(data.acreageTotal);
    data.acreagePersonalUse = parseInt(data.acreagePersonalUse);

    return data;
}


/**
 * 孵化器详细数据
 * 小程序端  点击我的数据之后拉取的详细数据
 * @param uscc 孵化器统一信用代码
 * @returns data 基础数据字段
 */
export async function selectFuHuaQiBaseData(uscc:string) {
    /** 这里中间件已经验证过uscc的可靠性了，不需要做多余的验证*/
    let dataBaseInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    /** 虚拟 */
    let virtualEnterpriseNum = await findEnterpriseCount({fuHuaQiUscc:uscc, state:configEnum.FUHUASTATE.虚拟孵化, draftLock:true}) || 0;
    /**截取返回 */
    let data:any = extractData(splitResultConfig.FuHuaQiBaseDataConfig, dataBaseInfo, false);
    data.enterpriseTotal =  await findEnterpriseCountByFuHuaQiUscc(uscc); //企业总数
    data.numOfEntities = data.enterpriseTotal - virtualEnterpriseNum; //实体企业总数 = 虚拟企业总数 - 虚拟企业数量
    data.numOfEntities = data.numOfEntities > 0 ? data.numOfEntities : 0;
    data.virtualEnterpriseNum = virtualEnterpriseNum;

    return data;
}


/**
 * 孵化器机构信息数据数据
 * 小程序端  点击机构信息之后拉取的详细数据
 * @param uscc 孵化器统一信用代码
 * @returns data 基础数据字段
 */
export async function selectOrganizationInfo(uscc:string) {
    /** 这里中间件已经验证过uscc的可靠性了，不需要做多余的验证*/
    let dataBaseInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    
    /** 根据配置截取返回 */
    let data:any = extractData(splitResultConfig.OrganizationBaseDataConfig, dataBaseInfo, false);

    return data;
}


/**
 * 修改孵化器中我的数据信息
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单内容
 * @returns {isSuccess:true/false};
 */
export async function updateFuHuaQiBaseData(uscc:string, param) {
    /**表单校验 */
    eccFormParam("更新孵化器基础数据", eccFormParamConfig.BaseParamUpdateConfig, param);
    if (param.hatchingGround && param.hatchingGround.length) {
        param.hatchingGround.forEach(hatchingGroundInfo => {
            eccFormParam("更新孵化器基础数据 经备案孵化场地", eccFormParamConfig.BaseParamUpdateHatchingGroundConfig, hatchingGroundInfo);
        });
    }

    let baseDataInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    /**这里无法判断数组里面的内容是否有变化 所以 hatchingGround 直接赋值  */
    let changeList = checkChange(param, baseDataInfo);
    for (let i = 0; i < changeList.length; i++) {
        let key = changeList[i];
        if (key == "virtualEnterpriseNum") continue;
        baseDataInfo[key] = param[key];
    }
    baseDataInfo["hatchingGround"] = param.hatchingGround;

    await baseDataInfo.save();

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

    return {isSuccess:true};
}


/**
 * 更新孵化器机构信息数据  （我的信息）
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单内容
 * @returns {isSuccess:true/false};
 */
export async function updateOrganizationData(uscc:string, param) {
    /**校验表单内容 */
    eccFormParam("更新孵化器机构信息数据",  eccFormParamConfig.OrganizationParamUpdateConfig, param);
    if (param.foundingTeamType && param.foundingTeamType != configEnum.TEAM.无) {
        param.foundingTeam.forEach((subInfo, subIndex) => {
            eccFormParam(`更新孵化器机构信息数据 创始团队 ${subIndex}`,  eccFormParamConfig.OrganizationParamFoundingTeamUpdateConfig, subInfo);
            eccEnumValue(`更新孵化器机构信息数据 创始团队 ${subIndex}`, "团队类型", configEnum.TEAM, subInfo.type);
        }); 
    } else param.foundingTeam = [];
    if (param.operationModel && param.operationModel.length && param.operationModel.indexOf(configEnum.OPERATIONMODEL.其他) > 0 ) {
        if (!param.operationModelDes) throw new BizError(ERRORENUM.表单校验失败, `缺失运营模式描述`);
    }
    /**校验是否符合枚举范围 */
    if (param.lv) eccEnumValue("更新孵化器机构信息数据", " 孵化器级别 ", configEnum.FUHUAQILV, param.fuHuaQiInvestmentStyle);
    if (param.industry) eccEnumValue("更新孵化器机构信息数据", " 领域 ", configEnum.FUHUAINDUSTRY, param.fuHuaQiInvestmentStyle);
    if (param.institutionalNature) eccEnumValue("更新孵化器机构信息数据", " 机构性质 ", configEnum.INSTITUTIONALNATURE, param.fuHuaQiInvestmentStyle);
    if (param.operationModel && param.operationModel.length) eccEnumValue("更新孵化器机构信息数据", " 运营模式 ", configEnum.OPERATIONMODEL, param.fuHuaQiInvestmentStyle);
    
    let baseDataInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    
    /**赋值内容  */
    let changeList = checkChange(param, baseDataInfo);
    for (let i = 0; i < changeList.length; i++) {
        let key = changeList[i];
        if (key == "operationName" || key == "uscc") continue;
        
        baseDataInfo[key] = param[key];
    }
    /**这里无法判断数组里面的内容是否有变化 所以 foundingTeam 直接赋值 */
    baseDataInfo["foundingTeam"] = param.foundingTeam;

    await baseDataInfo.save();

    /**更新分数 */
    await scoreBiz.updateScore(uscc, configEnum.SCOREWAYS.我的信息, false);

    return {isSuccess:true};
}



