crmApp.controller("WorkflowConfigController", WorkflowConfigController);

function WorkflowConfigController($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.list = {};
    vm.editing = {};
    vm.changesHistory = [];
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.showValidationMsgForAutoClosedJenisCawangan = false;
    vm.showValidationMsgForAutoClosedUnitType = false;
    vm.showDuplicatedMsg = false;
    vm.showValidationMsgForJenisCawCheckBalance = false;
    vm.showValidationMsgForJenisCukai = false;
    vm.checkBalanceDisabled = true;
    vm.autoClosedUnitDisabled = true;
    vm.autoClosedCawanganDisabled = true;
    vm.IsAutoClosedForJenisCawangan = false;
    vm.IsAutoClosedForUnitType = false;
    vm.hideDefaultUnitType = false;

    vm.dtOptions = DTOptionsBuilder.newOptions()
                    //.withOption('order', [[1, 'asc']])
                    .withPaginationType('full_numbers')
                    .withDisplayLength(10);

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

    vm.IsDefault = true;

    vm.init = function () {

        AdminSI.getworkflowconfig().then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;

            }
        });

        AdminSI.getWorkflowConfigDropdown().then(function (r) {
            if (r.status == 200) {
                for (var key in r.data) {
                    vm[key] = r.data[key];
                }
            }
        });


    };

    vm.addNew = function () {
        vm.editTitle = "Tambah Workflow";
        vm.SetAsGeneral = false;
        vm.IsIntegrationDMS = false;
        vm.IsEscalationToReMS = false;
        vm.IsAutoClose = false;
        vm.IsCheckBalance = false;
        vm.WFConfigID = 0;
        vm.Kategori1ID = "";
        vm.Kategori2ID = "";
        vm.Kategori3ID = "";
        vm.JenisCawanganID = "";
        vm.DefaultUnitTypeID = "";
        vm.AutoCloseUnitTypeID = "";
        vm.AutocloseSysID = "";
        vm.JenisCawanganAutoCloseUnitID = "";
        vm.kategori1Disabled = false;
        vm.kategori2Disabled = false;
        vm.kategori3Disabled = false;
        vm.JenisCawanganDisabled = false;
        vm.JenisDefaultUnitDisabled = false;
        vm.editMode = true;
        vm.showDuplicatedMsg = false;
        vm.IsActive = true;
 
        //drop down menu
        AdminSI.getWorkflowConfigDropdown().then(function (r) {
            if (r.status == 200) {
                for (var key in r.data) {
                    vm[key] = r.data[key];
                }
            }
        });
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
  
    }

    vm.SetGeneral = function (wfconfigID) {
        if ($('#IsDefault').is(':checked')) {
            if (vm.Kategori1ID > 0) {
                vm.Kategori1ID = "";
                vm.kategori1Disabled = true;
                vm.Kategori2ID = "";
                vm.kategori2Disabled = true;
                vm.Kategori3ID = "";
                vm.kategori3Disabled = true;
                vm.JenisCawanganID = ""
                vm.JenisCawanganDisabled = true;
                vm.DefaultUnitTypeID = "";
                vm.JenisDefaultUnitDisabled = true;

            }
            else {
                vm.kategori1Disabled = true;
                vm.kategori2Disabled = true;
                vm.kategori3Disabled = true;
                vm.IsAutoCheckBalance = true;
                vm.AutoCloseRuleDisabled = true;
                //vm.JenisCawanganDisabled = true;
                //vm.JenisDefaultUnitDisabled = true;
            }

        }
        else {
            vm.kategori1Disabled = false;
            vm.kategori2Disabled = true;
            vm.kategori3Disabled = true;
            vm.JenisCawanganDisabled = false;
            vm.JenisDefaultUnitDisabled = false;
            vm.IsAutoCheckBalance = false;
            vm.AutoCloseRuleDisabled = false;
        }
    }

    vm.openEdit = function (e) {
        resetValidationMsg();
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Edit Back Office Workflow";
        var filtered = $filter('filter')(vm.list, { "WFConfigID": id }, true);

        if (filtered.length > 0) vm.wf = filtered[0];
        
        vm.SetAsGeneral = vm.wf.IsDefault;
        if (vm.SetAsGeneral) {
            vm.kategori1Disabled = true;
            vm.kategori2Disabled = true;
            vm.kategori3Disabled = true;
            vm.IsAutoCheckBalance = true;
            vm.AutoCloseRuleDisabled = true;
            //vm.JenisCawanganDisabled = true;
            //vm.JenisDefaultUnitDisabled = true;
        }
        else {
            vm.kategori1Disabled = false;
            vm.kategori2Disabled = false;
            vm.kategori3Disabled = false;
            vm.JenisCawanganDisabled = false;
            vm.JenisDefaultUnitDisabled = false;
            vm.IsAutoCheckBalance = false;
            vm.AutoCloseRuleDisabled = false;
        }

        vm.IsIntegrationDMS = vm.wf.IsIntegrateDMS;
        vm.IsEscalationToReMS = vm.wf.IsEscalateReMS;
        vm.IsAutoClose = vm.wf.IsAutoClose;
        if (vm.IsAutoClose) {
            vm.checkBalanceDisabled = false;
            vm.autoClosedUnitDisabled = false;
            vm.autoClosedCawanganDisabled = false;
        }
        else {
            vm.checkBalanceDisabled = true;
            vm.autoClosedUnitDisabled = true;
            vm.autoClosedCawanganDisabled = true;
        }
        vm.IsCheckBalance = vm.wf.IsAutoCheckBalance;
        vm.WFConfigID = vm.wf.WFConfigID;

        var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: vm.wf.Kategori1ID }, true);
        if (m.length > 0 && m != undefined) {
            vm.Kategori1ID = m[0].Kategori1ID; vm.SubKategoriOptions = m[0].SubKategori;

            m = $filter('filter')(vm.SubKategoriOptions, { Kategori2ID: vm.wf.Kategori2ID }, true);
            if (m.length > 0 && m != undefined) {
                vm.Kategori2ID = m[0].Kategori2ID;
                vm.InnerSubKategoriOptions = m[0].InnerSubKategori;

                m = $filter('filter')(vm.InnerSubKategoriOptions, { Kategori3ID: vm.wf.Kategori3ID }, true);
                if (m != undefined && m.length > 0) {
                    vm.Kategori3ID = m[0].Kategori3ID;
                } else {
                    vm.Kategori3ID = "";
                }
            }
            else {
                vm.Kategori2ID = "";
                vm.Kategori3ID = "";
            }

        }
        else {
            vm.Kategori1ID = "";
            vm.Kategori2ID = "";
            vm.Kategori3ID = "";
        }

        m = $filter('filter')(vm.JenisCawanganOptions, { Value: vm.wf.JenisCawanganID }, true);
        if (m.length > 0) {
            vm.JenisCawanganID = m[0].Value;
        }
        else {
            vm.JenisCawanganID = "";
        }


        m = $filter('filter')(vm.UnitTypeOptions, { Value: vm.wf.DefaultUnitTypeID }, true);
        if (m.length > 0) {
            vm.DefaultUnitTypeID = m[0].Value;
        }
        else {
            vm.DefaultUnitTypeID = "";
        }


        m = $filter('filter')(vm.UnitTypeOptions, { Value: vm.wf.AutoCloseUnitTypeID }, true);
        if (m.length > 0) {
            vm.AutoCloseUnitTypeID = m[0].Value;
        }
        else {
            vm.AutoCloseUnitTypeID = "";
        }

        m = $filter('filter')(vm.JenisCawanganOptions, { Value: vm.wf.JenisCawanganAutoCloseUnitID }, true);
        if (m.length > 0) {
            vm.JenisCawanganAutoCloseUnitID = m[0].Value;
        }
        else {
            vm.JenisCawanganAutoCloseUnitID = "";
        }

        m = $filter('filter')(vm.AutoCloseSysOptions, { Value: vm.wf.KodAutocloseSysID }, true);
        if (m.length > 0) {
            vm.AutocloseSysID = m[0].Value;
        }
        else {
            vm.AutocloseSysID = "";
        }

        m = $filter('filter')(vm.JenisCukaiOptions, { Value: vm.wf.JenisCukaiLookupID }, true);
        if (m.length > 0) {
            vm.JenisCukaiLookupID = m[0].Value;
        }
        else {
            vm.JenisCukaiLookupID = "";
        }

        m = $filter('filter')(vm.JenisCawanganOptions, { Value: vm.wf.JenisCawCheckBalanceID }, true);
        if (m.length > 0) {
            vm.JenisCawCheckBalanceID = m[0].Value;
        }
        else {
            vm.JenisCawCheckBalanceID = "";
        }

        vm.IsActive = vm.wf.IsActive;


        vm.editMode = 1;
    };

    vm.save = function (myForm) {

        resetValidationMsg();

        var isDirty = myForm.$dirty;

        var kat = (vm.Kategori1ID || 0) + '|' + (vm.Kategori2ID || 0) + '|' + (vm.Kategori3ID || 0);
        var checkExist = $filter('filter')(vm.list, { "KategoriConsolidate": kat, "IsActive": true }, true);

        if (checkExist.length > 0 && checkExist[0].WFConfigID != vm.WFConfigID ) {   
            swal("Gagal!", "Workflow for this Kategori already exist!", "error");
            vm.showDuplicatedMsg = true;
        }
        else if ($('#IsAutoClose').is(':checked') && (vm.AutoCloseUnitTypeID == "" && vm.JenisCawanganAutoCloseUnitID == "")) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.IsAutoClosedForJenisCawangan = true;
            vm.IsAutoClosedForUnitType = true;
            vm.showValidationMsgForAutoClosedJenisCawangan = true;
            vm.showValidationMsgForAutoClosedUnitType = true;
        }
        else if ($('#IsAutoClose').is(':checked') && (vm.JenisCawanganAutoCloseUnitID == "" && vm.AutoCloseUnitTypeID)) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.IsAutoClosedForJenisCawangan = true;
            vm.IsAutoClosedForUnitType = false;
            vm.showValidationMsgForAutoClosedJenisCawangan = true;
            vm.showValidationMsgForAutoClosedUnitType = false;
        }
        else if ($('#IsAutoClose').is(':checked') && (vm.AutoCloseUnitTypeID == "" && vm.JenisCawanganAutoCloseUnitID)) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            //vm.IsAutoClosed = true;
            vm.IsAutoClosedForJenisCawangan = false;
            vm.IsAutoClosedForUnitType = true;
            vm.showValidationMsgForAutoClosedJenisCawangan = false;
            vm.showValidationMsgForAutoClosedUnitType = true;
        }
        else if (vm.IsCheckBalance && !vm.JenisCawCheckBalanceID) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsgForJenisCawCheckBalance = true;
        }
        else if (vm.IsCheckBalance && !vm.JenisCukaiLookupID) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsgForJenisCukai = true;
        }
        else {
            if ($('#IsDefault').is(':checked') && myForm.Kategori1Name.$valid == false) {
                myForm.$valid = true;
            }
            
            if (vm.JenisCawanganID == 6 || vm.JenisCawanganID == 7) {
                myForm.$valid = true;
            }

            if (myForm.$valid) {
                if (isDirty) {
                    if ($('#IsAutoClose').is(':checked')) {
                        if (vm.AutoCloseUnitTypeID == undefined) {
                            vm.showValidationMsg = true;
                        }
                    }
                    getChangeHistory(myForm);
                    var modelWF = {};
                    var model = {};

                    modelWF = {
                        WFConfigID: vm.WFConfigID,
                        IsDefault: $('#IsDefault').is(':checked') ? true : false,
                        Kategori1ID: (vm.Kategori1ID == undefined || vm.Kategori1ID == "") ? 0 : vm.Kategori1ID,
                        Kategori2ID: (vm.Kategori2ID == undefined || vm.Kategori2ID == "") ? 0 : vm.Kategori2ID,
                        Kategori3ID: (vm.Kategori3ID == undefined || vm.Kategori3ID == "") ? 0 : vm.Kategori3ID,
                        JenisCawanganID: (vm.JenisCawanganID == undefined || vm.JenisCawanganID == "") ? 0 : vm.JenisCawanganID,
                        DefaultUnitTypeID: (vm.DefaultUnitTypeID == undefined || vm.DefaultUnitTypeID == "") ? 0 : vm.DefaultUnitTypeID,
                        IsIntegrateDMS: $('#IsIntegrateDMS').is(':checked') ? true : false,
                        IsEscalateReMS: $('#IsEscalateReMS').is(':checked') ? true : false,
                        IsAutoClose: $('#IsAutoClose').is(':checked') ? true : false,
                        JenisCawanganAutoCloseUnitID: (vm.JenisCawanganAutoCloseUnitID == undefined || vm.JenisCawanganAutoCloseUnitID == "") ? 0 : vm.JenisCawanganAutoCloseUnitID,
                        AutoCloseUnitTypeID: (vm.AutoCloseUnitTypeID == undefined || vm.AutoCloseUnitTypeID == "") ? 0 : vm.AutoCloseUnitTypeID,
                        IsAutoCheckBalance: $('#IsAutoCheckBalance').is(':checked') ? true : false,
                        IsActive: $("input[name='IsActive']:checked").val(),
                        KategoriConsolidate: kat,
                        KodAutocloseSysID: (vm.AutocloseSysID == undefined || vm.AutocloseSysID == "") ? 0 : vm.AutocloseSysID,
                        JenisCawCheckBalanceID: vm.IsCheckBalance ? vm.JenisCawCheckBalanceID : 0,
                        JenisCukaiLookupID: vm.IsCheckBalance ? vm.JenisCukaiLookupID : 0
                    }

                    model = {
                        WorkflowConfig: modelWF,
                        ChangeHistory : vm.changesHistory,
                    } 

                    AdminSI.addNewWorkflowConfig(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });

                        }
                    });
                }
                else {
                    swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
                }
            } else {
                swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                vm.showValidationMsg = true;
            }
        }
    }

    vm.SetAutoClosed = function () {
        if ($('#IsAutoClose').is(':checked')) {
            vm.checkBalanceDisabled = false;
            vm.autoClosedUnitDisabled = false;
            vm.autoClosedCawanganDisabled = false;
        }
        else {
            if (vm.JenisCawanganAutoCloseUnitID > 0 || vm.AutoCloseUnitTypeID > 0) {
                vm.JenisCawanganAutoCloseUnitID = "";
                vm.AutoCloseUnitTypeID = "";
                vm.IsCheckBalance = false;
            }
            vm.checkBalanceDisabled = true;
            vm.autoClosedUnitDisabled = true;
            vm.autoClosedCawanganDisabled = true;

        }
    }

    vm.kategori1Changed = function (selectedKategori1ID) {
        vm.SubKategoriOptions = [];
        vm.kategori3Disabled = true;
        if (selectedKategori1ID == undefined) {
            vm.Kategori1Name = "";
        } else {
            vm.SubKategoriOptions = [];

            var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: selectedKategori1ID }, true);
            if (m != undefined && (m.length > 0)) {
                vm.SubKategoriOptions = m[0].SubKategori;
                vm.Kategori1Name = m[0].Kategori1Name;
                vm.kategori2Disabled = m[0].SubKategori.length > 0 ? false : true;
                if (vm.kategori2Disabled) {
                    vm.kategori3Disabled = true;
                    vm.InnerSubKategoriOptions = {
                    };
                }
            } else {
                vm.Kategori1Name = "";
            }
        }
    };

    vm.kategori2Changed = function (selectedKategori2ID) {
        vm.InnerSubKategoriOptions = [];
        var m = $filter('filter')(vm.SubKategoriOptions, { Kategori2ID: selectedKategori2ID }, true);
        if (m != undefined && m.length > 0) {
            vm.InnerSubKategoriOptions = m[0].InnerSubKategori;
            vm.Kategori2Name = m[0].Kategori2Name;
            vm.kategori3Disabled = m[0].InnerSubKategori.length > 0 ? false : true;
        } else {
            vm.Kategori2Name = "";
        }
    };

    vm.kategori3Changed = function (selectedKategori3ID) {
        var m = $filter('filter')(vm.InnerSubKategoriOptions, { Kategori3ID: selectedKategori3ID }, true);
        if (m != undefined && m.length > 0) {
            vm.Kategori3Name = m[0].Kategori3Name;
        } else {
            vm.Kategori3Name = "";
        }
    }

    vm.DeleteBackofficeWF = function (wfconfigID) {
        vm.editMode = false;
        var model = {
            WFConfigID: wfconfigID,
            IsActive: false
        };

        swal({
            title: "Are you sure you want to delete current back office workflow ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.deleteCurrentWorkflowConfig(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Updated Successfully!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


                    }
                });
            }
            else {
                swal("Cancelled", "Request cancelled.", "error");
            }
        });

    }

    vm.ChangeUnitType = function(selectedJenisCawanganID)
    {
        if (selectedJenisCawanganID == 6 || selectedJenisCawanganID == 7)
        {
            vm.DefaultUnitTypeID = ""
            return false;
        }
        else
        {
            if (vm.DefaultUnitTypeID != "")
                vm.DefaultUnitTypeID = vm.DefaultUnitTypeID;
            return true;
        }
    }

    function OpenEditModePage(wfconfigId) {
        var filtered = $filter('filter')(vm.list, { "WFConfigID": wfconfigId }, true);

        if (filtered.length > 0) vm.wf = filtered[0];

        vm.SetAsGeneral = vm.wf.IsDefault;
        if (vm.SetAsGeneral) {
            vm.kategori1Disabled = true;
            vm.kategori2Disabled = true;
            vm.kategori3Disabled = true;
        }
        else {
            vm.kategori1Disabled = false;
            vm.kategori2Disabled = false;
            vm.kategori3Disabled = false;
        }

        vm.IsIntegrationDMS = vm.wf.IsIntegrateDMS;
        vm.IsEscalationToReMS = vm.wf.IsEscalateReMS;
        vm.IsAutoClose = vm.wf.IsAutoClose;
        vm.IsCheckBalance = vm.wf.IsAutoCheckBalance;
        vm.WFConfigID = vm.wf.WFConfigID;

        //var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: vm.wf.Kategori1ID }, true);
        //if (m.length > 0)
        //{
        //    vm.Kategori1ID = m[0].Kategori1ID; vm.SubKategoriOptions = m[0].SubKategori;

        //    m = $filter('filter')(vm.SubKategoriOptions, { Kategori2ID: vm.wf.Kategori2ID }, true);
        //    if (m.length > 0)
        //        vm.Kategori2ID = m[0].Kategori2ID;
        //}
        //else
        //{
        vm.Kategori1ID = "";
        vm.Kategori2ID = "";
        //}

        m = $filter('filter')(vm.JenisCawanganOptions, { Value: vm.wf.JenisCawanganID }, true);
        if (m.length > 0)
            vm.JenisCawanganID = m[0].Value;

        m = $filter('filter')(vm.UnitTypeOptions, { Value: vm.wf.DefaultUnitTypeID }, true);
        if (m.length > 0)
            vm.DefaultUnitTypeID = m[0].Value;

        m = $filter('filter')(vm.UnitTypeOptions, { Value: vm.wf.AutoCloseUnitTypeID }, true);
        if (m.length > 0)
            vm.AutoCloseUnitTypeID = m[0].Value;

        m = $filter('filter')(vm.JenisCawanganOptions, { Value: vm.wf.JenisCawanganAutoCloseUnitID }, true);
        if (m.length > 0) {
            vm.JenisCawanganAutoCloseUnitID = m[0].Value;
        }
        else {
            vm.JenisCawanganAutoCloseUnitID = "";
        }


        vm.editMode = true;
    }

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

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive") {
                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)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else if ($(document.getElementById(key))[0].tagName == 'INPUT' && $(document.getElementById(key))[0].type == 'checkbox' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

    function resetValidationMsg() {
        vm.showValidationMsg = false;
        vm.showValidationMsgForAutoClosedJenisCawangan = false;
        vm.showValidationMsgForAutoClosedUnitType = false;
        vm.showDuplicatedMsg = false;
        vm.showValidationMsgForJenisCawCheckBalance = false;
        vm.showValidationMsgForJenisCukai = false;
    }

};