/**
 * 企业融资
 */
import moment = require("moment");
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { operationalData, selectData } from "../data/operationalData";
import { EnterpriseAwardUpdateConfig, EnterpriseFinancingUpdateConfig, EnterpriseManageInfoAddConfig, EnterpriseManageInfoUpdateConfig } from "../config/eccParam/enterprise";
import { eccFormParam } from "../util/verificationParam";
import { getMySqlMs, randomId } from "../tools/system";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/enum/errorEnum";
import * as enumConfig from "../config/enum/enum";
import { changeEnumValue } from "../util/verificationEnum";


//===============================================企业融资

/**
 * 企业融资-列表
 * 回显
 * @param uscc 
 */
export async function enterpriseFinancingInfo(eId) { 
    let filesList = ["rId",  "financingAmount", "financingRounds", "fuHuaQiInvestment", "fuHuaQiInvestmentStyle", "fuHuaQiInvestmentAmount", "investmentDate", "investmentInstitutionsName", "valuation"];
    
    let iprList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业融资, {eId}, filesList);

    let dataList:any[] = [];
    iprList.forEach(item => {
        let {
            rId, 
            financingAmount, 
            financingRounds, 
            fuHuaQiInvestment, 
            fuHuaQiInvestmentStyle, 
            fuHuaQiInvestmentAmount, 
            investmentDate, 
            investmentInstitutionsName, 
            valuation
        } = item;

        let info:any = {
            rId, financingAmount:parseFloat(financingAmount), financingRounds, fuHuaQiInvestment,
            investmentDate:new Date(investmentDate).valueOf(), investmentInstitutionsName, valuation
        };

        if (fuHuaQiInvestment == enumConfig.STATE.是) {
            info.fuHuaQiInvestmentStyle = fuHuaQiInvestmentStyle;
            info.fuHuaQiInvestmentAmount = parseFloat(fuHuaQiInvestmentAmount);
        }

        dataList.push(info);
    });

    dataList.sort((a, b) => {
        return new Date(b.investmentDate).valueOf() - new Date(a.investmentDate).valueOf();
    })

    return {dataList};
}


/**
 * 企业融资-修改
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterpriseFinancingInfo(eId, rId, param) {
    const FuncName = "企业修改融资信息"
    eccFormParam(FuncName, EnterpriseFinancingUpdateConfig, param );

    if (param.fuHuaQiInvestment == enumConfig.STATE.是) {
        if (!param.fuHuaQiInvestmentStyle || !param.fuHuaQiInvestmentAmount) throw new BizError(ERRORENUM.参数错误);
    } else {
        param.fuHuaQiInvestmentStyle = 0;
        param.fuHuaQiInvestmentAmount = 0;
    }
    let filesList = [ "rId", "financingAmount", "financingRounds", "fuHuaQiInvestment", "fuHuaQiInvestmentStyle", "fuHuaQiInvestmentAmount", "investmentDate", "investmentInstitutionsName", "valuation"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业融资, {rId, eId}, filesList)
    if (!iprInfo || !iprInfo.rId) throw new BizError(ERRORENUM.当前数据不存在); 
  
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业融资, param, {rId, eId});
    
    return {isSuccess:true};
}


/**
 * 企业融资-添加
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function createEnterpriseFinancingInfo(eId, param) {
    const FuncName = "企业修改参保信息"
    eccFormParam(FuncName, EnterpriseFinancingUpdateConfig, param );

   
    let addInfo:any = {
        rId:randomId(TABLEID.企业融资),
        eId,
        financingAmount:param.financingAmount,
        financingRounds:param.financingRounds,
        investmentDate:getMySqlMs(param.investmentDate),
        investmentInstitutionsName:param.investmentInstitutionsName,
        valuation:param.valuation,
    };
    addInfo.fuHuaQiInvestment = param.fuHuaQiInvestment;
    if (param.fuHuaQiInvestment == enumConfig.STATE.是) {
        if (!param.fuHuaQiInvestmentStyle || !param.fuHuaQiInvestmentAmount) throw new BizError(ERRORENUM.参数错误);
        addInfo.fuHuaQiInvestmentStyle = param.fuHuaQiInvestmentStyle;
        addInfo.fuHuaQiInvestmentAmount = param.fuHuaQiInvestmentAmount;
    } else {
        param.fuHuaQiInvestmentStyle = "[]";
        param.fuHuaQiInvestmentAmount = 0;
    }
      

    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业融资, addInfo, {});
    
    return {isSuccess:true};
}


/**
 * 企业融资-删除
 * @param param0 
 * @returns 
 */
export async function deleteEnterpriseFinancingInfo(eId, rId) {
    let filesList = ["rId",  "financingAmount", "financingRounds", "fuHuaQiInvestment", "fuHuaQiInvestmentStyle", "fuHuaQiInvestmentAmount", "investmentDate", "investmentInstitutionsName", "valuation"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业融资, {rId, eId}, filesList)
    if (!iprInfo || !iprInfo.rId) throw new BizError(ERRORENUM.当前数据不存在);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业融资, {}, {rId, eId});
    
    return {isSuccess:true};
}


//========================================================企业经营
export async function enterpriseManageInfo(eId, mId) {
    let filesList = [ "mId", "annual", "quarter",  "BI", "TXP", "RD"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {eId, mId}, filesList);
    if (!resInfo || !resInfo.mId) {
        throw new BizError(ERRORENUM.数据不存在);
    }

    let dataInfo = {
        mId:resInfo.mId,
        annual:moment(resInfo.annual).format("YYYY"),//年度
        quarter: changeEnumValue(enumConfig.QUARTER, resInfo.quarter),//季度
        BI:parseFloat(resInfo.BI),
        TXP:parseFloat(resInfo.TXP),
        RD:parseFloat(resInfo.RD)
    }

    return {dataInfo};
}


/**
 * 企业经营-添加季度
 */
// 季度配置数组
let quarterConf = ["第一季度", "第二季度", "第三季度", "第四季度"];

/**
 * 辅助函数：将年度和季度字符串转换为年份和季度序号
 * @param annual "2025第一季度"
 * @returns 
 */
function getYearAndQuarter(annual: string) {
    let year = annual.slice(0, 4);
    let annualquarter = annual.slice(4);
    let quarter = 0;
    quarterConf.forEach((item, index) => {
        if (annualquarter === item) {
            quarter = index + 1;
        }
    });
    return { year, quarter };
}


/**
 * 营收数据添加
 * @param eId 
 * @param mId 
 * @param param 
 * @returns 
 */
export async function updateEnterpriseManageInfo(eId, mId, param) {
    const FuncName = "企业修改企业营收记录"
    eccFormParam(FuncName, EnterpriseManageInfoUpdateConfig, param );
    
    //获取年份和季度
    // const { year, quarter} = getYearAndQuarter(param.annual);

    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {eId, mId}, ["annual", "quarter", "mId"]);
    if (!resInfo || !resInfo.mId) throw new BizError(ERRORENUM.数据不存在);

    // 查询是否存在同一年度同季度的数据
    // let disParam ={ eId, annual: getMySqlMs(`${resInfo.annual}-01-01 00:00:00`), quarter:resInfo.quarter };
    // let disInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, disParam, ["eId", "mId"]);
    // if (disInfo && disInfo.eId && disInfo.mId != mId) throw new BizError(ERRORENUM.不可重复添加同一年度数据);

    let dataInfo = {
        createTime:getMySqlMs(),
        // annual:getMySqlMs(`${resInfo.annual}-01-01 00:00:00`),
        // quarter:resInfo.quarter,//季度
        BI:param.BI,
        TXP:param.TXP,
        RD:param.RD,
        isUpdate:enumConfig.STATE.是
    }

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业经营信息, dataInfo, {eId, mId});

    return {dataInfo};
}


export async function createEnterpriseManageInfo(eId, param) {
    const FuncName = "企业添加企业营收记录"
    eccFormParam(FuncName, EnterpriseManageInfoAddConfig, param );

    // let annual = getMySqlMs(param.year);
    // 获取年份和季度
    const { year, quarter } = getYearAndQuarter(param.annual);

    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {eId, annual: getMySqlMs(`${year}-01-01 00:00:00`), quarter}, []);
    if (resInfo.annual) throw new BizError(ERRORENUM.不可重复添加同一年度数据);
    let addInfo = {
        mId:randomId(TABLEID.企业经营信息),
        eId,
        createTime:getMySqlMs(),
        annual:getMySqlMs(`${year}-01-01 00:00:00`),
        quarter,//季度
        BI:param.BI,
        TXP:param.TXP,
        RD:param.RD,
        state:0
    };

    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业经营信息, addInfo, {});

    return {isSuccess:true};
}


export async function deleteEnterpriseManageInfo(eId, mId) {
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, {mId, eId}, [])
    if (!resInfo || !resInfo.mId) throw new BizError(ERRORENUM.当前数据不存在);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业经营信息, {}, {mId, eId});
    
    return {isSuccess:true};
}


export async function enterpriseManageList(eId) {
    let filesList = [ "mId", "annual", "quarter", "BI", "TXP", "RD"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, {eId}, filesList);
    if (!resInfo) {
        throw new BizError(ERRORENUM.数据不存在);
    }

    let annualInfo = {};
    resInfo.forEach( info => {
        let year = moment(info.annual).format("YYYY");
        if (!annualInfo[year]) annualInfo[year] = [];
        annualInfo[year].push(
            {
                mId:info.mId,
                annual:year,
                quarter: changeEnumValue(enumConfig.QUARTER, info.quarter),//新增季度
                BI:info.BI || "0.00",
                TXP:info.TXP || "0.00",
                RD:info.RD || "0.00"
            }
        )
    })

    let dataInfo = [];
    for(let key in annualInfo) {
        let annual = {BI:0, TXP:0, RD:0};
        annualInfo[key].forEach( item => {
            annual.BI += parseFloat(item.BI);
            annual.TXP += parseFloat(item.TXP);
            annual.RD += parseFloat(item.RD);
        })
        annual["annual"] = key;

        dataInfo.push(annual);
    }

    dataInfo.sort((a, b) => {
        return b.annual - a.annual;
    });

    return {dataInfo};
}








