//计算式执行的具体方法
import { Fields, ICurrent_RPT, IDataObj, IGroupField, IParam } from "../index";
import { IParams } from "../interface/basic";
import { IDataObjProps } from '../interface/enum';
import { ReportDate } from '../public/ReportDate'

let FData: Record<string, IGroupField> = {};
let PData: Record<string, IParam> = {};
let DData: Record<string, any> = {};
let rpt = <ICurrent_RPT>{};
let orgData = <IDataObj>{};

const setupData = ($CURRENT_RPT: ICurrent_RPT, $CURRENT_DATA: IDataObj) => {
    rpt = $CURRENT_RPT;
    orgData = $CURRENT_DATA;
}
const resetData = () => {
    DData = {};
    FData = {};
    PData = {};
}
const getFieldValueArray = (field: IGroupField) => {
    let rst: any;
    if (field.DataNodeName === IDataObjProps.NA) {
        if (!field.data_field) {
            field.data_field = [];
        }
        rst = field.data_field;
    } else {
        if (!field.DataNodeName) {
            console.log('进来了特殊情况')
            // that means this is a self-defined discrete field!
            field.DataNodeName = IDataObjProps.discrete_data;
            // field.DataSeq = dataObj[IDataObjProps.discrete_data];
            orgData[IDataObjProps.discrete_data].push([]);
        }
        rst = orgData[field.DataNodeName][field.DataSeq];
    }
    if (rst === null || rst === undefined) rst = [];
    return rst;
}

//获取一般指标的指标对象($CURRENT_RPT.fields中的对象)
const F = (fieldID: number) => {
    if (FData[fieldID]) {
        return FData[fieldID];
    } else {
        for (const dataSet in rpt.fields) {
            for (const field in rpt.fields[dataSet]) {
                const newFieldID = field.replace('ID_', '');
                if (newFieldID === `${fieldID}`) {
                    FData[fieldID] = rpt.fields[dataSet][field];
                    DData[fieldID] = getFieldValueArray(rpt.fields[dataSet][field]);
                    return FData[fieldID];
                }
            }
        }
    }
    return false;
}

// 获取离散指标的指标对象($CURRENT_RPT.params中的对象,一般是打印页，总页数，当前页数)
const P = (fieldID: number) => {
    if (PData[fieldID]) {
        return PData[fieldID];
    } else {
        for (const field in rpt.params) {
            const fieldID = field.replace('ID_', '');
            if (fieldID === fieldID) {
                PData[fieldID] = rpt.params[field]
                DData[fieldID] = rpt.params[field].Default_Value;
                return rpt.params[field];
            }
        }
    }
    return false;
}

// 获取数据，只有一个参数时获取该指标所有数据（数组），两个参数时获取该指标中的第N个数据（值）
const D = (fieldID: number, valIndex?: number, newValue?: any) => {
    if (valIndex || valIndex === 0) {
        if (DData[fieldID]) {
            return DData[fieldID][valIndex];
        } else {
            if (!F(fieldID)) P(fieldID);
            if (DData[fieldID]) {
                if (DData[fieldID].length >= valIndex) {
                    if (!DData[fieldID][valIndex]&&DData[fieldID][valIndex]!==0) return '';
                    return DData[fieldID][valIndex];
                } else {
                    console.log(`指标id:${fieldID},${valIndex}>${DData[fieldID].length}，请检查`)
                    return '';
                }
            } else {
                console.log(`无ID为${fieldID}的指标，请检查`)
                return '';
            }
        }
    } else {
        if (DData[fieldID]) {
            return DData[fieldID];
        } else {
            if (!F(fieldID)) P(fieldID);
            if (DData[fieldID]) {
                return DData[fieldID];
            } else {
                console.log(`无ID为${fieldID}的指标，请检查`)
                return []
            }
        }
    }
}

//获取相应指标的数据长度
const L = (arg: any) => {
    if (arg in IDataObjProps) {
        return orgData[arg][0].length;
    } else {
        if (DData[arg]) {
            return DData[arg].length;
        } else {
            F(arg);
            if (DData[arg]) {
                return DData[arg];
            } else {
                console.log(`无ID为${arg}的指标，请检查`)
                return 0
            }
        }
    }
}

//获取当前页
const getCurrentPage = () => {
    let rst = 0;
    if (rpt && rpt.runTimePageData.currentPage) {
        rst = rpt.runTimePageData.currentPage;
    }
    return rst;
}

// 获取总页数
const getTotalPage = () => {
    let rst = 0;
    if (rpt) {
        rst = rpt.totalPages;
    }
    return rst;
}

//向目标对象赋值
const setFieldValue = (field: IGroupField, valIdx: number, newValue: any) => {
    if (field.DataNodeName === "NA") {
        if (!field.data_field) {
            field.data_field = [];
        }
        field.data_field[valIdx] = newValue;
    } else if (!field.DataNodeName) {
        //that means this is a self-defined discrete field!
        field.DataNodeName = IDataObjProps.discrete_data;
        field.DataSeq = orgData[IDataObjProps.discrete_data].length;
        orgData[IDataObjProps.discrete_data].push([]);
        orgData[field.DataNodeName][field.DataSeq][valIdx] = newValue;
    } else {
        orgData[field.DataNodeName][field.DataSeq][valIdx] = newValue;
    }
}
//反向设置原始数据
const setFieldValueArray = (field: IGroupField, newArr: any[]) => {
    if (newArr instanceof Array) {
        if (field.DataNodeName === 'NA') {
            field.data_field = newArr;
        } else {
            if (!field.DataNodeName) {
                // that means this is a self-defined discrete field!
                field.DataNodeName = IDataObjProps.discrete_data;
                field.DataSeq = orgData[IDataObjProps.discrete_data].length;
                orgData[IDataObjProps.discrete_data].push([]);
            }
            orgData[field.DataNodeName][field.DataSeq] = newArr;
        }
    }
}
//反向设置原始数据
const setFieldDefaultValue = (fieldID: number, newValue: any) => {
    rpt.params[`ID_${fieldID}`].Default_Value = newValue;
}


//该函数为共用方法，参数有两套组合：
// (指标id,更改后的数组)
// (指标id,需要更改的index,.需要更改的值)
const setData = (fieldID: number, arg1: number[] | string[] | number | string, arg2?: number | string) => {
    const field = F(fieldID)
    if (field) {
        if (arg1 instanceof Array) {
            if (DData[fieldID]) {
                DData[fieldID] = arg1;
                setFieldValueArray(field, arg1);
            } else {
                console.log(`无ID为${fieldID}的指标，请检查`)
            }
        } else {
            if (typeof (arg1) === 'number') {
                if (DData[fieldID]) {
                    if (arg1 <= DData[fieldID].length) {
                        DData[fieldID][arg1] = arg2;
                        setFieldValue(field, arg1, arg2);
                    } else {
                        console.log(`指标id:${fieldID},数据长度为${DData[fieldID].length},第二参数为${arg1}，请检查`)
                    }
                } else {
                    console.log(`无ID为${fieldID}的指标，请检查`)
                }
            }
        }
    } else if (P(fieldID)) {
        setFieldDefaultValue(fieldID, arg1);
        DData[fieldID] = arg1;
    }
}
//把数组每个元素都转换成数字
const getNumberArray = (data: string[] | undefined[] | [] | number[]) => {
    const rst: number[] = [];
    for (const item of data) {
        if (isNaN(Number(item))) {
            rst.push(0);
        } else {
            rst.push(Number(item));
        }
    }
    return rst;
}


const removeFieldValue = (fieldID: number, valIdx: number) => {
    const fField: (IGroupField) = <IGroupField>F(fieldID);
    if (fField) {
        DData[fieldID].splice(valIdx, 1);
    } else {
        console.log(`指标${fieldID}的数据不支持removeFieldValue操作`);
    }
}

const insertFieldValue = (fieldID: number, valIdx: number, newValue: number) => {
    let field = <IGroupField>F(fieldID);
    if (field) {
        DData[fieldID].splice(valIdx, 0, newValue);
    } else {
        console.log(`指标${fieldID}的数据不支持insertFieldValue操作`);
    }
}

//复制精度
const copyPrecision = (targetFieldID: number, orgFieldID: number) => {
    copyProperty(targetFieldID, orgFieldID, 'Precision');
}

const copyFixedPrecisionNum = (targetFieldID: number, orgFieldID: number) => {
    copyProperty(targetFieldID, orgFieldID, 'fixedPrecisionNum');
}

//复制属性
const copyProperty = (targetFieldID: number, orgFieldID: number, property: string) => {
    const targetField = <IGroupField>F(targetFieldID);
    const orgField = <IGroupField>F(orgFieldID);
    if (targetField && orgField) {
        if (orgField[property]) {
            if (!targetField[property]) {
                targetField[property] = {};
            }
            Object.assign(targetField[property], orgField[property]);
        } else {
            console.log(`指标${orgFieldID}不存在${property}属性`);
        }
    } else {
        console.log(`指标${targetFieldID}和${orgFieldID}的数据不支持copyProperty操作`);
    }
}

const setDate = (fieldID: number, format: string) => {
    const date = new ReportDate();
    setData(fieldID, date.Format(format));
}

const DLength = () => {
    if (orgData && orgData.detail_data) return orgData.detail_data[0].length
    return 0;
}

export default {
    setupData,
    P,
    F,
    D,
    getCurrentPage,
    getTotalPage,
    L,
    setFieldValue,
    setFieldValueArray,
    removeFieldValue,
    insertFieldValue,
    setData,
    resetData,
    getNumberArray,
    copyPrecision,
    copyFixedPrecisionNum,
    copyProperty,
    setDate,
    DLength
}


