/**
 * 企业融资相关逻辑
 * 作者: 李欣鸣
 * 包括新融资信息的增删改查
 * 
 */
import { FinancingParamConfig, FinancingParamUpdateConfig } from "../../config/checkParamConfig";
import { ERRORENUM } from "../../config/errorEnum";
import { EnterpriseFinancingInfoConfig } from "../../config/ojbectResultKeyConfig";
import { createFinancing, deleteEnterpriseFinancing, findFinancingCount, findFinancingInfoByTaskIdAndSucc, findFinancingList } from "../../data/enterprise/financing";
import { FinancingListConfig } from "../../config/ojbectResultKeyConfig";
import { BizError } from "../../util/bizError";
import { checkChange, checkParamater, extractData, getTaskId } from "../../util/tools";
import { findEnterpriseInfoByName, findEnterpriseListByFuHuaQiUsccName } from "../../data/enterprise/enterprise";
import { findFuHuaQiByName } from "../../data/fuHuaQi/fuhuaqi";
import moment = require("moment");


/**
 * 添加企业融资信息
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单配置
 * @returns {isSuccess:true/false}
 */
export async function createFinancingInfo(uscc:string, param) {
    checkParamater("录入企业融资信息", FinancingParamConfig, param);

    /**校验企业是否存在 */
    let enterpriseInfo = await findEnterpriseInfoByName(param.name);
    if (!enterpriseInfo) throw new BizError(ERRORENUM.该企业不存在, uscc, param.name);

    param.uscc = enterpriseInfo.uscc;//前端无需传入企业的uscc  库中需要企业的uscc

    const TaskId = getTaskId(uscc);
    
    /**一个企业一个月只能填报一次融资信息 */
    let dataBaseInfo = await findFinancingInfoByTaskIdAndSucc(TaskId, param.uscc);
    if ( dataBaseInfo&& dataBaseInfo.uscc) throw new BizError(ERRORENUM.该企业当月数据已存在, `${param.uscc}的融资信息已经存在`);

    await createFinancing(uscc, TaskId, param);

    return {isSuccess:true};
}


/**
 * 更新企业融资信息
 * 小程序端
 * 只能更新本月未提交的并且已经创建的企业融资信息
 * @param uscc 孵化器统一信用代码
 * @param param 表单配置
 * @returns {isSuccess:true/false}
 */
export async function updateFinancingInfo(uscc:string, param) {
    checkParamater("更新融资企业信息", FinancingParamUpdateConfig, param);

    const TaskId = getTaskId(uscc);
    let dataBaseInfo = await findFinancingInfoByTaskIdAndSucc(TaskId, param.uscc);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${TaskId}的任务`);
   
    let changeList = checkChange(param, dataBaseInfo);
    if ( !changeList.length ) throw new BizError(ERRORENUM.数据无更新, `${param.uscc}数据无更新`);
    changeList.forEach(key => {
        dataBaseInfo[key] = param[key];
    });

    await dataBaseInfo.save();

    return {isSuccess:true};
}


/**
 * 查询本月提交的企业融资信息
 * 小程序端
 * @param fuHuaQiUscc 孵化器统一信用代码
 * @param uscc 企业统一信用代码
 * @returns {data:{}}  表单
 */
export async function getEnterpriseFinancingByUscc(fuHuaQiUscc:string, uscc:string) {
    const TaskId = getTaskId(fuHuaQiUscc);

    let dataBaseInfo = await findFinancingInfoByTaskIdAndSucc(TaskId, uscc);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${uscc}这个企业的本次融资数据`);

    let data = extractData(EnterpriseFinancingInfoConfig, dataBaseInfo);

    return {data};
}


/**
 * 根据企业id删除草稿企业
 * 小程序端
 * @param fuHuaQiUscc 孵化器统一信用代码
 * @param uscc 企业统一信用代码
 * @returns {isSuccess:true/false}
 */
export async function deleteEnterpriseFinancingByUscc(fuHuaQiUscc:string, uscc:string) {
    const TaskId = getTaskId(fuHuaQiUscc);

    let dataBaseInfo = await findFinancingInfoByTaskIdAndSucc(TaskId, uscc);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${uscc}这个企业`);

    if (dataBaseInfo.draftLock) throw new BizError(ERRORENUM.已入库的数据不能删除, uscc);

    await deleteEnterpriseFinancing(uscc, TaskId);

    return {isSuccess:true};
}


/**
 * 获取本孵化器下的所有企业信息
 * 小程序端  用于下拉框使用
 * @param uscc 孵化器统一信用代码
 * @returns []  name:企业名称, logonAdd:注册地址, operatingAdd:经营地址
 */
export async function getFuHuaQiEnterpriseForSelect(uscc:string) {
    let enterpriseList = await findEnterpriseListByFuHuaQiUsccName(uscc);

    let dataList = [];
    enterpriseList.forEach( info => {
        dataList.push({
            name:info.name,
            logonAdd:info.logonAdd, 
            operatingAdd:info.operatingAdd
        });
    });
    
    return dataList;
}


/**
 * 融资企业信息列表
 * 管理后台端
 * @param monthData 数据月份 目前数据库没有该字段
 * @param fuHuaQiName 所属孵化器 
 * @param industry 行业领域
 * @param fuHuaQiInvestment 孵化器是否参与投资
 * @param page 页数 
 * @returns 
 */
export async function financingList(monthData:string, fuHuaQiName:string, industry, fuHuaQiInvestment:number, page:number) { 

    let fuHuaQiUscc = "";
    if (fuHuaQiName.length > 0) {
        let fuHuaQiInfo = await findFuHuaQiByName(fuHuaQiName);
        if(fuHuaQiInfo) fuHuaQiUscc = fuHuaQiInfo.uscc;
    }

    let selectParam:any = {};
    if ( monthData.length > 0 ) {
        let startT = moment(monthData).startOf('month').valueOf();
        let endT = moment(monthData).endOf('month').valueOf();
        selectParam.createTime = {'$gt':startT, '$lt':endT};
    }
    if (industry.length >0 ) selectParam.industry = industry;
    if (fuHuaQiUscc.length > 0) selectParam.fuHuaQiUscc = fuHuaQiUscc;
    if (fuHuaQiInvestment == 2 || fuHuaQiInvestment == 3) {
        selectParam.fuHuaQiInvestment = fuHuaQiInvestment == 2 ? true : false;
    }
        

    let dataBaseList = await findFinancingList(selectParam, (page-1)*10 );
    let count = await findFinancingCount(selectParam);
    let dataList = [];
    dataBaseList.forEach( info => {
        let changeData = extractData(FinancingListConfig, info);
        dataList.push(changeData);
    });

    return {count, dataList};
}