//EWA_CONF.LF.M
(function() {
    var ewa = EWA.F.FOS['@SYS_FRAME_UNID'];
    ewa.ReloadAfter = function(httpReferer) {

    };

    ewa.MDownEvent = function(tr, evt) {
        let tag = $(tr).attr('ewa_key');
        let conf = ewa._confs[tag];
        let obj = $(tr).next();
        obj.toggle();
    };

    function createBox(conf) {
        let tb = $(createParasBox(conf));
        for (let index in conf.children) {
            let chdConf = conf.children[index];
            let chdTb = createBox(chdConf);
            let a = conf.CONF_PARENT_TAG ? '<a class="closesetting tag-' + chdConf.CONF_TAG + '">关闭设置</a>' :
                '<a class="add tag-' + chdConf.CONF_TAG + '">ADD</a> | <a class="remove tag-' + chdConf.CONF_TAG + '">REMOVE</a>';
            let tr = $('<tr><td class="EWA_TD_L">' + chdConf.CONF_TAG +
                '</td><td style="text-align:center" class="EWA_TD_M">' +
                a + '</td><td class="EWA_TD_R">' + chdConf.CONF_MEMO +
                '</td></tr><tr><td style="padding: 0 15px" colspan=3></td></tr>');
            tb.append(tr);
            tr.find('a.closesetting').on('click', function() {
                let target = $(this).parent().parent().next();
                if ($(this).attr('closed')) {
                    $(this).attr('closed', '').text('关闭设置');
                    target.show();
                } else {
                    $(this).attr('closed', 'yes').text('打开设置');
                    target.hide();
                }
            });
            tr.find('a.add').on('click', function() {
                let target = $(this).parentsUntil('.pbox').last().parent();
                target.parent().append(target.clone(true));
            });
            tr.find('a.remove').on('click', function() {
                let target = $(this).parentsUntil('.pbox').last().parent();
                let name = target.attr('name');
                let jq = '.pbox[name="' + name + '"]';
                console.log(jq)
                if ($(jq).length == 1) {
                    $Tip('最后一个不能删除');
                } else {
                    target.remove();
                }
            });
            tb.find('td:last').append(chdTb);
        }
        return tb;
    }

    function createParasBox(conf) {
        let paras = ewa._conf_para[conf.CONF_TAG];
        var ss = ["<table class='pbox' name='" + conf.CONF_TAG + "'>"];
        for (let n in paras) {
            let p = paras[n];
            let s = '<tr><td class="EWA_TD_L">' + p.PARA_NAME +
                '</td><td  class="EWA_TD_M"><input type=text name="' + p.PARA_NAME + '"></td><td  class="EWA_TD_R">' + p.PARA_MEMO + '</td></tr>';
            ss.push(s);
        }
        ss.push('</table>');

        return ss.join('');
    }

    function getObj(exp) {
        return exp ? $('#EWA_LF_@sys_frame_unid').find(exp) : $('#EWA_LF_@sys_frame_unid');
    }

    function loadActionJson() {
        var u1 = new EWA_UrlClass(EWA.F.FOS["@SYS_FRAME_UNID"].Url);
        u1.AddParameter("ewa_action", "SACT0");
        u1.AddParameter("ewa_ajax", "json_all");
        var u = u1.GetUrl();
        $J(u, function(rst) {
            ewa._conf_para = $J2MAP1(rst[0], 'CONF_TAG');
            ewa._conf_dict = $J2MAP1(rst[1], 'CONF_TAG,PARA_NAME');
            let arrconfs = rst[2];
            let map = {};
            for (var n in arrconfs) {
                let conf = arrconfs[n];
                conf.children = [];
                map[conf.CONF_TAG] = conf;
            }
            for (let n in arrconfs) {
                let conf = arrconfs[n];
                if (!conf.CONF_PARENT_TAG) {
                    continue;
                }
                map[conf.CONF_PARENT_TAG].children.push(conf);
            }
            ewa._confs = map;

            let navigator = [];
            getObj('.ewa-lf-data-row').each(function() {
                let ptag = $(this).find('.ewa-col-CONF_PARENT_TAG').text();
                let tag = $(this).attr('ewa_key');
                let tr = $('<tr class="pbox-parent" id="new_' + tag + '"><td colspan=4 style="padding-left:20px"></td></tr>').insertAfter($(this));
                let conf = ewa._confs[tag];
                let box = createBox(conf)
                tr.find('td:last').append(box);

                let item = "<div><a tag='" + tag + "'>" + tag + " " + conf.CONF_MEMO + "</a></div>";
                navigator.push(item);
            });
            $('#conf_navigator').append(navigator.join(''));
            $('#conf_navigator a').on('click', function() {
                let tag = $(this).attr('tag');
                let target = $('tr[ewa_key="' + tag + '"]').position();
                $('#confs').scrollTop(target.top, 300)
            });


            for (let n in ewa._conf_dict) {
                if (n.indexOf(',name') < 0) {
                    continue;
                }

                let tags = n.split(',');
                let conf_tag = tags[0];
                let para_name = tags[1];

                let arr = ewa._conf_dict[n];

                let btnAdd = $('.add.tag-' + conf_tag);
                let parent = btnAdd.parentsUntil('.pbox').last().parent().parent();
                let i = 0;
                arr.map(v => {
                    if (i > 0) {
                        btnAdd.trigger('click');
                    }
                    i++;
                    let jq = 'input[name="' + para_name + '"]:last';
                    let ipt = parent.find(jq);
                    ipt.val(v.DICT_NAME);
                    ipt.parent().next().text(v.DICT_MEMO)
                });

            }

        });
    }

    function exportConf() {
        xml = new EWA_XmlClass();
        xml.LoadXml('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><ewa_confs />');

        let root = xml.XmlDoc.children[0];

        $('.pbox-parent').each(function() {
            $(this).find('.pbox:eq(0)').each(function() {
                exportConfOne(this, root, xml);
            });
        });

        let xmlCode = xml.GetXml();
        let xmlCodeTxt = $('#xmlCodeTxt');
        if (xmlCodeTxt.length == 0) {
            xmlCodeTxt = $('<textarea style="display:none" id=xmlCodeTxt></textarea>');
            $('body').append(xmlCodeTxt);
        }
        xmlCodeTxt.val(xmlCode);
        let url = '/EmpScriptV2/EWA_STYLE/editor/CodeMirror/index.html?__TYPE__=xml&__SID__=xmlCodeTxt';
        let height = document.documentElement.clientHeight - 88;
        dia = $Dialog(url, 'ewa_conf.xml', 1000, height, true, function() {
            let w = dia.getContent().getElementsByTagName('iframe')[0].contentWindow;

            w.beautify_code();
            w.editor.setFontSize(14.3);

            var blob = new Blob([w.editor.getValue()], {
                type: "text/xml"
            });

            let btnSave = w.$('<div><a>Download</a></div>');
            btnSave.css({
                'position': 'fixed',
                'left': 0,
                'right': 0,
                'bottom': 0,
                'background': '#fff',
                'height': 30,
                'z-index': 123,
                'display': 'flex',
                'align-items': 'center',
                'justify-content': 'center'
            });
            btnSave.find('a').css({
                'line-height': '26px',
                'font-size': 14.1
            }).attr({
                'download': 'ewa_conf.xml',
                'href': URL.createObjectURL(blob)
            });
            w.$('body').append(btnSave);
            w.$('#code').css('bottom', 30);

            console.log(1)
        });
    }

    function exportConfOne(tb, parent, xml) {
        let obj = $(tb);
        let name = obj.attr('name');
        let conf = ewa._confs[name];
        let comment = xml.XmlDoc.createComment(conf.CONF_MEMO);
        parent.appendChild(comment);
        let chd = xml.NewChild(name, parent);
        let tb1 = obj[0];
        for (let i = 0; i < tb1.rows.length; i++) {
            let tr = tb1.rows[i];
            let isSub = false;
            if (i === tb1.rows.length - 1) {
                let subTb = $(tr).find('.pbox:eq(0)');
                if (subTb.length > 0) {
                    isSub = true;
                    exportConfOne(subTb, chd, xml);
                }
            }
            if (!isSub) {
                let ipx = $(tr).find('input');
                if (ipx.length > 0) {
                    let name = ipx.attr('name');
                    let val = ipx.val();
                    chd.setAttribute(name.trim(), ipx.val());
                }
            }
        }
    }

    // 执行刷新后事件
    function init() {
        loadActionJson();
        ewa.ReloadAfter();

        $('a#dspall').on('click', function() {
            $('tr.pbox-parent').show();
        });
        $('a#hidall').on('click', function() {
            $('tr.pbox-parent').hide();
        });

        $('a#export').on('click', function() {
            exportConf();
        });
    }
    init();
})();