/**
 * 小程序端 孵化器入口 孵化器基础数据相关逻辑
 * 作者: lxm
 * 孵化器相关逻辑 包括孵化器的增删改查
 * 
 */
import * as eccFormParamConfig from "../../../config/eccParam/fuHuaQi";
import { findEnterpriseCount, findEnterpriseCountByFuHuaQiUscc, findEnterpriseTotalByFuHuaQiUscc } 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, eccReqParamater } from "../../../util/verificationParam";
import { changeEnumValue, eccEnumValue } from "../../../util/verificationEnum";
import * as scoreBiz from "./score";
import { addPoint } from "../../point";
import { FUHUAQINODEENUM, OPERATETYPEENUM, POINTTYPEENUM } from "../../../config/pointConfig";



/**
 * 主界面基础数据
 * 小程序端  首页的基础数据
 * @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;

    data.fuHuaEnterpriseTotal = dataBaseInfo.fuHuaEnterpriseTotal ? dataBaseInfo.fuHuaEnterpriseTotal : 0;
    data.fuHuaEnterpriseTotal += await findEnterpriseTotalByFuHuaQiUscc(uscc);

    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);
        });
    }
    if (param.isProfessionalTechnology) {
        if ( !param.professionalTechnologyName ) throw new BizError(ERRORENUM.参数错误, "修改孵化器=>我的数据信息", "缺少professionalTechnologyName" );
        if (!param.professionalTechnologyCreateTime ) throw new BizError(ERRORENUM.参数错误, "修改孵化器=>我的数据信息", "professionalTechnologyCreateTime" );
        if (!param.professionalTechnologyAmount) throw new BizError(ERRORENUM.参数错误, "修改孵化器=>我的数据信息", "professionalTechnologyAmount" );
    }
    /**
     * 校验 专业技术平台 参数   
     * 专业技术平台在3.1时候被单独成一个功能了
     */
    // if (param.isProfessionalTechnology) {
    //     const ProfessionalTechnologyConf = {
    //         professionalTechnologyName:"String",
    //         professionalTechnologyCreateTime:"Number",
    //         professionalTechnologyAmount:"Number",
    //     };
    //     const CheckProfessionalTechnologyConf = {
    //         professionalTechnologyName:param.professionalTechnologyName,
    //         professionalTechnologyCreateTime:param.professionalTechnologyCreateTime,
    //         professionalTechnologyAmount:param.professionalTechnologyAmount,
    //     };
    //     eccReqParamater(ProfessionalTechnologyConf, CheckProfessionalTechnologyConf);
    // } else {
    //     param.professionalTechnologyName = "";
    //     param.professionalTechnologyCreateTime = 0;
    //     param.professionalTechnologyAmount = 0;
    // }
    //校验是否与第三方机构合作
    if (param.isCooperation) {
        eccReqParamater({cooperationInstitutions:"String"}, {cooperationInstitutions:param.cooperationInstitutions});
    }else {
        param.cooperationInstitutions = "";
    }

    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;
        
        switch (key) {
            case "acreageTotal": 
                if (param[key] != baseDataInfo[key]) {
                    addPoint(POINTTYPEENUM.孵化器, uscc, FUHUAQINODEENUM.我的数据_总面积, baseDataInfo[key], param[key] );
                }
            break;
            case "acreagePersonalUse": 
                if (param[key] != baseDataInfo[key]) {
                    addPoint(POINTTYPEENUM.孵化器, uscc, FUHUAQINODEENUM.我的数据_自用面积, baseDataInfo[key], param[key] );
                }
            break;
            case "incubatedAcreage": 
                if (param[key] != baseDataInfo[key]) {
                    addPoint(POINTTYPEENUM.孵化器, uscc, FUHUAQINODEENUM.我的数据_在孵面积, baseDataInfo[key], param[key]);
                }
            break;
        }
       

        baseDataInfo[key] = param[key];


    }
    baseDataInfo["hatchingGround"] = param.hatchingGround;
    if (JSON.stringify(param['hatchingGround'] || []) != JSON.stringify(baseDataInfo['hatchingGround'] || [])) {
        addPoint(POINTTYPEENUM.孵化器, uscc, FUHUAQINODEENUM.我的数据_经备案孵化场地, 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.lv);
    if (param.industry) eccEnumValue("更新孵化器机构信息数据", " 领域 ", configEnum.FUHUAINDUSTRY, param.industry);
    if (param.institutionalNature) eccEnumValue("更新孵化器机构信息数据", " 机构性质 ", configEnum.INSTITUTIONALNATURE, param.institutionalNature);
    if (param.operationModel && param.operationModel.length) eccEnumValue("更新孵化器机构信息数据", " 运营模式 ", configEnum.OPERATIONMODEL, param.operationModel);
    //限制企业简介长度
    if (param.introduction) {
        if (param.introduction.length > 200) throw new BizError(ERRORENUM.字数超过200限制, "更新孵化器机构信息数据 孵化器简介");
    }
    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};
}

