crmApp.controller("AdminCommTemplateController", AdminCommTemplateController);

function AdminCommTemplateController($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, AdminSI) {

    var vm = this;
    vm.templatelist = {};
    vm.changesHistory = [];
    vm.DefaultBookmarkTemplateOptions =[];
    var isEmailTmplatesLoaded = false;
    var filtered = "";
    var constEmailTemplateTypeSystem = 'S';
    var constEmailTemplateTypeEFailing = 'A';
    var constEmailTemplateTypeGeneral = 'B';
    vm.showTemplateHtmlValidationMsg = false;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    editor = CKEDITOR.replace('TemplateHTML',
  {
      extraPlugins: 'bookmarktemplate,font,colorbutton',

      on: {
          pluginsLoaded: function () {
              var editor = this;
              editor.addCommand("onClickAddBookmark", {
                  exec: function (edt) {
                      $('#btnAddEmailBookmark').click();
                  }
              });

              editor.ui.addButton('Bookmark', {
                  label: "Add Bookmark ",
                  command: 'onClickAddBookmark',
                  toolbar: 'others',
                  hidpi: true,
                  icon: 'custom/icons/add/add.png'
              });
          },

          instanceReady: function (evt) {
              $(".cke_combo__bookmarktemplate").closest(".cke_toolbar").addClass("pull-right");

              $(".cke_top").append('<span class="cke_toolbar_break"></span><span class="cke_toolbar pull-right textRed" style="color:#EF5049!important;font-size:0.9em;font-family:Poppins, sans-serif;">*Note: [[Bookmarks]] in the templates will be replaced with data when sending email</span>');
          }
      }
  }
);

    vm.init = function () {

        AdminSI.getAllEmailTemplate().then(function (r) {
            if (r.status === 200) {
                vm.templatelist = r.data;
                vm.templatelistSys = $filter('filter')(vm.templatelist, { "TemplateType": 'S' }, true);
                vm.templatelistCus = $filter('filter')(vm.templatelist, { "TemplateType": '!S' }, true);

                if (vm.templatelistSys) {
                    for (i = 0; i < vm.templatelistSys.length; i++)
                        vm.templatelistSys[i].LastUpdatedDateTime = $filter('date')(vm.templatelistSys[i].LastUpdatedDateTime, $scope.DateTimeFormat);
                }

                if (vm.templatelistCus) {
                    for (i = 0; i < vm.templatelistCus.length; i++)
                        vm.templatelistCus[i].LastUpdatedDateTime = $filter('date')(vm.templatelistCus[i].LastUpdatedDateTime, $scope.DateTimeFormat);
                }
           
            }
        });
    };

    vm.ChangeTemplateByID = function (EmailTemplateID) {
        var filtered = $filter('filter')(vm.templatelist, { "TemplateID": EmailTemplateID }, true);
        if (filtered.length > 0) {
            vm.editing = filtered[0];
            editor.setData(vm.editing.TemplateHTML);
            editor.selTemplateID = "";
            //var a = editor.document.getById('bookmarkSignature')
            // if (!isEmailTmplatesLoaded) {
            CKEDITOR.instances.TemplateHTML.setData('');
            getEmailTemplateDDLOptions(vm.editing.TemplateID)
            // }


        }
    }

    vm.save = function (templateForm) {
        var isDirty = templateForm.$dirty;

        if (editor.checkDirty()) {
            isDirty = true;
            templateForm["TemplateHTML"].$pristine = false;
        }
        else
        {
                isDirty = true;
                templateForm.TemplateHTML.$valid = false;
                swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                vm.showTemplateHtmlValidationMsg = true;
                templateForm.TemplateTypeID.$valid = false;
                vm.showValidationMsg = false;
                templateForm.$valid = false;
        }


        if (templateForm.$valid) {
            if (isDirty) {
                getChangeHistory(templateForm);
                var templateModel = {};

                if (vm.editing.TemplateID == 0 || vm.editing.TemplateType !='S')
                {
                    var filtered = $filter('filter') (vm.JenisTemplateTypeOptions, {"Value": vm.editing.TemplateTypeID}, true);
                    if (filtered.length > 0)
                    vm.editing.TemplateType = filtered[0].Code;
                }

                if (vm.editing.LanguageID == undefined || vm.editing.LanguageID == null )
                {
                    vm.editing.LanguageID = 0;
                }

                var templateHTMLContent = editor.getData();

                if (vm.editing.TemplateType == constEmailTemplateTypeSystem) {
                    templateModel = {
                        TemplateHTML: templateHTMLContent,
                        TemplateID: vm.editing.TemplateID,
                        Subject: vm.editing.Subject,
                        TemplateType: constEmailTemplateTypeSystem,
                        LanguageID: vm.editing.LanguageID,
                        RefTableName: vm.editing.RefTableName,
                        TemplateName: vm.editing.TemplateName,
                        IsSystemTemplate: true,
                        IsActive: vm.editing.IsActive
                    }
                }
                else {
                    if (vm.editing.TemplateType == constEmailTemplateTypeEFailing) {
                        templateModel = {
                            TemplateHTML: templateHTMLContent,
                            TemplateID: vm.editing.TemplateID,
                            Subject: vm.editing.Subject,
                            TemplateType: constEmailTemplateTypeEFailing,
                            LanguageID: vm.editing.LanguageID,
                            RefTableName: vm.editing.RefTableName,
                            IsSystemTemplate: false,
                            TemplateName: vm.editing.TemplateName,
                            IsActive: vm.editing.IsActive,
                            TemplateBookmark: vm.DefaultBookmarkTemplateOptions

                        }
                    }
                    else {
                        templateModel = {
                            TemplateHTML: templateHTMLContent,
                            TemplateID: vm.editing.TemplateID,
                            Subject: vm.editing.Subject,
                            TemplateType: constEmailTemplateTypeGeneral,
                            LanguageID: vm.editing.LanguageID,
                            RefTableName: vm.editing.RefTableName,
                            IsSystemTemplate: false,
                            TemplateName: vm.editing.TemplateName,
                            IsActive: vm.editing.IsActive,
                            TemplateBookmark: vm.DefaultBookmarkTemplateOptions
                        }
                    }
                }

                var model = {
                    AdminTemplate: templateModel,
                    ChangeHistory: vm.changesHistory
                }

                AdminSI.updateTemplate(model).then(function (r) {
                    if (r.status === 200) {
                        if (r.data) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });
                        }
                        else
                            swal("Gagal", r.data, "error");
                    } else
                        swal("Gagal", r.data, "error");
                });
            }
            else
            {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        }
        else {
                swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                vm.showValidationMsg = true;
        }

    }

    vm.addNewCustomTemplate = function () {
        vm.editTitle = "Tambah Template Khusus";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.TemplateID = 0;
        //CKEDITOR.instances.TemplateHTML.setData('');
        vm.editing.TemplateHTML = "";
        editor.setData(vm.editing.TemplateHTML);
        getDefaultBookmarkDLLOption();
    };

    vm.addBookmarkValue = function () {
        var SelectedCurrentBookmark = editor.selTemplateID;
        if (SelectedCurrentBookmark.length > 0) {
            var str = '[[' + SelectedCurrentBookmark + ']]';
            editor.insertHtml(str, 'html');
        }

    }

    getDDLOptions().then(function (data) {

        for (var key in data) {
            vm[key] = data[key];
        }
    });

    function getDDLOptions() {
        var deferred = $q.defer();
        AdminSI.getAdminDDLOptions().then(function (r) {
            if (r.status === 200) {
                deferred.resolve(r.data);
            }
        });
        return deferred.promise;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                var newvalue = "";
                if ($(document.getElementById(key))[0].tagName == 'SELECT' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if ($(document.getElementById(key))[0]) {
                        if ($(document.getElementById(key))[0].selectedIndex && $(document.getElementById(key))[0].selectedIndex >= 0)
                            newvalue = $(document.getElementById(key))[0].options[$(document.getElementById(key))[0].selectedIndex].text;
                    }
                }
                else if ($(document.getElementById(key))[0].tagName == 'INPUT' && $(document.getElementById(key))[0].type == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    newvalue = $(document.getElementById(key))[0].parentElement.innerText.trim();
                }
                else {
                    newvalue = value.$viewValue;
                }

                vm.changesHistory.push({
                    ID: vm.WFConfigID,
                    FieldName: key,
                    DisplayName: displayName,
                    OldValue: '',
                    NewValue: newvalue,
                    IsChanged: !value.$pristine
                });
            }
        });
    };

    function CKupdate() {
        for (instance in CKEDITOR.instances) {
            CKEDITOR.instances[instance].updateElement();
            CKEDITOR.instances[instance].setData('');
        }
    }

    function getEmailTemplateDDLOptions(templateID) {

        comboEmailTmpls = editor.ui.get("bookmarktemplate");
        comboEmailTmpls.createPanel(editor);

        AdminSI.getAdminEmailTemplateBookmarkDDLOptions(templateID).then(function (r) {
            if (r.status == 200) {
                var data = r.data || {
                };
                lstGroupedTmpls = data;
                editor.lstGroupedTmpls = data;
                var delimiter = '|^~^|';
                $(editor).trigger("rebuildList")

                isEmailTmplatesLoaded = true;
                editor.isTemplateLoaded = true;
            }
        });
    }

    function getDefaultBookmarkDLLOption()
    {
        comboEmailTmpls = editor.ui.get("bookmarktemplate");
        comboEmailTmpls.createPanel(editor);

        lstGroupedTmpls = vm.DefaultBookmarkTemplateOptions;
        var delimiter = '|^~^|';
        for (i = 0; i < lstGroupedTmpls.length; i++) {
            comboEmailTmpls.add(lstGroupedTmpls[i].Text);
        }

    }

    vm.openEditList = function (e,TemplateType)
    {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        if (TemplateType == "S")
        {
            vm.editTitle = "Kemaskini Template Sistem";
        }
        else
        {
            vm.editTitle = "Kemaskini Template Khusus";
        }
       
        
        if (constEmailTemplateTypeSystem == TemplateType)
        {
            filtered = $filter('filter')(vm.templatelistSys, { "TemplateID": id }, true);
        }
        else
        {
            filtered = $filter('filter')(vm.templatelistCus, { "TemplateID": id }, true);
        }
        
        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.TemplateType == constEmailTemplateTypeEFailing)
        {
            var JenisTemplateFilter = $filter('filter')(vm.JenisTemplateTypeOptions, { "Code": vm.editing.TemplateType }, true);
            if (JenisTemplateFilter.length > 0) {
                vm.editing.TemplateTypeID = JenisTemplateFilter[0].Value;
            }
        }
        else
        {
            var JenisTemplateFilter = $filter('filter')(vm.JenisTemplateTypeOptions, { "Code": '!A'}, true);
            if (JenisTemplateFilter.length > 0) {
                vm.editing.TemplateTypeID = JenisTemplateFilter[0].Value;
            }
        }

        editor.setData(vm.editing.TemplateHTML);
        getEmailTemplateDDLOptions(vm.editing.TemplateID)

        vm.editMode = true;
    }

    vm.cancel = function ()
    {
        //vm.editMode = false;
        //vm.init();
        //vm.showValidationMsg = false;
        swal({
            title: "Adakah anda mahu batal email template yang sedang dikemasini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                location.reload();
            }
            else
            {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                vm.editMode = true;
            }
        });
    }

    vm.dtOptionsSys = DTOptionsBuilder.newOptions()
        .withDOM('tr')
            .withDisplayLength(50);

    vm.dtOptionsCus = DTOptionsBuilder.newOptions()        
       .withPaginationType('full_numbers')
       .withDisplayLength(10);

    vm.delete = function () {

        swal({
            title: "Adakah anda ingin hapus template emel ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                var templateModel = {};

                templateModel = {
                    TemplateID: vm.editing.TemplateID,
                }
                AdminSI.deleteEmailTemplate(templateModel).then(function (r) {
                    if (r.status === 200) {
                        if (r.data) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });
                        }
                        else
                            swal("Gagal", r.data, "error");
                    } else
                        swal("Gagal", r.data, "error");
                });

            }
            else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                vm.editMode = true;
            }
        });
    }
}