/**
 * Created by Tony on 2017/6/7.
 * 各种指标处理对象
 * 包括：可映射指标、报表已选指标集合、离散独立指标和参数
 */

'use strict'

let fieldMapTreeOprObj = {
    treeObj : null,
    currentNode: null,
    dataTypeDef: ['string', 'int32', 'int64', 'double', 'currency', 'date', 'image', 'object'],
    iniTree: function(rptTpl) {
        var me = this;
        let fieldMapList = me.buildTreeData(rptTpl);
        me.treeObj = $.fn.zTree.init($("#field_map_tree_reversed"), fieldMapSetting, fieldMapList);
        me.treeObj.expandAll(true);
        let topNodes = me.treeObj.getNodes();
        for (let node of topNodes) {
            me.treeObj.setChkDisabled(node, true);
        }
    },
    buildTreeData: function (rptTpl) {
        let rst = [];
        let private_setSubFields = function (parent, fieldList) {
            for (let field of fieldList) {
                if (field[JV.PROP_IS_ID]) {
                    field.checked = true;
                }
                field.Title = "ID: " + field[JV.PROP_ID];
                parent.items.push(field);
            }
        }

        if (rptTpl[JV.NODE_FIELD_MAP][JV.NODE_DISCRETE_FIELDS]) {
            rst.push({Name: JV.NODE_DISCRETE_FIELDS, items: [], isParent: true});
            private_setSubFields(rst[rst.length - 1], rptTpl[JV.NODE_FIELD_MAP][JV.NODE_DISCRETE_FIELDS])
        }
        if (rptTpl[JV.NODE_FIELD_MAP][JV.NODE_MASTER_FIELDS]) {
            rst.push({Name: JV.NODE_MASTER_FIELDS, items: [], isParent: true});
            private_setSubFields(rst[rst.length - 1], rptTpl[JV.NODE_FIELD_MAP][JV.NODE_MASTER_FIELDS])
        }
        if (rptTpl[JV.NODE_FIELD_MAP][JV.NODE_DETAIL_FIELDS]) {
            rst.push({Name: JV.NODE_DETAIL_FIELDS, items: [], isParent: true});
            private_setSubFields(rst[rst.length - 1], rptTpl[JV.NODE_FIELD_MAP][JV.NODE_DETAIL_FIELDS])
        }

        return rst;
    },
    copySelectedFieldList: function () {
        let me = fieldMapTreeOprObj, rst = [];
        if (me.treeObj) {
            let nodes = me.treeObj.getNodes();
            for (let node of nodes) {
                let item = {Name: node.Name, items: [], isParent: true, Title: ""};
                if (node.items) {
                    for (let subNode of node.items) {
                        let subItem = me.createMapFieldByNode(subNode);
                        item.items.push(subItem);
                    }
                }
                rst.push(item)
            }
        }
        return rst;
    },
    onClick: function (event,treeId,treeNode) {
        let me = fieldMapTreeOprObj;
        me.currentNode = treeNode;
        //then refresh the field map tab properties
        //数据类型
        // switch (me.dataTypeDef.indexOf(treeNode[JV.PROP_DATA_TYPE])) {
        //     case 0:
        //         $("#fieldDataTypeSelection").get(0).selectedIndex = 0;
        //         break;
        //     case 1:
        //     case 2:
        //     case 3:
        //     case 4:
        //         $("#fieldDataTypeSelection").get(0).selectedIndex = 1;
        //         break;
        //     case 5:
        //         $("#fieldDataTypeSelection").get(0).selectedIndex = 2;
        //         break;
        //     case 6:
        //         $("#fieldDataTypeSelection").get(0).selectedIndex = 3;
        //         break;
        //     default:
        //         $("#fieldDataTypeSelection").get(0).selectedIndex = 0;
        //         break;
        // }
        //映射指标
    },
    onBeforeRemove: function(treeId, treeNode){
        if (treeNode.level === 0) {
            return false;
        }
        return true;
    },
    beforeRename: function(treeId, treeNode, newName, isCancel) {
        if (isCancel) {
            return true;
        }
        if (treeNode.level === 0) {
            return false;
        }
        return true;
    },
    onBeforeDrop: function(treeId, treeNodes, targetNode, moveType){
        let rst = true;
        if (treeId === 'selectable_field_tree_reversed' || targetNode.level === 0 || moveType === 'inner') {
            rst = false;
        } else {
            //
        }
        return rst;
    },
    onRemove: function (e, treeId, treeNode) {
        //
    },
    onRename: function (e, treeId, treeNode, isCancel) {
        //
    },
    extractFieldMaps: function (rptTpl) {
        let me = this;
        for (let rootNode of me.treeObj.getNodes()) {
            rptTpl[JV.NODE_FIELD_MAP][rootNode.Name] = [];
            let idSeq = 1;
            for (let mappingFieldNode of rootNode.items) {
                let item = me.createMapFieldByNode(mappingFieldNode);
                if (mappingFieldNode.checked) {
                    item[JV.PROP_IS_ID] = true;
                    item[JV.PROP_ID_SEQ] = idSeq;
                    idSeq++;
                }
                rptTpl[JV.NODE_FIELD_MAP][rootNode.Name].push(item);
            }
        }
    },
    createMapFieldByNode: function (node) {
        let rst = {}, me = this;
        me.copyMapFieldNode(node, rst);
        return rst;
    },
    copyMapFieldNode: function (src, dest) {
        dest[JV.PROP_ID] = src[JV.PROP_ID];
        dest[JV.PROP_NAME] = src[JV.PROP_NAME];
        dest[JV.PROP_DATA_TYPE] = src[JV.PROP_DATA_TYPE];
        dest.mapExpression = src.mapExpression;
        dest.adHocFormula = src.adHocFormula;
        dest.descr = src.descr;
        dest.Title = "ID: " + src[JV.PROP_ID];
        if (src.Precision) {
            dest.Precision = src.Precision;
        }
    },
    refreshFields: function () {
        let me = this;
        if (me.treeObj && selectableFiledTreeOprObj.treeObj) {
            let selectableFields = [];
            let private_get_all_selectable_fields = function (fieldNode) {
                if (fieldNode.isParent) {
                    for (let dtlSF of fieldNode.items) {
                        private_get_all_selectable_fields(dtlSF);
                    }
                } else {
                    selectableFields.push(fieldNode);
                }
            };
            let selectableFieldNodes = selectableFiledTreeOprObj.treeObj.getNodes();
            for (let subFn of selectableFieldNodes) {
                private_get_all_selectable_fields(subFn);
            }
            let topNodes = me.treeObj.getNodes();
            for (let node of topNodes) {
                if (node.items && node.items.length > 0) {
                    for (let dtl of node.items) {
                        for (let sf of selectableFields) {
                            if (sf.ID === dtl.ID) {
                                me.copyMapFieldNode(sf, dtl);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
};

let selectableFiledTreeOprObj = {
    treeObj : null,
    currentNode: null,
    iniTree: function() {
        let me = this, params = {};
        params.userId = userID;
        CommonAjax.postEx("report_tpl_api/getMappingFields", params, 20000, true, function(result){
                let showRst = [];
                for (let item of result) {
                    me.decorateMappingFieldList(item);
                    if (item.items.length > 0) {
                        showRst.push(item);
                    }
                }
                me.treeObj = $.fn.zTree.init($("#selectable_field_tree_reversed"), selectableFieldSetting, showRst);
                let nodes = me.treeObj.getNodes();
                for (let node of nodes) {
                    me.treeObj.expandNode(node, true, false);
                }
                // me.treeObj.expandAll(true);
                showRst = null;
            }, null, null
        );
    },
    decorateMappingFieldList: function (rawMappingField) {
        let me = this;
        if (rawMappingField.items && rawMappingField.items.length > 0) {
            for (const subMappingField of rawMappingField.items) {
                me.decorateMappingFieldList(subMappingField);
            }
        } else {
            rawMappingField.Title = "ID: " + rawMappingField[JV.PROP_ID];
        }
    },
    onClick: function (event,treeId,treeNode) {
        let me = fieldMapTreeOprObj;
        me.currentNode = treeNode;
    },
    onBeforeDrag: function (treeId, treeNodes) {
        let rst = true;
        for (let node of treeNodes) {
            if (node.level === 0) {
                rst = false;
                break;
            }
        }
        return rst;
    },
    onBeforeDrop: function(treeId, treeNodes, targetNode, moveType){
        let rst = true;
        if (treeId === 'field_map_tree_reversed') {
            if ( (targetNode.level === 0 && moveType !== 'inner') || (targetNode.level > 0 && moveType === 'inner')) {
                rst = false;
            }
        } else {
            rst = false;
        }
        return rst;
    },
    addDiyDom: function (treeId, treeNode) {
        if (treeNode.level > 0) {
            let aObj = $("#" + treeNode.tId + "_a");
            if ($("#diyBtn_"+treeNode.ID).length>0) return;
            let editStr = "<span>&nbsp(" + treeNode.DataType + ")</span>";
            aObj.append(editStr);
            let btn = $("#diyBtn_"+treeNode.ID);
            if (btn) btn.bind("click", function(){alert("diy Button for " + treeNode.name);});
        }
    }
};

let discreteFieldParamTreeOprObj = {
    treeObj : null,
    currentNode: null,
    local_idx : 12000,
    iniTree: function(rptTpl) {
        var me = this;
        let fieldMapList = me.buildTreeData(rptTpl);
        me.treeObj = $.fn.zTree.init($("#tpl_discrete_fields_params_reversed"), discreteFieldParamSetting, fieldMapList);
        me.treeObj.expandAll(true);
    },
    buildTreeData: function(rptTpl){
        let me = this, rst = [];
        let disFieldNode = {Name: JV.NODE_NO_MAPPING_FIELDS, items: [], isParent: true, Title: ""};
        let disParamNode = {Name: JV.NODE_DISCRETE_PARAMS, items: [], isParent: true, Title: ""};
        rst.push(disFieldNode);
        rst.push(disParamNode);
        if (rptTpl[JV.NODE_NO_MAPPING_FIELDS] && rptTpl[JV.NODE_NO_MAPPING_FIELDS].length > 0) {
            for (let df of rptTpl[JV.NODE_NO_MAPPING_FIELDS]) {
                let node = {};
                node[JV.PROP_ID] = df[JV.PROP_ID];
                node[JV.PROP_FIELD_ID] = df[JV.PROP_ID];
                node[JV.PROP_NAME] = df[JV.PROP_NAME];
                node[JV.PROP_DATA_TYPE] = df[JV.PROP_DATA_TYPE];
                node.Title = "ID: " + df[JV.PROP_ID];
                disFieldNode.items.push(node);
                if (parseInt(df[JV.PROP_ID]) >= me.local_idx) me.local_idx = parseInt(df[JV.PROP_ID]) + 1;
            }
        }
        if (rptTpl[JV.NODE_DISCRETE_PARAMS]) {
            for (let dp of rptTpl[JV.NODE_DISCRETE_PARAMS]) {
                let node = {};
                node[JV.PROP_ID] = dp[JV.PROP_ID];
                node[JV.PROP_PARAM_ID] = dp[JV.PROP_ID];
                node[JV.PROP_NAME] = dp[JV.PROP_NAME];
                node[JV.PROP_DATA_TYPE] = dp[JV.PROP_DATA_TYPE];
                node[JV.PROP_DFT_VALUE] = dp[JV.PROP_DFT_VALUE];
                node.Title = "ID: " + dp[JV.PROP_ID];
                disParamNode.items.push(node);
                if (parseInt(dp[JV.PROP_ID]) >= me.local_idx) me.local_idx = parseInt(dp[JV.PROP_ID]) + 1;
            }
        }
        return rst;
    },
    getAndModifyLocalIdx: function() {
        let me = discreteFieldParamTreeOprObj, rst = me.local_idx;
        me.local_idx++;
        return rst;
    },
    addHoverDom: function(treeId, treeNode) {
        let me = discreteFieldParamTreeOprObj, sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.level > 0 || $("#addBtn_"+treeNode.tId).length > 0) return;
        let addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增子节点' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        let btn = $("#addBtn_"+treeNode.tId);
        if (btn) btn.bind("click", function(){
            if (treeNode[JV.PROP_NAME] === JV.NODE_NO_MAPPING_FIELDS) {
                let field = me.private_setup_dummy_discrete_field_node();
                let newNodes = [field];
                me.treeObj.addNodes(treeNode, -1, newNodes, true);
            } else if (treeNode[JV.PROP_NAME] === JV.NODE_DISCRETE_PARAMS) {
                let param = me.private_setup_dummy_discrete_param_node();
                let newNodes = [param];
                me.treeObj.addNodes(treeNode, -1, newNodes, true);
            }
        });
    },
    private_setup_dummy_discrete_field_node: function () {
        let me = discreteFieldParamTreeOprObj, rst = {};
        rst[JV.PROP_ID] = me.getAndModifyLocalIdx();
        rst[JV.PROP_NAME] = "新离散指标";
        rst[JV.PROP_DATA_TYPE] = "string";
        rst.descr = "";
        rst.Title = "ID: " + rst[JV.PROP_ID];
        return rst;
    },
    private_setup_dummy_discrete_param_node: function () {
        let me = discreteFieldParamTreeOprObj, rst = {};
        rst[JV.PROP_ID] = me.getAndModifyLocalIdx();
        rst[JV.PROP_NAME] = "新离散参数";
        rst[JV.PROP_DATA_TYPE] = "string";
        rst[JV.PROP_DFT_VALUE] = "";
        rst.Title = "ID: " + rst[JV.PROP_ID];
        return rst;
    },
    removeHoverDom: function(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    },
    onBeforeRemove: function(treeId, treeNode){
        let rst = true;
        if (treeNode.isParent) {
            rst = false;
        }
        return rst;
    },
    beforeRename: function(treeId, treeNode, newName, isCancel) {
        let rst = true;
        if (treeNode.isParent && !isCancel) {
            rst = false;
        }
        return rst;
    },
    onBeforeDrag: function (treeId, treeNodes) {
        let rst = true;
        for (let node of treeNodes) {
            if (node.level === 0) {
                rst = false;
                break;
            }
        }
        return rst;
    },
    onBeforeDrop: function(treeId, treeNodes, targetNode, moveType){
        // let rst = false;
        // if (targetNode.tId && targetNode.tId.indexOf("tpl_data_info_reversed") >= 0 && (!(targetNode.isParent && moveType !== 'inner')) ) {
        //     if (targetNode.level === 0) {
        //         if (targetNode.Name !== "离散信息" && moveType === 'inner') {
        //             rst = true;
        //         }
        //     } else {
        //         let parentNode = targetNode.getParentNode();
        //         if (parentNode.Name === "离散信息") {
        //             if (targetNode.Name === "Fields") {
        //                 rst = true;
        //             }
        //         } else if (parentNode.Name === "Fields") {
        //             rst = true;
        //         }
        //     }
        // }
        // return rst;
    },
    onRemove: function () {
        //
    },
    onRename: function () {
        //
    },
    extractFieldMaps: function (rptTpl) {
        let me = this;
        for (let rootNode of me.treeObj.getNodes()) {
            if (rootNode[JV.PROP_NAME] === JV.NODE_NO_MAPPING_FIELDS) {
                rptTpl[JV.NODE_NO_MAPPING_FIELDS] = [];
                for (let fNode of rootNode.items) {
                    rptTpl[JV.NODE_NO_MAPPING_FIELDS].push(me.createDiscreteFieldByNode(fNode));
                }
            } else if (rootNode[JV.PROP_NAME] === JV.NODE_DISCRETE_PARAMS) {
                rptTpl[JV.NODE_DISCRETE_PARAMS] = [];
                for (let pNode of rootNode.items) {
                    rptTpl[JV.NODE_DISCRETE_PARAMS].push(me.createDiscreteParamByNode(pNode));
                }
            }
        }
    },
    createDiscreteFieldByNode: function (node) {
        let rst = {};
        rst[JV.PROP_ID] = node[JV.PROP_ID];
        rst[JV.PROP_NAME] = node[JV.PROP_NAME];
        rst[JV.PROP_DATA_TYPE] = node[JV.PROP_DATA_TYPE];
        rst.descr = node.descr;
        return rst;
    },
    createDiscreteParamByNode: function (node) {
        let rst = {};
        rst[JV.PROP_ID] = node[JV.PROP_ID];
        rst[JV.PROP_NAME] = node[JV.PROP_NAME];
        rst[JV.PROP_DATA_TYPE] = node[JV.PROP_DATA_TYPE];
        rst[JV.PROP_DFT_VALUE] = node[JV.PROP_DFT_VALUE];
        return rst;
    }
};