{% block component %}
{{ name }} = {
    template: "#{{ name }}",
    router_path: "/{{ name }}",
    delimiters: ["[[", "]]"],
    props: {
        items: Array,
        items_headers: Array,
        items_relations: {
            default: function () {
                return {}
            },
        },
        group_by: String,
        hidden_fields: {
            default: function () {
                return []
            },
        },
        non_editable_fields: {
            default: function () {
                return []
            },
        },
        show_item: {
            default: "id",
        },
        show_url: {
            default: "{{ show_url|default:'' }}",
        },
    },

    data: function() {
        return {
            valid: false,
            dialog: false,
            dialogDelete: false,
            defaultItem: {},
            editedItem: {},
            search: null,
            default_hidden_fields: [{% for field in default_hidden_fields %}"{{ field }}",{% endfor %}],
            rules: {
                required: value => !!value || "{{_('Required') | escapejs}}",
            },
        }
    },

    computed: {
        editable_fields: function() {
            return this.items_headers.filter(e => e.editable).filter(e => !this.non_editable_fields.includes(e.value))
        },

        citems_headers: function() {
            return this.items_headers.filter(e => !this.hidden_fields.includes(e.value) && !this.default_hidden_fields.includes(e.value))
        },
    },

    watch: {
        dialog (val) {
            val || this.close()
        },
        dialogDelete (val) {
            val || this.closeDelete()
        },
    },

    methods: {

        formatDate (date) {
            return formatDate(date)
        },

        showItem (item) {
            this.$router.push({ name: this.show_url, params: { id: item[this.show_item] }})
        },

        editItem (item) {
            this.editedItem = Object.assign({}, item)
            this.dialog = true
        },

        deleteItem (item) {
            this.editedItem = Object.assign({}, item)
            this.dialogDelete = true
        },

        deleteItemConfirm () {
            this.$emit("deleteItem", this.editedItem)
            this.closeDelete()

        },

        close () {
            this.dialog = false
            this.editedItem = Object.assign({}, this.defaultItem)
        },

        closeDelete () {
            this.dialogDelete = false
            this.editedItem = Object.assign({}, this.defaultItem)
        },


        save () {

            const isValid = this.$refs.form.validate()
            if (!isValid) return

            if (this.editedItem.id == null) {

                this.$emit("createItem", this.editedItem)

            } else {

                this.$emit("editItem", this.editedItem)

            }

            this.close()
        },
    }
}

{% endblock %}
