/**
 * 孵化器经营数据填报
 * 
 */
import { FuHuaQiBusinessDataConfig } from "../../../config/eccFormParamConfig";
import { ERRORENUM } from "../../../config/errorEnum";
import { FuHuaQiBusinessDataInfoConfig } from "../../../config/splitResultConfig";
import { findBusinessByTaskId } from "../../../data/fuHuaQi/quarterTask/businessData";
import * as sysTools from "../../../tools/system";
import { BizError } from "../../../util/bizError";
import { extractData } from "../../../util/piecemeal";
import { eccFormParam } from "../../../util/verificationParam";


/**
 * 新添加孵化器经营数据填报
 * 小程序端
 * 逻辑是 将填报编辑状态修改为true 当库里=true时
 * @param uscc 孵化器的统一信用代码
 * @param param 
 * @returns {isSuccess:true/false}
 */
export async function createBusiness(uscc:string, param) {
    const TaskId = sysTools.getQuarterTaskId(uscc);
    eccFormParam("新添加孵化器季度填报", FuHuaQiBusinessDataConfig, param);

    let businessInfo = await findBusinessByTaskId(TaskId);
    /**不可以重复创建 */
    if ( businessInfo.isUpdate ) throw new BizError(ERRORENUM.该孵化器经营数据填报已存在, `孵化器 ${uscc}重复提交了经营数据`);

    /**更新状态和数据 */
    businessInfo.isUpdate = true;

    for (let key in param) {
        businessInfo[key] = param[key];
    }

    await businessInfo.save();
    
    return {isSuccess:true};
}


export async function deleteBusiness(uscc:string) {
    const TaskId = sysTools.getQuarterTaskId(uscc);

    let businessInfo = await findBusinessByTaskId(TaskId);
    /**删除校验 */
    if ( !businessInfo.isUpdate ) throw new BizError(ERRORENUM.未填报数据不能删除, `孵化器 ${uscc}删除经营数据时经营数据不存在`);
    if ( businessInfo.draftLock ) throw new BizError(ERRORENUM.已提交的数据不能进行操作, `孵化器 ${uscc}尝试 删除 已经提交的经营数据`);

    /**更新状态和数据 */
    businessInfo.isUpdate = false;

    for (let key in FuHuaQiBusinessDataConfig) {
        businessInfo[key] = 0;
    }

    await businessInfo.save();
    
    return {isSuccess:true};
}


export async function selectBusiness(uscc:string) {
    const TaskId = sysTools.getQuarterTaskId(uscc);

    let businessInfo = await findBusinessByTaskId(TaskId);
    /**不可以重复创建 */
    if ( !businessInfo.isUpdate ) throw new BizError(ERRORENUM.请先填报数据, `孵化器 ${uscc}调用回显接口时经营数据不存在`);
    if ( businessInfo.draftLock ) throw new BizError(ERRORENUM.已提交的数据不能进行操作, `孵化器 ${uscc}尝试 回显 已经提交的经营数据`);

    let businessData = extractData(FuHuaQiBusinessDataInfoConfig, businessInfo, false)

    return {businessData};
}



export async function updateBusiness(uscc:string, param) {
    const TaskId = sysTools.getQuarterTaskId(uscc);
    eccFormParam("修改孵化器季度填报", FuHuaQiBusinessDataConfig, param);

    let businessInfo = await findBusinessByTaskId(TaskId);
    /**不可以重复创建 */
    if ( !businessInfo.isUpdate ) throw new BizError(ERRORENUM.请先填报数据, `孵化器 ${uscc}调用修改接口时经营数据不存在`);
    if ( businessInfo.draftLock ) throw new BizError(ERRORENUM.已提交的数据不能进行操作, `孵化器 ${uscc}尝试 修改 已经提交的经营数据`);

    /**更新状态和数据 */

    for (let key in param) {
        businessInfo[key] = param[key];
    }

    await businessInfo.save();
    
    return {isSuccess:true};
}