'use strict';

angular.module('adminCompanyProfile', [])
    .controller('CompanyProfileController', [
        '$scope', 'AppUtil', 'APIName', '$stateParams', 'util', '_', '$state', 'checkbox', 'userConfig',
        '$compile', '$route', 'app', 'session', 'sortPage', '$window',
        function ($scope, AppUtil, APIName, $stateParams, util, _, $state, checkbox, userConfig,
                  $compile, $route, app, session, sortPage, $window) {
            $scope.script_pattern = app.SCRIPT_PATTERN;

            $scope.changeTabAdmin = function (tab) {
                $scope.tab = tab;
                checkbox.cleanUp();
                if (tab === 1) {
                } else if (tab === 2) {
                    // Reset selectedItems
                    $scope.selectedItems = [];
                }
                localStorage.tabsAdmin = tab;
            };

            $scope.doBack = function () {
                $window.history.back();
            };

            var activeTab = localStorage.tabsAdmin;
            $scope.tab = Number(activeTab) || 1;
            localStorage.tabsAdmin = $scope.tab;

            $scope.isJapaneseLanguage = session.isJapanese();
            $scope.company_id = $stateParams.id;
            $scope.tab_company = util.translate("tab_title.company_setting");
            $scope.tab_team_list = util.translate("tab_title.team_list");
            $scope.disable = false;
            $scope.isChange = false;
            $scope.timezones = [
                {value: -12, name: util.translate("timezone.GMT_-12")},
                {value: -11, name: util.translate("timezone.GMT_-11")},
                {value: -10, name: util.translate("timezone.GMT_-10")},
                {value: -9, name: util.translate("timezone.GMT_-9")},
                {value: -8, name: util.translate("timezone.GMT_-8")},
                {value: -7, name: util.translate("timezone.GMT_-7")},
                {value: -6, name: util.translate("timezone.GMT_-6")},
                {value: -5, name: util.translate("timezone.GMT_-5")},
                {value: -4, name: util.translate("timezone.GMT_-4")},
                {value: -3, name: util.translate("timezone.GMT_-3")},
                {value: -2, name: util.translate("timezone.GMT_-2")},
                {value: -1, name: util.translate("timezone.GMT_-1")},
                {value: 0, name: util.translate("timezone.GMT_0")},
                {value: 1, name: util.translate("timezone.GMT_+1")},
                {value: 2, name: util.translate("timezone.GMT_+2")},
                {value: 3, name: util.translate("timezone.GMT_+3")},
                {value: 4, name: util.translate("timezone.GMT_+4")},
                {value: 5, name: util.translate("timezone.GMT_+5")},
                {value: 6, name: util.translate("timezone.GMT_+6")},
                {value: 7, name: util.translate("timezone.GMT_+7")},
                {value: 8, name: util.translate("timezone.GMT_+8")},
                {value: 9, name: util.translate("timezone.GMT_+9")},
                {value: 10, name: util.translate("timezone.GMT_+10")},
                {value: 11, name: util.translate("timezone.GMT_+11")},
                {value: 12, name: util.translate("timezone.GMT_+12")}
            ];

            $scope.languages = [
                {id: 1, value: "auto", name: util.translate("language.auto")},
                {id: 2, value: "en", name: util.translate("language.en")},
                {id: 3, value: "ja", name: util.translate("language.ja")},
                {id: 4, value: "vi", name: util.translate("language.vi")}
            ];

            $scope.billingcycles = [
                {id: 1, value: 30},
                {id: 2, value: 60},
                {id: 3, value: 90}
            ];

            $scope.currencies = [
                {id: 1, value: "USD"},
                {id: 2, value: "VND"},
                {id: 3, value: "YEN"}
            ];

            $scope.companyData = {};
            $scope.companyAdmin = {};
            $scope.companyAdmin.language = $scope.languages[0];
            $scope.companyAdmin.timezone = $scope.timezones[0];

            var objUrl = {
                method: APIName.GET_COMPANY_INFO.method,
                name: APIName.GET_COMPANY_INFO.name + $stateParams.id
            };

            AppUtil.createRequest(objUrl, {}, function (res) {
                var companyInfo = res.data.company;
                var userCompInfo = res.data.user;
                // load company info data
                $scope.companyData.companyId = companyInfo.id;
                $scope.companyData.name = companyInfo.name;
                $scope.companyData.isTrial = companyInfo.trial;
                $scope.companyData.billingCycle = _.find($scope.billingcycles, {value: companyInfo.billing_cycle});
                $scope.companyData.currency = _.find($scope.currencies, {value: companyInfo.currency});
                $scope.companyData.company_create_date = util.formatDateBasedOnDiff(companyInfo.create_date, "", session.getCurrentLanguage(), session.getUser().time_zone);

                $scope.companyAdmin.userId = userCompInfo.user_id;
                $scope.companyAdmin.first_name = userCompInfo.first_name;
                $scope.companyAdmin.last_name = userCompInfo.last_name;
                $scope.companyAdmin.middle_name = userCompInfo.middle_name;
                $scope.companyAdmin.email_address = userCompInfo.mail_address;
                $scope.companyAdmin.user_create_date = userCompInfo.signup_date;
                $scope.companyAdmin.timezone = _.find($scope.timezones, {value: userCompInfo.time_zone});
                $scope.companyAdmin.language = _.find($scope.languages, {value: userCompInfo.lang});

                session.setCurrency($scope.companyData.currency ? $scope.companyData.currency.value: "USD");

                var originCompany = angular.copy($scope.companyData);
                var originUser = angular.copy($scope.companyAdmin);

                // Watch model to see the change
                $scope.$watch("companyData", function (newValue) {

                    // Compare input values with orgin values
                    if (angular.equals(newValue, originCompany)) {
                        $scope.isChangeCompany = false;
                        return;
                    } else {
                        $scope.isChangeCompany = true;
                        return;
                    }

                }, true);

                $scope.$watch("companyAdmin", function (newValue) {

                    // Compare input values with orgin values
                    if (angular.equals(newValue, originUser)) {
                        $scope.isChangeUser = false;
                        return;
                    } else {
                        $scope.isChangeUser = true;
                        return;
                    }

                }, true);
            }, function (error) {
                $state.go("companyList");
            });


            // Do submit
            $scope.submitCompany = false;
            $scope.submitUser = false;
            $scope.updateCompanyProfile = function (valid) {

                if (!valid)
                    return;

                $scope.submitCompany = true;

                var params = {};

                params['company_name'] = $scope.companyData.name;
                params['billing_cycle'] = $scope.companyData.billingCycle.value;
                params['currency'] = $scope.companyData.currency.value;
                params['is_trial'] = $scope.companyData.isTrial;

                var objUrl = {
                    method: APIName.EDIT_COMPANY.method,
                    name: APIName.EDIT_COMPANY.name + $scope.companyData.companyId
                };

                AppUtil.createRequest(objUrl, params, function (res) {
                    AppUtil.showSuccess({text: util.translate('default_toast.save_success')});
                    // Let the rootScope the user info has been changed
                    $scope.$emit("$companyInfoHasChanged", res.data);
                    $state.reload();
                    $scope.submitCompany = false;

                }, function (error) {
                    AppUtil.showError({
                        text: util.translate("sever_errors." + error.status)
                    });
                    $scope.submitCompany = false;
                });
            };

            $scope.updateUserProfile = function (valid) {

                if (!valid)
                    return;

                $scope.submitUser = true;

                var params = {};

                // params['user_update_id'] = $scope.companyAdmin.userId;
                params['first_name'] = $scope.companyAdmin.first_name;
                params['middle_name'] = $scope.companyAdmin.middle_name;
                params['last_name'] = $scope.companyAdmin.last_name;
                params['time_zone'] = $scope.companyAdmin.timezone.value;
                params['language'] = $scope.companyAdmin.language.value;

                // Do update
                AppUtil.createRequest({
                    url: APIName.EDIT_USER.name + $scope.companyAdmin.userId,
                    method: APIName.EDIT_USER.method
                }, params, function (res) {
                    AppUtil.showSuccess({text: util.translate('default_toast.save_success')});
                    // Let the rootScope the user info has been changed
                    $scope.$emit("$userInfoHasChanged", res.data);
                    $state.reload();
                    $scope.submitUser = false;
                }, function (data) {
                    $scope.submitUser = false;
                    AppUtil.showError({text: util.translate("sever_errors." + data.status)});
                });
            };

            $scope.change = false;

            $scope.table;

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

            // Create params for team list
            function makeParam(data) {
                return {
                    search_key: data.search.value.trim(),
                    page_size: data.length,
                    page_number: data.start / data.length + 1,
                    sort_field: data.columns[data.order[0].column].data,
                    asc_sort: data.order[0].dir === "asc",
                    company_id: $stateParams.id

                };
            }
            // Datatable obj
            $scope.table;

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

                    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: data.columns[data.order[0].column].data,
                        asc_sort: data.order[0].dir === "asc",
                        company_id: $stateParams.id
                    };

                    AppUtil.createRequest(APIName.GET_TEAM_LIST, params, function (res) {

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

                        localStorage.setItem(sortPage.COMPANY_TEAM_LIST, JSON.stringify(storeParams));
                        $.each(res.data.content, function (key, value) {
                            var status = "";
                            if (value.status === 1) {
                                status = util.translate("status.team.active");
                            } else if (value.status === 2) {
                                status = util.translate("status.team.delete");
                            } else if (value.status === 5) {
                                status = util.translate("status.team.pending");
                            } else if (value.status === 6) {
                                status = util.translate("status.team.trial");
                            }else if (value.status === 7) {
                                status = util.translate("status.team.suspecting");
                            }
                            json.data.push({
                                team_id: value.team_id,
                                name: value.name,
                                mailAddress: value.email_address,
                                createdDate: value.create_date,
                                status: status,
                                team_status: value.status,
                            });
                        });
                        // Insert value
                        callback(json);
                    });
                },
                "rowCallback": function (row, data) {
                    if (data.team_status === 2) {
                        $("td:eq(0)", row).addClass("text-center").html("<span></span>");
                    } else {
                        $("td:eq(0)", row).addClass("text-center").html("<input icheck-table type='checkbox' class='icheckbox' role='child-checkbox' id='" + data.team_id + "'>");
                    }
                    if (session.getUser().role_id !== userConfig.COMPANY_ADMIN.role) {
                        $("td:eq(1)", row).html("<a ui-sref='adminTeamProfile({company_id: \"" + $stateParams.id + "\",id: \"" + data.team_id + "\"})' class='name' ng-click='removeTab()'><div class='ellipsis' mytip='" + data.name + "' mytip-placement='top-left' mytip-show-when = '200'>" + data.name + "</div></a>");
                    } else {
                        $("td:eq(1)", row).html("<a ui-sref='adminTeamProfile({company_id: \"" + $stateParams.id + "\",id: \"" + data.team_id + "\"})' class='name' ng-click='removeTab()'><div class='ellipsis' mytip='" + data.name + "' mytip-placement='top-left' mytip-show-when = '200'>" + data.name + "</div></a>");
                    }
                    $("td:eq(2)", row).html("<div class='ellipsis' mytip='" + data.mailAddress + "' mytip-placement='top-left' mytip-show-when = '250'>" + data.mailAddress + "</div>");
                    $("td:eq(3)", row).addClass("hidden-sm-phone hidden-xs hidden-sm").html("<div>" + util.formatDateBasedOnDiff(data.createdDate, "", session.getCurrentLanguage(), session.getUser().time_zone) + "</div>");
                    if (data.team_status === 1) {
                        $("td:eq(4)", row).addClass("text-center").html("<span class='label label-success'>" + data.status + "</span>");
                    } else if (data.team_status === 2) {
                        $("td:eq(4)", row).addClass("text-center").html("<span class='label label-danger'>" + data.status + "</span>");
                    } else if (data.team_status === 5) {
                        $("td:eq(4)", row).addClass("text-center").html("<span class='label label-warning'>" + data.status + "</span>");
                    }else if (data.team_status === 7) {
                        $("td:eq(4)", row).addClass("text-center").html("<span class='label label-primary'>" + data.status + "</span>");
                    } else {
                        $("td:eq(4)", row).addClass("text-center").html("<span class='label' style='background-color:#cba00d;'>" + data.status + "</span>");
                    }


                    // Custom add more pro
                    // TODO
                    row.ondblclick = function () {
                        $state.go("adminTeamProfile", {
                            company_id: (session.getUser().role_id !== userConfig.COMPANY_ADMIN.role) ? $scope.companyData.companyId : $stateParams.id,
                            id: data.team_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": "team_id"},
                    {"data": "name"},
                    {"data": "mailAddress"},
                    {"data": "createdDate"},
                    {"data": "status"}

                ],
                "columnDefs": [
                    {'orderable': false, 'targets': [0]}
                ]
            };

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

            // Show confirm 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;

                angular.forEach(items, function (item) {

                    var objUrl = {
                        method: APIName.TEAM_STATUS.method,
                        name: APIName.TEAM_STATUS.name + item + APIName.TEAM_STATUS.surfix + 2
                    };

                    AppUtil.createRequest(objUrl, null, function () {

                        $scope.table.draw();
                        // Reset selectedItems
                        $scope.selectedItems = [];

                    }, function (error) {
                        // Close toast
                        AppUtil.closeToast();
                        // Clean
                        $scope.selectedItems = [];
                    });
                });
                AppUtil.createToast({
                    text: util.translate("default_toast.deactivate_success"),
                    'type': 'success'
                });
            }
        }]);
