/**
 * 企业经营数据
 */

import * as verificationEnumTools from "../util/verificationEnum";
import * as configEnum from "../config/enum";
import * as industryEnum from "../config/enum/industryEnum";
import * as manageData from "../data/manage";
import { checkChange, extractData, getManageData } from "../util/piecemeal";
import * as splitResultConfig from '../config/splitResultConfig';
import { eccFormParam } from "../util/verificationParam";
import { ManageAddConfig, ManageUpdateConfig } from "../config/eccParam/admin";
import { randomId } from "../tools/system";
import { TABLEID } from "../config/enum/dbEnum";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/errorEnum";
import moment from "moment";


/**
 * 经营数据-列表
 * @param name 企业名称
 * @param year 数据年度
 * @param period 数据时间 上半年、下半年、全年
 * @param page 页
 * @returns 
 */
export async function manageList(name:string, year:number, period:number, page:number) {
    let selectParam:any = {};
    if (name) {
        selectParam.name = {"$regex":`${name}`};
    }
    if (year) {
        selectParam.year = year;
    }
    if (period) {
        selectParam.period = period;
    }

    /**需要用到的查询数据 */
    let manageDbList = await manageData.findManageListToPageSort(selectParam, (page - 1) * 10, {year: -1});
    let count = await manageData.findManageCount(selectParam);//符合查询条件的数据总数

    /**组合返回结果 */
    let dataList = [];
    manageDbList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.manageListConfig, info, true);

        /**将枚举值转为字符 */
        changeData.period = verificationEnumTools.changeEnumValue(configEnum.PERIOD, changeData.period);

        dataList.push(changeData);
    })

    return {count, dataList};
}


/**
 * 经营数据-新增
 * @param param 
 */
export async function manageCreate(param) {
    /**校验表单参数 */
    eccFormParam("管理后台新增经营数据企业", ManageAddConfig, param);
    /**校验枚举 */
    verificationEnumTools.eccEnumValue('管理后台新增经营数据', 'period', configEnum.PERIOD, param.period);

    /**校验经营数据是否重复 */
    let isAdd = await getManageData(param.uscc, param.year, param.period);
    if (!isAdd) throw new BizError(ERRORENUM.请勿重复提交填报数据, `${param.uscc}已有${param.year}年${param.period}时间经营数据`);

    let manageInfo = {
        id: randomId(TABLEID.企业经营数据),
        uscc: param.uscc,
        name: param.name,
        year: param.year,
        period: param.period,
        BI: param.BI,
        VAT: param.VAT,
        CIT: param.CIT,
        PIT: param.PIT,
        RD: param.RD,
        isSubmit:true,
        createTime:new Date().valueOf(),
    }

    await manageData.createDataByParam(manageInfo);

    return {isSuccess:true};
}


/**
 * 经营数据-回显
 * @param uscc 
 */
export async function manageInfo(id:string) {
    /**校验企业 */
    let manageDbInfo = await manageData.findManageByParam({id});
    if (!manageDbInfo || !manageDbInfo.id) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个经营数据`);

    let dataInfo = {
        uscc: manageDbInfo.uscc,
        name: manageDbInfo.name,
        year: manageDbInfo.year,
        period: manageDbInfo.period, //verificationEnumTools.changeEnumValue(configEnum.PERIOD, manageDbInfo.period)
        BI: manageDbInfo.BI,
        VAT: manageDbInfo.VAT,
        CIT: manageDbInfo.CIT,
        PIT: manageDbInfo.PIT,
        RD: manageDbInfo.RD,
    };

    return {dataInfo};
}


/**
 * 经营数据-修改
 * @param uscc 
 * @param param 
 */
export async function manageUpdate(id:string, param) {
    /**校验参数 */
    eccFormParam("管理后台修改经营数据企业", ManageUpdateConfig, param);

    /**校验枚举 */
    verificationEnumTools.eccEnumValue('管理后台修改经营数据企业', 'industry', industryEnum.ALLINDUSTRY, param.industry);
    verificationEnumTools.eccEnumValue('管理后台修改经营数据企业', 'registrationStatus', configEnum.REGISTRATIONSTATUS, param.registrationStatus);
    verificationEnumTools.eccEnumValue('管理后台修改经营数据企业', 'progressStatus', configEnum.PROGRESSSTATUS, param.progressStatus);

    /**校验企业 */
    let manageDbInfo = await manageData.findManageByParam({id});
    if (!manageDbInfo || !manageDbInfo.id) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个企业`);

    /**修改字段 */
    let changeList = checkChange(param, manageDbInfo);
    if (!changeList.length) throw new BizError(ERRORENUM.数据无更新, `${param.name}数据无更新`);
    changeList.forEach(key => {
        manageDbInfo[key] = param[key];
    });

    await manageDbInfo.save();

    return {isSuccess:true};
}


/**
 * 经营数据-删除
 * @param id 
 */
export async function manageDelete(id:string) {
    let manageDbInfo = await manageData.findManageByParam({id});
    if (!manageDbInfo || !manageDbInfo.name) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个企业`);

    await manageData.removeOneData(id);

    return {isSuccess:true};
}


/**
 * 导出经营数据信息列表
 * @param name 企业名称
 * @param year 数据年度
 * @param period 数据期间 上半年、下半年、全年
 * @returns 二维数组，第一行为表头，后续行为数据
 */
export async function outPutManageData(name: string, year: number, period: number, id:string[]) {
    /** 拼接查询条件 */
    let selectParam: any = {};
    if (name) {
        selectParam.name = { "$regex": `${name}` };
    }
    if (year) {
        selectParam.year = year;
    }
    if (period) {
        selectParam.period = period;
    }
    if (id) {
        selectParam.id = {"$in": id};
    }

    /** 查询经营数据 */
    let manageDbList = await manageData.findManageListByParam(selectParam);

    /** 表头定义 */
    const titleList = [
        "企业名称",
        "统一社会信用代码",
        "数据年度",
        "数据期间",
        "营业收入（万元）",
        "增值税（万元）",
        "企业所得税（万元）",
        "个人所得税（万元）",
        "研发投入（万元）",
        "提交状态"
    ];

    /** 字段映射 */
    const keyList = [
        "name",
        "uscc",
        "year",
        "period",
        "BI",
        "VAT",
        "CIT",
        "PIT",
        "RD",
        "isSubmit"
    ];

    let dataList = [titleList]; // 第一行为表头

    manageDbList.forEach(info => {
        /** 提取数据 */
        let changeData: any = extractData(splitResultConfig.manageListConfig, info, true);

        /** 枚举值转文本 */
        changeData.period = verificationEnumTools.changeEnumValue(configEnum.PERIOD, changeData.period) || "未选择";
        changeData.isSubmit = info.isSubmit ? "已提交" : "未提交";

        /** 数字格式化（保留两位小数） */
        const numberKeys = ["BI", "VAT", "CIT", "PIT", "RD"];
        numberKeys.forEach(key => {
            if (changeData[key] !== null && changeData[key] !== undefined) {
                changeData[key] = parseFloat(changeData[key]).toFixed(2);
            }
        });

        /** 生成一行数据 */
        let row = [];
        keyList.forEach(key => {
            let value = changeData[key];
            if (value === null || value === undefined || value === "") {
                value = "-";
            }
            row.push(value);
        });

        dataList.push(row);
    });

    return dataList;
}





