/**
 * Created by Tony on 2017/7/7.
 */

let expr_templates = [
    // {Name: "整理序号(单层)", Expression: "let destField = $JE.F(/*指标ID*/,$CURRENT_RPT);\n  destField[JV.PROP_AD_HOC_DATA] = [];\n  for (let innerFmlIdx = 0; innerFmlIdx < $CURRENT_DATA[JV.DATA_DETAIL_DATA][0].length; innerFmlIdx++) {\n    $JE.setFieldValue(destField, $CURRENT_DATA, innerFmlIdx, (innerFmlIdx + 1));\n}"},
    {Name: "转换大写金额", Expression: "let capF = $JE.F(/*目标指标ID*/, $CURRENT_RPT), orgF = $JE.F(/*原始指标ID*/, $CURRENT_RPT);\n $JE.setFieldValue(capF, $CURRENT_DATA, 0, $JE.$STR_UTIL.convertToCaptionNum(parseFloat($JE.getFieldValue(orgF, $CURRENT_DATA, 0, 0)).toFixed(2), true, true));"},
    {Name: "总计汇总", Expression: "let totalFee = $JE.F(/*目标指标ID*/,$CURRENT_RPT), bill1 = $JE.F(/*原始指标ID*/,$CURRENT_RPT);\n let sumValue = 0.0;\n sumValue += parseFloat($JE.getFieldValue(bill1,$CURRENT_DATA,0,0));\n $JE.setFieldValue(totalFee,$CURRENT_DATA,0,sumValue);"},
    {Name: "格式化指标时间", Expression: "let dtF = $JE.F(/*时间指标ID*/,$CURRENT_RPT);\n let dt = new Date($JE.getFieldValue(dtF, $CURRENT_DATA, 0, 0));\n $JE.setFieldValue(dtF, $CURRENT_DATA, 0, dt.Format($ME.format));"},
    {Name: "依据单位调整格式(小数位数)", Expression: "let decimalField = $JE.F(3281,$CURRENT_RPT),\n	unitField = $JE.F(/*单位指标ID*/,$CURRENT_RPT),\n	targetField = $JE.F(/*原始目标指标ID*/,$CURRENT_RPT),\n	outputField = $JE.F(/*真正输出目标指标ID*/,$CURRENT_RPT);\nlet tmpObj = {}, key_prefix = 'key_';\nlet dfv = $JE.getFieldValue(decimalField, $CURRENT_DATA, 0, null);\nif (dfv instanceof Array) {\n	for (let dcmf of dfv) {\n		tmpObj[key_prefix + dcmf['unit']] = dcmf['decimal'];\n	}\n	for (let dtlIdx = 0; dtlIdx < $CURRENT_DATA[JV.DATA_DETAIL_DATA][0].length; dtlIdx++) {\n		let ukey = key_prefix + $JE.getFieldValue(unitField, $CURRENT_DATA, dtlIdx, '其他未列单位');\n		let fstr = '#.####';\n		if (tmpObj[ukey]) {\n			fstr = '#.';\n			for (let fIdx = 0; fIdx < tmpObj[ukey]; fIdx++) {\n				fstr += '#';\n			}\n		}\n		let val = $JE.getFieldValue(targetField, $CURRENT_DATA, dtlIdx, '0');\n		val = $JE.$STR_UTIL.formatNumber(fstr, val);\n		$JE.setFieldValue(outputField,$CURRENT_DATA,dtlIdx, val);\n	}\n}"}
];

let calculationTreeOprObj = {
    treeObj : null,
    currentNode: null,
    iniTree: function(rptTpl) {
        var me = this;
        let fieldMapList = me.buildTreeData(rptTpl);
        me.treeObj = $.fn.zTree.init($("#rpt_tpl_formulas"), caculationSetting, fieldMapList);
        me.treeObj.expandAll(true);
        $("#exprDetail")[0].style.display = "none";
        // $("#exprFormat").get(0).value = "";
        // $("#exprContent").get(0).value = "";
    },
    buildExprTemplates: function () {
        let et = $("#exprTemplatesSelect");
        for (let i = 0; i < expr_templates.length; i++) {
            et.append("<option>" + expr_templates[i].Name + "</option>");
        }
    },
    buildRunType: function() {
        let et = $("#exprRunType");
        et.append("<option value='" + JV.RUN_TYPE_BEFORE_PAGING + "'>预运行</option>");
        et.append("<option value='" + JV.RUN_TYPE_BEFORE_OUTPUT + "'>实时运行</option>");
    },
    buildTreeData: function (rptTpl) {
        let me = this, rst = {"Name": "计算式", items: []};
        if (rptTpl[JV.NODE_FORMULAS]) {
            for (let cItem of rptTpl[JV.NODE_FORMULAS]) {
                let node = {};
                me.copyContent(cItem, node);
                node[JV.PROP_NAME] = cItem[JV.PROP_NAME];
                node[JV.PROP_RUN_TYPE] = cItem[JV.PROP_RUN_TYPE];
                node[JV.PROP_EXPRESSION] = cItem[JV.PROP_EXPRESSION];
                node["format"] = (cItem["format"])?cItem["format"]:"";
                rst.items.push(node);
            }
        }
        return rst;
    },
    copyContent: function(source, target) {
        target[JV.PROP_NAME] = source[JV.PROP_NAME];
        target[JV.PROP_RUN_TYPE] = source[JV.PROP_RUN_TYPE];
        target[JV.PROP_EXPRESSION] = source[JV.PROP_EXPRESSION];
        target["format"] = (source["format"])?source["format"]:"";
    },
    changeRunType: function (dom) {
        let me = calculationTreeOprObj;
        if (me.currentNode) {
            me.currentNode[JV.PROP_RUN_TYPE] = dom.value;
        }
    },
    setTemplateExpression: function (dom) {
        let selIdx = $("#exprTemplatesSelect")[0].selectedIndex;
        $("#exprContent")[0].value = expr_templates[selIdx].Expression;
    },
    changeFormat: function (dom) {
        let me = calculationTreeOprObj;
        if (me.currentNode) {
            me.currentNode["format"] = dom.value;
        }
    },
    changeExpression: function (dom) {
        let me = calculationTreeOprObj;
        if (me.currentNode) {
            me.currentNode[JV.PROP_EXPRESSION] = dom.value;
        }
    },
    onClick: function (event,treeId,treeNode) {
        let me = calculationTreeOprObj;
        me.currentNode = treeNode;
        if (treeNode.level === 0) {
            $("#exprDetail")[0].style.display = "none";
        } else {
            $("#exprDetail")[0].style.display = "";
            if (treeNode[JV.PROP_RUN_TYPE] === JV.RUN_TYPE_BEFORE_PAGING) {
                $("#exprRunType")[0].selectedIndex = 0;
            } else {
                $("#exprRunType")[0].selectedIndex = 1;
            }
            $("#exprFormat")[0].value = (treeNode["format"])?treeNode["format"]:"";
            $("#exprContent")[0].value = treeNode[JV.PROP_EXPRESSION];
            //
        }
    },
    onBeforeRemove: function(treeId, treeNode){
        let rst = false;
        if (treeNode.level > 0) {
            rst = confirm('请确认是否真的删除?');
        }
        return rst;
    },
    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 = false;
        if (targetNode.level === 1 && (moveType === "next" || moveType === "prev")) {
            return true;
        }
        return rst;
    },
    addHoverDom: function(treeId, treeNode) {
        let me = calculationTreeOprObj, sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length > 0 || treeNode.level > 0) {
            return;
        } else {
            let addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            let btn = $("#addBtn_"+treeNode.tId);
            btn.bind("click", function(){
                let newNodes = [], node = {};
                node[JV.PROP_NAME] = "新计算式";
                node[JV.PROP_RUN_TYPE] = JV.RUN_TYPE_BEFORE_PAGING;
                node[JV.PROP_EXPRESSION] = "";
                node["format"] = "";
                newNodes.push(node);
                me.treeObj.addNodes(treeNode, -1, newNodes, true);
            });
        }
    },
    removeHoverDom: function(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    },
    extractCalculation: function (rptTpl) {
        let me = this, newCaclList = [];
        let topNode = me.treeObj.getNodes()[0];
        for (let node of topNode.items) {
            let item = {};
            me.copyContent(node, item);
            newCaclList.push(item);
        }
        rptTpl[JV.NODE_FORMULAS] = newCaclList;
    }
}