'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/4/23
 * @version
 */

$(document).ready(function () {
    /**
     * 判断是否是 加减乘除 符号
     * @param value
     * @returns {boolean}
     */
    const isOperate1 = function (value) {
        const operatorString = "+-*/";
        return operatorString.indexOf(value) > -1;
    };
    // 删除规则计算参数按钮是否显示
    const refreshDelParamVisible = function () {
        if ($('#rule').children().length > 1) {
            $('#delParam').show();
        } else {
            $('#delParam').hide();
        }
    };
    // 合成新增参数的html
    const addParamHtml = function (html, param) {
        if (!param || param.length === 0) { return; }
        html.push('<span class="badge badge-light" title="' + param.text() + '"');
        html.push(' name="' + param.text() + '"');
        html.push(' code="' + param.attr('value') + '">');
        html.push(param.text());
        html.push('</span>');
    };
    // 弹窗设置指标计算规则
    $('a[name=setRule]').click(function () {
        const isOperator = function (value) {
            const operatorString = "+-*/()";
            return operatorString.indexOf(value) > -1;
        };
        const splitByOperator = function (expr) {
            const exprStack = [];
            const result = [];
            for(let i = 0, len = expr.length; i < len; i++){
                const cur = expr[i];
                if(cur !== ' ' ){
                    exprStack.push(cur);
                }
            }
            let param = '', isParamBefore = false;
            while(exprStack.length > 0){
                const cur = exprStack.shift();
                if (isOperator(cur)) {
                    if (isParamBefore) {
                        result.push(param);
                        param = '';
                    }
                    result.push(cur);
                    isParamBefore = false;
                } else {
                    param = param + cur;
                    isParamBefore = true;
                    if (exprStack.length === 0) {
                        result.push(param);
                        param = '';
                    }
                }
            }
            return result;
        };
        const rule = $(this).attr('value');
        const index = this.parentNode.parentNode;
        $('#rule').attr('curIndex', index.attributes['index_id'].nodeValue);
        $('span', $('#rule')).remove();
        const html = [];
        const params = splitByOperator(rule);
        for (let i = 0, iLen = params.length; i < iLen; i++) {
            if (isOperator(params[i])) {
                html.push('<span class="badge badge-light" title="' + params[i] + '" code="' + params[i] + '" name="' + params[i] + '">' + params[i] + '</span>');
            } else {
                const p = $('option[value='+ params[i] +']:first');
                addParamHtml(html, p);
            }
        }
        $('#delParam').before(html.join(''));
        refreshDelParamVisible();
        $('#set-count').modal('show');
    });
    // 编辑计算规则，选择要添加的计算参数类型
    $('#paramType').change(function () {
        const param = this.selectedIndex === 0 ? 'globalParams' : (this.selectedIndex === 1 ? 'nodeParams' : 'calcParams');
        $('div[name=param]').hide();
        $('#' + param).show();
    });
    // 编辑计算规则，添加计算参数到规则
    $('#addParam').click(function () {
        const lastParam = $('#delParam').prev();
        const paramType = $('#paramType')[0];
        const addParam = function () {
            const paramId = paramType.selectedIndex === 0 ? 'globalParams' : (paramType.selectedIndex === 1 ? 'nodeParams' : 'calcParams');
            const paramSelect = $('select', $('#' + paramId))[0];
            if (paramSelect.children.length > 0 && paramSelect.selectedIndex >= 0) {
                const param = paramSelect.children[paramSelect.selectedIndex];
                const html = [];
                addParamHtml(html, $(param));
                $('#delParam').before(html.join(''));
                $('#paramAlert').hide();
            } else {
                $('#paramAlert').text('无选定参数').show();
            }
        };
        if (lastParam && lastParam.length > 0) {
            const calcSelect = $('select', $('#calcParams'))[0];
            if (isOperate1(lastParam.attr('code'))) {
                if (paramType.selectedIndex === 2) {
                    if (calcSelect.selectedIndex !== 4) {
                        $('#paramAlert').text('计算式后请输入参数').show();
                    } else {
                        addParam();
                    }
                } else {
                    addParam();
                }
            } else if (lastParam.attr('code') === '(') {
                if (paramType.selectedIndex === 2) {
                    $('#paramAlert').text('左括号后请输入参数').show();
                } else {
                    addParam();
                }
            } else if (lastParam.attr('code') === ')') {
                if (paramType.selectedIndex === 2) {
                    if (calcSelect.selectedIndex < 4) {
                        addParam();
                    } else {
                        $('#paramAlert').text('右括号后请输入计算式').show();
                    }
                } else {
                    $('#paramAlert').text('右括号后请输入计算式').show();
                }
            } else {
                if (paramType.selectedIndex === 2) {
                    if (calcSelect.selectedIndex === 4) {
                        $('#paramAlert').text('2个参数之间需要一个计算式').show();
                    } else {
                        addParam();
                    }
                } else {
                    $('#paramAlert').text('2个参数之间需要一个计算式').show();
                }
            }
            // if (!isOperate1(lastParam.attr('code')) && paramType.selectedIndex !== 2) {
            //     $('#paramAlert').text('2个参数之间需要一个计算式').show();
            // } else if (isOperate1(lastParam.attr('code')) && paramType.selectedIndex === 2 ) {
            //     const paramSelect = $('select', $('#calcParams'));
            //     if (paramSelect.selectedIndex === 4) {
            //         addParam();
            //     } else if (paramSelect.selectedIndex === 5) {
            //         const leftBracket = $('span[code=(]');
            //         const rightBracket = $('span[code=)]');
            //         if (leftBracket.length > rightBracket.length) {
            //             addParam();
            //         } else {
            //             $('#paramAlert').text('添加")"前请先添加"("').show();
            //         }
            //     } else {
            //         $('#paramAlert').text('计算式后只可添加参数').show();
            //     }
            // } else {
            //     addParam();
            // }
        } else if (paramType.selectedIndex === 2) {
            const paramSelect = $('select', $('#calcParams'));
            if (paramSelect.selectedIndex === 4) {
                addParam()
            } else {
                $('#paramAlert').text('计算式前需含有参数').show();
            }
        } else {
            addParam();
        }
    });
    // 编辑计算规则，删除规则中计算参数
    $('#delParam').click(function () {
        $('#delParam').prev().remove();
        refreshDelParamVisible();
    });
    // 设置指标计算规则
    $('#ruleOk').click(function () {
        const lastParam = $('#delParam').prev();
        const leftBracket = $("span[code='(']").length, rightBracket = $("span[code=')']").length;
        if (!lastParam) {
            $('#paramAlert').text('未设置计算规则').show();
        } else if (isOperate1(lastParam.attr('code'))) {
            $('#paramAlert').text('计算式后应添加参数').show();
        } else if (lastParam.attr('code') === '(' || leftBracket !== rightBracket) {
            $('#paramAlert').text('计算式错误，请检查').show();
        } else {
            const indexRow = $('tr[index_id=' + $('#rule').attr('curIndex') + ']');
            const params = $('span', $('#rule'));
            const data = {
                id: $('#rule').attr('curIndex'),
                rule: '',
                calc_rule: '',
                parse_rule: '',
            };
            for (const p of params) {
                const code = $(p).attr('code');
                const name = $(p).attr('name');
                data.rule = data.rule + name;
                data.calc_rule = data.calc_rule + code;
                data.parse_rule = code === name ? data.parse_rule + code : data.parse_rule + code + '(' + name + ')';
            }

            postData('/template/setIndexRule', data, function () {
                $('a', indexRow).val(data.calc_rule);
                $('td[name=rule]', indexRow).text(data.rule);
                const aHtml = $('a', indexRow)[0].outerHTML;
                $('td[name=parse_rule]', indexRow).empty();
                $('td[name=parse_rule]', indexRow).append(data.parse_rule + aHtml);
                $('paramAlert').hide();
                $('#set-count').modal('hide');
            }, function () {
                $('#paramAlert').text('提交计算规则失败，请重试').show();
            })
        }
    });
    // 指标节点，绑定分项节点
    $('#nodeMatchCode').blur(function () {
        const self = $(this);
        if (self.val() === self.attr('org-value')) { return; }
        const nodeId = GetUrlQueryString('id');
        postData('/template/updateNodeMatch', {
            id: nodeId ? nodeId : 1,
            match_key: $(this).val(),
        }, function (data) {
            self.attr('org-value', data.match_key);
            self.attr('title', data.match_type_str);
            self.attr('data-original-title', data.match_type_str);;
        }, function (data) {
            self.val(data.match_key);
            self.attr('org-value', data.match_key);
            self.attr('title', data.match_type_str);
            self.attr('data-original-title', data.match_type_str);;
        });
    });
    // 指标参数，绑定参数取值(分项编号)
    $('input[name=nodeParamMatchCode]').blur(function () {
        const self = $(this);
        if (self.val() === self.attr('org-value')) { return; }
        const nodeId = GetUrlQueryString('id');
        const paramCode = $(this).parent().parent().prev().attr('code');
        postData('/template/updateParamMatch', {
            node_id: nodeId ? nodeId : 1,
            code: paramCode,
            match_key: $(this).val(),
        }, function (data) {
            self.attr('org-value', data.match_key);
        }, function () {
            self.val(self.attr('org-value'));
        })
    });
    // 指标参数，绑定参数取值(分项编号)
    $('input[name=globalParamMatchCode]').blur(function () {
        const self = $(this);
        if (self.val() === self.attr('org-value')) { return; }
        const nodeId = GetUrlQueryString('id');
        const paramCode = $(this).parent().parent().prev().attr('code');
        postData('/template/updateParamMatch', {
            node_id: 0,
            code: paramCode,
            match_key: $(this).val(),
        }, function (data) {
            self.attr('org-value', data.match_key);
        }, function () {
            self.val(self.attr('org-value'));
        })
    });
    // 指标参数，选择取值类别
    $('a[name=paramMatchNum]').click(function () {
        const self = $(this);
        const newMatchNum = self.attr('value');
        const oldMatchNum = self.parent().prev().val();
        if (newMatchNum === oldMatchNum) { return; }
        const nodeId = GetUrlQueryString('id');
        const paramCode = $(this).parent().parent().parent().parent().prev().attr('code');
        postData('/template/updateParamMatch', {
            node_id: nodeId ? nodeId : 1,
            code: paramCode,
            match_num: newMatchNum,
        }, function (data) {
            self.parent().prev().val(data.match_num);
            self.parent().prev().text(data.match_num_str);
        }, function (data) {
            self.parent().prev().val(data.match_num);
            self.parent().prev().text(data.match_num_str);
        })
    });
});