basicDataModule
    .controller('BasicDataFinancialInfrastructureController', ['$scope', '$log', 'SweetAlert', 'organizationStructureService', '$translate', 'businessUnitService', 'customerService',
        function($scope, $log, SweetAlert, organizationStructureService, $translate, businessUnitService, customerService) {
            'use strict';

            var successAddMessage = $translate.instant('OrganizationStructureAddSuccess');
            var successEditMessage = $translate.instant('OrganizationStructureEditSuccess');
            var successDeleteMessage = $translate.instant('OrganizationStructureDeleteSuccess');
            var operationDeleteMessage = $translate.instant('OrganizationStructureOperationSuccess');
            var notAllowDisableMessage = $translate.instant('notAllowDisableMessage');


            $scope.add = function(newrow) {

                organizationStructureService.addOrganizationStructure(newrow).success(function(guid) {
                    SweetAlert.success(successAddMessage);
                });
            };

            $scope.edit = function(newcontent) {
                organizationStructureService.updateOrganizationStructure(newcontent).success(function(guid) {
                    SweetAlert.success(successEditMessage);
                });
            };

            $scope.remove = function(id) {
                organizationStructureService.deleteOrganizationStructure(id).success(function(guid) {
                    SweetAlert.success(successDeleteMessage);
                });
            };

            $scope.stop = function(id) {
                organizationStructureService.updateOrganizationStructure(id).success(function(successFlag) {
                    $scope.updateflag = successFlag;
                    $scope.$broadcast('to-child', successFlag);
                    if (successFlag) {
                        SweetAlert.success(operationDeleteMessage);
                    } else {
                        SweetAlert.warning(notAllowDisableMessage);
                    }
                });
            };

            //BusinessUnit
            $scope.addbs = function(newrow) {

                businessUnitService.addBusinessUnit(newrow).success(function(guid) {
                    SweetAlert.success(successAddMessage);
                });
            };

            $scope.editbs = function(newcontent) {
                businessUnitService.updateBusinessUnit(newcontent).success(function(guid) {
                    SweetAlert.success(successEditMessage);
                });
            };

            $scope.removebs = function(id) {
                businessUnitService.deleteBusinessUnit(id).success(function(guid) {
                    SweetAlert.success(successDeleteMessage);
                });
            };

            $scope.stopbs = function(id) {
                businessUnitService.updateBusinessUnit(id).success(function(successFlag) {
                    $scope.updateflag = successFlag;
                    $scope.$broadcast('to-child', successFlag);
                    if (successFlag) {
                        SweetAlert.success(operationDeleteMessage);
                    } else {
                        SweetAlert.warning(notAllowDisableMessage);
                    }
                });
            };

            $scope.showOperateLogPop = function() {
                $scope.isShowLog = true;
                // $('#showOperatePop').modal('show');
            };

            var getUserPermission = function() {

                var list = [];

                var basicData = constant.adminPermission.basicData;
                list.push(basicData.orangizationStructure.queryCode);
                list.push(basicData.businessUnit.queryCode);
                list.push(basicData.areaManage.queryCode);
                list.push(basicData.enterpriseAccountSet.queryCode);
                list.push(basicData.customerList.queryCode);

                $scope.$root.checkUserPermissionList(list).success(function(data) {

                    $scope.orangizationStructureShow = data[basicData.orangizationStructure.queryCode];
                    $scope.businessUnitShow = data[basicData.businessUnit.queryCode];
                    $scope.areaManageShow = data[basicData.areaManage.queryCode];
                    $scope.enterpriseAccountSetShow = data[basicData.enterpriseAccountSet.queryCode];
                    $scope.customerListShow = data[basicData.customerList.queryCode];

                });
            };

            (function initialize() {
                $log.debug('BasicDataInfrastructureController.ctor()...');

                getUserPermission();

            })();
        }
    ]);

basicDataModule.directive('basicDataFinancialInfrastructure', ['$log',
    function ($log) {
        'use strict';
        $log.debug('BasicDataInfrastructure.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/financialData/basicDataInfrastructure/basic-data-infrastructure.html' + '?_=' + Math.random(),
            replace: true,
            scope: {
                state:'='
            },
            controller: 'BasicDataFinancialInfrastructureController',
            link: function (scope, element) {
                //$log.info(scope.state);
            }
        };
    }
]);
basicDataModule
.controller('customerListManageController', ['$scope', '$log', 'SweetAlert', 'customerService', 'enterpriseAccountService', 'uiGridConstants', '$translate', 'Upload', 'apiInterceptor', '$interval', '$timeout','$q',
    function ($scope, $log, SweetAlert, customerService, enterpriseAccountService, uiGridConstants, $translate, Upload, apiInterceptor, $interval, $timeout, $q) {
        'use strict';
         
        var successAddMessage = $translate.instant('OrganizationStructureAddSuccess');
        var successEditMessage = $translate.instant('OrganizationStructureEditSuccess');
        var successDeleteMessage = $translate.instant('OrganizationStructureDeleteSuccess');
        var confirmToDelete = $translate.instant('ConfirmToDelete');
        var ImportErrorMsg = $translate.instant('ImportErrorMsg');
        var noItemSelected = $translate.instant('NoItemSelected');
        var depulicateNote = $translate.instant('CustomerDuplicateNode');
        var confirmImportOverwriteTitle = $translate.instant('ConfirmImportOverwriteTitle');
        var confirmImportOverwriteText = $translate.instant('ConfirmImportOverwriteText');

        var resumable = true;
        var uploadUrl = apiInterceptor.webApiHostUrl + '/customer/Upload';
        //var uploadUrl = apiInterceptor.webApiHostUrl + '/init/Upload';

        var showError = function (resultMsg) {

            var errMsg = $translate.instant(resultMsg);
            SweetAlert.warning(errMsg);
        };

        //获取企业账套列表
        var loadEnterpriseAccountSetList = function () {
            enterpriseAccountService.getEnterpriseAccountSetList().success(function (data) {
                if (data && data.length > 0) {
                    $scope.enterpriseAccountSetList = data;
                }
            });
        };

        //ng-repeat,根据字符串转换为json对象
        var getJson = function (obj) {
            if (obj) {
                return JSON.parse(obj);
            }

        }
        //根据账套ID获取客户列表
        var loadCustomerListBySetID = function () {

            resetErrorTab();
            resetUIGridStatus();

            var id = $scope.accountSetID;

            $scope.hasCustomerList = false;
            customerService.getByID(id).success(function (data) {
                if (data.customerList && data.customerList.length > 0) {
                    $scope.customerList = data.customerList;
                    $scope.gridOptions.data = data.customerList;

                    //查看是否有错误信息
                    loadImportErrorInfoList(data.validateInfoList);

                    $scope.hasCustomerList = true;
                }
                else {
                    $scope.hasCustomerList = false;
              
                }
            });
        };
      
        //reset hightlight to false.
        var setDefaultTheme = function () {
            if ($scope.gridOptions.data && $scope.gridOptions.data.length > 0) {
                $scope.gridOptions.data.forEach(function (row) {
                    row.isHighLight = false;
                });
            }
        };

        //当选择错误信息时,highlight data
        $scope.chooseRelavantRow = function (err) {

            //setDefaultTheme();

            if (err && err.inValidateCodeList && err.inValidateCodeList.length > 0) {
                err.inValidateCodeList.forEach(function (row) {

                    var matchList = _.filter($scope.gridOptions.data, function (num) {
                        return num.code === row
                    });

                    if (matchList && matchList.length > 0) {
                        matchList.forEach(function (row2) {
                            row2.isHighLight = !row2.isHighLight;
                        });
                    }

                });
            }
        };

        var loadImportErrorInfoList = function (data) {
            
            if (data && data.length > 0) {
                var totalLength = 0;
                var i = 1;
                data.forEach(function (row) {

                    totalLength += row.inValidateCodeList.length;

                    row.detail = row.inValidateCodeList.join(constant.comma);
                    if (row.type === 'CustomerDuplicateNode') {
                        row.isRepeatError = true;
                    } else {
                        row.isRepeatError = false;
                    }

                    row.type = $translate.instant(row.type);
                    row.index = i;
                    i++;
                });

                showErrTab(data,totalLength);

            }
            else {
                resetErrorTab();
            }
        };

        var init = function () {
            $('#importCustomerListSet').modal('hide');
            resetErrorTab();
            loadEnterpriseAccountSetList();
            CheckHasAccountSet();
        };
        //没有选择企业账套时,显示请选择账套
        var CheckHasAccountSet = function () {
            if (!$scope.accountSetID) {
                $scope.hasEnterpriseAccountSet = false;
                //没有选择账套,肯定没有客户列表
                $scope.hasCustomerList = false;
            }
            else {
                $scope.hasEnterpriseAccountSet = true;
            }
        };

        var resetErrorStatus = function () {
            var currentForm = $('#addcustomerForm');
            $.each(currentForm.children(), function (index, element) {
                $(element).find('.has-error').removeClass('has-error');
            });
            validator.resetForm();
        };

        var resources = {
            codeRequired: $translate.instant('CustomerCodeEmptyNode'),
            nameRequired: $translate.instant('CustomerNameEmptyNode'),
            customerDuplicateNode: $translate.instant('CustomerDuplicateNode')
        };


        $.validator.addMethod("codeDuplicate", function (value, element, param) {

            if ($scope.customerList && $scope.customerList.length > 0) {

                var objects = $.grep($scope.customerList, function (n, i) {
                    return $scope.editModel.id != n.id && $.trim(n.code) == $.trim(value);
                });

                return objects && objects.length < 1;  //if < 1, then pass the validation
            }
            return true;
        });


        var validator = $("#addcustomerForm").validate({
            errorClass: "has-error",
            rules: {
                code: {
                    required: true,
                    codeDuplicate: true
                },
                name: {
                    required: true
                }
            },
            messages: {
                code: {
                    required: resources.codeRequired,
                    codeDuplicate: depulicateNote
                },
                name: {
                    required: resources.nameRequired
                }
            },
            errorPlacement: function (error, element) {
                setErrorStyle(error, element);
            }
        });

        var setErrorStyle = function (error, element) {
            if (element.hasClass('has-error')) {
                element.parent().addClass('has-error');
                error.insertAfter(element);
                error.addClass('label');
            }
        };

        $scope.hideErrorLine = function () {
            $scope.ImportErrorLine = false;
            $scope.ImportErrorTab = false;  //不显示
            setErrorWrapCssDefault();
        };

        var resetErrorTab = function () {
            $scope.ImportErrorTab = false;
            $scope.ImportErrorTag = false;
            $scope.importErrorTips = null;
            $scope.ImportErrorLine = false;
            // $scope.errorGridOptions.data = [];
            resetErrorStatus();
        };

        $scope.search = function () {
            $scope.gridApi.grid.refresh();
        };

        var $contentResizerCustomer=$("#content-resizer-customer");
        var $topIcon = $("#customer-topIcon");
        var $customerErrorWarp = $("#customer-error-warp");
        //点击Icon切换显示错误列表
        $scope.toggleErrorTab = function () {
            $scope.ImportErrorTab = !$scope.ImportErrorTab;
            //topIcon and content-resize gapBottom 15px
            if (!$scope.ImportErrorTab) {
                setErrorWrapCssDefault();
            } else {

                var resizeBottemHeight = $contentResizerCustomer.css('bottom');
                $log.debug('resizeBottemHeight: ' + resizeBottemHeight);
                if (parseInt(resizeBottemHeight) < 130)
                {
                    $contentResizerCustomer.css('bottom', '130px');
                    $topIcon.css({
                        bottom: '124px',
                    });

                    $customerErrorWarp.css('height', '130px');
                }
            }
        };

        var setErrorWrapCssDefault = function () {
            $contentResizerCustomer.css('bottom', '26px');
            $topIcon.css({
                bottom: '20px',
            });

            $customerErrorWarp.css('height', '26px');
        };

        //enterprise list onchange then repopulate the customer list
        $scope.loadCustomerListBySetID = function () {
            CheckHasAccountSet();
        
            loadCustomerListBySetID();
            setErrorWrapCssDefault();
        };

        var resetUIGridStatus = function () {
            //切换 的时候设置全选为false
            $scope.gridApi.grid.selection.selectAll = false;
            $scope.gridOptions.data = [];
            $scope.gridErrorOptions.data = [];
            $scope.customerList = null;
        };

        //when import failed, then show error list
        var showErrTab = function (data,errorLength) {
            $scope.ImportErrorTab = false;  //默认不显示
            $scope.ImportErrorTag = true;
            $scope.ImportErrorLine = true;
            $scope.importErrorTips = $translate.instant('ImportErrorTips').format(errorLength);
            $scope.gridErrorOptions.data = data;
        };
       
        $scope.popupImportFileModel = function () {
            if ($scope.file) $scope.file = null;
            $('#importCustomerListSet').modal('show');
        };
    
        //pop up model to add or edit customer
        var fillModel = function () {
            resetErrorStatus();
            $scope.editModel = {};

            var set = _.find($scope.enterpriseAccountSetList, function(num){return num.id === $scope.accountSetID;});

            $scope.editModel.enterpriceAccountSetName = set.name;
            $scope.editModel.enterpriseAccountSetID = $scope.accountSetID;
        };

        $scope.popupNewCustomer = function ()
        {
            $scope.isAdd = true;
            fillModel();
            $('#addCustomerModel').modal('show');
        }
       
        $scope.popupEditCustomer = function (customer) {

            $scope.gridApi.selection.clearSelectedRows();
            $scope.isAdd = false;
            fillModel();
            $scope.editModel = angular.extend($scope.editModel, customer);

            $('#addCustomerModel').modal('show');
        }

        //save or edit customer
        $scope.saveCustomer = function () {

            if (!($('#addcustomerForm').valid())) {
                return;
            }

            var customer = [];

            var enterpriseAccountSetID = $scope.accountSetID;
            var code = $scope.editModel.code;
            var name = $scope.editModel.name;
            if (!code || !name) return false;

            //add customer
            if ($scope.isAdd) {
                customer.push({ id: PWC.newGuid(), code: code, name: name, enterPriseAccountID: enterpriseAccountSetID });
                customerService.addRange(customer).success(function (data) {
                    var result = data[0];
                    if (result && result.data && result.result == false && result.resultMsg != null) {
                        showError(result.resultMsg);
                        return false;
                    }
                    $('#addCustomerModel').modal('hide');
                    SweetAlert.success(successAddMessage);
                    loadCustomerListBySetID();
                });
            }
                //edit customer
            else {
                customer.push({ id: $scope.editModel.id, code: code, name: name, enterPriseAccountID: enterpriseAccountSetID });

                customerService.updateRange(customer).success(function (data) {
                    var result = data[0];
                    if (result && result.data && result.result == false && result.resultMsg != null) {
                        showError(result.resultMsg);
                        return false;
                    }
                    $('#addCustomerModel').modal('hide');
                    SweetAlert.success(successEditMessage);
                    loadCustomerListBySetID();
                });
            }
        };

        var confirmWarningWindow = function (title, text) {
            var deferred = $q.defer();
            SweetAlert.swal({
                title: title,
                text: text,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                allowOutsideClick:false,
                confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: false,
                closeOnCancel: true
            },
              function (isConfirm) {
                  deferred.resolve(isConfirm);
              });

            return deferred.promise;
        };

        $scope.deleteSelectedCustomers = function () {

            var selectedRows = $scope.gridApi.selection.getSelectedRows();
            if (selectedRows.length === 0) {
                SweetAlert.warning(noItemSelected);
                return;
            }

            confirmWarningWindow(confirmToDelete, '').then(function (data) {
                if (data) {
                    var customerArr = [];
                    selectedRows.forEach(function (item) {
                        customerArr.push(item);
                    });

                    deleteCustomer(customerArr);
                }
            });
        };
        //delete customer action
        var deleteCustomer = function (customerArr) {

            customerService.deleteRange(customerArr).success(function (result) {
                SweetAlert.success(successDeleteMessage);
                loadCustomerListBySetID();
            });
        };

        //delete single row customer
        $scope.removeCustomer = function (customer) {

            $scope.gridApi.selection.clearSelectedRows();

            confirmWarningWindow(confirmToDelete, '').then(function (data) {
                if (data) {
                    var customerArr = [];
                    customerArr.push(customer);
                    deleteCustomer(customerArr);
                }
            });
        };

        //覆盖导入
        $scope.ImportCustomerOverwrite = function () {
            if (!$scope.file || !$scope.file.name) {

                SweetAlert.warning($translate.instant('SelectCustomerFileRequired'));
                return;
            }
            confirmWarningWindow(confirmImportOverwriteTitle, confirmImportOverwriteText).then(function (data) {
                if (data) {
                    ImportCustomer(constant.import.overwrite);
                }
            });
        };

        //追加导入
        $scope.ImportCustomerAppend = function () {

            ImportCustomer(constant.import.append);
        }
        //upload file
        var ImportCustomer = function (action) {
          
            if (!$scope.file || !$scope.file.name) {

                SweetAlert.warning($translate.instant('SelectCustomerFileRequired'));
                return;
            }

            var tempFileName = PWC.newGuid() + '.dat';
         
            var token = $('input[name="__RequestVerificationToken"]').val();
            // updateProgressToZero();
            Upload.upload({
                url: uploadUrl,
                data: {
                    cancel: false,
                    enterpriseAccountID: $scope.accountSetID,
                    filename: $scope.file.name,
                    tempFileName: tempFileName,
                    action:  action
                },
                file: $scope.file,
                resumeChunkSize: resumable ? $scope.chunkSize : null,
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken,
                    __RequestVerificationToken: token,
                    withCredentials: true
                }, withCredentials: true
            }).then(function (resp) {
                // $log.debug('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + JSON.stringify(resp.data));
                var ret = resp.data;
                if (ret && ret.length == 0) {
                    // 全部导入成功
                    $('#importCustomerListSet').modal('hide');
                    SweetAlert.success($translate.instant('ImportSuccess'));
                } else {
                    // 提示没有导入成功的数据
                    //var errorInfo = $translate.instant('ImportPartialSuccess');
                    var errorMsg = '';
                    if (ret[0].resultMsg && constant.customer.errorArray.indexOf(ret[0].resultMsg) > -1) {
                        errorMsg = ret[0].resultMsg;
                    }
                    else {
                        errorMsg = 'ImportPartialSuccess';
                    }
                    var errorInfo = $translate.instant(errorMsg);
                    SweetAlert.swal({
                        title: $translate.instant('BasicDataCustomer'),
                        text: errorInfo,
                        type: "warning",
                        showCancelButton: false,
                        closeOnConfirm: false,
                        closeOnCancel: true,
                        html: true
                    });
                   $("#importCustomerListSet").modal('hide');
                }
                loadCustomerListBySetID();

            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                $log.debug('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            });

        };


        var initErrorUIGrid = function () {
            $scope.gridErrorOptions = {
                rowHeight: constant.UIGrid.errorRowHeight,
                selectionRowHeaderWidth: constant.UIGrid.errorRowHeaderWidth,
                enableColumnMenus: false,
                enableSorting: true,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                enableRowSelection: false, // 行选择是否可用,默认为true; 如果想选择任意位置和勾勾,需要设置为false
                enableRowHeaderSelection: false,
               // enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                enableSelectAll: false, // 选择所有checkbox是否可用,默认为true; 
                multiSelect: false,// 是否可以选择多个,默认为true;
                columnDefs: [
                    {
                        field: 'SequenceNo',
                        name: $translate.instant('SequenceNo'),
                        width: '15%',
                        cellTemplate: '<div  class="text-align-left-padding" ng-click="grid.appScope.chooseRelavantRow(row.entity)"><span>{{row.entity.index}}</span></div>'
                    },
                   {
                       field: 'type',
                       name: $translate.instant('ErrorMesssage'),
                       width: '20%',
                       cellTemplate: '<div  class="text-align-left-padding" ng-click="grid.appScope.chooseRelavantRow(row.entity)"><span>{{row.entity.type}}</span></div>'
                   },
                    {
                        field: 'detail',
                        name: $translate.instant('CustomerCode'),
                        cellTemplate: '<div  class="text-align-left-padding" ng-click="grid.appScope.chooseRelavantRow(row.entity)">' +
                          '<span title="{{row.entity.detail}}">{{row.entity.detail | limitString:95 }}</span>' +
                      '</div>',
                        width: '65%'

                    }
               

                ],

                onRegisterApi: function (gridApi) {
                    $scope.grideErrorApi = gridApi;

                    $interval(function () {
                        $scope.grideErrorApi.core.handleWindowResize();
                    }, 500, 60 * 60 * 8);
                }
            }
        };


        $scope.getGridHeight = function () {

            if ($scope.isLoadComplete && $scope.hasCustomerList) {
                var y = $("#customerDataList").height();

                // Enough space
                if (y > constant.UIGrid.gapHeight) {
                    y = y - constant.UIGrid.gapHeight;
                    return { height: y + "px" };
                } else {

                    return { height: '0px' };
                }
            }

            return {};
        };

        $scope.getErrorGridHeight = function () {

            if ($scope.isLoadComplete) {
                var y = $("#customer-error-warp").height();

                // Enough space
                if (y > constant.UIGrid.gapHeight) {
                    y = y - constant.UIGrid.gapHeight;
                    return { height: y + "px" };
                } else {

                    return { height: '0px' };
                }
            }

            return {};
        };

        var initListUIGrid = function () {

            var operateStr = '';

            if ($scope.hasEditPermission){
                operateStr = '<div class="ui-grid-cell-contents> <a class="operate-btn" href="javascript:void(0)">\
                                <i class="material-icons">&#xE254;</i>&nbsp;\
                                <span ng-click="grid.appScope.popupEditCustomer(row.entity)">{{"Edit"|translate}}</span>\ </a>\&nbsp;&nbsp;| &nbsp;&nbsp;\
                             <a class="operate-btn" href="javascript:void(0)">\
                                <i class="material-icons highlight-tag">&#xE872;</i>&nbsp;\
                                <span ng-click="grid.appScope.removeCustomer(row.entity)">{{"Delete"|translate}}</span>\ </a>'+
                                '</div>';

            } else{
                                
                operateStr = '<div class="ui-grid-cell-contents '+constant.noPermissionClass + '">\
                                <a class="operate-btn" href="javascript:void(0)" >\
                                <i class="material-icons">&#xE254;</i>&nbsp;\
                                <span>{{"Edit"|translate}}</span>\ </a>\&nbsp;&nbsp;| &nbsp;&nbsp;\
                             <a class="operate-btn" href="javascript:void(0)">\
                                <i class="material-icons highlight-tag">&#xE872;</i>&nbsp;\
                                <span>{{"Delete"|translate}}</span>\ </a>'+
                                '</div>';
            }

            $scope.gridOptions = {
                rowHeight: constant.UIGrid.rowHeight,
                selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
                enableSorting: true,
                enableColumnMenus: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                enableRowSelection: false, // 行选择是否可用,默认为true; 如果想选择任意位置和勾勾,需要设置为false
                enableRowHeaderSelection: true,
                enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                enableSelectAll: true, // 选择所有checkbox是否可用,默认为true; 
                multiSelect: true,// 是否可以选择多个,默认为true;
                virtualizationThreshold: 60,
                rowTemplate: '<div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ng-class="{\'ui-grid-row-header-cell\':col.isRowHeader,\'red-color\':row.entity.isHighLight }"  ui-grid-cell></div>',

                columnDefs: [
                    {
                        field: 'code',
                        name: $translate.instant('CustomerCode'),
                        width: '35%',
                        cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.code}}">{{row.entity.code}}</span></div>'
                    },
                    {
                        field: 'name',
                        name: $translate.instant('CustomerName'),
                        width: '40%',
                        cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.name}}">{{row.entity.name}}</span></div>'
                    },
                    {
                        field: 'Operation',
                        name: $translate.instant('Operation'),
                        cellTemplate: operateStr,

                        width: '25%',
                        headerCellClass: 'operate-text-align-center'
                         
                    }
                ],

                onRegisterApi: function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.grid.registerRowsProcessor($scope.singleFilter, 200);

                    var onRowsRenderedOff = gridApi.core.on.rowsRendered(null, function () {
                        onRowsRenderedOff(); // run once
                        PWC.triggerRowSelectOnClick('#customerlistUIGrid'); 
                    });

                    $interval(function () {
                        $scope.gridApi.core.handleWindowResize();
                    }, 500, 60 * 60 * 8);
                }
            };

            $scope.singleFilter = function (renderableRows) {
              
                var matcher = new RegExp($scope.searchEASText);
                renderableRows.forEach(function (row) {

                    try {
                        var match = false;
                        ['code', 'name'].forEach(function (field) {
                            if (row.entity[field].match(matcher)) {
                                match = true;
                            }
                        });
                        if (!match) {
                            row.visible = false;
                        }
                    } catch (e) {
                        $log.debug('singleFilter-match:' + JSON.stringify(row.entity));
                    }
                });
                return renderableRows;
            };

        };
 

         var havePermission = function() {
                $scope.$root.checkUserPermission(constant.adminPermission.basicData.customerList.editCode).success(function(data) {
                    $scope.hasEditPermission = data;

                    initListUIGrid();
                    initErrorUIGrid();
                    init();
           
                });
            };

        (function initialize() {

            $scope.hasEditPermission = false;
            havePermission();

            $scope.isLoadComplete = false;
            $log.debug('customerListManageController.ctor()...');
            $timeout(function () {

                $scope.isLoadComplete = true;

            }, 500);

        })();
    }
]);
basicDataModule.directive('customerListManage', ['$log', 'SweetAlert', '$translate',
    function ($log, SweetAlert, $translate) {
        'use strict';
        $log.debug('customerListManageController.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/financialData/customerListManage/customer-list-manage.html' + '?_=' + Math.random(),
            scope:
            {
                //addCustFn: '&addCustomer',
                //removeCustlFn: '&removeCustomer',
                //editCustFn: '&editCustomer',
                //deleteCustFn:'&removeCustomer',
                //attr: '@',
                //list:'=bind'
            },
            controller: 'customerListManageController'
            //link: function (scope, element, attrs, $element) {
                
        };
    }
]);
basicDataModule.directive('slideToggle', function () {
    return {
        restrict: 'A',      
        scope:{
            isOpen: "=slideToggle"
        },  
        link: function(scope, element, attr) {
            var slideDuration = parseInt(attr.slideToggleDuration, 10) || 200; 
            if (attr.startShown=="false") {
                element.hide();
            }
            scope.$watch('isOpen', function(newVal,oldVal){
                if(newVal !== oldVal){ 
                    element.stop().slideToggle(slideDuration);
                }
            });
        }
    }; 
});


basicDataModule
    .controller('EnterpriseAccountManageController', ['$scope', '$log', 'SweetAlert', 'keywordmapService', 'uiGridConstants', '$translate', 'enterpriseAccountService', 'Upload', 'apiInterceptor', 'templateFormulaService', 'stdAccountService', '$interval', '$timeout', '$q', 'region',
        function ($scope, $log, SweetAlert, keywordmapService, uiGridConstants, $translate, enterpriseAccountService, Upload, apiInterceptor, templateFormulaService, stdAccountService, $interval, $timeout, $q, region) {

            'use strict';

            // default enterprise account
            var defaultEnterpriceAccount = {
                id: '0',
                name: '',
                fullName: '',
                code: '',
                parentCode: '',
                acctLevel: 0,
                selectValue: ' '
            };

            // 添加关联机构ID
            var addEnterpriceAccountSetRelevantOrg = 'addEnterpriceAccountSetRelevantOrg';

            // 编辑关联机构
            var updateEnterpriceAccountSetRelevantOrg = 'updateEnterpriceAccountSetRelevantOrg';

            var expiredDateTo = $translate.instant('ExpiredDateTo');
            // upload file url
            var uploadUrl = apiInterceptor.webApiHostUrl + '/enterpriseAccountManage/Upload';
            var resumable = true;

            // is active map
            var isActiveMap = {
                false: 'Disable',
                true: 'Enable'
            };

            // is actived map
            var isActivedMap = {
                false: 'Disabled',
                true: 'Enabled'
            };

            var parseObj = function (obj) {
                return JSON.parse(obj);
            }

            $scope.enterpriseAccountSetSelect = function (obj) {

                if (obj) {
                    // set
                    $scope.enterpriseAccountSetSelectJson = obj.id;
                } else {

                    // get
                    if ($scope.enterpriseAccountSetSelectJson) {

                        var obj = _.find($scope.enterpriseAccountList, function (num) {
                            return num.id === $scope.enterpriseAccountSetSelectJson;
                        });

                        return obj;
                    } else {
                        return null;
                    }
                }
            };

            $scope.selectStandardAccount = function (obj) {
                if (obj) {
                    // set
                    $scope.selectStandardAccountID = obj.id;
                } else {

                    // get
                    if ($scope.selectStandardAccountID) {
                        return _.find($scope.enterpriceAccountList, function (num) {
                            return num.id === $scope.selectStandardAccountID
                        });

                    } else {
                        return null;
                    }
                }
            };

            // last edit code
            $scope.lastCode = null;

            // all enterprise account list
            var allEnterpriceAccountList = [];

            var errorTypeList = [
                constant.enterpriceAccount.codeEmpty,
                constant.enterpriceAccount.codeMaxLength,
                constant.enterpriceAccount.enterpriseAccountNameEmpty,
                constant.enterpriceAccount.nameMaxLength,
                constant.enterpriceAccount.directionFormatError,
                constant.enterpriceAccount.acctPropFormatError,
                constant.enterpriceAccount.noParentCode
            ];

            // load enterprice account list
            var loadEnterpriceAccountList = function () {
                enterpriseAccountService.getListByEnterpriseAccountSetID($scope.enterpriseAccountSetSelectID).success(function (result) {

                    var data = result.enterpriseAccountList;

                    data.forEach(function (row) {

                        row.selectValue = row.code + ' ' + row.fullName;
                        row.isActiveStr = $translate.instant(isActivedMap[row.isActive]);

                        if (row.parentCode) {
                            row.parent = row.parentCode + ' ' + row.parentName;
                        } else {
                            row.parent = '';
                        }

                        row.directionStr = $scope.directionMap[row.direction + ''];

                        if (row.acctProp <= 6 && row.acctProp >= 0) {
                            row.acctPropStr = $scope.acctPropArray[row.acctProp];
                        } else {
                            //row.acctPropStr = row.acctProp + '';
                            row.acctPropStr = '';
                        }

                    });

                    var list = data.concat();
                    list = _.sortBy(list, 'code');

                    if (list && list.length > 0) {
                        list.splice(0, 0, defaultEnterpriceAccount);
                    } else {
                        list = [];
                        list.push(defaultEnterpriceAccount);
                    }

                    $scope.enterpriceAccountList = list;

                    allEnterpriceAccountList = copyArray(list);
                    $scope.gridOptions.data = data;
                    $scope.gridOptions.noData = data.length === 0;
                    setDefaultTheme();
                    if ($scope.lastCode) {

                        var entity = _.find(list, function (num) {
                            return num.code === $scope.lastCode;
                        });
                        if (entity) {
                            $scope.singleSelected = {};
                            $scope.singleClick(entity);
                            scrollSetting();
                        }
                    }

                    loadImportErrorInfoList(result.validateInfoList);
                });
            };

            var loadImportErrorInfoList = function (data) {
                setErrorWrapCssDefault();

                if (data && data.length > 0) {
                    var i = 1;
                    data.forEach(function (row) {
                        row.detail = row.inValidateCodeList.join(constant.comma);
                        if (row.type === 'EnterpriceAccountRepeat') {
                            row.isRepeatError = true;
                        } else {
                            row.isRepeatError = false;
                        }

                        row.type = $translate.instant(row.type);
                        row.index = i;
                        i++;
                    });
                }

                $scope.importErrorInfoList = data;

                $scope.importErrorTips = $translate.instant('ImportErrorTips').format($scope.importErrorInfoList.length);
                if ($scope.importErrorInfoList && $scope.importErrorInfoList.length > 0) {
                    $scope.ImportErrorTag = true;

                    $timeout(function () {
                        $scope.toggleErrorTab();

                    }, 100);

                } else {
                    $scope.ImportErrorTag = false;
                }
                $scope.ImportErrorTab = false;

                $scope.errorGridOptions.data = data;

            };

            // copy array
            var copyArray = function (data) {
                var copyRet = [];
                if (data && data.length > 0) {
                    data.forEach(function (row) {
                        copyRet.push(row);
                    });
                }

                return copyRet;
            };

            // load enterpriseAccountSetList
            var loadEnterpriseAccountSetList = function () {


                enterpriseAccountService.getEnterpriseAccountSetList().success(function (data) {

                    if (data && data.length > 0) {
                        // data = _.sortBy(data, 'name');
                        data = sortByEnterpriseName(data);
                    }

                    $scope.enterpriseAccountSetList = data;

                    if (data && data.length > 0) {
                        $scope.hasEnterpriseAccountSet = true;

                        // 默认设置为上次编辑或者添加的账套
                        // 如果没有就设置为第一条数据
                        var setDefault = false;
                        if ($scope.editModel && $scope.editModel.name && $scope.editModel.name.length > 0) {
                            var first = _.find(data, function (num) {
                                return num.name === $scope.editModel.name
                            });

                            if (first && first.name) {
                                $scope.enterpriseAccountSetSelectID = first.id;
                                setDefault = true;
                            }
                        }

                        if (!setDefault) {
                            $scope.enterpriseAccountSetSelectID = data[0].id;
                        }

                        $scope.changeEnterpriseAccountSet();

                        //loadEnterpriceAccountList();
                    } else {
                        $scope.hasEnterpriseAccountSet = false;
                    }
                });
            };

            // 添加关联机构列表
            $scope.newRelevantOrgList = function () {

                $scope.editModel = {};
                $scope.isAdd = true;
                var set = _.find($scope.enterpriseAccountSetList, function (num) {
                    return num.id === $scope.enterpriseAccountSetSelectID
                });
                $scope.editModel.id = $scope.enterpriseAccountSetSelectID;

                $scope.editModel.name = set.name;
                $scope.editModel.enterpriseAccountSetOrgList = [];

                $scope.addEnterpriseAccountSetOrg();

                $('#' + addEnterpriceAccountSetRelevantOrg).modal('show');
            };



            $scope.changeEnterpriseAccountSet = function () {
                if (!$scope.enterpriseAccountSetSelectID) {
                    return;
                }

                $scope.ImportErrorTag = false;
                $scope.ImportErrorTab = false;
                loadEnterpriceAccountList();

                loadEnterpriseAccountSet();
            };

            var loadEnterpriseAccountSet = function () {
                enterpriseAccountService.getEnterpriseAccountSet($scope.enterpriseAccountSetSelectID).success(function (data) {

                    if (data && data.enterpriseAccountSetOrgList && data.enterpriseAccountSetOrgList.length > 0) {

                        data.enterpriseAccountSetOrgList.forEach(function (row) {
                            // {{row.entity.effectiveDateStr}}{{"ExpiredDateTo"|translate}}{{row.entity.expiredDateStr}}

                            if (!row.effectiveDateStr && !row.expiredDateStr) {

                            } else {
                                row.effectiveSection = row.effectiveDateStr + expiredDateTo + row.expiredDateStr;

                                if (!row.effectiveDateStr && row.expiredDateStr) {
                                    row.isRight = true;
                                }
                            }

                        });

                    }

                    $scope.orgGridOptions.data = data.enterpriseAccountSetOrgList;
                });
            };

            var load = function () {

                if ($scope.singleSelected && $scope.singleSelected.id) {
                    // 选中
                    enterpriseAccountService.get($scope.singleSelected.id).success(function (data) {
                        $scope.editModel = data;

                        // $scope.enterpriceAccountList = _.filter(allEnterpriceAccountList, function(num) {
                        //  return num.code !== data.code
                        // });

                        $scope.enterpriceAccountList = getParentList(allEnterpriceAccountList, data.code);
                        // $scope.selectStandardAccount(_.find($scope.enterpriceAccountList, function(num) {
                        //     return num.code === data.parentCode
                        // }));

                        // if (!$scope.selectStandardAccount()) {
                        //     $scope.selectStandardAccount(defaultEnterpriceAccount);
                        // }

                        $scope.selectDirection = _.find($scope.directionList, function (num) {
                            return num.id === data.direction
                        });
                        $scope.selectAcctProp = _.find($scope.acctPropList, function (num) {
                            return num.id === data.acctProp
                        });
                        $scope.isAdd = false;
                    });
                    resetErrorStatus();
                    $('#addEnterpriceAccountPop').modal('show');
                } else {
                    $log.debug('please select one keywordMap...');
                    SweetAlert.warning($translate.instant('PleaseChooseEnterpriseAccount'));
                    return;
                }
            };

            var getParentList = function (allEnterpriceAccountList, code) {

                var currentSubList = getSubEnterpriseAccountList(allEnterpriceAccountList, code);

                var notCurrentNodeList = _.filter(allEnterpriceAccountList, function (num) {
                    return num.code !== code;
                });


                var notCurrentAndSubNodeList = notCurrentNodeList;
                if (notCurrentNodeList && notCurrentNodeList.length > 0 && currentSubList && currentSubList.length > 0) {
                    notCurrentAndSubNodeList = _.filter(notCurrentNodeList, function (num) {
                        var inSubNode = _.find(currentSubList, function (num2) {
                            return num2.code === num.code;
                        });

                        if (inSubNode) {
                            return false;
                        } else {
                            return true;
                        }
                    });
                }

                return notCurrentAndSubNodeList;
            };

            var getSubEnterpriseAccountList = function (allEnterpriceAccountList, code) {
                var list = _.filter(allEnterpriceAccountList, function (num) {
                    return num.parentCode === code;
                });

                if (list && list.length > 0) {
                    list.forEach(function (row) {
                        var tempList = getSubEnterpriseAccountList(allEnterpriceAccountList, row.code);

                        if (tempList && tempList.length > 0) {
                            list = _.union(list, tempList);
                        }
                    });
                }

                return list;
            };

            $scope.codeChange = function (code) {
                $scope.editModel.checkHasParent = true;
                if (code) {

                    var result = null;
                    for (var i = code.length - 1; i >= 0; i--) {
                        result = _.find($scope.enterpriceAccountList, function (num) {
                            return num.code === code.substr(0, i);
                        });

                        if (result) {
                            break;
                        }
                    }

                    if (result) {
                        $scope.editModel.parentCode = result.code;
                        $scope.editModel.parentFullName = result.fullName;
                        $scope.editModel.parentAcctLevel = result.acctLevel;
                    }
                }

            };

            var save = function () {
                if (!$scope.editModel.checkHasParent) {
                    // 直接点的保存,没有上级科目
                    $scope.codeChange($scope.editModel.code);
                }

                if (!($('#addEnterpriceAccountForm').valid())) {
                    return;
                }

                $scope.editModel.isActive = true;
                $scope.editModel.ruleType = 2;
                $scope.editModel.enterpriseAccountSetID = $scope.enterpriseAccountSetSelectID;

                if ($scope.editModel.parentCode && $scope.editModel.parentCode.length > 0) {
                    $scope.editModel.fullName = $scope.editModel.parentFullName + '-' + $scope.editModel.name;
                    $scope.editModel.acctLevel = $scope.editModel.parentAcctLevel + 1;
                } else {
                    $scope.editModel.acctLevel = 1;
                    $scope.editModel.fullName = $scope.editModel.name;
                    $scope.editModel.parentCode = null;
                }

                if ($scope.selectDirection && $scope.selectDirection.id) {
                    $scope.editModel.direction = $scope.selectDirection.id;
                }

                if ($scope.selectAcctProp && $scope.selectAcctProp.id) {
                    $scope.editModel.acctProp = $scope.selectAcctProp.id;
                }

                if ($scope.isAdd) {
                    enterpriseAccountService.add($scope.editModel).success(function (data) {
                        if (!data.result) {
                            var errorList = [];
                            var template = $translate.instant(data.resultMsg);
                            SweetAlert.warning(template);
                            return;
                        };

                        $scope.lastCode = $scope.editModel.code;

                        SweetAlert.success($translate.instant('SaveSuccess'));
                        $('#addEnterpriceAccountPop').modal('hide');
                        loadEnterpriceAccountList();
                    });
                } else {
                    enterpriseAccountService.update($scope.editModel).success(function (data) {
                        if (!data.result) {
                            var errorList = [];
                            var template = $translate.instant(data.resultMsg);

                            SweetAlert.warning(template);
                            return;
                        };

                        $scope.lastCode = $scope.editModel.code;
                        SweetAlert.success($translate.instant('SaveSuccess'));

                        $('#addEnterpriceAccountPop').modal('hide');
                        loadEnterpriceAccountList();
                    });
                }
            };

            var search = function () {
                $scope.dataGridApi.grid.refresh();
            };

            // 新增
            var newModel = function () {
                $scope.editModel = {};

                $scope.isAdd = true;
                $scope.enterpriceAccountList = allEnterpriceAccountList;
                $scope.selectStandardAccount(defaultEnterpriceAccount);
                $scope.selectDirection = null;
                $scope.selectAcctProp = _.find($scope.acctPropList, function (num) {
                    return num.id === -1
                });
                $scope.file = null;
                resetErrorStatus();
                $('#addEnterpriceAccountPop').modal('show');
            };

            var resetErrorStatus = function () {
                var currentForm = $('#addEnterpriceAccountForm');
                $('#addEnterpriceAccountForm .has-error > label').remove();

                $('#addEnterpriceAccountForm').find('.has-error').removeClass('has-error');
                validator.resetForm();
            };

            var resources = {
                codeRequired: $translate.instant('EnterpriceAccountCodeRequired'),
                nameRequired: $translate.instant('EnterpriceAccountNameRequired'),
                selectDirectionRequired: $translate.instant('StandardAccountRequired'),
                //selectAcctPropRequired: $translate.instant('StandardAccountAccountTypesRequired'),
                setnameRequired: $translate.instant('EnterpriceAccountSetNameRequired'),
                setcodeRequired: $translate.instant('EnterpriseAccountSetCodeRequired'),
                setfileRequired: $translate.instant('EnterpriceAccountSetFileRequired'),
                enterpriseAccountSetNameRepeat: $translate.instant('EnterpriseAccountSetNameRepeat'),
                enterpriseAccountSetCodeRepeat: $translate.instant('EnterpriseAccountSetCodeRepeat'),
                organizationRequired: $translate.instant('SelectOrganizationRequired'),
                effectiveDateRequired: $translate.instant('EffectiveDateRequired'),
                expiredDateRequired: $translate.instant('ExpiredDateRequired')
            };


            var validator = $("#addEnterpriceAccountForm").validate({
                errorClass: "has-error",
                rules: {
                    code: {
                        required: true
                    },
                    name: {
                        required: true
                    },
                    selectDirection: {
                        required: true
                    },
                    //selectAcctProp: {
                    //    required: true
                    //},
                    organization: {
                        required: true
                    },
                    effectiveDate: {
                        required: true
                    },
                    expiredDate: {
                        required: true
                    }
                },
                messages: {
                    code: {
                        required: resources.codeRequired
                    },
                    name: {
                        required: resources.nameRequired
                    },
                    selectDirection: {
                        required: resources.selectDirectionRequired
                    },
                    //selectAcctProp: {
                    //    required: resources.selectAcctPropRequired
                    //},
                    organization: {
                        required: resources.organizationRequired
                    },
                    effectiveDate: {
                        required: resources.effectiveDateRequired
                    },
                    expiredDate: {
                        required: resources.expiredDateRequired
                    }

                },
                errorPlacement: function (error, element) {
                    setErrorStyle(error, element);
                }
            });

            var setErrorStyle = function (error, element) {
                if (element.hasClass('has-error')) {
                    element.parent().addClass('has-error');
                    error.insertAfter(element);
                    error.addClass('label');
                }
            };

            var validatorset = $("#addEnterpriceAccountSetForm").validate({
                errorClass: "has-error",
                rules: {
                    name: {
                        required: true,
                        remote: {
                            type: "get",
                            url: apiInterceptor.webApiHostUrl + "/enterpriseAccountManage/enterpriseAccountSetNameValidate",
                            data: {
                                id: function () {
                                    return $("#enterpriseAccountSetID").val();
                                },
                                name: function () {
                                    return $("#enterpriseAccountSetName").val();
                                }
                            },
                            dataType: "json",
                            dataFilter: function (data, type) {

                                var ret = JSON.parse(data);
                                if (ret && ret.result)
                                    return true;
                                else
                                    return false;
                            }
                        }
                    },
                    code: {
                        required: true,
                        remote: {
                            type: "get",
                            url: apiInterceptor.webApiHostUrl + "/enterpriseAccountManage/enterpriseAccountSetCodeValidate",
                            data: {
                                id: function () {
                                    return $("#enterpriseAccountSetID").val();
                                },
                                code: function () {
                                    return $("#enterpriseAccountSetCode").val();
                                }
                            },
                            dataType: "json",
                            dataFilter: function (data, type) {

                                var ret = JSON.parse(data);
                                if (ret && ret.result)
                                    return true;
                                else
                                    return false;
                            }
                        }
                    },
                    fileName: {
                        // 把这条注释条, ng-required生效
                        // required: true
                    },
                    organization: {
                        // required: true
                    },
                    effectiveDate: {
                        // required: true
                    },
                    expiredDate: {
                        // required: true
                    }

                },
                messages: {
                    name: {
                        required: resources.setnameRequired,
                        remote: resources.enterpriseAccountSetNameRepeat
                    },
                    code: {
                        required: resources.setcodeRequired,
                        remote: resources.enterpriseAccountSetCodeRepeat
                    },
                    fileName: {
                        required: resources.setfileRequired
                    },
                    organization: {
                        required: resources.organizationRequired
                    },
                    effectiveDate: {
                        required: resources.effectiveDateRequired
                    },
                    expiredDate: {
                        required: resources.expiredDateRequired
                    }

                },
                errorPlacement: function (error, element) {
                    setErrorStyle(error, element);
                }
            });

            var resetErrorStatusSet = function () {
                var currentForm = $('#addEnterpriceAccountSetForm');
                $('#addEnterpriceAccountSetForm .has-error > label').remove();
                currentForm.find('.has-error').removeClass('has-error');
                validatorset.resetForm();
            };

            var modifyIsActive = function () {

                if ($scope.singleSelected && $scope.singleSelected.id) {

                    SweetAlert.swal({
                        title: $translate.instant('Confirm') + $scope.isActiveBtStr + '?',
                        text: $translate.instant('ComfirmEnterpriceAccountIsActive').formatObj({
                            isActiveStr: $scope.isActiveBtStr,
                            code: $scope.singleSelected.code,
                            fullName: $scope.singleSelected.fullName
                        }),
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: $translate.instant('Confirm'),
                        cancelButtonText: $translate.instant('Cancel'),
                        closeOnConfirm: false,
                        closeOnCancel: true
                    },
                        function (isConfirm) {
                            if (isConfirm) {
                                // 选中
                                var model = $scope.singleSelected;
                                model.isActive = !model.isActive;
                                enterpriseAccountService.isactive(model).success(function (data) {

                                    // SweetAlert.info('info', 'log success');
                                    if (!data.result) {
                                        model.isActive = !model.isActive;
                                        //SweetAlert.swal($translate.instant(data.resultMsg));
                                        SweetAlert.warning($translate.instant(data.resultMsg));
                                        return;
                                    } else {

                                        SweetAlert.success($translate.instant('SaveSuccess'));
                                        //SweetAlert.swal($translate.instant('Confirm') + $scope.isActiveBtStr, $translate.instant('Confirm') + $scope.isActiveBtStr + $translate.instant("SaveSuccess"), "success");
                                        loadEnterpriceAccountList();

                                        var newModel = _.find($scope.gridOptions.data, function (num) {
                                            return num.id === model.id
                                        });
                                        newModel.repeatSingleClick = true;
                                        $scope.singleClick(newModel);
                                    }
                                });
                            }
                        });
                } else {
                    $log.debug('please select one keywordMap...');
                }
            };

            $scope.parentChange = function () {

                var tempselectStandardAccount = $scope.selectStandardAccount();
                if (tempselectStandardAccount && tempselectStandardAccount.code && tempselectStandardAccount.code.length > 0) {
                    $scope.selectDirection = _.find($scope.directionList, function (num) {
                        return num.id === tempselectStandardAccount.direction
                    });
                    $scope.selectAcctProp = _.find($scope.acctPropList, function (num) {
                        return num.id === tempselectStandardAccount.acctProp
                    });
                } else {
                    $scope.selectDirection = null;
                    $scope.selectAcctProp = null;
                }
            };

            $scope.newAccountSetModal = function () {
                $scope.editModel = {};
                $scope.editModel.enterpriseAccountSetOrgList = [];
                $scope.editModel.RegionNames = '';
                $scope.isAdd = true;
                resetErrorStatusSet();
                $scope.file = null;
                $('#addEnterpriceAccountSetPop').modal('show');
            };

            $scope.saveEnterpriseAccountSet = function () {

                resetErrorStatusSet();
                if (!($('#addEnterpriceAccountSetForm').valid())) {
                    return;
                }

                if ($scope.isAdd && !$scope.file) {
                    SweetAlert.warning($translate.instant(resources.setfileRequired));
                    return;
                }

                enterpriseAccountSetOrgValidate();
            };

            // 验证机构唯一性
            var enterpriseAccountSetOrgValidate = function () {
                var model = {
                    id: $scope.editModel.id,
                    enterpriseAccountSetOrgList: []
                };

                // if (!getEnterpriseAccountSetOrgListUI()) {
                //     return;
                // }

                // model.enterpriseAccountSetOrgList = $scope.editModel.saveOrgList;

                enterpriseAccountService.enterpriseAccountSetOrgValidate(model).success(function (data) {
                    if (data && data.result) {
                        // 验证成功
                        saveEditEnterpriseAccountSet();
                    } else {
                        if (data.data && data.data.length > 0) {
                            var orgNameList = [];
                            var i = 1;
                            data.data.forEach(function (row) {
                                orgNameList.push(i + '.' + $translate.instant('OrganizationName') + ':' + row.organizationName);
                                i++;
                            });

                            orgNameList = getLimitLogs(orgNameList);

                            var str = orgNameList.join('<br/>');

                            str = "<div class='text-left'>" + str + '</div>';

                            SweetAlert.swal({
                                title: $translate.instant(data.resultMsg),
                                text: str,
                                type: "warning",
                                showCancelButton: false,
                                confirmButtonColor: "#DD6B55",
                                confirmButtonText: $translate.instant('Confirm'),
                                cancelButtonText: $translate.instant('Cancel'),
                                closeOnConfirm: false,
                                closeOnCancel: false,
                                html: true
                            });

                        }
                    }

                });
            };

            var saveEditEnterpriseAccountSet = function () {
                resetErrorStatus();
                if (!($('#addEnterpriceAccountSetForm').valid())) {
                    return;
                }

                if ($scope.isAdd) {
                    $scope.isImportAppend = false;
                    importData();
                } else {

                    // 有文件的修改
                    if ($scope.file) {

                        SweetAlert.swal({
                            title: $translate.instant('ComfirmImportData'),
                            text: $translate.instant('EnterpriseAccountSetOverLayImportTips'),
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonColor: "#DD6B55",
                            confirmButtonText: $translate.instant('Confirm'),
                            cancelButtonText: $translate.instant('Cancel'),
                            closeOnConfirm: false,
                            closeOnCancel: true
                        },
                            function (isConfirm) {
                                if (isConfirm) {
                                    // 选中
                                    importData();
                                }
                            });

                    } else {
                        // 没有文件修改
                        var model = {
                            id: $scope.enterpriseAccountSetSelectID,
                            name: $scope.editModel.name,
                            code: $scope.editModel.code
                            // enterpriseAccountSetOrgList: []
                        };

                        // if (!getEnterpriseAccountSetOrgListUI()) {
                        //     return;
                        // }

                        // model.enterpriseAccountSetOrgList = $scope.editModel.saveOrgList;

                        enterpriseAccountService.updateEnterpriseAccountSet(model).success(function (data) {
                            if (data && data.result) {
                                $('#addEnterpriceAccountSetPop').modal('hide');
                                SweetAlert.success($translate.instant('SaveSuccess'));
                                loadEnterpriseAccountSetList();
                            } else {
                                swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                            }
                        });
                    }
                }
            };

            var importData = function () {
                if (!$scope.file || !$scope.file.name) {

                    SweetAlert.info($translate.instant('SelectCustomerFileRequired'));
                    return;
                }

                var deferred = $q.defer();

                var tempFileName = PWC.newGuid() + '.dat';
                var token = $('input[name="__RequestVerificationToken"]').val();

                // if (!getEnterpriseAccountSetOrgListUI()) {
                //     return;
                // }

                // var orgList = $scope.editModel.saveOrgList;
                // var json = JSON.stringify(orgList);

                var enterpriseAccountSetID = $scope.isAdd ? '' : $scope.enterpriseAccountSetSelectID;

                $('#busy-indicator-container').show();

                // updateProgressToZero();
                Upload.upload({
                    url: uploadUrl,
                    data: {
                        cancel: false,
                        filename: $scope.file.name,
                        tempFileName: tempFileName,
                        Remark: $scope.remark,
                        name: $scope.editModel.name,
                        code: $scope.editModel.code,
                        // selectedOrgList: json,
                        enterpriseAccountSetID: enterpriseAccountSetID,
                        isImportAppend: $scope.isImportAppend,
                    },
                    file: $scope.file,
                    resumeChunkSize: resumable ? $scope.chunkSize : null,
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                        Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken,
                        __RequestVerificationToken: token,
                        withCredentials: true
                    },
                    __RequestVerificationToken: token,
                    withCredentials: true
                }).then(function (resp) {
                    var ret = resp.data;
                    $('#busy-indicator-container').hide();
                    deferred.resolve();
                    if (ret.result) {

                        $scope.errList = [];
                        $scope.ImportErrorTag = false;
                        // 全部导入成功
                        $('#addEnterpriceAccountSetPop').modal('hide');
                        $('#importEnterpriceAccountSetPop').modal('hide');
                        if ($scope.isAdd) {
                            SweetAlert.success($translate.instant('AddSuccess'));
                        } else {
                            SweetAlert.success($translate.instant('ImportSuccess'));
                        }

                        loadEnterpriseAccountSetList();
                    } else {

                        if (ret.resultMsg && ret.resultMsg.length > 0) {
                            SweetAlert.warning($translate.instant(ret.resultMsg));
                            //SweetAlert.swal($translate.instant(ret.resultMsg));
                            $scope.errList = [];
                            $scope.ImportErrorTag = false;
                        } else {
                            // 提示没有导入成功的数据
                            var codeNameList = [];

                            var errorInfo = $translate.instant('ImportErrorTips').format(ret.data.length);
                            $scope.errList = ret.data;
                            $scope.ImportErrorTag = true;
                            loadEnterpriseAccountSetList();

                            SweetAlert.swal({
                                title: $translate.instant('EnterpriceAccountManage'),
                                text: errorInfo,
                                type: "info",
                                showCancelButton: false,
                                closeOnConfirm: false,
                                closeOnCancel: true,
                                html: true
                            });

                        }
                    }

                }, function (resp) {
                    deferred.resolve();

                    if (resp.statusText === 'HttpRequestValidationException') {
                        SweetAlert.warning($translate.instant('HttpRequestValidationException'));
                    } else {
                        SweetAlert.warning('SaveFail');
                    }

                    console.log('Error status: ' + resp.status);
                }, function (evt) {
                    deferred.resolve();
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    $log.debug('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
                });
            };

            $scope.overlayUpload = function () {
                $scope.isImportAppend = false;
                if ($scope.file) {

                    SweetAlert.swal({
                        title: $translate.instant('ComfirmImportData'),
                        text: $translate.instant('EnterpriseAccountSetOverLayImportTips'),
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: $translate.instant('Confirm'),
                        cancelButtonText: $translate.instant('Cancel'),
                        closeOnConfirm: false,
                        closeOnCancel: true
                    },
                        function (isConfirm) {
                            if (isConfirm) {

                                $scope.editModel = {};
                                var set = _.find($scope.enterpriseAccountSetList, function (num) {
                                    return num.id === $scope.enterpriseAccountSetSelectID;
                                });
                                $scope.editModel.name = set.name;

                                $scope.isAdd = false;
                                // 选中
                                importData();
                            }
                        });
                } else {
                    SweetAlert.info($translate.instant('SelectCustomerFileRequired'));
                    return;
                }
            };

            $scope.editEnterpriseAccountSet = function () {
                $scope.editModel = {};
                $scope.isAdd = false;
                resetErrorStatusSet();
                $scope.file = null;
                enterpriseAccountService.getEnterpriseAccountSet($scope.enterpriseAccountSetSelectID).success(function (data) {
                    $scope.editModel = data;
                    $scope.editModel.IsEdit = true;
                    setEditEnterpriseAccountSetOrgList();
                });

                $('#addEnterpriceAccountSetPop').modal('show');
            };

            var scrollSetting = function () {
                var ex = document.getElementById("enterpriseAccountUIGrid");
                if (ex) {
                    ex.scrollTop = ex.scrollHeight;
                }
            };

            var getLimitLogs = function (arr) {

                if (arr.length > constant.errorMaxLine) {
                    $log.debug(JSON.stringify(arr));
                    arr = arr.slice(0, constant.errorMaxLine);
                    arr.push('.....');
                    return arr;
                }

                return arr;
            };


            $scope.toggleErrorTab = function () {
                $scope.ImportErrorTab = !$scope.ImportErrorTab;

                // topIcon and content-resize gapBottom 15px
                if (!$scope.ImportErrorTab) {
                    setErrorWrapCssDefault();
                } else {

                    if (parseInt($('#content-resizer').css('bottom')) < 100) {
                        $('#content-resizer').css('bottom', '100px');
                        $('#topIcon').css({
                            bottom: '90px',
                        });

                        $('.error-wrap').css('height', '100px');
                    }
                }
            };

            var setErrorWrapCssDefault = function () {
                $('#content-resizer').css('bottom', '25px');
                $('#topIcon').css({
                    bottom: '15px',
                });

                $('.error-wrap').css('height', '0px');
            };

            var setDefaultTheme = function () {
                if ($scope.gridOptions.data && $scope.gridOptions.data.length > 0) {
                    $scope.gridOptions.data.forEach(function (row) {
                        row.isHighLight = false;
                    });
                }
            };

            $scope.chooseRelavantRow = function (err) {

                setDefaultTheme();

                var selectedAccount = null;

                var index = 0;

                if (err && err.inValidateCodeList && err.inValidateCodeList.length > 0) {
                    err.inValidateCodeList.forEach(function (row) {

                        var matchList = _.filter($scope.gridOptions.data, function (num) {
                            return num.code === row
                        });

                        if (matchList && matchList.length > 0) {

                            if (!selectedAccount) {
                                selectedAccount = matchList[0];

                                index = _.findIndex($scope.gridOptions.data, function (num) {
                                    return num.code === row;
                                });
                            }

                            matchList.forEach(function (row2) {
                                row2.isHighLight = true;
                                $log.debug(row2.code);
                            });
                        }

                    });
                }

                if (selectedAccount) {

                    $timeout(function () {
                        $scope.singleSelected = {};
                        $scope.singleClick(selectedAccount);
                        scrollSetting();

                        var gridApi = $scope.dataGridApi;
                        var rowIndex = gridApi.grid.renderContainers.body.visibleRowCache.indexOf(gridApi.grid.rows[index]);
                        gridApi.grid.element[0].getElementsByClassName("ui-grid-viewport")[0].scrollTop = rowIndex * gridApi.grid.options.rowHeight;
                    }, 100);

                }
            };

            $scope.getGridHeight = function () {

                if ($scope.isLoadComplete) {
                    var y = $("#enterprise-account-error-wrap").height();

                    // Enough space
                    if (y > constant.UIGrid.gapHeight) {
                        y = y - constant.UIGrid.gapHeight;
                        return {
                            height: y + "px"
                        };
                    } else {

                        return {
                            height: '0px'
                        };
                    }
                }

                return {};
            }

            $scope.getEnterpriseAccountUIGridHeight = function () {
                if ($scope.isLoadComplete) {
                    var y = $('.import-result').height();
                    if (y > constant.UIGrid.gapHeight) {
                        y = y - constant.UIGrid.gapHeight;
                        return {
                            height: y + "px"
                        };
                    }

                    return {};
                }

                return {};
            };

            $scope.getOrgListUIGridHeight = function () {
                if ($scope.isLoadComplete) {
                    var y = $('.enterprise-account-list-wrap').height();
                    if (y > constant.UIGrid.gapHeight) {
                        // y = y - constant.UIGrid.gapHeight + 4;
                        return {
                            height: y + "px"
                        };
                    }
                }

                return {};
            };

            var clearRepeatData = function (row) {

                SweetAlert.swal({
                    title: $translate.instant('ConfirmOperation'),
                    text: $translate.instant('ClearRepeatItemTips'),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('Cancel'),
                    closeOnConfirm: false,
                    closeOnCancel: true
                },
                    function (isConfirm) {
                        if (isConfirm) {

                            enterpriseAccountService.clearRepeatEnterpriseAccountList($scope.enterpriseAccountSetSelectID, row.inValidateCodeList).success(function (data) {

                                if (data && data.result) {
                                    SweetAlert.success($translate.instant('SaveSuccess'));
                                }

                                loadEnterpriceAccountList();
                            });
                        }
                    });
            };

            var errorGridOptionsFun = function () {
                $scope.errorGridOptions = {
                    rowHeight: 30,
                    selectionRowHeaderWidth: 30,
                    enableSorting: true,
                    enableColumnMenus: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableRowSelection: false, // 行选择是否可用,默认为true; 如果想选择任意位置和勾勾,需要设置为false
                    enableRowHeaderSelection: false,
                    enableFullRowSelection: false, //是否点击行任意位置后选中,默认为false
                    enableSelectAll: false, // 选择所有checkbox是否可用,默认为true; 
                    multiSelect: false, // 是否可以选择多个,默认为true;
                    columnDefs: [{
                        field: 'index',
                        name: $translate.instant('SequenceNo'),
                        width: '10%',
                        cellTemplate: '<div class="ui-grid-cell-contents" ng-click="grid.appScope.chooseRelavantRow(row.entity)"><span>{{row.entity.index}}</span></div>'
                    }, {
                        field: 'type',
                        name: $translate.instant('ErrorMesssage'),
                        width: '30%',
                        cellTemplate: '<div class="ui-grid-cell-contents" ng-click="grid.appScope.chooseRelavantRow(row.entity)"><span>{{row.entity.type}}</span></div>'
                    }, {
                        field: 'errorMsg',
                        name: $translate.instant('EnterpriseAccountErrorCodeList'),
                        cellTemplate: '<div class="ui-grid-cell-contents" ng-click="grid.appScope.chooseRelavantRow(row.entity)">' +
                            '<span title="{{row.entity.detail}}">{{row.entity.detail}}</span>' +

                            '</div>',
                        width: '45%',
                    }, {
                        name: $translate.instant('OrganizationStructureOperation'),
                        width: '15%',
                        headerCellClass: 'center',
                        enableFiltering: false,
                        cellTemplate: '<div class="grid-operation">' +
                            '<a ng-show="row.entity.isRepeatError" class="btn btn-in-grid" href="javascript:void(0)" ng-click="grid.appScope.clearRepeatData(row.entity)"> <i class="material-icons">clear</i><span>{{"ClearRepeatItem" | translate }}</span></a>' +

                            '</div>'
                    }],

                    onRegisterApi: function (gridApi) {
                        $scope.errorGridApi = gridApi;

                        $interval(function () {
                            $scope.errorGridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };
            };


            var setEditEnterpriseAccountSetOrgList = function () {
                if (!$scope.editModel.enterpriseAccountSetOrgList) {
                    $scope.editModel.enterpriseAccountSetOrgList = [];
                }

                var index = 1;
                $scope.editModel.enterpriseAccountSetOrgList.forEach(function (item) {
                    item.fromID = 'from' + index;
                    item.toID = 'to' + index;
                    index++;

                    $timeout(function () {

                        $("#" + item.fromID).datepicker({
                            minViewMode: 1,
                            autoclose: true,
                            language: region,
                            format: "yyyy-mm"
                        });

                        $("#" + item.toID).datepicker({
                            minViewMode: 1,
                            autoclose: true,
                            language: region,
                            format: "yyyy-mm"
                        });

                        $("#" + item.fromID).on('changeDate', function () {

                            if ($("#" + item.fromID).val === '') {

                            } else {
                                $("#" + item.toID).datepicker('setStartDate', $("#" + item.fromID).val());
                            }
                        });


                    }, 100);
                });
            };

            $scope.addEnterpriseAccountSetOrg = function () {

                var index = $scope.editModel.enterpriseAccountSetOrgList.length + 1;
                var item = {
                    organizationName: '',
                    organizationID: '',
                    componentSelectedOrg: null,
                    fromID: 'from' + index,
                    toID: 'to' + index
                };

                $scope.editModel.enterpriseAccountSetOrgList.push(item);

                $timeout(function () {

                    $("#" + item.fromID).datepicker({
                        minViewMode: 1,
                        autoclose: true,
                        language: region,
                        format: "yyyy-mm"
                    });

                    $("#" + item.toID).datepicker({
                        minViewMode: 1,
                        autoclose: true,
                        language: region,
                        format: "yyyy-mm"
                    });

                    $("#" + item.fromID).on('changeDate', function () {

                        if ($("#" + item.fromID).val === '') {

                        } else {
                            $("#" + item.toID).datepicker('setStartDate', $("#" + item.fromID).val());
                        }
                    });


                }, 100);
            };

            $scope.deleteEnterpriseAccountSetOrg = function (x) {
                if (x) {
                    $scope.editModel.enterpriseAccountSetOrgList.splice(jQuery.inArray(x, $scope.editModel.enterpriseAccountSetOrgList), 1);
                };
            };

            var getEnterpriseAccountSetOrgListUI = function () {

                var enterpriseAccountSetOrgList = [];
                var isError = false;
                if ($scope.editModel.enterpriseAccountSetOrgList && $scope.editModel.enterpriseAccountSetOrgList.length > 0) {
                    for (var i = 0; i <= $scope.editModel.enterpriseAccountSetOrgList.length - 1; i++) {
                        var row = $scope.editModel.enterpriseAccountSetOrgList[i];
                        var item = {
                            OrganizationID: row.organizationID,
                            EffectiveDateStr: row.effectiveDateStr,
                            ExpiredDateStr: row.expiredDateStr,
                            EnterpriseAccountSetID: $scope.editModel.id
                        };

                        if (!row.organizationID) {
                            SweetAlert.warning(resources.organizationRequired);
                            return false;
                        }

                        if (!row.effectiveDateStr) {
                            // row.effectiveDateStr = constant.date.minDate;
                            //SweetAlert.warning(resources.effectiveDateRequired);
                            // return false;
                        }

                        if (!row.expiredDateStr) {
                            //row.expiredDateStr = constant.date.maxDate;
                            // SweetAlert.warning(resources.expiredDateRequired);
                            // return false;
                        }

                        if (row.effectiveDateStr && row.expiredDateStr && !validateDate(row.effectiveDateStr, row.expiredDateStr)) {
                            SweetAlert.warning($translate.instant('EffectiveDateAreaProblem'));
                            return false;
                        }

                        enterpriseAccountSetOrgList.push(item);
                    };
                }

                $scope.editModel.saveOrgList = enterpriseAccountSetOrgList;
                return true;
            };

            var validateDate = function (from, to) {
                var fromDate = new Date(from + '-01');
                var toDate = new Date(to + '-01');
                toDate.setMonth(toDate.getMonth() + 1);
                toDate.setDate(toDate.getDate() - 1);

                if (fromDate <= toDate) {
                    return true;
                } else {
                    return false;
                }
            };

            var dataType = {
                isPrefixNumber: function (value) {
                    var reg = /^\d+/;
                    if (reg.test(value)) {
                        return true;
                    } else {
                        return false;
                    }
                },
                isPrefixChar: function (value) {
                    var reg = /^[a-zA-Z]+/;
                    if (reg.test(value)) {
                        return true;
                    } else {
                        return false;
                    }
                },
                isPrefixNumberOrChar: function (value) {
                    if (dataType.isPrefixNumber(value)) {
                        return true;
                    }

                    if (dataType.isPrefixChar(value)) {
                        return true;
                    }

                    return false;
                }
            }

            var sortByEnterpriseName = function (data) {
                if (data && data.length > 0) {

                    var charList = [];
                    var nocharList = [];

                    data.forEach(function (row) {
                        if (dataType.isPrefixNumberOrChar(row.name)) {
                            row.nameSort = row.name;

                            if (row.nameSort) {
                                row.nameSort = row.nameSort.toLowerCase();
                            }

                            charList.push(row);

                        } else {
                            nocharList.push(row);
                        }

                    });

                    charList = _.sortBy(charList, 'nameSort');

                    nocharList = nocharList.sort(function compareFunction(param1, param2) {
                        return param1.name.localeCompare(param2.name, 'zh');
                    });

                    var all = _.union(charList, nocharList);
                    return all;
                }

                return data;
            };

            $scope.importAppend = function () {
                $scope.isImportAppend = true;
                $scope.editModel = {};
                var set = _.find($scope.enterpriseAccountSetList, function (num) {
                    return num.id === $scope.enterpriseAccountSetSelectID;
                });

                $scope.editModel.name = set.name;
                $scope.isAdd = false;
                importData();
            };

            $scope.popupImport = function () {
                $scope.file = null;
                $('#importEnterpriceAccountSetPop').modal('show');
            };

            // 机构的UIGrid初始化
            var orgUIGridInit = function () {

                var operateStr = '';

                if ($scope.hasEditPermission) {
                    operateStr = '<div class="project-manage-grid-operation ui-grid-cell-contents">' +
                        '<span ng-click="grid.appScope.editRelevantOrg(row.entity)" class="operate-span" role="button" tabindex="0" aria-hidden="false" style=""><i class="material-icons middle black-color">create</i></span>' +
                        '<span ng-click="grid.appScope.deleteRelevantOrg(row.entity)" class="operate-span" role="button" tabindex="0" aria-hidden="false" style=""><i class="material-icons button-icons middle delete red-color">delete</i></span>' +
                        '</div>';
                } else {
                    operateStr = '<div class="project-manage-grid-operation ui-grid-cell-contents">' +
                        '<span class="operate-span no-permission" role="button" tabindex="0" aria-hidden="false" style=""><i class="material-icons middle black-color">create</i></span>' +
                        '<span class="operate-span no-permission" role="button" tabindex="0" aria-hidden="false" style=""><i class="material-icons button-icons middle delete red-color">delete</i></span>' +
                        '</div>';
                }

                $scope.orgGridOptions = {
                    rowHeight: 40,
                    selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
                    enableFullRowSelection: true,
                    enableRowSelection: true,
                    enableSorting: true,
                    enableFiltering: false,
                    enableColumnMenus: false,
                    enableRowHeaderSelection: false,
                    multiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    columnDefs: [{
                        field: 'organizationName',
                        name: $translate.instant('FieldorgName'),
                        width: '30%',
                        headerCellClass: 'right',
                        enableFiltering: false,

                        cellTemplate: '<div class="ui-grid-cell-contents right"><a title="{{row.entity.organizationName}}" href="#/organization/{{row.entity.organizationID}}">{{row.entity.organizationName}}<a></div>'
                    }, {
                        field: 'EffectiveDateStr',
                        name: $translate.instant('EffectiveDateStr'),
                        width: '40%',
                        headerCellClass: '',
                        cellTemplate: '<div class="ui-grid-cell-contents" ng-class="{\'padding-right45\':row.entity.isRight}"><span title="{{row.entity.effectiveSection}}">{{row.entity.effectiveSection}}<span></div>'
                    }, {
                        name: $translate.instant('Operation'),
                        width: '30%',
                        headerCellClass: 'center',
                        enableFiltering: false,
                        cellTemplate: operateStr
                    }],
                    onRegisterApi: function (gridApi) {
                        $scope.orgGridApi = gridApi;
                        $interval(function () {
                            $scope.orgGridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };


            };

            // 添加关联机构
            $scope.addRelevantOrgList = function () {
                var model = {
                    id: $scope.editModel.id,
                    name: $scope.editModel.name,
                    enterpriseAccountSetOrgList: []
                };

                if (!getEnterpriseAccountSetOrgListUI()) {
                    return;
                }

                model.enterpriseAccountSetOrgList = $scope.editModel.saveOrgList;

                enterpriseAccountService.addEnterpriseAccountSetOrg(model).success(function (data) {
                    if (data && data.result) {
                        $('#' + addEnterpriceAccountSetRelevantOrg).modal('hide');
                        SweetAlert.success($translate.instant('SaveSuccess'));
                        loadEnterpriseAccountSet();
                    } else {
                        swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                    }
                });
            };

            // 编辑关联机构
            $scope.editRelevantOrg = function (model) {
                $scope.editModel = {};
                $scope.isAdd = false;
                var set = _.find($scope.enterpriseAccountSetList, function (num) {
                    return num.id === $scope.enterpriseAccountSetSelectID;
                });
                $scope.editModel.id = set.id;
                $scope.editModel.name = set.name;
                $scope.editModel.enterpriseAccountSetOrgList = [];

                var vmModel = angular.copy(model);
                $scope.editModel.enterpriseAccountSetOrgList.push(vmModel);
                setEditEnterpriseAccountSetOrgList();

                $('#' + updateEnterpriceAccountSetRelevantOrg).modal('show');
            };

            // 保存修改的关联机构
            $scope.updateRelevantOrg = function () {
                var updateModel = $scope.editModel.enterpriseAccountSetOrgList[0];
                updateModel.enterpriseAccountSetName = $scope.editModel.name;
                enterpriseAccountService.updateEnterpriseAccountSetOrg(updateModel).success(function (data) {

                    if (data && data.result) {
                        $('#' + updateEnterpriceAccountSetRelevantOrg).modal('hide');
                        SweetAlert.success($translate.instant('SaveSuccess'));
                        loadEnterpriseAccountSet();
                    } else {
                        swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                    }
                });
            };

            // 删除关联机构
            $scope.deleteRelevantOrg = function (model) {
                SweetAlert.swal({
                    title: $translate.instant('Confirm') + $translate.instant('DeleteRelevantOrg') + '?',
                    text: $translate.instant('Confirm') + $translate.instant('DeleteRelevantOrg') + model.organizationName,
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('Cancel'),
                    closeOnConfirm: false,
                    closeOnCancel: true
                },
                    function (isConfirm) {
                        if (isConfirm) {
                            // 选中
                            var deleteModel = {
                                id: model.enterpriseAccountSetID,
                                name: model.enterpriseAccountSetName,
                                enterpriseAccountSetOrgList: [],
                            };

                            deleteModel.enterpriseAccountSetOrgList.push(model);

                            enterpriseAccountService.deleteEnterpriseAccountSetOrg(deleteModel).success(function (or) {
                                if (or) {
                                    if (or.result === true) {
                                        SweetAlert.success($translate.instant('deleteOneRole'));
                                        loadEnterpriseAccountSet();
                                    } else {
                                        SweetAlert.warning($translate.instant(or.resultMsg));
                                    }
                                }
                            });
                        }

                    });
            };

            $scope.downEntepriseAccountTemplate = function () {
                enterpriseAccountService.downEntepriseAccountTemplate();


            };


            var getUserPermission = function () {

                var list = [];

                var userManageTemp = constant.adminPermission.basicData.enterpriseAccountSet;
                list.push(userManageTemp.addCode);
                list.push(userManageTemp.editCode);

                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    $scope.hasAddPermission = data[userManageTemp.addCode];
                    $scope.hasEditPermission = data[userManageTemp.editCode];

                    afterGetPermission();
                });
            };


            // 获取权限之后显示
            var afterGetPermission = function () {
                $scope.downloadEnterpriseAccountUrl = apiInterceptor.webApiHostUrl + '/enterpriseAccountManage/downEntepriseAccountTemplate';
                $log.debug('EnterpriseAccountManageController.ctor()...');
                $scope.clearRepeatData = clearRepeatData;
                $scope.errorGridOptionsFun = errorGridOptionsFun;
                errorGridOptionsFun();
                $scope.enterpriceAccountList = [];
                $scope.search = search;
                $scope.newModel = newModel;
                $scope.save = save;
                $scope.load = load;
                $scope.modifyIsActive = modifyIsActive;
                $scope.hasEnterpriseAccountSet = true;
                $scope.acctPropArray = ['', $translate.instant('StandardAccountAcctPropAsset'),
                    $translate.instant('StandardAccountAcctPropDebt'),
                    $translate.instant('StandardAccountAcctPropCommon'),
                    $translate.instant('StandardAccountAcctPropInterest'),
                    $translate.instant('StandardAccountAcctPropCost'),
                    $translate.instant('StandardAccountAcctPropProfitAndLoss')
                ];
                $scope.directionMap = {
                    '1': $translate.instant('StandardAccountDebit'),
                    '-1': $translate.instant('StandardAccountCredit')
                };

                $scope.selectStandardAccount(defaultEnterpriceAccount);
                $scope.selectDirection = null;
                $scope.selectAcctProp = null;
                $scope.defaultEnterpriceAccount = defaultEnterpriceAccount;

                $scope.isActiveBtStr = $translate.instant(isActiveMap[false]);

                $scope.directionList = [{
                    id: 1,
                    name: $translate.instant('StandardAccountDebit')
                }, {
                    id: -1,
                    name: $translate.instant('StandardAccountCredit')
                }, ];

                $scope.acctPropList = [
                    { id: -1, name: '' },
                    {
                        id: 1,
                        name: $translate.instant('StandardAccountAcctPropAsset')
                    }, {
                        id: 2,
                        name: $translate.instant('StandardAccountAcctPropDebt')
                    }, {
                        id: 3,
                        name: $translate.instant('StandardAccountAcctPropCommon')
                    }, {
                        id: 4,
                        name: $translate.instant('StandardAccountAcctPropInterest')
                    }, {
                        id: 5,
                        name: $translate.instant('StandardAccountAcctPropCost')
                    }, {
                        id: 6,
                        name: $translate.instant('StandardAccountAcctPropProfitAndLoss')
                    },
                ];

                loadEnterpriseAccountSetList();

                $scope.singleSelected = {};

                $scope.singleClick = function (entity) {
                    if ($scope.singleSelected && entity.id === $scope.singleSelected.id && !entity.repeatSingleClick) {
                        $scope.isActiveBtStr = $translate.instant(isActiveMap[false]);
                        $scope.singleSelected = {};
                    } else {
                        $scope.isActiveBtStr = $translate.instant(isActiveMap[!entity.isActive]);

                        if (entity.repeatSingleClick) {
                            entity.isActiveStr = $translate.instant(isActivedMap[entity.isActive]);
                        }

                        $scope.singleSelected = entity;
                    }
                }

                $scope.gridOptions = {
                    rowHeight: 40,
                    selectionRowHeaderWidth: 40,
                    enableFullRowSelection: true,
                    enableRowSelection: true,
                    enableSorting: true,
                    enableFiltering: false,
                    enableColumnMenus: false,
                    enableRowHeaderSelection: false,
                    multiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    rowTemplate: '<div sglclick="grid.appScope.singleClick(row.entity)" >' +
                        '  <div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ng-class="{\'header-cell-class\':col.isRowHeader,\'single-row-select\':row.entity.id===grid.appScope.singleSelected.id,\'red-color\':row.entity.isHighLight }"  ui-grid-cell></div>' +
                        '</div>',

                    columnDefs: [{
                        field: 'code',
                        name: $translate.instant('EnterpriceAccountCode'),
                        width: '15%',
                        cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.code}}">{{row.entity.code}}</span></div>'
                    }, {
                        field: 'name',
                        name: $translate.instant('EnterpriceAccountName'),
                        width: '31%',
                        cellTemplate: '<div class="ui-grid-cell-contents"><span title="{{row.entity.name}}">{{row.entity.name}}</span></div>'
                    }, {
                        field: 'parent',
                        name: $translate.instant('StandardAccountSuperiorAccount'),
                        width: '32%',
                    }, {
                        field: 'directionStr',
                        name: $translate.instant('StandardAccountDirection'),
                        width: '11%',
                    }, {
                        field: 'acctPropStr',
                        name: $translate.instant('StandardAccountAccountTypes'),
                        width: '11%',
                    }

                        //, {
                        //    field: 'isMappedStr',
                        //    name: $translate.instant('IsMappedStatus'),
                        //    width: '11%'
                        //}

                        //, {
                        //    field: 'isActiveStr',
                        //    name: $translate.instant('IsActiveStatus'),
                        //    width: '11%'
                        //},

                    ],
                    onRegisterApi: function (gridApi) {
                        $scope.dataGridApi = gridApi;
                        $scope.dataGridApi.grid.registerRowsProcessor($scope.singleFilter, 200);
                        $interval(function () {
                            $scope.dataGridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };

                $scope.singleFilter = function (renderableRows) {
                    var matcher = new RegExp($scope.searchEASText);
                    renderableRows.forEach(function (row) {

                        try {
                            var match = false;
                            ['code', 'name', 'parent', 'directionStr', 'acctPropStr'].forEach(function (field) {
                                if (row.entity[field] && row.entity[field].match(matcher)) {
                                    match = true;
                                }
                            });

                            if (!match) {
                                row.visible = false;
                            }
                        } catch (e) {
                            $log.debug('singleFilter-match:' + JSON.stringify(row.entity));
                        }
                    });
                    return renderableRows;
                };

                $scope.loadEnterpriceAccountList = loadEnterpriceAccountList;

                orgUIGridInit();
                $timeout(function () {

                    $scope.isLoadComplete = true;

                }, 500);
            };


            var KeyDown = function () { //屏蔽鼠标右键、Ctrl+n、shift+F10、F5刷新、退格键   
                //alert("ASCII代码是:"+event.keyCode);   
                if ((window.event.altKey) &&
                    ((window.event.keyCode == 37) || //屏蔽 Alt+ 方向键 ←   
                        (window.event.keyCode == 39))) { //屏蔽 Alt+ 方向键 →   
                    // alert("不准你使用ALT+方向键前进或后退网页!");

                    $('#addEnterpriceAccountPop').modal('hide');
                    $('#addEnterpriceAccountSetPop').modal('hide');
                    $('#importEnterpriceAccountSetPop').modal('hide');
                    $('#addEnterpriceAccountSetRelevantOrg').modal('hide');
                    $('#updateEnterpriceAccountSetRelevantOrg').modal('hide');
                    // $('#addEnterpriceAccountPop').modal('hide');

                    event.returnValue = true;
                }
                // if ((event.keyCode == 8) || //屏蔽退格删除键   
                //      (event.keyCode == 116) || //屏蔽 F5 刷新键   
                //       (event.keyCode == 112) || //屏蔽 F1 刷新键   
                //      (event.ctrlKey && event.keyCode == 82)) { //Ctrl + R   
                //      
                //     event.keyCode = 0; 
                //     event.returnValue = false;   
                //     // alert("不准你使用快捷!");
                // }
                // if ((event.ctrlKey) && (event.keyCode == 78)) //屏蔽 Ctrl+n   
                // {
                //     alert("ctrl + n");  
                //     event.returnValue = false;
                // }
                // if ((event.shiftKey) && (event.keyCode == 121)) //屏蔽 shift+F10   
                // {   alert(" shift+F10 ");  
                //     event.returnValue = false;   }
                // if (window.event.srcElement.tagName == "A" && window.event.shiftKey)    {    window.event.returnValue = false; //屏蔽 shift 加鼠标左键新开一网页   
                //         }

                // if ((window.event.altKey) && (window.event.keyCode == 115)) { //屏蔽Alt+F4   
                //         
                //     // alert('Alt+F4');
                //     //window.showModelessDialog("about:blank","","dialogWidth:1px;dialogheight:1px");   
                //     return false;
                // }
            }

            document.onkeydown = KeyDown;

            (function initialize() {
                //testErrorShowParams();

                getUserPermission();

            })();
        }
    ]);
basicDataModule.directive('enterpriseAccountManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('enterpriseAccountManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/financialData/enterpriseAccountManage/enterprise-account-manage.html' + '?_=' + Math.random(),
            scope: {},
            controller: 'EnterpriseAccountManageController',
            link: function (scope, element) {

            }
        };
    }
]);


basicDataModule.directive('sglclick', ['$parse','$log', function ($parse, $log) {

     'use strict';
        $log.debug('sglclick.ctor()...');

    return {

        restrict: 'A',
        link: function (scope, element, attr) {
            var fn = $parse(attr['sglclick']);
            var delay = 300, clicks = 0, timer = null;
            element.on('click', function (event) {
                clicks++;  //count clicks
                if (clicks === 1) {
                    timer = setTimeout(function () {
                        scope.$apply(function () {
                            fn(scope, { $event: event });
                        });
                        clicks = 0;             //after action performed, reset counter
                    }, delay);
                } else {
                    clearTimeout(timer);    //prevent single-click action
                    clicks = 0;             //after action performed, reset counter
                }
            });
        }
    };
}]);
basicDataModule
.controller('ProductManageController', ['$scope', '$log', 'SweetAlert', '$translate', '$timeout', 'productService',
    function ($scope, $log, SweetAlert, $translate, $timeout, productService) {
        'use strict';

        var loadData = function () {
            productService.getProductList().success(function (data) {
                $scope.productList = data;
                initDXGrid();
            });
        };

        var initDXGrid = function () {
            $scope.dataGridOptions = {
                dataSource: $scope.productList,
                showBorders: true,
                height: 535,
                columns: [
                    { caption: '年份', dataField: 'fYear' },
                    { caption: '产品标识', dataField: "fSetID" },
                    { caption: '产品编号', dataField: "fSetCode" },
                    { caption: '产品描述(名称)', dataField: "fSetName" },
                    { caption: '财务主管', dataField: "fManager" },
                    { caption: '启用年份', dataField: "fStartYear" },
                    { caption: '启用月份', dataField: "fStartMonth" },
                    { caption: '所属机构', dataField: "accountDepartment" }]
            };
        };

        (function initialize() {
            $log.debug('ProductManageController.ctor()...');
            loadData();
        })();
    }
]);

basicDataModule.directive('productManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('productManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/financialData/productManage/product-manage.html' + '?_=' + Math.random(),
            scope: {},
            controller: 'ProductManageController',
            link: function (scope, element) {

            }
        };
    }
]);
basicDataModule
.controller('StandardAccountManageController', ['$scope', '$log', 'SweetAlert', 'keywordmapService', 'uiGridConstants', 'stdAccountService', '$translate', 'orgService',
    function ($scope, $log, SweetAlert, keywordmapService, uiGridConstants, stdAccountService, $translate, orgService) {
        'use strict';

        var loadProjectIndustryList = function () {
            orgService.getProjectIndustrys().success(function (orgData) {
                $scope.projectIndustryList = orgData;
            });
        };

        var defaultSelectStandardAccount = {
            id: 0,
            name: '',
            fullName: '',
            code: '',
            parentCode: '',
            acctLevel: 0,
            selectValue: ' '
        };

        var loadstdAccountList = function () {
            stdAccountService.GetStdAccountList().success(function (data) {

                data.forEach(function (row) {
                    row.directionStr = $scope.directionMap[row.direction + ''];
                    row.acctPropStr = $scope.acctPropArray[row.acctProp];
                    row.selectValue = row.code + ' ' + row.fullName;
                });

                var list = data.concat();
                list = _.sortBy(list, 'code');

                if (list && list.length > 0) {
                    list.splice(0, 0, defaultSelectStandardAccount);
                } else {
                    list = [];
                    list.push(defaultSelectStandardAccount);
                }

                $scope.stdAccountList = list;
                $scope.gridOptions.data = data;
                $scope.gridOptions.noData = data.length === 0;
                $log.debug('keywordmapService.get...');
            });
        };

        var loadKeyWordMapList = function () {

            keywordmapService.get(1).success(function (data) {
                $scope.gridOptions.data = data;
                $scope.gridOptions.noData = data.length === 0;
                $log.debug('keywordmapService.get...');
            });
        };

        var load = function () {
            var selectedKeywordMapList = $scope.gridApi.selection.getSelectedRows();

            if (selectedKeywordMapList && selectedKeywordMapList.length > 0) {
                // 选中
                stdAccountService.get(selectedKeywordMapList[0].id).success(function (data) {
                    $scope.editModel = data;
                    $scope.isAdd = false;

                    $scope.selectStandardAccount = _.find($scope.stdAccountList, function (num) { return num.code === data.parentCode });

                    if (!$scope.selectStandardAccount) {
                        $scope.selectStandardAccount = defaultSelectStandardAccount;
                    }

                    $scope.selectDirection = _.find($scope.directionList, function (num) { return num.id === data.direction });
                    $scope.selectAcctProp = _.find($scope.acctPropList, function (num) { return num.id === data.acctProp });
                    $scope.selectProjectIndustry = _.find($scope.projectIndustryList, function (num) { return num.id === data.industryID });

                    $('#addStandardAccountPop').modal('show');
                });
            }
            else {
                $log.debug('please select one keywordMap...');
            }
        };

        var changesStdAccountSelect = function () {
            if ($scope.selectAccount) {
                $scope.editModel.name = $scope.selectAccount.name;
                $scope.editModel.stdFullName = $scope.selectAccount.fullName;
                $scope.editModel.stdCode = $scope.selectAccount.code;
            } else {
                $scope.editModel.name = '';
                $scope.editModel.stdFullName = '';
                $scope.editModel.stdCode = '';
            }
        };

        var save = function () {

            if (!($('#addStandardAccountForm').valid())) {
                return;
            }

            $scope.editModel.isActive = 1;
            $scope.editModel.ruleType = 2;
            if ($scope.selectStandardAccount && $scope.selectStandardAccount.code && $scope.selectStandardAccount.code.length > 0) {
                $scope.editModel.parentCode = $scope.selectStandardAccount.code;
                $scope.editModel.fullName = $scope.selectStandardAccount.fullName + '-' + $scope.editModel.name;
                $scope.editModel.acctLevel = $scope.selectStandardAccount.acctLevel + 1;
            } else {
                $scope.editModel.acctLevel = 1;
                $scope.editModel.fullName = $scope.editModel.name;
            }

            if ($scope.selectProjectIndustry && $scope.selectProjectIndustry.id) {
                $scope.editModel.industryID = $scope.selectProjectIndustry.id;
            }

            if ($scope.selectDirection && $scope.selectDirection.id) {
                $scope.editModel.direction = $scope.selectDirection.id;
            }

            if ($scope.selectAcctProp && $scope.selectAcctProp.id) {
                $scope.editModel.acctProp = $scope.selectAcctProp.id;
            }

            if ($scope.isAdd) {
                stdAccountService.add($scope.editModel).success(function (data) {
                    if (!data.result) {
                        var errorList = [];
                        var template = $translate.instant(data.resultMsg);
                        data.data.forEach(function (row) {
                            var error = template.formatObj({ code: row.code, name: row.name });
                            errorList.push(error);
                        });
                        showInfo('region', errorList.join(';', errorList), 'addStandardAccountPop');
                        //SweetAlert.info("region", errorList.join(';', errorList));
                        //$log.debug("add error",  errorList.join(';', errorList));
                        return;
                    };

                    $('#addStandardAccountPop').modal('hide');
                    loadstdAccountList();
                });
            } else {
                stdAccountService.update($scope.editModel).success(function (data) {
                    if (!data.result) {
                        var errorList = [];
                        var template = $translate.instant(data.resultMsg);
                        data.data.forEach(function (row) {
                            var error = template.formatObj({ code: row.code, name: row.name });
                            errorList.push(error);
                        });

                        //SweetAlert.info("region", errorList.join(';', errorList));
                        showInfo('region', errorList.join(';', errorList), 'addStandardAccountPop');
                        return;
                    };

                    $('#addStandardAccountPop').modal('hide');
                    loadstdAccountList();
                });
            }
        };

        var search = function () {
            $scope.gridApi.grid.refresh();
        };

        // 新增
        var newModel = function () {
            $scope.editModel = {};
            $scope.isAdd = true;
            $scope.selectStandardAccount = defaultSelectStandardAccount;
            $scope.selectDirection = null;
            $scope.selectAcctProp = null;
            resetErrorStatus();
            $('#addStandardAccountPop').modal('show');
        };

        var resetErrorStatus = function () {
            var currentForm = $('#addStandardAccountForm');
            $.each(currentForm.children(), function (index, element) {

                // 去除div
                $(element).children('div').removeClass('has-error');
            });
            validator.resetForm();
        };

        var resources = {
            codeRequired: $translate.instant('StandardAccountCodeRequired'),
            nameRequired: $translate.instant('StandardAccountNameRequired'),
            selectDirectionRequired: $translate.instant('StandardAccountRequired'),
            selectAcctPropRequired: $translate.instant('StandardAccountAccountTypesRequired')
        };


        var validator = $("#addStandardAccountForm").validate({
            errorClass: "has-error",
            rules: {
                code: {
                    required: true
                },
                name: {
                    required: true
                },
                selectDirection: {
                    required: true
                },
                selectAcctProp: {
                    required: true
                }
            },
            messages: {
                code: {
                    required: resources.codeRequired
                },
                name: {
                    required: resources.nameRequired
                },
                selectDirection: {
                    required: resources.selectDirectionRequired
                },
                selectAcctProp: {
                    required: resources.selectAcctPropRequired
                }
            },
            errorPlacement: function (error, element) {
                setErrorStyle(error, element);
            }
        });

        var setErrorStyle = function (error, element) {
            if (element.hasClass('has-error')) {
                element.parent().addClass('has-error');
                error.insertAfter(element);
                error.addClass('label');
                // error.addClass('label-danger');
            }
        };

        var modifyIsActive = function () {
            var selectedKeywordMapList = $scope.gridApi.selection.getSelectedRows();

            if (selectedKeywordMapList && selectedKeywordMapList.length > 0) {

                SweetAlert.swal({
                    title: $translate.instant('ComfirmDisable') + '?',
                    text: $translate.instant('ComfirmStandardAccountDisable').formatObj({ code: selectedKeywordMapList[0].code, fullName: selectedKeywordMapList[0].fullName }),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55", confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('Cancel'),
                    closeOnConfirm: false,
                    closeOnCancel: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        // 选中
                        var model = selectedKeywordMapList[0];
                        model.isActive = !model.isActive;
                        stdAccountService.isactive(model).success(function (data) {

                            SweetAlert.info('info', 'log success');
                            if (!data.result) {
                                SweetAlert.info('info', $translate.instant(data.resultMsg));
                                return;
                            } else {
                                SweetAlert.swal($translate.instant('ComfirmDisable') + '!', $translate.instant("ComfirmDisableSuccess"), "success");
                                loadstdAccountList();
                            }
                        });
                    }
                });
            }
            else {
                $log.debug('please select one keywordMap...');
            }
        };


        var showInfo = function (title, msg, id) {
            if (id) {
                $('#' + id).modal('hide');
            }
            SweetAlert.swal({
                title: title,
                text: msg,
                type: "info",
                showCancelButton: false,
                confirmButtonClass: "btn-info",
                confirmButtonText: $translate.instant('Confirm'),
                closeOnConfirm: true
            },
            function () {
                if (id) {
                    $('#' + id).modal('show');
                }
            });
        };

        (function initialize() {
            $log.debug('StandardAccountManageControllerController.ctor()...');
            $scope.stdAccountList = [];
            $scope.search = search;
            $scope.newModel = newModel;
            $scope.changesStdAccountSelect = changesStdAccountSelect;
            $scope.save = save;
            $scope.load = load;
            $scope.modifyIsActive = modifyIsActive;
            $scope.acctPropArray = ['', $translate.instant('StandardAccountAcctPropAsset'),
                $translate.instant('StandardAccountAcctPropDebt'),
                 $translate.instant('StandardAccountAcctPropCommon'),
                 $translate.instant('StandardAccountAcctPropInterest'),
                 $translate.instant('StandardAccountAcctPropCost'),
                 $translate.instant('StandardAccountAcctPropProfitAndLoss')];
            $scope.directionMap = { '1': $translate.instant('StandardAccountDebit'), '-1': $translate.instant('StandardAccountCredit') };

            $scope.selectStandardAccount = defaultSelectStandardAccount;
            $scope.selectDirection = null;
            $scope.selectAcctProp = null;

            $scope.directionList = [
                { id: 1, name: $translate.instant('StandardAccountDebit') },
                { id: -1, name: $translate.instant('StandardAccountCredit') },
            ];

            $scope.acctPropList = [
                 { id: 1, name: $translate.instant('StandardAccountAcctPropAsset') },
                 { id: 2, name: $translate.instant('StandardAccountAcctPropDebt') },
                 { id: 3, name: $translate.instant('StandardAccountAcctPropCommon') },
                 { id: 4, name: $translate.instant('StandardAccountAcctPropInterest') },
                 { id: 5, name: $translate.instant('StandardAccountAcctPropCost') },
                 { id: 6, name: $translate.instant('StandardAccountAcctPropProfitAndLoss') },
            ];

            loadProjectIndustryList();
            loadstdAccountList();
            //loadKeyWordMapList();

            $scope.gridOptions = {
                rowHeight: 45,
                selectionRowHeaderWidth: 45,
                enableFullRowSelection: true,
                enableRowSelection: true,
                enableSorting: false,
                enableFiltering: false,
                enableColumnMenus: false,
                enableRowHeaderSelection: false,
                multiSelect: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                columnDefs: [
                  {
                      field: 'code', name: $translate.instant('StandardAccountCode'), width: '20%', headerCellClass: 'header-cell-class',
                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.code}}</span></div>'
                  },
                  {
                      field: 'name', name: $translate.instant('StandardAccountName'), width: '30%', headerCellClass: 'header-cell-class',
                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.name}}</span></div>'
                  },
                  {
                      field: 'parentName', name: $translate.instant('StandardAccountSuperiorAccount'), width: '30%', headerCellClass: 'header-cell-class',
                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.parentName}}</span></div>'
                  },
                  {
                      field: 'directionStr', name: $translate.instant('StandardAccountDirection'), width: '10%', headerCellClass: 'header-cell-class',
                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.directionStr}}</span></div>'
                  },
                  {
                      field: 'acctPropStr', name: $translate.instant('StandardAccountAccountTypes'), width: '10%', headerCellClass: 'header-cell-class',
                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.acctPropStr}}</span></div>'
                  }
                ],
                onRegisterApi: function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.grid.registerRowsProcessor($scope.singleFilter, 200);
                }
            };

            $scope.singleFilter = function (renderableRows) {
                var matcher = new RegExp($scope.searchText);
                renderableRows.forEach(function (row) {
                    var match = false;
                    ['code', 'name', 'parentName', 'directionStr', 'acctPropStr'].forEach(function (field) {
                        if (row.entity[field].match(matcher)) {
                            match = true;
                        }
                    });
                    if (!match) {
                        row.visible = false;
                    }
                });
                return renderableRows;
            };

        })();

    }
]);
basicDataModule.directive('standardAccountManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('standardAccountManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/financialData/standardAccountManage/standard-account-manage.html' + '?_=' + Math.random(),
            scope: {},
            controller: 'StandardAccountManageController',
            link: function (scope, element) {

            }
        };
    }
]);
basicDataModule
    .controller('BasicDataMasterInfrastructureController', ['$scope', '$log', 'SweetAlert', 'organizationStructureService', '$translate', 'businessUnitService', 'customerService',
        function($scope, $log, SweetAlert, organizationStructureService, $translate, businessUnitService, customerService) {
            'use strict';

            var successAddMessage = $translate.instant('OrganizationStructureAddSuccess');
            var successEditMessage = $translate.instant('OrganizationStructureEditSuccess');
            var successDeleteMessage = $translate.instant('OrganizationStructureDeleteSuccess');
            var operationDeleteMessage = $translate.instant('OrganizationStructureOperationSuccess');
            var notAllowDisableMessage = $translate.instant('notAllowDisableMessage');


            $scope.add = function(newrow) {

                organizationStructureService.addOrganizationStructure(newrow).success(function(guid) {
                    SweetAlert.success(successAddMessage);
                });
            };

            $scope.edit = function(newcontent) {
                organizationStructureService.updateOrganizationStructure(newcontent).success(function(guid) {
                    SweetAlert.success(successEditMessage);
                });
            };

            $scope.remove = function(id) {
                organizationStructureService.deleteOrganizationStructure(id).success(function(guid) {
                    SweetAlert.success(successDeleteMessage);
                });
            };

            $scope.stop = function(id) {
                organizationStructureService.updateOrganizationStructure(id).success(function(successFlag) {
                    $scope.updateflag = successFlag;
                    $scope.$broadcast('to-child', successFlag);
                    if (successFlag) {
                        SweetAlert.success(operationDeleteMessage);
                    } else {
                        SweetAlert.warning(notAllowDisableMessage);
                    }
                });
            };

            //BusinessUnit
            $scope.addbs = function(newrow) {

                businessUnitService.addBusinessUnit(newrow).success(function(guid) {
                    SweetAlert.success(successAddMessage);
                });
            };

            $scope.editbs = function(newcontent) {
                businessUnitService.updateBusinessUnit(newcontent).success(function(guid) {
                    SweetAlert.success(successEditMessage);
                });
            };

            $scope.removebs = function(id) {
                businessUnitService.deleteBusinessUnit(id).success(function(guid) {
                    SweetAlert.success(successDeleteMessage);
                });
            };

            $scope.stopbs = function(id) {
                businessUnitService.updateBusinessUnit(id).success(function(successFlag) {
                    $scope.updateflag = successFlag;
                    $scope.$broadcast('to-child', successFlag);
                    if (successFlag) {
                        SweetAlert.success(operationDeleteMessage);
                    } else {
                        SweetAlert.warning(notAllowDisableMessage);
                    }
                });
            };

            $scope.showOperateLogPop = function() {
                $scope.isShowLog = true;
                // $('#showOperatePop').modal('show');
            };

            var getUserPermission = function() {

                var list = [];

                var basicData = constant.adminPermission.basicData;
                list.push(basicData.orangizationStructure.queryCode);
                list.push(basicData.businessUnit.queryCode);
                list.push(basicData.areaManage.queryCode);
                list.push(basicData.enterpriseAccountSet.queryCode);
                list.push(basicData.customerList.queryCode);

                $scope.$root.checkUserPermissionList(list).success(function(data) {

                    $scope.orangizationStructureShow = data[basicData.orangizationStructure.queryCode];
                    $scope.businessUnitShow = data[basicData.businessUnit.queryCode];
                    $scope.areaManageShow = data[basicData.areaManage.queryCode];
                    $scope.enterpriseAccountSetShow = data[basicData.enterpriseAccountSet.queryCode];
                    $scope.customerListShow = data[basicData.customerList.queryCode];

                });
            };

            (function initialize() {
                $log.debug('BasicDataInfrastructureController.ctor()...');

                getUserPermission();

            })();
        }
    ]);

basicDataModule.directive('basicDataMasterInfrastructure', ['$log',
    function ($log) {
        'use strict';
        $log.debug('BasicDataInfrastructure.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/masterData/basicDataInfrastructure/basic-data-infrastructure.html' + '?_=' + Math.random(),
            replace: true,
            scope: {
                state:'='
            },
            controller: 'BasicDataMasterInfrastructureController',
            link: function (scope, element) {
                //$log.info(scope.state);
            }
        };
    }
]);
basicDataModule
    .controller('businessUnitController', ['$scope', '$log', 'SweetAlert', '$translate', 'businessUnitService', 'uiGridConstants', 'Upload', 'apiInterceptor', '$interval',
        function($scope, $log, SweetAlert, $translate, businessUnitService, uiGridConstants, Upload, apiInterceptor, $interval) {
            'use strict';

            // 模态框的编辑状态 true 编辑状态,false 创建状态
            $scope.isEdit = false;

            var formValidator = null;

            //当前编辑对象
            $scope.editingObject = { ID: "", Name: "", IsActive: true };

            var editModalSelector = ".business-unit #edit-modal";

            //显示指定消息编码对应的翻译文本信息
            var showError = function(messageCode) {
                var errMsg = $translate.instant(messageCode);
                SweetAlert.warning(errMsg);
            };

            //清空当前编辑字段值
            $scope.resetEditingObject = function() {
                $scope.editingObject = { ID: "", Name: "", IsActive: true };

                var elms = $(editModalSelector).find("form:first div[data-for]");
                elms.html("");
                elms.attr("class", "validate-success");
            }

            //创建(添加)新事业部,使用模态框实现编辑入口
            $scope.createNewData = function() {
                $scope.isEdit = false;

                $scope.resetEditingObject();

                $(editModalSelector).modal('show');
            };

            //编辑焦点行数据
            $scope.editFocusedRow = function(data) {
                $scope.isEdit = true;

                $scope.editingObject = { ID: data.id, Name: data.name, IsActive: data.isActive };

                $(editModalSelector).modal('show');
            };

            //保存当前正在编辑数据行,经过界面初步校验后才会进入本功能
            $scope.saveEditRow = function() {
                if ($scope.editingObject == null) {
                    showError("BusinessUnitNoSelected");
                    return;
                }

                if (!($(editModalSelector).find("#edit-form").valid())) {
                    return;
                }

                var businessUnitArray = [];
                businessUnitArray.push($scope.editingObject);

                var successedFun = function(rst) {
 
                    $scope.refreshData();
                     
                    $(editModalSelector).modal('hide');

                    if ($scope.isEdit) {
                        SweetAlert.success($translate.instant("OrganizationStructureEditSuccess"));
                    } else {
                        SweetAlert.success($translate.instant("OrganizationStructureAddSuccess"));
                    }
                }

                if ($scope.isEdit) {
                    businessUnitService.updateBusinessUnit(businessUnitArray).success(successedFun);

                } else {
                    businessUnitService.addBusinessUnit(businessUnitArray).success(successedFun);
                }
            };

            //取消保存当前编辑行
            $scope.cancelEditBusinessUnit = function() {
                $(editModalSelector).modal('hide');
            };

            //停用或启用当前事业部
            $scope.activeBusinessUnit = function(data) {
                data.isActive = !data.isActive;
                var businessUnitArray = [];
                businessUnitArray.push(data);

                businessUnitService.updateBusinessUnit(businessUnitArray).success(function(rst) {
                    $scope.refreshData();
                });
            };

            //获取事业部数据
            $scope.refreshData = function() {
                businessUnitService.getBusinessUnitList().success(function(data) {
                    $scope.gridOptions.data = data;
                });
            };

            $scope.getGridHeight = function() {
                return { height: $(".business-unit-containers .list-container").height() + "px" };
            }

            function intiUiGrid() {

                var opertionStr = '';
                if ($scope.hasEditPermission) {
                    opertionStr = '<div class="business-unit-gridcell-operation">' +
                        '<a ng-click="grid.appScope.editFocusedRow(row.entity)">' +
                        '    <i class="material-icons" style="margin-right: 10px;">&#xE254;</i>' +
                        '    <span>{{"OrganizationStructureEdit"|translate}}</span>' +
                        '</a>' +
                        '<a atms-permission permission-code="{{$root.adminPermission.basicData.businessUnit.editCode}}" ng-click="grid.appScope.activeBusinessUnit(row.entity)" ng-if="row.entity.isActive">' +
                        '    <i class="material-icons" style="color:#3f3f40">&#xE15C;</i>' +
                        '    <span>{{"BusinessUnitDisabledNode"|translate}}</span>' +
                        '</a>' +
                        '<a atms-permission permission-code="{{$root.adminPermission.basicData.businessUnit.editCode}}" ng-click="grid.appScope.activeBusinessUnit(row.entity)" ng-if="!row.entity.isActive">' +
                        '    <i class="material-icons" style="color:#e64400">&#xE038;</i>' +
                        '    <span>{{"BusinessUnitEnableNode"|translate}}</span>' +
                        '</a>' +
                        '</div>'
                } else {
                    opertionStr = '<div class="business-unit-gridcell-operation ' + constant.noPermissionClass + '">' +
                        '<a>' +
                        '    <i class="material-icons" style="margin-right: 10px;">&#xE254;</i>' +
                        '    <span>{{"OrganizationStructureEdit"|translate}}</span>' +
                        '</a>' +
                        '<a ng-if="row.entity.isActive">' +
                        '    <i class="material-icons" style="color:#3f3f40">&#xE15C;</i>' +
                        '    <span>{{"BusinessUnitDisabledNode"|translate}}</span>' +
                        '</a>' +
                        '<a  ng-if="!row.entity.isActive">' +
                        '    <i class="material-icons" style="color:#e64400">&#xE038;</i>' +
                        '    <span>{{"BusinessUnitEnableNode"|translate}}</span>' +
                        '</a>' +
                        '</div>'
                }

                $scope.gridOptions = {
                    rowHeight: constant.UIGrid.rowHeight,
                    selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
                    enableSorting: true,
                    enableColumnMenus: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableRowSelection: true,
                    enableFullRowSelection: true,
                    enableRowHeaderSelection: false,
                    multiSelect: false,
                    columnDefs: [{
                        field: 'name',
                        name: $translate.instant('BusinessUnitName'),
                        width: '50%',
                        cellTemplate: '<div class="business-unit-gridcell-name"><span>{{row.entity.name}}</span><span ng-hide="true">{{row.entity.id}}</span></div>'
                    }, {
                        field: 'isActive',
                        name: $translate.instant('BusinessUnitStatus'),
                        width: '20%',
                        cellTemplate: '<div class="business-unit-gridcell-isactive">' +
                            '<span ng-if="row.entity.isActive">{{"BusinessUnitActive"|translate}}</span>' +
                            '<span ng-if="!row.entity.isActive">{{"BusinessUnitDisabled"|translate}}</span>' +
                            '</div>'
                    }, {
                        field: 'Operation',
                        name: $translate.instant('Operation'),
                        width: '30%',
                        cellTemplate: opertionStr
                    }],

                    onRegisterApi: function(gridApi) {
                        $scope.gridApi = gridApi;
                        $scope.gridApi.grid.registerRowsProcessor($scope.singleFilter, 200);
                        $interval(function() {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };

                $scope.singleFilter = function(renderableRows) {

                    var matcher = new RegExp($scope.searchEASText);
                    renderableRows.forEach(function(row) {

                        try {
                            var match = false;
                            ['code', 'name'].forEach(function(field) {
                                if (row.entity[field].match(matcher)) {
                                    match = true;
                                }
                            });
                            if (!match) {
                                row.visible = false;
                            }
                        } catch (e) {
                            $log.debug('singleFilter-match:' + JSON.stringify(row.entity));
                        }
                    });
                    return renderableRows;
                };
            }

            function intiValidate() {

                $.validator.addMethod("BURepeated", function(value, element, param) {
                    if ($scope.gridOptions.data && $scope.gridOptions.data.length > 0) {
                        var objects = $.grep($scope.gridOptions.data, function(n, i) {
                            return $scope.editingObject.ID != n.id && $.trim(n.name) == $.trim(value);
                        });

                        return objects.length < 1;
                    }

                    return true;

                });

                formValidator = $(editModalSelector).find("#edit-form").validate({
                    debug: true,

                    rules: {
                        Name: {
                            required: true,
                            minlength: 2,
                            maxlength: 50,
                            BURepeated: true
                        },
                        IsActive: {
                            required: "input[name='IsActive']:checked"
                        }
                    },
                    messages: {
                        Name: {
                            required: $translate.instant('BusinessUnitEmptyNode'),
                            minlength: $translate.instant('BusinessUnitEmptyNode'),
                            maxlength: $translate.instant('BusinessUnitOutOfLengthNode'),
                            BURepeated: $translate.instant('BusinessUnitDuplicateNode')
                        },
                        IsActive: $translate.instant('BusinessUnitStatusUnsureness')
                    },
                    errorPlacement: function(error, element) {
                        var elm = $(element).parents("form:first");
                        elm = elm.find("div[data-for='" + element.attr("name") + "']");
                        elm.html(error);
                        elm.attr("class", "validate-fail");
                    }
                });
            }

            var havePermission = function() {
                $scope.$root.checkUserPermission(constant.adminPermission.basicData.businessUnit.editCode).success(function(data) {
                    $scope.hasEditPermission = data;
                    intiUiGrid();
                    $scope.refreshData();
                    intiValidate();
                });
            };

            (function initialize() {
                $log.debug('businessUnitController.ctor()...');
                $scope.hasEditPermission = false;
                havePermission();

            })();
        }
    ]);

basicDataModule.directive('businessUnit', ['$log', 'SweetAlert', '$translate',
    function ($log, SweetAlert, $translate) {
        'use strict';
        $log.debug('businessUnit.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/masterData/businessUnit/business-unit.html' + '?_=' + Math.random(),
            scope:
            {
                //addCtrlFn: '&addBsFn',
                //removeCtrlFn: '&removeBsFn',
                //editCtrlFn: '&editBsFn',
                //stopCtrlFn: '&stopBsFn',
                //attr: '@',
                //list:'=bind'
            },
            controller: 'businessUnitController',
            //link: function (scope, element, attrs, $element) {
            //    var originalContent, target, isEdit, isAdd;
            //    var originalArray = [];
            //    var isNodeActive = $translate.instant('OrganizationStructureActive');
            //    var isNodeDisabled = $translate.instant('OrganizationStructureDisabled');
            //    var disableNode = $translate.instant('OrganizationStructureDisabledNode');
            //    var activeNode = $translate.instant('OrganizationStructureEnableNode');
            //    var emptyNote = $translate.instant('BusinessUnitEmptyNode');
            //    var outOfLengthNote = $translate.instant('BusinessUnitOutOfLengthNode');
            //    var depulicateNote = $translate.instant('BusinessUnitDuplicateNode');
            //    var addInvalidNote = $translate.instant('OrganizationStructureOperationAddInvalid');
            //    var editInvalidNote = $translate.instant('OrganizationStructureOperationEditInvalid');

            //    //添加行的时候删除行
            //    $(document).on('click', '.remove-bs-row', function () {
            //        var tr = $(this).parent().parent();
            //        var id = $(tr).children('td').eq(2).text();
            //        $(tr).remove();

            //        if (id !== '') {
            //            scope.removeCtrlFn({ id: id });
            //        }

            //        if ($('.remove-bs-row').length == 0) {
            //            $(".bs-save-group").css('display', 'none');
            //            isAdd = false;
            //        }
            //    });

            //    //选中行
            //    $(document).on('click', '#businessUnitTable tr:not(.header)', function (evt) {
            //        $("#businessUnitTable tr").removeClass("selected");
            //        $(this).toggleClass('selected');

            //        target = $("#businessUnitTable tr.selected td");

            //    });

            //    //编辑
            //    scope.editBusinessUnit = function (e, org) {

            //        if (isAdd) {
            //            SweetAlert.warning(editInvalidNote);
            //            return;
            //        }

            //        var elem;

            //        isEdit = true; isAdd = false;
            //        $(".bs-save-group").css('display', 'block');

            //        elem = (e.srcElement || e.target);  //for IE: e.srcElement, others, e.target
            //        target = $(elem).parent().parent().parent().children('td');

            //        scope.currentTarget = target;
            //        scope.currentOrg = org;

            //        var element = $(target).eq(0);
            //        originalContent = $(element).text();
            //        var result = $.grep(originalArray, function (e) { return e.id === org.id });
            //        if (result.length === 0 || originalContent != '') {
            //            //add to originalArray for the cancel 
            //            originalArray.push({ 'id': org.id, 'content': originalContent });

            //            $(element).addClass("cellEditing");
            //            $(element).html("<input type='text' class='form-control' value='" + originalContent + "' /></div>");
            //            $(element).children().first().focus();
            //            $(element).children().first().keypress(function (e) {
            //                if (e.which == 13) {
            //                    var newContent = $(element).children().first().val();
            //                    $(element).text(newContent);
            //                    $(element).removeClass("cellEditing");
            //                }
            //            });
            //        }
            //    };

            //    //取消保存
            //    scope.cancelBusinessUnit = function (e) {
            //        var elem = (e.srcElement || e.target);  //for IE: e.srcElement, others, e.target
            //        if (isEdit) {

            //            var element = $(".cellEditing");
            //            element.each(function (index) {
            //                var td = $(this).parent().children('td').eq(2);
            //                var id = $(td).text();
            //                var obj = $.grep(originalArray, function (x) { return x.id === id });
            //                if (obj.length > 0) {
            //                    $(this).text(obj[0].content);
            //                    $(this).removeClass("cellEditing");
            //                }
            //            });
            //            originalArray = [];
            //            isEdit = false;
            //        } else {
            //            $('.new-add-bs').remove();
            //            isAdd = false;
            //        }
            //        $(".bs-save-group").css('display', 'none');
            //    };

            //    $("#btnAddBusinessUnit").on('click', function () {
            //        if (isEdit) {
            //            SweetAlert.warning(addInvalidNote);
            //            return;
            //        }
            //        isEdit = false; isAdd = true;
            //        $(".bs-save-group").css('display', 'block');
            //        $('#businessUnitTable tr:last').after('<tr class="new-add-bs"><td><input type="text" class="form-control new-add-input" value="" /></td><td>' + isNodeActive + '</td><td><i class="fa fa-times remove-bs-row" aria-hidden="true"></i></td></tr>');

            //    });

            //    //保存
            //    scope.saveBusinessUnit = function (e) {
            //        if (isEdit) {
            //            //编辑保存
            //            var elem = (e.srcElement || e.target);  //for IE: e.srcElement, others, e.target
            //            var element = $(".cellEditing");
            //            var newValues = [];
            //            var idArray = [];

            //            element.each(function (index) {
            //                var td = $(this).parent().children('td');
            //                var newContent = $(td).eq(0).children().first().val();
            //                var isActive = $(td).eq(1).text();
            //                var id = $(td).eq(2).text();
            //                idArray.push(id);
            //                newValues.push({
            //                    id: id, name: newContent, isActive: isActive
            //                });
            //            });

            //            var validationResult = formValidation(newValues);

            //            if (!validationResult.duplicateFlag && !validationResult.emptyFlag && !validationResult.outOfLengthFlag) {
            //                isEdit = false;
            //                $(".bs-save-group").css('display', 'none');

            //                element.each(function (index) {
            //                    var td = $(this).parent().children('td');
            //                    var firstTd = $(td).eq(0);
            //                    var newVal = $(firstTd).children().first().val();
            //                    $(firstTd).text(newVal);
            //                    $(firstTd).removeClass("cellEditing");
            //                });

            //                scope.editCtrlFn({
            //                    newcontent: newValues
            //                });

            //                originalArray = [];
            //            }

            //        } else {
            //            //新增层级
            //            var newaddTarget = $('.new-add-input');
            //            var values = [];
            //            var hasName = true;
            //            var outOfLength = false;
            //            var duplicate = false;
            //            var newValues = [];

            //            $(newaddTarget).each(function () {
            //                var guid = PWC.newGuid();
            //                var name = $(this).val();

            //                newValues.push({
            //                    id: guid, name: name, isActive: true
            //                });
            //            });

            //            var validationResult = formValidation(newValues);

            //            if (!validationResult.duplicateFlag && !validationResult.emptyFlag && !validationResult.outOfLengthFlag) {
            //                $(".bs-save-group").css('display', 'none');
            //                $('.new-add-bs').remove();
            //                var newAdd = {
            //                    newrow: newValues
            //                };
            //                newValues.forEach(function (item) {
            //                    scope.businessUnitList.push(item);
            //                });
            //                scope.addCtrlFn(newAdd);
            //                originalArray = [];
            //            }
            //        }
            //    };

            //    //停用和启用
            //    var currentId;
            //    scope.stopOrActiveBusinessUnit = function (org) {

            //        currentId = org.id;
            //        var name = org.name;
            //        var id = org.id;
            //        var updateArray = [];
            //        var values = { id: id, name: name, isActive: !org.isActive };
            //        updateArray.push(values);

            //        scope.stopCtrlFn({ newcontent: updateArray });

            //        scope.$on('to-child', function (event, successFlag) {
            //            if (successFlag) {
            //                var item = _.where(scope.businessUnitList, { id: currentId });
            //                item[0].isActive = values.isActive;
            //            }
            //        });
            //    };

            //    //form validation before saving add/edit operation
            //    var formValidation = function (newValues) {

            //        var duplicateFlag = false;
            //        var emptyFlag = false;
            //        var outOfLengthFlag = false;

            //        //判断同时输入多个的时候不能重复
            //        var uniqueList = _.uniq(newValues, function (item, key, name) {
            //            return item.name;
            //        });

            //        if (uniqueList.length != newValues.length) {
            //            duplicateFlag = true;
            //        }

            //        newValues.forEach(function (item) {

            //            var filterResult = _.find(scope.businessUnitList, { name: item.name });
            //            //如果找的这个object和newvalue的id是同一个的话,不是重复 
            //            if (filterResult != undefined && filterResult.id !== item.id) {
            //                duplicateFlag = true;
            //            } else if (item.name === '') {
            //                emptyFlag = true;
            //            } else if (PWC.getLength(item.name) > constant.businessUnit.BUmaxLength) {
            //                outOfLengthFlag = true;
            //            }
            //        });

            //        //give notice to user
            //        if (emptyFlag) {
            //            SweetAlert.warning(emptyNote);
            //        } else if (duplicateFlag) {
            //            SweetAlert.warning(depulicateNote);
            //        } else if (outOfLengthFlag) {
            //            SweetAlert.warning(outOfLengthNote);
            //        }

            //        return {
            //            duplicateFlag: duplicateFlag,
            //            emptyFlag: emptyFlag,
            //            outOfLengthFlag: outOfLengthFlag
            //        };
            //    };
            //}
        };
    }
]);
basicDataModule
.controller('KeyvalueManageController', ['$scope', '$log', 'SweetAlert',
    function ($scope, $log, SweetAlert) {
        'use strict';

        (function initialize() {
            $log.debug('KeyvalueManageController.ctor()...');

        })();

    }
]);
basicDataModule.directive('keyvalueManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('keyvalueManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/masterData/keyvalueManage/keyvalue-manage.html' + '?_=' + Math.random(),
            scope: {},
            controller: 'KeyvalueManageController',
            link: function (scope, element) {

            }
        };
    }
]);
basicDataModule
    .controller('orangizationStructureManageController', ['$scope', '$log', 'SweetAlert', 'organizationStructureService', '$translate', 'uiGridConstants', 'Upload', 'apiInterceptor', '$interval',
        function($scope, $log, SweetAlert, organizationStructureService, $translate, uiGridConstants, Upload, apiInterceptor, $interval) {
            'use strict';

            // 模态框的编辑状态 true 编辑状态,false 创建状态
            $scope.isEdit = false;

            var formValidator = null;

            //当前编辑对象
            $scope.editingObject = { ID: "", name: "", IsActive: true };

            var editModalSelector = ".orangization-structure #edit-modal";

            //显示指定消息编码对应的翻译文本信息
            var showError = function(messageCode) {
                var errMsg = $translate.instant(messageCode);
                SweetAlert.warning(errMsg);
            };

            //清空当前编辑字段值
            $scope.resetEditingObject = function() {
                $scope.editingObject = { ID: "", name: "", IsActive: true };

                var elms = $(editModalSelector).find("form:first div[data-for]");
                elms.html("");
                elms.attr("class", "validate-success");
            }

            //创建(添加)新事业部,使用模态框实现编辑入口
            $scope.createNewData = function() {
                $scope.isEdit = false;

                $scope.resetEditingObject();

                $(editModalSelector).modal('show');
            };

            //编辑焦点行数据
            $scope.editFocusedRow = function(data) {
                $scope.isEdit = true;

                $scope.editingObject = { ID: data.id, name: data.name, IsActive: data.isActive };

                $(editModalSelector).modal('show');
            };

            //保存当前正在编辑数据行,经过界面初步校验后才会进入本功能
            $scope.saveEditRow = function() {

                if ($scope.editingObject == null) {
                    showError("OrganizationStructureNoSelected");
                    return;
                }
                if ($scope.editingObject && $scope.editingObject.name.trim().length == 0) {
                    showError("OrganizationStructureEmptyNode");
                    return;
                }

                if (!($(editModalSelector).find("#edit-form").valid())) {
                    return;
                }

                var osArray = [];
                osArray.push($scope.editingObject);

                var successedFun = function(rst) {
                    $scope.refreshData();

                    $(editModalSelector).modal('hide');

                    if ($scope.isEdit) {
                        SweetAlert.success($translate.instant("OrganizationStructureEditSuccess"));
                    } else {
                        SweetAlert.success($translate.instant("OrganizationStructureAddSuccess"));
                    }
                }

                if ($scope.isEdit) {
                    organizationStructureService.updateOrganizationStructure(osArray).success(successedFun);
                } else {
                    organizationStructureService.addOrganizationStructure(osArray).success(successedFun);
                }
            };

            //取消保存当前编辑行
            $scope.cancelEditOS = function() {
                $(editModalSelector).modal('hide');
            };

            //停用或启用当前事业部
            $scope.activeOS = function(data) {

                data.isActive = !data.isActive;
                var osArray = [];
                osArray.push(data);

                organizationStructureService.updateOrganizationStructure(osArray).success(function(rst) {
                    $scope.refreshData();
                });
            };

            //获取事业部数据
            $scope.refreshData = function() {
                organizationStructureService.getOrganizationStructureList().success(function(data) {
                    $scope.gridOptions.data = data;
                });
            };

            $scope.getGridHeight = function() {
                return { height: $(".orangization-structure-containers .list-container").height() + "px" };
            }

            function intiUiGrid() {

                var operation = "";
                if ($scope.hasEditPermission){
                    operation = '<div class="orangization-structure-gridcell-operation">' +
                            '<a ng-click="grid.appScope.editFocusedRow(row.entity)">' +
                            '    <i class="material-icons" style="margin-right: 10px;">&#xE254;</i>' +
                            '    <span>{{"OrganizationStructureEdit"|translate}}</span>' +
                            '</a>' +
                            '<a ng-click="grid.appScope.activeOS(row.entity)" ng-if="row.entity.isActive">' +
                            '    <i class="material-icons" style="color:#3f3f40">&#xE15C;</i>' +
                            '    <span>{{"OrganizationStructureDisabledNode"|translate}}</span>' +
                            '</a>' +
                            '<a ng-click="grid.appScope.activeOS(row.entity)" ng-if="!row.entity.isActive">' +
                            '    <i class="material-icons" style="color:#e64400">&#xE038;</i>' +
                            '    <span>{{"OrganizationStructureEnableNode"|translate}}</span>' +
                            '</a>' +
                            '</div>'
                } else{
                    operation = '<div class="orangization-structure-gridcell-operation ' + constant.noPermissionClass + '">' +
                            '<a enabled="false" >' +
                            '    <i class="material-icons" style="margin-right: 10px;">&#xE254;</i>' +
                            '    <span>{{"OrganizationStructureEdit"|translate}}</span>' +
                            '</a>' +
                            '<a enabled="false" ng-if="row.entity.isActive">' +
                            '    <i class="material-icons" style="color:#3f3f40">&#xE15C;</i>' +
                            '    <span>{{"OrganizationStructureDisabledNode"|translate}}</span>' +
                            '</a>' +
                            '<a enabled="false" ng-if="!row.entity.isActive">' +
                            '    <i class="material-icons" style="color:#e64400">&#xE038;</i>' +
                            '    <span>{{"OrganizationStructureEnableNode"|translate}}</span>' +
                            '</a>' +
                            '</div>'
                }

                $scope.gridOptions = {
                    rowHeight: constant.UIGrid.rowHeight,
                    selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
                    enableSorting: true,
                    enableColumnMenus: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableRowSelection: true,
                    enableFullRowSelection: true,
                    enableRowHeaderSelection: false,
                    multiSelect: false,
                    columnDefs: [{
                        field: 'name',
                        name: $translate.instant('OrganizationStructureName'),
                        width: '50%',
                        cellTemplate: '<div class="orangization-structure-gridcell-name"><span>{{row.entity.name}}</span><span ng-hide="true">{{row.entity.id}}</span></div>'
                    }, {
                        field: 'isActive',
                        name: $translate.instant('OrganizationStructureStatus'),
                        width: '20%',
                        cellTemplate: '<div class="orangization-structure-gridcell-isactive">' +
                            '<span ng-if="row.entity.isActive">{{"OrganizationStructureActive"|translate}}</span>' +
                            '<span ng-if="!row.entity.isActive">{{"OrganizationStructureDisabled"|translate}}</span>' +
                            '</div>'
                    }, {
                        field: 'Operation',
                        name: $translate.instant('Operation'),
                        width: '30%',
                        cellTemplate: operation
                    }],

                    onRegisterApi: function(gridApi) {
                        $scope.gridApi = gridApi;
                        $scope.gridApi.grid.registerRowsProcessor($scope.singleFilter, 200);
                        $interval(function() {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };

                $scope.singleFilter = function(renderableRows) {

                    var matcher = new RegExp($scope.searchEASText);
                    renderableRows.forEach(function(row) {

                        try {
                            var match = false;
                            ['code', 'name'].forEach(function(field) {
                                if (row.entity[field].match(matcher)) {
                                    match = true;
                                }
                            });
                            if (!match) {
                                row.visible = false;
                            }
                        } catch (e) {
                            $log.debug('singleFilter-match:' + JSON.stringify(row.entity));
                        }
                    });
                    return renderableRows;
                };
            }

            function intiValidate() {

                $.validator.addMethod("OSRepeated", function(value, element, param) {
                    var objects = $.grep($scope.gridOptions.data, function(n, i) {
                        return $scope.editingObject.ID != n.id && $.trim(n.name) == $.trim(value);
                    });

                    return objects.length < 1;
                });

                formValidator = $(editModalSelector).find("#edit-form").validate({
                    debug: true,

                    rules: {
                        name: {
                            required: true,
                            minlength: 2,
                            maxlength: 50,
                            OSRepeated: true
                        },
                        IsActive: {
                            required: "input[name='IsActive']:checked"
                        }
                    },
                    messages: {
                        name: {
                            required: $translate.instant('OrganizationStructureEmptyNode'),
                            minlength: $translate.instant('OrganizationStructureEmptyNode'),
                            maxlength: $translate.instant('OrganizationStructureOutOfLengthNode'),
                            OSRepeated: $translate.instant('OrganizationStructureDuplicateNode')
                        },
                        IsActive: $translate.instant('OrganizationStructureStatusUnsureness')
                    },
                    errorPlacement: function(error, element) {
                        var elm = $(element).parents("form:first");
                        elm = elm.find("div[data-for='" + element.attr("name") + "']");
                        elm.html(error);
                        elm.attr("class", "validate-fail");
                    }
                });
            }

            var havePermission = function() {
                $scope.$root.checkUserPermission(constant.adminPermission.basicData.orangizationStructure.editCode).success(function(data) {
                    $scope.hasEditPermission = data;

                    intiUiGrid();

                    $scope.refreshData();

                    intiValidate();
                });
            };

            (function initialize() {
                $log.debug('orangizationStructureManageController.ctor()...');
                $scope.hasEditPermission = false;

                havePermission();
            })();
        }
    ]);

basicDataModule.directive('orangizationStructureManage', ['$log', 'SweetAlert', '$translate',
    function ($log, SweetAlert, $translate) {
        'use strict';
        $log.debug('orangizationStructureManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/masterData/orangizationStructureManage/orangization-structure-manage.html' + '?_=' + Math.random(),
            scope:
            {
                addCtrlFn: '&addFn',
                removeCtrlFn: '&removeFn',
                editCtrlFn: '&editFn',
                stopCtrlFn: '&stopFn',
                attr: '@',
                list:'=bind'
            },
            controller: 'orangizationStructureManageController',
            //link: function (scope, element, attrs, $element) {
                 
            //    var originalContent, target, isEdit, isAdd;
            //    var originalArray = [];
            //    var isNodeActive = $translate.instant('OrganizationStructureActive');
            //    var isNodeDisabled = $translate.instant('OrganizationStructureDisabled');
            //    var disableNode = $translate.instant('OrganizationStructureDisabledNode');
            //    var activeNode = $translate.instant('OrganizationStructureEnableNode');
            //    var emptyNote = $translate.instant('OrganizationStructureEmptyNode');
            //    var outOfLengthNote = $translate.instant('OrganizationStructureOutOfLengthNode');
            //    var depulicateNote = $translate.instant('OrganizationStructureDuplicateNode'); 
            //    var addInvalidNote = $translate.instant('OrganizationStructureOperationAddInvalid');
            //    var editInvalidNote = $translate.instant('OrganizationStructureOperationEditInvalid');

            //    //添加行的时候删除行
            //    $(document).on('click', '.remove-row', function () {
            //        var tr=$(this).parent().parent();
            //        var id = $(tr).children('td').eq(2).text(); 
            //        $(tr).remove();

            //        if (id !== '') {
            //            scope.removeCtrlFn({ id: id });
            //        }

            //        if ($('.remove-row').length == 0) {
            //            $(".save-group").css('display', 'none');
            //            isAdd = false;
            //        }
            //    });

            //    //选中行
            //    $(document).on('click', '#orgTable tr:not(.header)', function (evt) {
            //        $("#orgTable tr").removeClass("selected");
            //        $(this).toggleClass('selected');
                     
            //        target = $("#orgTable tr.selected td");
                     
            //    });
    
            //   //编辑
            //    scope.edit = function (e, org) {
                     
            //        if (isAdd) {
            //            SweetAlert.warning(editInvalidNote);
            //            return;
            //        }

            //        var elem;

            //        isEdit = true; isAdd = false;
            //        $(".save-group").css('display', 'block');
                    
            //        elem = (e.srcElement||e.target);  //for IE: e.srcElement, others, e.target
            //        target=$(elem).parent().parent().parent().children('td');
                    
            //        scope.currentTarget = target;
            //        scope.currentOrg =org;
                    
            //        var element = $(target).eq(0); 
            //        originalContent = $(element).text();
            //        var result=$.grep(originalArray,function(e){ return e.id===org.id});
            //        if (result.length === 0 || originalContent!='') {
            //            //add to originalArray for the cancel 
            //            originalArray.push({ 'id': org.id, 'content': originalContent });

            //            $(element).addClass("cellEditing");
            //            $(element).html("<input type='text' class='form-control' value='" + originalContent + "' /></div>");
            //            $(element).children().first().focus();
            //            $(element).children().first().keypress(function (e) {
            //                if (e.which == 13) {
            //                    var newContent = $(element).children().first().val();
            //                    $(element).text(newContent);
            //                    $(element).removeClass("cellEditing");
            //                }
            //            });
            //        }   
            //    };
                
            //    //取消保存
            //    scope.cancel = function (e) {
            //        var elem = (e.srcElement || e.target);  //for IE: e.srcElement, others, e.target
            //        if (isEdit) {

            //            var element = $(".cellEditing");
            //            element.each(function (index) {
            //                var td = $(this).parent().children('td').eq(2);
            //                var id = $(td).text();
            //                var obj = $.grep(originalArray, function (x) { return x.id === id });
            //                if (obj.length > 0) {
            //                    $(this).text(obj[0].content);
            //                    $(this).removeClass("cellEditing");
            //                } 
            //            });
            //            originalArray = [];
            //            isEdit = false;
            //        } else {
            //            $('.new-add').remove();
            //            isAdd = false;
            //        }
            //        $(".save-group").css('display', 'none');
            //    };
  
            //    $("#btnAddOrgStructure").on('click', function () {
            //        if (isEdit) {
            //            SweetAlert.warning(addInvalidNote);
            //            return;
            //        }
            //        isEdit = false; isAdd = true;
            //        $(".save-group").css('display', 'block');
            //        $('#orgTable tr:last').after('<tr class="new-add"><td><input type="text" class="form-control new-add-input" value="" /></td><td>' + isNodeActive + '</td><td><i class="fa fa-times remove-row" aria-hidden="true"></i></td></tr>');

            //    });
                 
            //    //保存
            //    scope.save = function (e) {
            //        if (isEdit) {
            //            //编辑保存
            //            var elem = (e.srcElement || e.target);  //for IE: e.srcElement, others, e.target
            //            var element = $(".cellEditing");
            //            var newValues = [];
            //            var idArray = [];

            //            element.each(function (index) {
            //                var td = $(this).parent().children('td');
            //                var newContent = $(td).eq(0).children().first().val();
            //                var isActive = $(td).eq(1).text();
            //                var id = $(td).eq(2).text();
            //                idArray.push(id);
            //                newValues.push({
            //                    id: id, name: newContent, isActive: isActive
            //                });
            //            });

            //            var validationResult = formValidation(newValues);

            //            if (!validationResult.duplicateFlag && !validationResult.emptyFlag && !validationResult.outOfLengthFlag) {
            //                isEdit = false;
            //                $(".save-group").css('display', 'none');
                         
            //                element.each(function (index) {
            //                    var td = $(this).parent().children('td');
            //                    var firstTd = $(td).eq(0);
            //                    var newVal = $(firstTd).children().first().val();
            //                    $(firstTd).text(newVal);
            //                    $(firstTd).removeClass("cellEditing");
            //                });
                             
            //                scope.editCtrlFn({
            //                    newcontent: newValues
            //                });

            //                originalArray = [];
            //            } 
                         
            //        } else {
            //            //新增层级
            //            var newaddTarget = $('.new-add-input');
            //            var values = [];
            //            var hasName = true;
            //            var outOfLength = false;
            //            var duplicate = false;
            //            var newValues = [];

            //            $(newaddTarget).each(function () {
            //                var guid = PWC.newGuid();
            //                var name = $(this).val();
                             
            //                newValues.push({
            //                    id: guid, name: name, isActive: true
            //                });
            //            });

            //            var validationResult = formValidation(newValues);
                          
            //            if (!validationResult.duplicateFlag && !validationResult.emptyFlag && !validationResult.outOfLengthFlag) {
            //                $(".save-group").css('display', 'none');
            //                $('.new-add').remove();
            //                var newAdd = {
            //                    newrow: newValues
            //                };
            //                newValues.forEach(function (item) {
            //                    scope.organizationStructureList.push(item);
            //                });
            //                scope.addCtrlFn(newAdd);
            //                originalArray = [];
            //            } 
            //        }
            //    };
 
            //    //停用和启用
            //    var currentId;
            //    scope.stopOrActive=function (org) {
                  
            //        currentId = org.id;
            //        var name =org.name;
            //        var id =org.id;
            //        var updateArray = [];
            //        var values = { id: id, name: name, isActive: !org.isActive };
            //        updateArray.push(values);

            //        scope.stopCtrlFn({ newcontent: updateArray });

            //        scope.$on('to-child', function (event, successFlag) {
            //            if (successFlag) {
            //                var item = _.where(scope.organizationStructureList, { id: currentId });
            //                item[0].isActive = values.isActive; 
            //              }
            //           });
            //    };


            //    //form validation before saving add/edit operation
            //    var formValidation = function (newValues) {

            //        var duplicateFlag = false;
            //        var emptyFlag = false;
            //        var outOfLengthFlag = false;

            //        //判断同时输入多个的时候不能重复
            //        var uniqueList = _.uniq(newValues, function (item, key, name) {
            //            return item.name;
            //        });

            //        if (uniqueList.length != newValues.length) {
            //            duplicateFlag = true;
            //        }

            //        newValues.forEach(function (item) {
                         
            //            var filterResult = _.find(scope.organizationStructureList, { name: item.name });
            //            //如果找的这个object和newvalue的id是同一个的话,不是重复 
            //            if (filterResult!=undefined && filterResult.id !== item.id) {
            //                duplicateFlag = true;
            //            } else if (item.name === '') {
            //                emptyFlag = true;
            //            } else if (PWC.getLength(item.name) > constant.organizationStructManage.nameMaxLength) {
            //                outOfLengthFlag = true;
            //            }
            //        });

            //        //give notice to user
            //        if (emptyFlag) {
            //            SweetAlert.warning(emptyNote);
            //        } else if (duplicateFlag) {
            //            SweetAlert.warning(depulicateNote);
            //        } else if (outOfLengthFlag) {
            //            SweetAlert.warning(outOfLengthNote);
            //        }

            //        return {
            //            duplicateFlag: duplicateFlag,
            //            emptyFlag: emptyFlag,
            //            outOfLengthFlag: outOfLengthFlag
            //        };
            //    };
            //}
        };
    }
]);
basicDataModule
    .controller('RegionManageController', ['$scope', '$log', 'SweetAlert', 'regionService', '$translate', 'areaRegionService', 'uiGridTreeViewConstants', '$timeout', 'areaService', '$q',
        function ($scope, $log, SweetAlert, regionService, $translate, areaRegionService, uiGridTreeViewConstants, $timeout, areaService, $q) {
            'use strict';

            var tree;
            $scope.my_tree = tree = {};
            $scope.defaultCity = {
                id: '',
                parentID: '',
                name: ''
            };

            $scope.regionTypeData = [{
                type: 0,
                name: $translate.instant('AdministrativeRegions')
            }, {
                type: 1,
                name: $translate.instant('CustomArea')
            }];

            var isActiveMap = {
                false: 'Enable',
                true: 'Disable'
            };

            $scope.awesomeCallback = function (node, tree) {
                // Do something with node or tree
                $log.info('callback');
            };

            $scope.otherAwesomeCallback = function (node, isSelected, tree) {
                // Do soemthing with node or tree based on isSelected
                $log.info('other call back', node);
                $scope.tree = tree;
            }


            var getProvinceAndCityList = function (branch) {
                var citys = [];
                if (branch.itemData.data.isArea) {
                    // 如果是自定义区域

                    if (branch.children && branch.children.length > 0) {
                        branch.children.forEach(function (row) {
                            if (!row.itemData.data.isArea) {
                                var tempList = getProvinceAndCityList(row);

                                citys = _.union(citys, tempList);
                            }
                        });
                    }


                } else {
                    // 如果是行政区域, 省
                    if (branch.children && branch.children.length > 0) {
                        var tempCities = [];
                        branch.children.forEach(function (row) {
                            citys.push({
                                id: row.itemData.id,
                                name: row.text,
                                level: 2,
                                status: 2,
                                parentId: row.itemData.parentId,
                            });
                        });

                        //var allCities = _.find($scope.provinceCityData, function(num) {
                        //    return num.id === branch.itemData.id
                        //});

                        //if (allCities && allCities.children && allCities.children.length === branch.children.length) {
                        //    citys.push({
                        //        id: branch.itemData.id,
                        //        name: branch.text,
                        //        level: 1,
                        //        status: 2
                        //    });
                        //} else {
                        //    citys.push({
                        //        id: branch.itemData.id,
                        //        name: branch.text,
                        //        level: 1,
                        //        status: 1
                        //    });
                        //}

                    } else {
                        // 市
                    }
                }

                return citys;
            };

            var colorPanel = {

                // 颜色列表
                // yellow,orange,gold
                colorList: ['#FFB300', '#FEE002', '#FFFA23'],

                createNew: function () {
                    var colorPanelInstance = {};
                    colorPanelInstance.index = 0;
                    colorPanelInstance.getNextColor = function () {
                        if (colorPanelInstance.index >= colorPanel.colorList.length - 1) {
                            colorPanelInstance.index = 0;
                        } else {
                            colorPanelInstance.index++;
                        }

                        return colorPanel.colorList[colorPanelInstance.index];
                    }

                    return colorPanelInstance;
                }
            };

            var colorPanelInstance = colorPanel.createNew();

            //var loadRegionTree = function () {
            //    $scope.doing_async = true;
            //    regionService.getSettingRegionTree().success(function (data) {
            //        initParam();
            //        setAreaRegionTreeColor(data);
            //        $scope.areaRegionTreeData = data;

            //        $timeout(function () {

            //            if ($scope.selectedBranch) {
            //                $scope.gridInstance.selectItem($scope.selectedBranch.key);
            //            } else {
            //                $scope.gridInstance.selectItem(data[0].id);
            //            }
            //        }, 20);

            //    });
            //};


            var setAreaRegionTreeColor = function (data) {
                if (data && data.length > 0) {

                    data.forEach(function (row) {

                        var color = colorPanelInstance.getNextColor();
                        row.data.color = color;

                        if (row.items && row.items.length > 0) {
                            row.items.forEach(function (row2) {
                                setColor(row2, color);
                            });
                        }
                    });

                    // if (data[0].items && data[0].items.length > 0) {
                    //     data[0].items.forEach(function(row) {
                    //         var color = colorPanelInstance.getNextColor();
                    //         row.data.color = color;

                    //         if (row.children && row.children.length > 0) {
                    //             row.children.forEach(function(row2) {
                    //                 setColor(row2, color);
                    //             });
                    //         }
                    //     });
                    // }
                }

            };

            var orders = new DevExpress.data.ODataStore({
                url: "http://localhost:20001/api/v1/region/getSettingRegionTree"
            });

            var dataSource = new DevExpress.data.DataSource({
                load: function (loadOptions) {
                    var d = new $.Deferred();

                    regionService.getSettingRegionTree().success(function (data) {


                        initParam();
                        setAreaRegionTreeColor(data);
                        //$scope.areaRegionTreeData = data;

                        $timeout(function () {

                            if ($scope.selectedBranch) {
                                $scope.gridInstance.selectItem($scope.selectedBranch.key);
                            } else {

                                // 菜单直接点进来就可以加一级
                                // $scope.gridInstance.selectItem(data[0].id);
                            }
                        }, 20);

                        d.resolve(data);

                    });

                    return d.promise();
                }
            });

            $scope.unSelectArea = function (event) {

                var className = event.target.className;
                if (className && (className.indexOf('cannot-click') > -1 || className.indexOf('material-icons') > -1)) {
                    return;
                }

                $scope.gridInstance.unselectAll();
                $scope.selectedBranch = null;
                initParam();
                $timeout(refreshMap, 20);
            };

            var loadRegionTree = function () {
                $scope.areaTreeViewOptions = {
                    // bindingOptions: {
                    //     dataSource: 'areaRegionTreeData',
                    //     searchValue: 'searchValue',
                    //     expandAllEnabled: 'expandAll',
                    // },
                    itemTemplate: 'itemAreaTreeTemplate',
                    dataStructure: "plain",
                    //dataSource: new DevExpress.data.DataSource({
                    //    store: new DevExpress.data.ODataStore({
                    //        url: "http://localhost:20001/api/v1/region/getSettingRegionTree"
                    //    })
                    //}),
                    dataSource: dataSource,
                    // remoteOperations: {
                    //     sorting: true,
                    //     //paging: true
                    // },
                    // selection: {
                    //     mode: "single"
                    // },
                    selectionMode: 'single', //单选
                    loadPanel: {
                        enabled: true
                    },
                    scrolling: {
                        mode: "virtual"
                    },
                    keyExpr: "uniqueId",
                    showRowLines: true,
                    showColumnLines: true,
                    rowAlternationEnabled: true,
                    showBorders: true,
                    // selectAllText: $translate.instant('SelectAll'),
                    selectByClick: true, // 点击选中
                    scrollDirection: 'vertical', //Accepted Values: 'vertical' | 'horizontal' | 'both'
                    selectNodesRecursive: false, //级联选择
                    onInitialized: function (e) {
                        $scope.gridInstance = e.component;
                    },
                    onItemClick: function (e) {

                        // $scope.gridInstance.selectItem(e.node.key);
                        // if ($scope.selectedBranch != null && $scope.selectedBranch.key === e.node.key){
                        //     //默认全部不选择
                        //     $scope.gridInstance.unselectAll();

                        //     $scope.selectedBranch = null;
                        //     $timeout(refreshMap, 20);
                        //     return;
                        // }

                        $scope.selectedBranch = e.node;

                        // 可以添加的条件
                        if ($scope.hasEditPermission) {
                            $scope.isActiveOperate = $scope.selectedBranch.itemData.data.isActive;
                            if ($scope.selectedBranch.itemData.data.isActive) {

                                if ($scope.selectedBranch.itemData.data.isArea) {
                                    $scope.canEdit = true;
                                    $scope.canAdd = true;
                                    $scope.isActiveStr = $translate.instant(isActiveMap[$scope.selectedBranch.itemData.data.isActive]);

                                } else {
                                    $scope.canEdit = false;
                                    $scope.canAdd = false;
                                    $scope.isActiveStr = '';
                                }

                            } else {
                                $scope.canAdd = false;
                                $scope.canEdit = false;
                                $scope.isActiveStr = $translate.instant(isActiveMap[$scope.selectedBranch.itemData.data.isActive]);
                            }
                        }

                        $timeout(refreshMap, 20);
                    }

                };
            };

            var setColor = function (branch, color) {
                branch.data.color = color;
                if (branch.items && branch.items.length) {
                    branch.items.forEach(function (row) {
                        setColor(row, color);
                    });
                }
            };

            var loadProvinceAndCity = function () {
                regionService.getProvinceAndCityTreeList().success(function (data) {

                    // 只取有效的数据
                    //data = _.filter(data, function (num) { return num.isActive });
                    //$scope.provinceList = _.filter(data, function (num) { return num.levelType === 1 });
                    //$scope.allCityList = _.filter(data, function (num) { return num.levelType === 2 });
                    $scope.provinceCityData = data;
                });
            };

            var selectRegion = function (region) {
                $scope.selectedBranch = region;
                $scope.selectedRegion = region.data;
                $scope.selectedRegion.isActiveStr = $translate.instant(isActiveMap[$scope.selectedRegion.isActive]);

                if (!$scope.selectedRegion.isActive) {
                    $scope.canAdd = false;
                } else {
                    if ($scope.selectedRegion.isArea) {
                        $scope.canAdd = true;
                    } else {
                        $scope.canAdd = false;
                    }
                }

                refreshMap();
            };

            var refreshMap = function () {
                $timeout(function () {
                    if ($scope.mychart) {
                        var option = angular.copy($scope.option);

                        var data = [];

                        if ($scope.selectedBranch && $scope.selectedBranch.parent === null) {

                            // 如果是根节点
                            if ($scope.selectedBranch.children && $scope.selectedBranch.children.length > 0) {
                                $scope.selectedBranch.children.forEach(function (row) {
                                    var tempCity = getAreaCityRecursive(row);
                                    var tempData = getMapData(tempCity, row);

                                    if (tempData && tempData.length > 0) {
                                        data = _.union(data, tempData);
                                    }
                                });
                            }

                        } else {
                            var areaCity = getAreaCityRecursive($scope.selectedBranch);

                            var tempData = getMapData(areaCity, $scope.selectedBranch);
                            if (tempData && tempData.length > 0) {
                                data = _.union(data, tempData);
                            }
                        }

                        if (data && data.length > 0) {
                            option.series[0].data = data;
                            $scope.mychart.setOption(option);
                        } else {
                            option.series[0].data = [];
                            $scope.mychart.setOption(option);
                        }
                    }
                }, 0);
            };

            var getMapData = function (areaCity, branch) {

                var data = [];
                if (areaCity && areaCity.length > 0) {

                    var reg = /省$/gi;
                    var cityreg = /市$/gi;
                    areaCity.forEach(function (row) {

                        //will replace with constanct variable
                        if (row === '香港特别行政区') {
                            row = '香港';
                        } else if (row === '澳门特别行政区') {
                            row = '澳门';
                        }

                        var item = {
                            name: row.replace(reg, '').replace(cityreg, ''),
                            value: randomData(),
                            itemStyle: {
                                normal: {
                                    areaColor: branch.itemData.data.color
                                }
                            }
                        };

                        data.push(item);
                    });
                }

                return data;
            };

            var getAreaCityRecursive = function (branch) {
                var citys = [];
                if (!branch || !branch.itemData || !branch.itemData.data) {
                    return citys;
                }

                if (branch.itemData.data.isArea) {
                    // 如果是自定义区域

                    if (branch.children && branch.children.length > 0) {
                        var tempCities = [];
                        branch.children.forEach(function (row) {
                            var temp = getAreaCityRecursive(row);
                            if (temp && temp.length > 0) {
                                tempCities = _.union(tempCities, temp);
                            }
                        });

                        citys = _.union(citys, tempCities);
                    }

                } else {
                    // 如果是行政区域
                    if (branch.children && branch.children.length > 0) {
                        var tempCities = [];

                        tempCities.push(branch.text);
                        citys = _.union(citys, tempCities);
                    } else { }
                }

                return citys;
            };

            var newRegion = function ($event) {

                if (!$scope.canAdd) {
                    return;
                    $event.stopPropagation();
                }

                $scope.editModel = {};
                if ($scope.selectedBranch) {
                    $scope.editModel.mergerName = $scope.selectedBranch.itemData.data.mergerName;
                }

                $scope.editModel.isfirstShow = true;
                $scope.isAdd = true;
                $scope.editModel.RegionNames = [];

                // 如果是选择行政省,则添加输入框中,行政省不能选
                if ($scope.canAdd && $scope.selectedBranch && $scope.selectedBranch.children && $scope.selectedBranch.children.length > 0 && !$scope.selectedRegion.isArea) {
                    $scope.selectProvince = _.find($scope.provinceList, function (num) {
                        return num.id + '' === $scope.selectedBranch.itemData.id
                    });
                    $scope.loadCity();
                } else {
                    $scope.selectProvince = null;
                    $scope.selectCity = null;
                }
                resetErrorStatus();

                $scope.editModel.SelectedCityList = [];

                $('#addRegionPop').modal('show');
                $event.stopPropagation();
            };

            var changeRegionName = function () {
                if (!$scope.editModel.name) {
                    $scope.editModel.name = '';
                }

                $scope.editModel.mergerName = $scope.selectedRegion.mergerName + ',' + $scope.editModel.name;
                $scope.editModel.shortName = $scope.editModel.name;
            };

            var save = function () {

                resetErrorStatus();
                if (!($('#addRegionForm').valid())) {
                    return;
                }

                var selectedCity = $scope.selectedNodeList;
                console.log('selectedCity', selectedCity);

                //var tree = $scope.editModel.MyTree;
                var areaId = $scope.selectedBranch ? $scope.selectedBranch.itemData.id : null;


                var parentId = $scope.selectedBranch ? $scope.selectedBranch.itemData.parentId : null;
                var name = $scope.editModel.areaName;

                //增加区域的情况
                if ($scope.isAdd) {

                    $scope.editModel.IsEdit = false;

                    var saveModel = {
                        parentId: areaId,
                        name: name,
                        cityList: selectedCity
                    };

                    console.log(saveModel);

                    areaRegionService.add(saveModel).success(function (data) {
                        if (!data.result) {
                            swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                            return;
                        }

                        SweetAlert.success($translate.instant('SaveSuccess'));
                        refreshAreaRegionTree();

                        $('#addRegionPop').modal('hide');
                    });
                } else { //编辑区域的情况

                    var saveModel = {
                        id: areaId,
                        parentId: $scope.selectedBranch.itemData.parentId,
                        name: name,
                        cityList: selectedCity,
                        isActive: true
                    };

                    areaRegionService.update(saveModel).success(function (data) {
                        if (!data.result) {
                            swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                            return;
                        }

                        SweetAlert.success($translate.instant('SaveSuccess'));
                        refreshAreaRegionTree();
                        $('#addRegionPop').modal('hide');
                    });
                }
            };

            var addCityToMap = function (model) {
                if (model.isArea) {
                    return;
                }

                if ($scope.mychart) {
                    var option = $scope.option;

                    var areaCity = [];
                    if (model.provinceRegionID && model.cityRegionID) {
                        // 指定市
                        areaCity.push(model.cityName);
                    } else {
                        // 某一个省的所有市
                        var cityNameList = _.pluck($scope.cityList, 'name');
                        cityNameList = _.filter(cityNameList, function (num) {
                            return num !== ''
                        });
                        areaCity = cityNameList;
                    }

                    var item = getMapData(areaCity, $scope.selectedBranch);
                    if (!option.series[0].data || option.series[0].data.length === 0) {
                        option.series[0].data = [];
                    }

                    // 两个数组union起来
                    option.series[0].data = _.union(option.series[0].data, item);

                    $timeout(function () {
                        $scope.mychart.setOption(option);
                    }, 100);
                }
            };

            var selectedCityList = [];
            var getCity = function (item) {

                if (item.children.length == 0) {
                    selectedCityList.push(item);
                    return;
                }

                item.children.forEach(function (itm) {
                    getCity(itm);
                });
            };

            var edit = function ($event) {
                $scope.isAdd = false;
                $scope.editModel = $scope.selectedRegion;
                selectedCityList = [];

                var selectItem = $scope.selectedBranch;
                var selectedProvinceCityInfo = getProvinceAndCityList(selectItem);

                $scope.editModel.SelectedCityList = selectedProvinceCityInfo;

                $scope.editModel.IsEdit = true;
                $scope.selectRegionType = $scope.regionTypeData[1];
                $scope.selectProvince = null;
                $scope.selectCity = null;
                $scope.editModel.areaName = $scope.selectedBranch.text;
                resetErrorStatus();
                $('#addRegionPop').modal('show');
                $event.stopPropagation();
            };

            var cancel = function () {

                if ($scope.selectedRegion.id) {
                    $scope.isEdit = false;
                    $scope.selectedRegion.isEditRegionItem = false;
                } else {
                    $scope.isAdd = false;
                    $scope.isEdit = false;
                    $scope.selectedRegion.parentNode.subRegionList = _.filter($scope.selectedRegion.parentNode.subRegionList, function (num) {
                        return num.id
                    });
                }
            };

            var regionItemDbClick = function (model) {

                if (!$scope.isEdit) {
                    $scope.selectedRegion = model;
                    $scope.selectedRegion.pinYin = '';
                    $scope.selectedRegion.isEditRegionItem = true;
                    $scope.selectedRegion.editName = $scope.selectedRegion.name;
                    $scope.isEdit = true;
                }
            };


            var resetErrorStatus = function () {
                var currentForm = $('#addRegionForm');
                $.each(currentForm.children(), function (index, element) {
                    // $(element).find('.has-error').removeClass('has-error');
                    $(element).find('.has-error label').remove();
                });
                validator.resetForm();
            };

            // 启用禁用
            var updateIsActive = function ($event) {
                var updateModel = {};
                updateModel.isActive = !$scope.selectedBranch.itemData.data.isActive;
                updateModel.id = $scope.selectedBranch.itemData.id;
                updateModel.text = $scope.selectedBranch.text;


                SweetAlert.swal({
                    title: $translate.instant('Confirm') + $scope.isActiveStr + '?',
                    text: $translate.instant('ComfirmRegionIsActive').formatObj({
                        isActiveStr: $scope.isActiveStr,
                        regionName: updateModel.text
                    }),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('Cancel'),
                    closeOnConfirm: false,
                    closeOnCancel: true
                },
                    function (isConfirm) {
                        if (isConfirm) {

                            areaService.isactive(updateModel).success(function (data) {
                                if (!data.result) {

                                    if (data.resultMsg) {
                                        swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                                    } else {
                                        var errorList = [];
                                        var template = $translate.instant(data.resultMsg);

                                        var orgNameList = data.data.join(',');
                                        swal($translate.instant('SaveFail'), template.formatObj({
                                            orgNameList: orgNameList
                                        }), 'warning');
                                    }

                                    updateModel.isActive = !$scope.selectedRegion.isActive;
                                    return;
                                };

                                SweetAlert.success($translate.instant('SaveSuccess'));
                                refreshAreaRegionTree();
                                $event.stopPropagation();
                            });
                        }
                    });

            };

            var resources = {
                provinceRequired: $translate.instant('ProvinceRequired'),
                areaNameRequired: $translate.instant('AreaNameRequired')
            };

            var validator = $("#addRegionForm").validate({
                errorClass: "has-error",
                rules: {
                    province: {
                        required: true
                    },
                    areaName: {
                        required: true,
                        maxlength: 50
                    }
                },
                messages: {
                    province: {
                        required: resources.provinceRequired
                    },
                    areaName: {
                        required: resources.areaNameRequired,
                        maxlength: $translate.instant('AreaNameOutOfLengthNode'),
                    }
                },
                errorPlacement: function (error, element) {
                    setErrorStyle(error, element);
                }
            });

            var setErrorStyle = function (error, element) {
                if (element.hasClass('has-error')) {
                    element.parent().addClass('has-error');
                    error.insertAfter(element);
                    error.addClass('label');
                    // error.addClass('label-danger');
                }
            };

            var setCollapsedID = function (model) {
                if (model.parentNode) {
                    $scope.collapsedIDList.push(model.parentNode.id);
                    setCollapsedID(model.parentNode);
                }
            };

            var setParentNodeList = function (model) {
                if (model.subRegionList && model.subRegionList.length > 0) {
                    model.subRegionList.forEach(function (row) {
                        row.parentNode = model;
                        setParentNodeList(row);
                    });
                }
            };

            // id:主键ID
            // node:对应节点
            // model:添加的时候的数据
            var reloadById = function (id, node, model) {

                regionService.getAreRegionTreeByNodeID(id).success(function (data) {
                    if (data && data.length > 0) {
                        var oldData = node.data;
                        node.children = angular.copy(data[0].children);
                        node.label = data[0].label;
                        node.data = angular.copy(data[0].data);
                        node.data.isRoot = oldData.isRoot;
                        if (!oldData.color) {
                            oldData.color = colorPanelInstance.getNextColor();
                        }
                        setColor(node, oldData.color);
                        $scope.selectedRegion.isActiveStr = $translate.instant(isActiveMap[$scope.selectedRegion.isActive]);

                        selectRegion(node);
                        //if (model) {
                        //    addCityToMap(model);
                        //}
                    }
                });
            };

            var randomData = function () {
                return Math.round(Math.random() * 1000);
            };

            $scope.drawChinaMap = function () {
                //var mychart = echarts.init(document.getElementById('chinaMap'));

                $.get('/app-resources/map/china.json', function (chinaJson) {
                    $scope.chinaJson = chinaJson;

                    echarts.registerMap('china', chinaJson);
                    var mychart = echarts.init(document.getElementById('chinaMap'));
                    var option = {
                        //visualMap: {
                        //    min: 0,
                        //    max: 2500,
                        //    left: 'left',
                        //    top: 'bottom',
                        //    text: ['高', '低'],           // 文本,默认为数值文本
                        //    show: false,
                        //},
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: []
                        },
                        series: [{
                            type: 'map',
                            map: 'china',
                            nameMap: {
                                'China': '中国'
                            },
                            label: {
                                normal: {
                                    show: true,
                                    textStyle: {

                                        // #c12e34, 改label字体的颜色
                                        color: '#894A00'
                                    }
                                },
                                emphasis: {
                                    //textStyle: {
                                    //    color: '#fff'
                                    //}
                                }
                            },
                            itemStyle: {
                                normal: {
                                    areaColor: '#C9C9C9',
                                    borderColor: 'white',
                                    borderWidth: 0.5,
                                    label: {
                                        show: false
                                    }
                                },
                                emphasis: {
                                    areaColor: '#F2D997',
                                    label: {
                                        show: true
                                    }
                                }
                            },
                            scaleLimit: {
                                min: 1
                            },
                            selectedMode: false,
                            roam: true,
                            data: []
                        }]
                    };

                    $scope.option = option;
                    mychart.setOption(option);


                    //mychart.on('click', function (parmas) {

                    //});

                    //mychart.dispatchAction({
                    //    type: 'highlight',
                    //    // 可选,系列 index,可以是一个数组指定多个系列
                    //    seriesIndex: 0,
                    //    // 可选,系列名称,可以是一个数组指定多个系列
                    //    dataIndex: 1,
                    //    // 可选,数据的 名称
                    //});

                    //mychart.dispatchAction({
                    //    type: 'highlight',
                    //    // 可选,系列 index,可以是一个数组指定多个系列
                    //    seriesIndex: 0,
                    //    // 可选,系列名称,可以是一个数组指定多个系列
                    //    dataIndex: 29,
                    //    // 可选,数据的 名称
                    //});

                    //mychart.dispatchAction({
                    //    type: 'highlight',
                    //    // 可选,系列 index,可以是一个数组指定多个系列
                    //    seriesIndex: 0,
                    //    // 可选,系列名称,可以是一个数组指定多个系列
                    //    dataIndex: 28
                    //    // 可选,数据的 名称
                    //});

                    mychart.on('click', function (parmas) {

                    });

                    $scope.mychart = mychart;
                });



                //mychart.setOption(option);
            };

            $scope.changeRegionType = function () {
                if ($scope.selectRegionType.id == 0) {

                    $scope.editModel.areaName = '';
                } else {
                    $scope.selectProvince = null;
                    $scope.selectCity = null;
                }
            };

            $scope.loadCity = function () {
                $scope.cityList = _.filter($scope.allCityList, function (num) {
                    return num.parentID === $scope.selectProvince.id
                });

                if ($scope.cityList != null && $scope.cityList.length > 0) {
                    // 加上默认的城市
                    $scope.cityList.splice(0, 0, $scope.defaultCity);
                } else {
                    $scope.cityList.push($scope.defaultCity);
                }

                $scope.selectCity = $scope.defaultCity;
            };


            var havePermission = function () {
                $scope.$root.checkUserPermission(constant.adminPermission.basicData.areaManage.editCode).success(function (data) {
                    $scope.hasEditPermission = data;
                    initParam();
                });
            };


            var initParam = function () {
                $scope.isActiveStr = '';
                $scope.isAdd = true;
                $scope.isEdit = false;
                $scope.canEdit = false;

                if ($scope.hasEditPermission) {
                    $scope.canAdd = true;
                } else {
                    $scope.canAdd = false;
                }
            };

            var refreshAreaRegionTree = function () {
                dataSource.reload()
                //$scope.gridInstance.repaint();
            };

            (function initialize() {

                $log.debug('RegionManageController.ctor()...');
                $scope.regionList = [];

                $scope.selectedRegion = {};
                $scope.selectedRegion.isActiveStr = $translate.instant(isActiveMap[false]);;

                $scope.selectRegion = selectRegion;
                $scope.newRegion = newRegion;

                // $scope.newRegionNode = newRegionNode;
                $scope.changeRegionName = changeRegionName;

                $scope.save = save;
                $scope.edit = edit;
                $scope.updateIsActive = updateIsActive;

                $scope.hasEditPermission = false;
                havePermission();
                //loadAreaTree();
                loadRegionTree();
                $scope.drawChinaMap();
                //loadProvinceAndCity();
            })();
        }
    ]);

basicDataModule.directive('regionManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('regionManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/masterData/regionManage/region-manage.html' + '?_=' + Math.random(),
            scope: {},
            replace: true,
            controller: 'RegionManageController',
            link: function (scope, element) {

            }
        };
    }
]);
basicDataModule
.controller('WordLibraryManageController', ['$scope', '$log', 'SweetAlert', 'keywordmapService', 'uiGridConstants', 'stdAccountService', '$translate',
    function ($scope, $log, SweetAlert, keywordmapService, uiGridConstants, stdAccountService, $translate) {
        'use strict';

        var loadstdAccountList = function () {
            stdAccountService.GetStdAccountList().success(function (data) {
                data.forEach(function (row) {
                    row.optionText = row.code + ' ' + row.fullName;
                });

                $scope.stdAccountList = data;
            });
        };

        var loadKeyWordMapList = function () {

            keywordmapService.get(1).success(function (data) {
                $scope.gridOptions.data = data;
                $scope.gridOptions.noData = data.length === 0;
                $log.debug('keywordmapService.get...');
            });
        };

        var loadSingleKeyWordMap = function () {
            var selectedKeywordMapList = $scope.gridApi.selection.getSelectedRows();

            if (selectedKeywordMapList && selectedKeywordMapList.length > 0) {
                // 选中
                keywordmapService.getsingle(selectedKeywordMapList[0].id).success(function (data) {
                    $scope.editModel = data;
                    $scope.editModel
                    $scope.isAdd = false;
                    $scope.selectAccount = _.find($scope.stdAccountList, function (num) { return num.code === data.standardCode });

                    $('#addKeywordMapPop').modal('show');
                });
            }
            else {
                $log.debug('please select one keywordMap...');
            }
        };

        var changesStdAccountSelect = function () {
            if ($scope.selectAccount) {
                $scope.editModel.name = $scope.selectAccount.name;
                $scope.editModel.stdFullName = $scope.selectAccount.fullName;
                $scope.editModel.standardCode = $scope.selectAccount.code;
            } else {
                $scope.editModel.name = '';
                $scope.editModel.stdFullName = '';
                $scope.editModel.standardCode = '';
            }
        };

        var save = function () {
            if (!($('#addKeywordMapForm').valid())) {
                return;
            }

            $scope.editModel.isActive = 1;
            if ($scope.isAdd) {
                keywordmapService.add($scope.editModel).success(function (data) {
                    if (!data.result) {
                        var errorList = [];

                        if (data.data != null && data.data.length > 0) {
                            for (var i = 0; i < data.data.length; i++) {
                                if (!data.data[i].result && data.data[i].resultMsg) {
                                    var fullNameList = _.map(data.data[i].data, function (num) { return num.fullName; });
                                    var fullNameListStr = fullNameList.join(',', fullNameList);
                                    var error = $translate.instant(data.data[i].resultMsg) + '';
                                    error = error.formatObj({ code: $scope.editModel.standardCode, fullNameList: fullNameListStr });
                                    errorList.push(error);
                                }
                            }
                        }

                        SweetAlert.info("region", errorList.join(';', errorList));
                        return;
                    };

                    $log.debug(data);
                    $('#addKeywordMapPop').modal('hide');
                    loadKeyWordMapList();
                });
            } else {
                keywordmapService.update($scope.editModel).success(function (data) {
                    if (!data.result) {
                        SweetAlert.info('info', $translate.instant(data.resultMsg));
                        return;
                    }

                    $('#addKeywordMapPop').modal('hide');
                    loadKeyWordMapList();
                });
            }
        };

        var search = function () {
            $scope.gridApi.grid.refresh();
        };

        // 新增
        var newKeywordMap = function () {
            $scope.editModel = {};
            $scope.isAdd = true;
            $scope.selectAccount = null;
            resetErrorStatus();
            $('#addKeywordMapPop').modal('show');
        };

        var resetErrorStatus = function () {
            var currentForm = $('#addKeywordMapForm');
            $.each(currentForm.children(), function (index, element) {

                // 去除div
                $(element).children('div').removeClass('has-error');
            });
            validator.resetForm();
        };

        var resources = {
            stdCodeRequired: $translate.instant('AccountKeywordStandardCodeRequired'),
            fullNameRequired: $translate.instant('AccountKeywordTextRequired')
        };


        var validator = $("#addKeywordMapForm").validate({
            errorClass: "has-error",
            rules: {
                stdCode: {
                    required: true
                },
                fullName: {
                    required: true
                }
            },
            messages: {
                stdCode: {
                    required: resources.stdCodeRequired
                },
                fullName: {
                    required: resources.fullNameRequired
                }
            },
            errorPlacement: function (error, element) {
                setErrorStyle(error, element);
            }
        });

        var setErrorStyle = function (error, element) {
            if (element.hasClass('has-error')) {
                element.parent().addClass('has-error');
                error.insertAfter(element);
                error.addClass('label');
                // error.addClass('label-danger');
            }
        };

        var modifyIsActive = function () {
            var selectedKeywordMapList = $scope.gridApi.selection.getSelectedRows();

            if (selectedKeywordMapList && selectedKeywordMapList.length > 0) {

                SweetAlert.swal({
                    title: $translate.instant('ComfirmDisable') + '?',
                    text: $translate.instant('ComfirmAccountMappingKeywordDisable').formatObj({ code: selectedKeywordMapList[0].standardCode, name: selectedKeywordMapList[0].name, fullName: selectedKeywordMapList[0].fullName }),
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55", confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('Cancel'),
                    closeOnConfirm: false,
                    closeOnCancel: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        // 选中
                        var model = selectedKeywordMapList[0];
                        model.isActive = model.isActive === 1 ? 0 : 1;
                        keywordmapService.isactive(model).success(function (data) {
                            if (!data.result) {
                                SweetAlert.info('info', $translate.instant(data.resultMsg));
                                return;
                            } else {
                                SweetAlert.swal($translate.instant('ComfirmDisable') + '!', $translate.instant("ComfirmDisableSuccess"), "success");
                                loadKeyWordMapList();
                            }
                        });
                    }
                });
            }
            else {
                $log.debug('please select one keywordMap...');
            }
        };

        (function initialize() {
            $log.debug('WordLibraryManageController.ctor()...');
            $scope.stdAccountList = [];
            $scope.search = search;
            $scope.newKeywordMap = newKeywordMap;
            $scope.changesStdAccountSelect = changesStdAccountSelect;
            $scope.save = save;
            $scope.loadSingleKeyWordMap = loadSingleKeyWordMap;
            $scope.modifyIsActive = modifyIsActive;

            loadstdAccountList();
            loadKeyWordMapList();

            $scope.gridOptions = {
                rowHeight: 45,
                selectionRowHeaderWidth: 45,
                enableFullRowSelection: true,
                enableRowSelection: true,
                enableSorting: false,
                enableFiltering: false,
                enableColumnMenus: false,
                enableRowHeaderSelection: false,
                multiSelect: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                columnDefs: [
	              {
	                  field: 'standardCode', name: $translate.instant('StandardAccountCode'), width: '20%', headerCellClass: 'header-cell-class',
	                  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.standardCode}}</span></div>'
	              },
	              {
	                  field: 'name', name: $translate.instant('StandardAccountName'), width: '40%', headerCellClass: 'header-cell-class',
	                  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.name}}</span></div>'
	              },
	              {
	                  field: 'fullName', name: $translate.instant('AccountKeywordText'), width: '40%', headerCellClass: 'header-cell-class',
	                  cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.fullName}}</span></div>'
	              }
                ],
                onRegisterApi: function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.grid.registerRowsProcessor($scope.singleFilter, 200);
                }
            };

            $scope.singleFilter = function (renderableRows) {
                var matcher = new RegExp($scope.searchText);
                renderableRows.forEach(function (row) {
                    var match = false;
                    ['standardCode', 'name', 'fullName'].forEach(function (field) {
                        if (row.entity[field].match(matcher)) {
                            match = true;
                        }
                    });
                    if (!match) {
                        row.visible = false;
                    }
                });
                return renderableRows;
            };

        })();

    }
]);
basicDataModule.directive('wordLibraryManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('wordLibraryManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/basicData/masterData/wordLibraryManage/word-library-manage.html' + '?_=' + Math.random(),
            scope: {},
            controller: 'WordLibraryManageController',
            link: function (scope, element) {

            }
        };
    }
]);