(function() {
    window.CDocsTable = getDocsTable();

    function getDocsTable () {
        function DocsTable (params) {
            this.data = params.docs;
            this.target = params.target;
            this.Table = null;
        }

        DocsTable.prototype = {
            init: function () {
                this.Table = this._render(
                    this.target, 
                    this._getGridOptions({
                        data: this.data
                    })
                );
            },
            update: function (newData) {
                this.Table.gridOptions.api.setRowData(newData);
            },
            updateDoc: function (doc) {
                const rowData = [];

                this.Table.gridOptions.api.forEachNode(function (node) {
                    var data = node.data;
                    if (doc.id === data.id) {
                        data.__params = doc;
                    }
                    rowData.push(data);
                });

                this.update(rowData);
            },

            /**
             * @private _getGridOptions
             * @param {Object} params 
             * @returns {Object}
             */
            _getGridOptions: function (params) {
                var self = this;
                var options = {
                    rowData: [],
                    columnDefs: this._getHead(),
                    defaultColDef: {
                        flex: 1
                    },
                    components: {
                        didoxCellRender: getDidoxCellRenderer()
                    },
                    onCellClicked: this._onCellClick.bind(this),
                    localeText: this.getGridLocal()
                };

                options.rowData = this._setRowData(params.data);

                return options;
            },

            _onCellClick: function (params) { 
                if (params.colDef.field !== 'didox') {
                    return null;
                }
                var doc = this.getDoc(params);
                var target = params.event.target;
                var $target = $(target);
                var action = $target.attr('doc-action');

                switch (action) {
                    case 'create':
                        if (!App.isDocCreated(doc)) {
                            this._createDoc(doc);
                        } 
                        return;
                    case 'sign':
                        if (!App.isDocSign(doc)) {
                            this._signDoc(doc);
                        }
                        return;
                    case 'delete':
                        var type = $target.attr('data-delete');

                        if (App.getDiDocId(doc)) {
                            switch (type) {
                                case 'indraft':
                                    this._delteDraftDoc(doc);
                                    break;
                                case 'sign':
                                    this._deleteDoc(doc);
                                    break;
                            }
                        }
                        
                        return;
                }
            },

            _createDoc: function (doc) {
                var self = this;

                DocSign.createDoc(doc, function (diDoc) {
                    var id = diDoc._id;
                    var valuse = {};

                    valuse[App.getB24DocId()] = id;

                    App.setBxDocValues(doc, valuse, function (res) {
                        self.updateDoc(res.document);
                    }, function (er) {
                        App.showMessage(er);
                    });
                });
            },
            _signDoc: function (doc) {
                var self = this;

                DocSign.signDoc(App.getDiDocId(doc), function (diDoc) {
                    var valuse = {};

                    valuse[App.getB24DicSign()] = 1;

                    App.setBxDocValues(doc, valuse, function (res) {
                        App.addActivity(doc, App.getDocSignText(doc), function () {
                            self.updateDoc(res.document);
                        });
                    }, function (er) {
                        App.showMessage(er);
                    });
                }, function (error) {
                    var valuse = {};

                    valuse[App.getB24DicSign()] = 0;

                    App.setBxDocValues(doc, valuse, function (res) {
                        App.addActivity(doc, App.getDocSignText(doc), function () {
                            self.updateDoc(res.document);
                        });
                    }, function (er) {
                        App.showMessage(er);
                    });
                });
            },
            _deleteDoc: function (doc) {
                var id = App.getDiDocId(doc), self = this;

                DocSign.deleteDoc(id, function (res) {
                    var values = {};

                    values[App.getB24DocId()] = '';
                    values[App.getB24DicSign()] = '';

                    App.setBxDocValues(doc, values, function (res) {
                        App.addActivity(doc, App.getDocSignRemoveText(doc), function () {
                            App.showMessage('Удалено');
                            self.updateDoc(res.document);
                        });
                    }, function (er) {
                        App.showMessage(er);
                    });
                }, function (er) {
                    App.showMessage('При удалении возникла ошибка');
                });
            },
            _delteDraftDoc: function (doc) {
                var id = App.getDiDocId(doc), self = this;

                DocSign.deleteDraftDoc(id, function (res) {
                    var values = {};

                    values[App.getB24DocId()] = '';
                    values[App.getB24DicSign()] = '';

                    App.setBxDocValues(doc, values, function (res) {
                        App.showMessage('Удалено');
                        self.updateDoc(res.document);
                    });
                }, function (er) {
                    App.showMessage('При удалении возникла ошибка');
                });
            },

            getGridLocal: function () {
                return {
                    noRowsToShow: 'Документы не найдены'
                }
            },

            /**
             * @private _render
             * @param {String} target 
             * @param {Object} options 
             * @returns {Class}
             */
            _render: function (target, options) {
                // create the grid passing in the div to use together with the columns & data we want to use
                return new agGrid.Grid(document.querySelector(target), options);
            },

            /**
             * @private _getHead
             * @returns {Array}
             */
            _getHead: function () {
                return [
                    {
                        headerName: 'ID',
                        field: 'id',
                        width: 102,
                        flex: undefined
                    },
                    {
                        headerName: 'Имя',
                        field: 'name',
                    },
                    {
                        headerName: 'Дата',
                        field: 'date',
                    },
                    {
                        headerName: ' ',
                        field: 'didox',
                        cellRendererSelector: (params) => ({
                            component: 'didoxCellRender',
                        }),
                        cellRendererParams: {
                            label: 'Click'
                        }
                    },
                ];
            },

            /**
             * @private _setRowData
             * @param {Array} arr 
             * @returns {Array}
             */
            _setRowData: function (arr) {
                return arr.map(function (data, index) {
                    return {
                        index: index+1,
                        name: data.title,
                        date: moment(data.createTime).format(App.uiGetFullDate()),
                        id: data.id,
                        didox: '',
                        __params: data
                    };
                });
            },

            getDoc: function (cellParams) {
                return cellParams.data.__params;
            }
        }

        return DocsTable;
    }

    function getDidoxCellRenderer () {

        function DidoxCellRender () {
            this.el;

            this.createDocText = 'Отправить в черновики';
            this.signDocText = 'Подписать с ЭЦП';
            this.removeDocText = 'Удалить';
            this.signedDocText = 'Подписано';
        }

        DidoxCellRender.prototype = {
            init: function (params) {
                this.el = this.getTemplate(params);
            },

            getTemplate: function (params) {
                var doc = params.data.__params;
                var el = document.createElement('div');
                var s =  document.createElement('span');
                s.className = 'mx-2';
                s.innerText = '/';
                
                if (App.isDocCreated(doc)) {
                    if (App.isDocSign(doc)) {
                        $(el).append([
                            '<span class="text-green-600">'+this.signedDocText+'</span>',
                            s,
                            this.delteDocBtn('sign')
                        ]);
                    } else {
                        $(el).append([
                            this.signDocBtn(),
                            s,
                            this.delteDocBtn('indraft')
                        ]);
                    }
                } else {
                    el.appendChild(
                        this.createDocBtn()
                    );
                }
                
                return el;
            },

            createDocBtn: function (btn) {
                var btn = this._createBtn({
                    class: 'text-blue-',
                    text: this.createDocText,
                    attr: {
                        'doc-action': 'create'
                    }
                });

                return btn;
            },
            signDocBtn: function () {
                var btn = this._createBtn({
                    class: 'text-blue-600',
                    text: this.signDocText,
                    attr: {
                        'doc-action': 'sign'
                    }
                });

                return btn;
            },
            delteDocBtn: function (type) {
                var btn = this._createBtn({
                    class: 'text-red-600',
                    text: this.removeDocText,
                    attr: {
                        'doc-action': 'delete',
                        'data-delete': type
                    },
                });

                return btn;
            },

            _createBtn: function (params) {
                var btn = document.createElement('button');
                btn.type = 'button';
                btn.className = params.class;
                btn.innerText = params.text;

                if (params.attr) {
                    Object.keys(params.attr).forEach(function (attr) {
                        var attrVal = params.attr[attr];
                        btn.setAttribute(attr, attrVal);
                    });
                }

                return btn;
            },

            getGui: function () {
                return this.el;
            }
        }

        return DidoxCellRender;
    }
})()