'use strict';
angular.module('company-list', [])

    .controller('CompanyList', [
        '$scope', '$state', 'AppUtil', 'APIName', '$', 'session', '$compile', 'checkbox', 'util', '$q', "sortPage", "app",
        function ($scope, $state, AppUtil, APIName, $, session, $compile, checkbox, util, $q, sortPage, app) {

            $scope.sessionToken = session.getToken();

            // Create params for project list
            function makeParam(data) {
                var sortField;
                switch (data.order[0].column) {
                    case 1:
                        sortField = "name";
                        break;
                    case 2:
                        sortField = "createDate";
                        break;
                    default:
                        sortField = "createDate";
                        break;
                }
                return {
                    search_key: data.search.value.trim(),
                    page_size: data.length,
                    page_number: data.start / data.length + 1,
                    asc_sort: data.order[0].dir === 'asc',
                    sort_field: sortField
                };

            }

            // Datatable obj
            $scope.table;

            // Selected items
            $scope.selectedItems = [];

            var companyPagingSettings = JSON.parse(localStorage.getItem(sortPage.COMPANY_LIST));
            if (!companyPagingSettings) {
                companyPagingSettings = {
                    search_key: "",
                    page_size: app.LIST_PAGE_SIZE,
                    page_number: 1,
                    display_start: 0,
                    sort_key: 2,
                    asc_sort: false
                }
            }

            function convertSortField(sortKey) {
                var sortField;
                switch (sortKey) {
                    case 1:
                        sortField = "name";
                        break;
                    case 2:
                        sortField = "createDate";
                        break;
                    default:
                        sortField = "createDate";
                        break;
                }
                return sortField;
            }

            // Datatable options
            $scope.opts = {
                "order": [
                    companyPagingSettings.sort_key,
                    companyPagingSettings.asc_sort ? "asc" : "desc"
                ],
                "search": {
                    "search": companyPagingSettings.search_key
                },
                pageLength: companyPagingSettings.page_size,
                displayStart: companyPagingSettings.display_start,
                "ajax": function (data, callback) {

                    var objUrl = {
                        method: APIName.GET_COMPANY_LIST.method,
                        url: APIName.GET_COMPANY_LIST.name
                    };

                    var storeParams = {
                        search_key: "",
                        page_size: data.length,
                        display_start: 0,
                        sort_key: data.order[0].column,
                        page_number: data.start / data.length + 1,
                        asc_sort: data.order[0].dir === "asc"
                    };

                    var params = {
                        search_key: data.search.value.trim(),
                        page_size: data.length,
                        page_number: data.start / data.length + 1,
                        sort_field: convertSortField(data.order[0].column),
                        asc_sort: data.order[0].dir === "asc"
                    };

                    AppUtil.createRequest(objUrl, params, function (res) {

                        var json = {
                            "recordsTotal": res.data.total_elements,
                            "recordsFiltered": res.data.total_elements,
                            "data": []
                        };

                        localStorage.setItem(sortPage.COMPANY_LIST, JSON.stringify(storeParams));

                        $.each(res.data.content, function (key, value) {
                            var status = "";
                            if (value.status === 1) {
                                status = util.translate("status.team.active");
                            }

                            json.data.push({
                                company_id: value.id,
                                company_name: value.name,
                                created_date: value.create_date,
                                status: status
                            });
                        });
                        // Insert value
                        callback(json);

                        // $('input:checkbox[role=parent-checkbox]').prop('checked', false).trigger('tblUpdateCheckbox');
                    });
                },
                "rowCallback": function (row, data) {
                    $("td:eq(0)", row).addClass("text-center").html("<input icheck-table type='checkbox' class='icheckbox' role='child-checkbox' id='" + data.company_id + "'>");
                    $("td:eq(1)", row).html("<a href='#/super-admin/company-profile/" + data.company_id + "' class='name' ng-click='removeTab()'><div class='ellipsis' mytip='" + data.company_name + "' mytip-placement='top-left' mytip-show-when = '200'>" + data.company_name + "</div></a>");
                    $("td:eq(2)", row).html("<div>" + util.formatDateBasedOnDiff(data.created_date, "", session.getCurrentLanguage(), session.getUser().time_zone) + "</div>");
                    $("td:eq(3)", row).html("<span class='label label-success'>" + data.status + "</span>");

                    // Custom add more pro
                    // TODO
                    row.ondblclick = function () {
                        $state.go("companyProfile", {id: data.company_id});
                        $scope.$apply();
                    };
                },
                "drawCallback": function (s) {
                    // We should use directive to change data & bind event
                    checkbox.bindCheck(s.nTable, function (array) {

                        // We can get the list after items have been checked
                        $scope.selectedItems = array;

                        // Let it knows
                        $scope.$digest();
                    });

                    // Using compile service
                    $compile(s.nTBody)($scope);
                },
                "columns": [
                    {"data": "company_id"},
                    {"data": "company_name"},
                    {"data": "created_date"},
                    {"data": "status"}
                ],
                "columnDefs": [
                    {
                        'orderable': false,
                        'targets': [0, 3]
                    }
                ]
            };

            $scope.removeTab = function () {
                localStorage.removeItem("tabsAdmin");
            };

            // Show confim remove
            $scope.confirmDelete = function () {

                // Show modal
                AppUtil.confirm({
                    title: util.translate("message.team.title"),
                    message: util.translate("message.team.content"),
                    buttons: [{
                        label: util.translate("button.cancel"),
                        cssClass: 'btn btn-warning',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: util.translate("button.ok"),
                        cssClass: 'btn btn-primary',
                        action: function (dialog) {
                            // Do delete
                            doDeleteTeam();
                            dialog.close();
                        }
                    }]
                });
            };

            // Do delete
            function doDeleteTeam() {

                var items = $scope.selectedItems;

                if (items.length === 0)
                    return;

                var reqs = [];
                items.forEach(function (item) {
                    var params = {company_id: item};
                    var objUrl = {
                        method: APIName.ADMIN_DEACTIVE_COMPANY.method,
                        name: APIName.ADMIN_DEACTIVE_COMPANY.name
                    };

                    reqs.push(AppUtil.createRequest(objUrl, params, function () {

                    }, function (error) {
                        // Close toast
                        AppUtil.closeToast();
                        // Clean
                        $scope.selectedItems = [];
                    }));
                });
                AppUtil.showSuccess({text: util.translate("default_toast.delete_success")});
                if (reqs.length > 0) {
                    // Post all reqs
                    $q.all(reqs).then(function () {
                        $scope.table.draw();
                        $scope.selectedItems = [];
                        checkbox.cleanUp();
                        AppUtil.closeToast();
                    });
                }

            }
        }]);
