{% extends "framework/base.html" %}
{#{% load i18n %}#}
{% block header %}
    <title>{{ _('字典定义 编辑') }}</title>
{% endblock %}


{% block content %}
    <div class="row header">
        <div class="col-sm-5">
            <h1>{{ _('字典定义') }}
                <small>{{ _('编辑') }}</small>
            </h1>
        </div>
    </div>

    <hr><br>

    <form action="/log_def/dict_define/save?{% if data.id %}id={{ data.id }}{% endif %}{% if request.query_params.is_copy %}&is_copy=1{% endif %}"
          method="POST"
          class="form-horizontal"
          role="form">
        <div class="row edit-container">
            <div class="col-sm-12">
                {{ csrf_input }}


                <div class="form-group" style="display:none">
                    <label class="col-sm-3 control-label no-padding-right" for="id_id">

                        {{ _('id') }} </label>

                    <div class="col-sm-8">
                        <input type="number" id="id_id" name="id"
                               class="form-control" value="{{ data.id  or "" }}"


                        >


                    </div>
                </div>


                <div class="form-group" style="">
                    <label class="col-sm-3 control-label no-padding-right" for="id_name">
                        <span class="text-danger">*</span>
                        {{ _('字典名') }} </label>

                    <div class="col-sm-8">
                        <input type="text" id="id_name" name="name"
                               class="form-control" value="{{ data.name  or "" }}"
                               maxlength=100
                               required=true
                        >


                    </div>
                </div>


                <div class="form-group" style="">
                    <label class="col-sm-3 control-label no-padding-right" for="id_key">
                        <span class="text-danger">*</span>
                        {{ _('标识名') }} </label>

                    <div class="col-sm-8">
                        <input type="text" id="id_key" name="key"
                               class="form-control" value="{{ data.key  or "" }}"
                               maxlength=50
                               required=true
                        >


                    </div>
                </div>


                <div class="form-group" style="">
                    <label class="col-sm-3 control-label no-padding-right" for="id_group">

                        {{ _('组') }} </label>

                    <div class="col-sm-8">
                        <input type="text" id="id_group" name="group"
                               class="form-control" value="{{ data.group  or "" }}"
                               maxlength=50

                        >

                    </div>
                </div>
                <div class="form-group" style="">
                    <label class="col-sm-3 control-label no-padding-right" for="id_remark">
                        <span class="text-danger">*</span>
                        {{ _('备注') }} </label>

                    <div class="col-sm-8">

                        <textarea type="text" id="id_remark" name="remark"
                                  class="form-control"
                                  maxlength=400
                                  required=true
                        >{{ data.remark  or "" }}</textarea>


                    </div>
                </div>

                <div class="form-group" style="">
                    <label class="col-sm-3 control-label no-padding-right" for="id_type">

                        {{ _('字典的类型') }} </label>

                    <div class="col-sm-8">
                        <select class="form-control col-lg-5 select2"
                                id="id_type"
                                data-placeholder="{{ _('字典的类型') }}"
                                name="type"
                                svalue="{{ data.type }}">
                            {% for o in data.serializer.instance.SELECT_CHOICES %}
                                <option value="{{ o.0 }}" data-default-json='{{ o.2 }}'>{{ o.1 }}</option>
                            {% endfor %}
                        </select>

                        <a id="quick_add" class="" href="javascript:void(0)">[快速添加]</a>
                    </div>
                </div>

                <div class="form-group" style="">
                    <label class="col-sm-3 control-label no-padding-right" for="id_remark">
                        <span class="text-danger">*</span>
                        {{ _('键值') }} </label>

                    <div class="col-sm-8">

                        <textarea type="text" id="id_dict" name="dict"
                                  class="form-control"
                                  maxlength=400
                                  required=true
                        >{{ data.json_dict }}</textarea>

                    </div>

                </div>
                <div class="form-group" style="">
                    <label class="col-sm-3 control-label no-padding-right">
                        <span class="text-danger">*</span>
                        {{ _('帮助') }} </label>

                    <div class="col-sm-8">
                                        <pre>

 图片键值：
        例如：img_path_format：showGirlWholeBody/sg___key__.png
        图片路径：/static/img/showGirlWholeBody/sg_1000.png
                </pre>

                    </div>

                </div>


            </div>
        </div>


        <div class="row pane edit-save-bar">
            <div class="col-sm-offset-3 col-sm-3">
                <input id="reset-btn" class="btn btn-default" type="reset" value="{{ _('重 置') }}">
                <button id="save-btn" class="btn btn-primary " type="button">
                    {{ _('保 存') }}
                </button>

            </div>
            <div class="col-sm-6">
                <div class="pull-right">
                    <button id="save-edit-btn" class="btn btn-info " type="button">
                        {{ _('保存并继续编辑') }}
                    </button>
                    <button id="save-add-btn" class="btn btn-info " type="button">
                        {{ _('保存并增加另一个') }}
                    </button>
                </div>
            </div>
        </div>


    </form>
    <div id="quick_div" style="display:none">
        每行以逗号或空格分割项目编号
        <label><input type="checkbox" id="key_in_left">右边为key *通常为id</label>
        <hr>
        <textarea id="quick_textarea" style="height:300px;width: 100%"></textarea>
        <hr>
        <input id="quick_btn_save" type="button" class="btn btn-sm btn-primary" value="确定">
        <label><input type="checkbox" id="quick_append" checked="checked">追加</label>
    </div>


    <script>

        function text_split_to_json(text, k_index) {
//字符串转json
            var lines = text.split(/\n/)
            var _dict = {}
            k_index = k_index ? 1 : 0
            var v_index = k_index == 0 ? 1 : 0
            // console.dir([k_index,v_index])
            for (var i in lines) {
                var line = lines[i]
                var fields = line.split(/[,\t ]+/)
                if (fields.length >= 2) {
                    _dict[fields[k_index]] = fields[v_index]
                }
            }
            //console.dir(_dict)
            return _dict
        }


        function Dict_Editor(textarea_obj) {
            var This = this
            var textarea_obj = textarea_obj
            var container = textarea_obj.parent()
            this.is_textarea_hide = false
            this.textarea_obj = textarea_obj
            $("#quick_add").after($('<a>', {
                'html': '[ 转换 ]',
                'style': "margin-left:10px; color:red;",
                'href': "javascript:void(0)",
                click: function () {
                    This.toggle()

                }
            }))
            this.show_input = function () {
                This.to_inputs()
                This.is_textarea_hide = true
                textarea_obj.hide()
            }

            this.hide_input = function () {
                var div_cont = textarea_obj.nextAll('div')
                This.to_dict(div_cont)
                This.is_textarea_hide = false
                textarea_obj.show()
                div_cont.remove()
            }

            this.toggle = function () {//转换
                if (This.is_textarea_hide) {
                    This.hide_input()

                } else {
                    This.show_input()

                }
            }

            this.to_dict = function (div_cont) {
                var _dict = {}
                div_cont.find('div').each(function (i, ele) {
                    var _k_v = $(this).find(':text')
                    if (_k_v[0].value) {
                        _dict[_k_v[0].value] = _k_v[1].value
                    }
                })
                textarea_obj.val(JSON.stringify(_dict))

            }

            this.to_inputs = function () {//json转为输入框
                var _dict = $.parseJSON(textarea_obj.val() || '{}')
                _dict = $.isEmptyObject(_dict) ? {"": ""} : _dict
                textarea_obj.nextAll('div').remove()

                var _inputs_div = $('<div>')

                for (var i in _dict) {
                    _inputs_div.append(This._make_div_input(i, _dict[i]))
                }

                _inputs_div.append($('<a>', {
                    "html": "增加", "href": "javascript:void(0)","class":"btn btn-xs btn-primary", click: function () {
                        $(this).before(This._make_div_input("", ""))
                    }
                }))
                /*
                _inputs_div.append($('<a>',{"html":"转换","href":"javascript:void(0)","style":"float:right",click:function(){
                   This.toggle()
                }}))
                */
                container.append(_inputs_div)

            }

            this._make_div_input = function (key, value) {
                var _div = $('<div class="form-inline">')
                _div.append('  键:  ')
                _div.append($(' <input>', {type: "text", val: key, name: "key",class:"form-control"}))
                _div.append('  值:  ')
                _div.append($(' <input>', {type: "text", val: value, name: "value",class:"form-control"}))
                _div.append($('<a>', {
                    html: "  x  ", href: "javascript:void(0)", click: function () {
                        _div.remove()
                    }
                }))
                return _div
            }
        }


        $('#quick_add').click(function () {
            $('#quick_textarea').val('')
            $('#quick_div').dialog({"title": "快速添加", "top": "25%"})

        })

        //快速输入
        $('#quick_btn_save').click(function () {
            var dict_container = $('[name="dict"]')
            var dict_input = text_split_to_json($('#quick_textarea').val(), $('#key_in_left').is(':checked'))
            var _dict = {}
            if ($('#quick_append').attr("checked")) {//如果是追加
                var source_dict = JSON.parse(dict_container.val())
                _dict = $.extend(source_dict, dict_input)
            } else {
                _dict = dict_input
            }

            dict_container.val(JSON.stringify(_dict))

        })

        //-----------------------------------
        var dict_editor = new Dict_Editor($('[name="dict"]'))

        var textarea_obj = dict_editor.textarea_obj

        $('[name="type"]').change(function () {

            switch (parseInt(this.value)) {

                case 1:
                    if (!confirm('确定切换到数据表？')) {
                        return false
                    }
                    ;
                    break;
                case 2:
                    if (!confirm('确定切换到文件？')) {
                        return false
                    }
                    ;

                    break;
                case 3:
                    if (!confirm('确定切换到目录？')) {
                        return false
                    }
                    ;

                    break;

                default:

                    break
            }


            if (this.value != '0') {
                console.dir(this[this.value])
                var table_dict = $(this[this.value]).attr('data-default-json')
                textarea_obj.val(table_dict)
                dict_editor.show_input()
            }

        })


    </script>

    <script>
        var $form = $('form')
        $form.submit(function (e) {
            stopEevent(e)
            return false
        })

        function ajaxPostData(ele, callback) {
            if (dict_editor.is_textarea_hide) {
                dict_editor.toggle()
            }
            clearHelpText()
            $(ele).attr("disabled", true);
            $.ajax({
                async: true,
                type: "POST",
                url: $form.attr('action'),
                dataType: 'json',
                data: JSON.stringify($form.serializeToJSON()),
                contentType: 'application/json',
                success: function (rsp) {
                    if (rsp.code == 0) {
                        $('[name="id"]').val(rsp.data.id)
                        art.dialog(rsp.msg).time(1)
                        clearHelpText()
                        callback ? callback(rsp) : null
                    } else {
                        rsp.data ? addHelpText(rsp.data) : alertMsg(rsp.msg)
                    }
                },
                error: function (jqXHR, statusText, errorMsg) {
                    ajaxError(jqXHR, statusText, errorMsg)

                },
                complete: function (jqXHR, statusText) {
                    $(ele).removeAttr("disabled");
                }

            })
        }

        $('#save-add-btn').click(function () {
            ajaxPostData(this, function (rsp) {
                if (rsp.code == 0) {
                    window.location.href = window.location.pathname
                }
            })
        })

        $('#save-edit-btn').click(function () {
            ajaxPostData(this, function (rsp) {
                $form.attr('action', '/log_def/dict_define/save?id=' + rsp.data.id)
                refreshParentTable()

            })
        })

        $('#save-btn').click(function () {
            ajaxPostData(this, function (rsp) {
                refreshParentTable()
                closeSelfDialog()
            })
        })

    </script>
{% endblock %}
