{% load i18n %}
{% load admin_urls static admin_list simpletags %}
<div class="actions">

    <input type="hidden" name="action" value=""/>

    {% if has_add_permission %}
        {% url cl.opts|admin_urlname:'add' as add_url %}

        <el-button size="small" type="primary" icon="el-icon-plus" data-name="add_item"
                   url="{% add_preserved_filters add_url is_popup to_field %}">
            {% trans 'Add' %}
        </el-button>
    {% endif %}

    {% for field in action_form.fields.action.choices %}
        {% if field.0 %}

            {% if field.0 == 'delete_selected' %}
                <el-button size="small" type="danger" data-name="{{ field.0 }}" class="stop-submit"
                           icon="el-icon-delete" @click="delSelected('{{ field.0 }}')">{% trans 'Delete' %}</el-button>
                <input type="hidden" name="select_across" v-model="select_across" value="0" class="select-across">
            {% else %}
                <input type="hidden" name="select_across" v-model="select_across" value="0" class="select-across">
                <input type="hidden" name="file_format" v-model="file_format">
                {% if field.0 == 'export_admin_action' %}
                    <el-select size="small" filterable v-model="file_format" style="width: 80px;">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <el-button size="small" icon="fas fa-download" data-name="{{ field.0 }}">{{ field.1 }}</el-button>
                {% else %}

                    <el-button v-if="customButton.{{ field.0 }}.layer" size="small"
                               :eid="customButton.{{ field.0 }}.eid"
                               :icon="customButton.{{ field.0 }}.icon" :style="customButton.{{ field.0 }}.style"
                               :type="customButton.{{ field.0 }}.type" data-name="{{ field.0 }}">{{ field.1 }}
                    </el-button>
                    <el-button v-else size="small" :eid="customButton.{{ field.0 }}.eid"
                               :icon="customButton.{{ field.0 }}.icon" :style="customButton.{{ field.0 }}.style"
                               :confirm="customButton.{{ field.0 }}.confirm"
                               :type="customButton.{{ field.0 }}.type" data-name="{{ field.0 }}">{{ field.1 }}
                    </el-button>
                {% endif %}
            {% endif %}
        {% endif %}
    {% endfor %}

    {% if cl.formset and cl.result_count %}
        <input type="hidden" name="_save" value="{% trans 'Save' %}"/>
        <el-button size="small" icon="el-icon-circle-check" type="success"
                   @click="formSubmit()">{% trans 'Save' %}</el-button>
    {% endif %}

    <el-button size="small" data-name="import_admin_action" v-for="item in exts" :key="item.name"
               @click="extClick(item)">
        <span :class="getIcon(item.name)"></span>
        <span v-text="item.name"></span>
    </el-button>

    {% block actions-counter %}
        {% if actions_selection_counter %}
            <span class="action-counter" data-actions-icnt="{{ cl.result_list|length }}">{{ selection_note }}</span>
            {% if cl.result_count != cl.result_list|length %}
                <span class="all">{{ selection_note_all }}</span>
                <span class="question">
            <a href="#"
               onclick="selectAll()"
               title="{% trans "Click here to select the objects across all pages" %}">{% blocktrans with cl.result_count as total_count %}Select all {{ total_count }} {{ module_name }}{% endblocktrans %}</a>
        </span>
                <span class="clear">
            <a href="#" onclick="unSelect()">{% trans "Clear selection" %}</a>
        </span>
            {% endif %}
        {% endif %}
    {% endblock %}

    <el-button-group size="small" class="btn-group">
        {% if cl.search_fields or cl.has_filters %}
            <a href="javascript:;" @click="searchDisplay()" class="el-button el-button--default el-button--small"><span
                    class="el-icon-search"></span></a>
        {% endif %}
        <a href="javascript:;" @click="reload()" class="el-button el-button--default el-button--small"><span
                class="el-icon-refresh"></span></a>
        <a href="javascript:;" @click="openNewPage()" class="el-button el-button--default el-button--small"><span
                class="el-icon-news"></span></a>

    </el-button-group>

</div>
<div id="layer_app">
    <el-dialog
            :title="title"
            :visible.sync="visible"
            :width="layer.width||'50%'">
        <el-alert v-if="layer.tips" :title="layer.tips" type="success" :closable="false"></el-alert>
        <el-form ref="form" :model="params" :label-width="layer.labelWidth||'80px'" size="small">
            <el-form-item v-for="item in params" :label="item.label"
                          :rules="[{ required: item.require||false, trigger: 'blur' }]">
                <el-select v-if="item.type=='select'" :style="{width:item.width}" :size="item.size"
                           v-model="item.value">
                    <el-option
                            v-for="node in item.options"
                            :key="node.key"
                            :label="node.label"
                            :value="node.key">
                    </el-option>
                </el-select>

                <el-date-picker
                        v-else-if="item.type=='date'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value"
                        type="date">
                </el-date-picker>

                <el-date-picker
                        v-else-if="item.type=='datetime'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value"
                        type="datetime">
                </el-date-picker>

                <el-rate
                        v-else-if="item.type=='rate'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value">
                </el-rate>
                <el-color-picker
                        v-else-if="item.type=='color'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value">
                </el-color-picker>
                <el-slider
                        v-else-if="item.type=='slider'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value">
                </el-slider>
                <el-switch
                        v-else-if="item.type=='switch'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value">
                </el-switch>
                <el-input-number
                        v-else-if="item.type=='input_number'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value">
                </el-input-number>

                <el-checkbox-group
                        v-else-if="item.type=='checkbox'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value">

                    <el-checkbox v-for="node in item.options" v-model="node.key" :label="node.label"
                                 :key="node.key"></el-checkbox>

                </el-checkbox-group>

                <el-radio-group
                        v-else-if="item.type=='radio'"
                        :style="{width:item.width}"
                        :size="item.size"
                        v-model="item.value">

                    <el-radio v-for="node in item.options" v-model="node.key" :label="node.label"
                              :key="node.key"></el-radio>

                </el-radio-group>

                <input v-else-if="item.type=='file'" type="file" :ref="item.key"/>

                <el-input v-else v-model="item.value" :type="item.type" :style="{width:item.width}"
                          :size="item.size"></el-input>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="layerSubmit()" v-text="layer.confirm_button||'确定'"></el-button>
            <el-button @click="visible = false" v-text="layer.cancel_button||'取消'"></el-button>
        </span>
    </el-dialog>
</div>
<script type="text/javascript" src="{% static 'admin/simpleui-x/automatic/dicts.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/simpleui-x/automatic/segment.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/simpleui-x/js/axios.min.js' %}"></script>
<script type="text/javascript">

    const layerApp = new Vue({
        el: '#layer_app',
        data: {
            visible: false,
            title: '弹出层',
            params: [],
            layer: {},
            rules: [],
            action: ''
        },
        methods: {
            layerSubmit() {
                const self = this;
                //校验
                for (let key in self.params) {
                    let item = self.params[key];
                    if (item.require) {
                        if (!item.value || item.value == '' || item.length == 0) {
                            self.$message.error(`"${item.label}" Can't be empty.`)
                            return;
                        }
                    }
                }

                //开始提交
                let data = new FormData();
                //方法名
                data.append('_action', self.action);
                let selecteds = [];
                $("#result_list .selected input[name='_selected_action']").each((index, item) => selecteds.push(item.value));
                data.append('_selected', selecteds.join(','));
                data.append('select_across',document.querySelector("input[name='select_across']").value)
                //获取选中的数据

                data.append('csrfmiddlewaretoken', document.querySelector('[name="csrfmiddlewaretoken"]').value);
                for (let key in self.params) {
                    let item = self.params[key];
                    if (item.type === "file") {
                        data.append(item.key, self.$refs[item.key][0].files[0]);
                    } else if (item.value) {
                        data.append(item.key, item.value);
                    }
                }

                axios.post('{% get_model_ajax_url %}', data).then(res => {
                    if (res.data.status == 'success') {
                        self.visible = false;
                        //1.5s 后刷新
                        setTimeout(() => window.location.reload(), 1000);
                    }
                    self.$message({
                        message: res.data.msg,
                        type: res.data.status
                    });
                }).catch(err => self.$message.error(err));
            }
        }
    })

    //弹出层处理
    function layer(data, action) {
        layerApp.layer = data.layer;
        layerApp.title = data.layer.title;
        layerApp.params = data.layer.params;
        layerApp.action = action;

        layerApp.$nextTick(() => {
            layerApp.visible = true;
        });

    }

    function actionsCleaning(name) {
        $("#changelist-form input[name='action']").val(name);
        $("#changelist-form [name='_save']").removeAttr('name');
        $("#changelist-form [name!='']").each(function () {
            var obj = $(this);
            if (obj.attr('name') && obj.attr('name').indexOf('form-') == 0) {
                obj.removeAttr('name');
            }
        });
    }

    var _action = new Vue({
        el: '.actions',
        data: {
            select_across: 0,
            file_format: 1,
            show: true,
            options: [{
                value: 0,
                label: 'csv'
            }, {
                value: 1,
                label: 'xls'
            }, {
                value: 2,
                label: 'xlsx'
            }, {
                value: 3,
                label: 'tsv'
            }, {
                value: 4,
                label: 'ods'
            }, {
                value: 5,
                label: 'json'
            }, {
                value: 6,
                label: 'yaml'
            }, {
                value: 7,
                label: 'html'
            }],
            customButton:{% autoescape off %}{% custom_button %}{% endautoescape %},
            exts: []
        },
        created() {
            if (localStorage && typeof (localStorage.searchStatus) != 'undefined') {
                this.show = localStorage.searchStatus == 'true';
            }
        },
        watch: {
            'show': function (newValue) {
                obj = document.querySelector('.xfull')
                if (!newValue) {
                    //隐藏
                    document.getElementById('toolbar').style.display = 'none';
                    if (obj) {
                        obj.style.display = 'none';
                    }
                } else {
                    //显示
                    document.getElementById('toolbar').style.display = 'inherit';
                    if (obj) {
                        obj.style.display = 'inherit';
                    }
                }
                if (localStorage) {
                    localStorage['searchStatus'] = newValue;
                }
            }
        },
        methods: {
            searchDisplay: function () {
                this.show = !this.show;
            },
            reload: function () {
                window.location.reload()
            },
            openNewPage: function () {
                window.open(window.location.href)
            },
            getIcon: getIcon,
            extClick: function (item) {
                window.location.href = item.url;
            },
            formSubmit: function () {
                $("#changelist-form").submit();
            },
            delSelected: function (name) {
                actionsCleaning(name);
                var self = this;

                // 增加非空判断！
                if ($("#changelist-form").serializeArray().length <= 2) {
                    this.$message.error(getLanuage("Please select at least one option!"));
                    return;
                }

                //#67 #66 修复删除问题，改为弹出确认

                this.$confirm(getLanuage('Are you sure you want to delete the selected?'))
                    .then(_ => {
                        self.formSubmit();
                    }).catch(_ => {

                });
            }
        }
    });

    function selectAll() {
        _action.select_across = 1;
    }

    function unSelect() {
        _action.select_across = 0;
    }


    $(function () {
        action_btns = $(".actions button").not('.stop-submit');
        action_btns.click(function () {
            var url = $(this).attr("url");
            var eid = $(this).attr('eid');
            var confirm = $(this).attr('confirm');
            var checkbox_checked = $(".action-checkbox input:checked").length;
            var data_name = $(this).attr('data-name');
            var _vue = new Vue();

            //这边处理弹出层对话框
            if (eid) {
                for (var i in _action.customButton) {
                    var temp = _action.customButton[i];
                    if (temp.eid == eid && temp.layer) {
                        layer(temp, i);
                        return;
                    }
                }
            }

            //TODO 需要做国际化
            if (checkbox_checked == 0 && data_name != "add_item" && !_action.customButton[data_name].action_url) {
                _vue.$alert(getLanuage("Please select at least one option!"), '', {
                    type: 'warning'
                })
            } else if (confirm) {
                _vue.$confirm(confirm, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => done.call(this));

            } else {
                done.call(this)
            }

            function done() {

                if (eid) {
                    for (var i in _action.customButton) {
                        var temp = _action.customButton[i];
                        if (temp.eid == eid) {
                            if (typeof (temp.action_type) != 'undefined') {

                                if (!temp.action_url) {
                                    this.$notify({
                                        title: 'error',
                                        message: 'action must contain attributes:action_url! ',
                                        type: 'error',
                                        dangerouslyUseHTMLString: true
                                    });
                                    return;
                                }

                                switch (temp.action_type) {
                                    case 0:
                                        window.location.href = temp.action_url;
                                        break;
                                    case 1:
                                        parent.window.app.openTab({
                                            url: temp.action_url,
                                            icon: temp.icon || 'fa fa-file',
                                            name: temp.short_description,
                                            breadcrumbs: []
                                        });
                                        break;
                                    case 2:
                                        window.open(temp.action_url);
                                        break;
                                }
                                console.log('中断后续操作');
                                return;
                            }
                            //终止执行
                            break;
                        }
                    }
                }
                if (url) {
                    window.location.href = url;
                    return;
                }

                if ($(this).attr('data-name')) {
                    var name = $(this).attr("data-name");
                    actionsCleaning(name);
                }
                $("#changelist-form").submit();
            }
        });
    });
</script>
