invoiceModule.controller('outputReconciliationEntitiesController', ['$scope', '$log', 'uiGridConstants', 'SweetAlert', '$translate', 'stdAccountService', '$interval', 'orgService', '$timeout', '$q', 'commonWebService', 'loginContext', '$uibModal', 'outputReconciliationConfiguration',
    function($scope, $log, uiGridConstants, SweetAlert, $translate, stdAccountService, $interval, orgService, $timeout, $q, commonWebService, loginContext, $uibModal, outputReconciliationConfiguration) {
        'use strict';


        var entityModule = {
            OrganizationList: [],

            allOrgs: $translate.instant('AllOrganization'),
            name: 'name',
            id: 'id',
            // uiOrgID: 'ApplyingEntitesControls',
            uiOrgID: window.PWC.newGuid(),
            orgText: $translate.instant('AllOrganization'),

            // 选中机构ID列表
            selectOrgList: [],
            selectOrgMap: {},


            // 有效的机构列表,包括所有机构,id,name,parentID,expanded
            orgList: [],
            main: function() {

                $scope.uiOrgID = entityModule.uiOrgID;
                $scope.openEntityModal = function() {

                    if ($scope.editModel.type === 'query' || $scope.editModel.type === 'edit' || $scope.editModel.type === 'copy') {
                        entityModule.openEditModal($scope.editModel.applyEntities);
                    } else {
                        entityModule.openModal();
                    }
                };

                $scope.add = function() {
                    entityModule.openEditModal($scope.selectList);
                };
            },

            loadData: function() {
                orgService.getOrganizationFilterList().success(function(data) {

                    entityModule.OrganizationList = data;
                    entityModule.orgList = entityModule.getOrgDropDownList();

                    mainModule.parseViewList();
                });
            },

            openModal: function() {

                var editModel = {

                };

                $scope.editEntityModel = editModel;

                mainModule.initModalControls();

                var parnet = $('#outputReconciliationConfigurationEditModalBody');

                var modalInstance = $uibModal.open({
                    animation: true,
                    backdrop: false,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'ApplyingEntitesDetailsModal.html',
                    windowClass: 'edit-invoice-modal-wrapper',
                    scope: $scope,
                    size: 'entity-size',
                    appendTo: parnet,
                    resolve: {
                        editModel: $scope.editModel
                    }
                });

                modalInstance.result.then(function(data) {
                    // 确定关闭
                }, function() {
                    // 取消关闭
                });

                $scope.saveApplyingEntitesDetailsModal = function() {

                    $scope.editModel.selectOrgList = entityModule.selectOrgList;
                    modalInstance.close({});
                };

                $scope.cancelApplyingEntitesDetailsModal = function() {
                    modalInstance.dismiss('cancel');
                };

                $timeout(function() {
                    entityModule.drawGridList(entityModule.orgList);
                }, 100);
            },

            openEditModal: function(selectOrgList) {

                var orgIdList = _.pluck(selectOrgList, 'organizationID');

                var data = angular.copy(entityModule.orgList);

                var index = 0;

                data.forEach(function(r) {

                    if (orgIdList.indexOf(r.id) > -1) {
                        r.isSelected = true;
                    } else {
                        r.isSelected = false;
                    }

                    r.viewName = r.code + ' ' + r.name;
                    r.index = index;
                    index ++;

                });

                var editModel = {

                };

                $scope.editEntityModel = editModel;

                // mainModule.initModalControls();

                var parnet = $('#outputReconciliationConfigurationEditModalBody');

                var modalInstance = $uibModal.open({
                    animation: true,
                    backdrop: false,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'ApplyingEntitesDetailsModal.html',
                    windowClass: 'edit-invoice-modal-wrapper',
                    scope: $scope,
                    size: 'entity-size',
                    appendTo: parnet,
                    resolve: {
                        editModel: $scope.editModel
                    }
                });

                modalInstance.result.then(function(data) {
                    // 确定关闭
                }, function() {
                    // 取消关闭
                });

                $scope.saveApplyingEntitesDetailsModal = function() {

                    // $scope.editModel.selectOrgList = entityModule.selectOrgList;

                    var selectOrgTempList = [];

                    if (!entityModule.selectOrgList || entityModule.selectOrgList.length === 0) {
                        entityModule.selectOrgList = [];

                        selectOrgTempList = [];
                    } else {
                        selectOrgTempList = entityModule.selectOrgList;
                    }

                    var result = [];

                    selectOrgTempList.forEach(function(r) {

                        var item = {};

                        item.organizationID = r.id;
                        item.organizationCode = r.code;

                        result.push(item);
                    });

                    $scope.selectList = result;

                    mainModule.parseViewList();

                    modalInstance.close({});
                };

                $scope.cancelApplyingEntitesDetailsModal = function() {
                    modalInstance.dismiss('cancel');
                };

                $timeout(function() {
                    console.log('open');
                    entityModule.drawGridList(data);
                    console.log('open end');
                }, 100);
            },

            filterDropDownOrgList: function(orgList, selectIDList, idCol) {
                if (!orgList || orgList.length === 0) {
                    return orgList;
                }

                // 什么都没有选
                if (!selectIDList) {
                    return orgList;
                }

                // 按照条件进行过滤
                orgList = _.filter(orgList, function(row) {

                    return selectIDList.indexOf(row[idCol]) > -1;
                });

                return orgList;
            },


            filterOrgs: function() {
                if (entityModule.OrganizationList && entityModule.OrganizationList.length > 0) {

                    // 只要启用的和有权限的机构
                    var filter = _.filter(entityModule.OrganizationList, function(row) {
                        return row.isActive;
                    });


                    return filter;

                } else {
                    return [];
                }
            },

            // 获取机构drop down的list
            getOrgDropDownList: function() {
                var showList = entityModule.filterOrgs();
                showList = angular.copy(showList);
                for (var i = 0; i < showList.length; i++) {
                    var item = showList[i];
                    item.selected = false;
                    item.expanded = true;


                    if (item.parentID === null) {
                        continue;
                    }

                    var parentNode = _.find(showList, function(num) {
                        return num.id === item.parentID
                    });

                    if (parentNode) {
                        continue;
                    }

                    item.parentID = getParentID(item, entityModule.OrganizationList, showList);
                }

                var idList = _.pluck(showList, 'id');

                $scope.selectedOrganizationList = idList;

                return showList;
            },

            drawGridList: function(data) {
                if (!$scope.selectList) {
                    $scope.selectList = [];
                }

                var selectKeyIDs = _.pluck($scope.selectList, 'organizationCode');
                $("#" + entityModule.uiOrgID).dxDataGrid({
                    dataSource: data,
                    keyExpr: 'code',
                    height: 400,
                    selectAllText: $translate.instant('SelectAll'),
                    // rowAlternationEnabled: true,
                    selectedRowKeys: selectKeyIDs,
                    paging: {
                        enabled: false
                    },
                    columns: [
                        { dataField: 'viewName', caption: $translate.instant('SelectAll') }
                    ],
                    showBorders: true,
                    selection: {
                        mode: 'multiple',
                        showCheckBoxesMode: "always"
                    },
                    onSelectionChanged: function(args) {
                        entityModule.selectOrgList = args.selectedRowsData;
                    }
                });

                // $timeout(function(){
                //     $("#" + entityModule.uiOrgID).dxDataGrid('instance').selectRows(selectKeyIDs, false);
                // },10);


                // $("#" + entityModule.uiOrgID).dxDataGrid({
                //     "dataSource": [{
                //             "ID": 1,
                //             "CompanyName": "Super Mart of the West",
                //             "City": "Bentonville",
                //             "State": "Arkansas"
                //         },
                //         {
                //             "ID": 2,
                //             "CompanyName": "Electronics Depot",
                //             "City": "Atlanta",
                //             "State": "Georgia"
                //         },
                //         {
                //             "ID": 3,
                //             "CompanyName": "K&S Music",
                //             "City": "Minneapolis",
                //             "State": "Minnesota"
                //         },
                //         {
                //             "ID": 4,
                //             "CompanyName": "Tom's Club",
                //             "City": "Issaquah",
                //             "State": "Washington"
                //         },
                //         {
                //             "ID": 5,
                //             "CompanyName": "E-Mart",
                //             "City": "Hoffman Estates",
                //             "State": "Illinois"
                //         }
                //     ],
                //     "keyExpr": "ID",
                //     "selectedRowKeys": [
                //         1,
                //         2,
                //         3
                //     ],
                //     "selection": {
                //         "mode": "multiple",
                //         "showCheckBoxesMode": "always"
                //     }
                // });



            
            },
            drawOrgTreeList: function(data) {

                // var getShowData = function(){

                //     var data = angular.copy(entityModule.orgList);
                //     if (data && $scope.selectList && $scope.selectList.length > 0){

                //         $scope.selectList.forEach(function(s){

                //             var find = _.find(data, function(d){
                //                 return d.id === s.organizationID;
                //             });

                //             find.selected = true;
                //         });
                //     }

                //     return data;
                // };


                // var showData = getShowData();




                $("#" + entityModule.uiOrgID).dxTreeView({
                    dataSource: data,
                    dataStructure: "plain",
                    keyExpr: "id",
                    parentIdExpr: "parentIDStr",
                    selectionMode: "multiple",
                    displayExpr: "name",
                    selectByClick: true,
                    noDataText: '',
                    // height: 300,
                    itemTemplate: function(itemData, itemIndex, itemElement) {

                        var str = itemData.code + ' ' + itemData.name;
                        itemElement.append("<span title='" + str + "'>" + str + "</span>");
                    },
                    onContentReady: function(args) {},
                    selectNodesRecursive: false,
                    expandAllEnabled: true,
                    showCheckBoxesMode: "selectAll",
                    selectAllText: entityModule.allOrgs,
                    onItemSelectionChanged: function(args) {

                    },
                    onSelectionChanged: function(args) {
                        entityModule.selectOrgList = args.component.getSelectedNodesKeys();
                    }
                });

            },

            // 机构drop down list
            drawOrgDropDownList: function(data) {

                entityModule.selectOrgList = _.pluck(data, 'id');

                $scope.onChanged({ model: entityModule.selectOrgList });

                var syncTreeViewSelection = function(treeView, value, isReady) {

                    if (isReady) {
                        $scope.selectedOrganizationList = entityModule.selectOrgList;
                        $scope.onChanged({ model: entityModule.selectOrgList });
                    } else {
                        $scope.selectedOrganizationList = value;
                        $scope.onChanged({ model: value });
                    }
                };


                entityModule.orgDropDownInstantce = $("#" + entityModule.uiOrgID).dxDropDownBox({
                    value: '',
                    showClearButton: false,
                    contentTemplate: function(e) {
                        var value = e.component.option("value"),
                            $treeView = $("<div>").dxTreeView({
                                dataSource: data,
                                dataStructure: "plain",
                                keyExpr: "id",
                                parentIdExpr: "parentIDStr",
                                selectionMode: "multiple",
                                displayExpr: "name",
                                selectByClick: true,
                                noDataText: '',
                                height: 300,
                                itemTemplate: function(itemData, itemIndex, itemElement) {

                                    var str = itemData.code + ' ' + itemData.name;
                                    itemElement.append("<span title='" + str + "'>" + str + "</span>");
                                },
                                onContentReady: function(args) {},
                                selectNodesRecursive: false,
                                expandAllEnabled: true,
                                showCheckBoxesMode: "selectAll",
                                selectAllText: entityModule.allOrgs,
                                onItemSelectionChanged: function(args) {

                                },
                                onSelectionChanged: function(args) {
                                    var value = args.component.getSelectedNodesKeys();
                                    var text = '';
                                    if (value && value.length === data.length) {
                                        text = entityModule.allOrgs;
                                    } else {
                                        text = '选中' + value.length + '个机构';
                                    }

                                    entityModule.selectOrgList = value;
                                    e.component.option("value", text);
                                    entityModule.orgText = text;
                                    syncTreeViewSelection(entityModule.orgTreeView, value, false);
                                }
                            });

                        entityModule.orgTreeView = $treeView.dxTreeView("instance");
                        entityModule.orgText = e.component.option("text");


                        return $treeView;
                    }
                });
            }

        };



        var mainModule = {

            main: function() {

                if (!$scope.selectList) {
                    $scope.selectList = [];
                }

                entityModule.loadData();
                entityModule.main();

                // $scope.add = mainModule.add;

                $scope.delete = mainModule.delete;
            },

            parseViewList: function() {
                $scope.selectList.forEach(function(r) {
                    var org = _.find(entityModule.orgList, function(o) {

                        return o.id === r.organizationID;
                    });

                    if (org) {
                        r.value = org.code + ' ' + org.name;
                    }

                    r.suffix = ';';
                });


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

                    var length = $scope.selectList.length - 1;
                    $scope.selectList[length].suffix = '';
                }
            },
            add: function() {
                var length = $scope.selectList.length;

                var prefixStr = '';
                if (length !== 0) {
                    prefixStr = ';';
                }

                var obj = {
                    id: window.PWC.newGuid(),
                    value: '',
                    suffix: prefixStr,
                };

                $scope.selectList.push(obj);
            },

            delete: function(obj) {
                if ($scope.selectList && $scope.selectList.length > 0) {

                    var findIndex = _.indexOf($scope.selectList, obj);

                    if (findIndex > -1) {
                        $scope.selectList.splice(findIndex, 1);
                    }

                    if (findIndex === 0 && $scope.selectList.length >= 0) {
                        $scope.selectList[0].prefix = '';
                    }
                }
            },

        };

        (function initializa() {

            mainModule.main();

            $log.debug('outputReconciliationKeywordsController.ctor()...');


        })();
    }
]);