systemConfigurationModule.controller('ruleEngineeConfigController', ['$scope', '$translate', '$log', 'ruleEngineService', 'KeyValueConfigService', 'orgService', 'templateGroupService', 'ruleEngineOp','ruleEngineComparer',
    function ($scope, $translate, $log, ruleEngineService, KeyValueConfigService, orgService, templateGroupService, ruleEngineOp, ruleEngineComparer) {
        var taxRuleSetingGroupsBk, taxPayerReportMappingExceptionsBk, defaultTaxPayerReportMappingBk,taxRuleSettingOrginal,taxReportRuleOrginal
        function init() {
            $scope.state = 0;
            $scope.taxPayerReportState = 0;
            $scope.taxPayerReportMappingExceptions = [];
            $scope.taxRuleSettingsExceptionGroups = {}
            $scope.reportTypes = [];
            $scope.orgs = [];
            $scope.operation = {};
            $scope.currentSelectedOrgs = {value:[]};
            //load data.
            ruleEngineService.getTaxPayerReportMapping().success(function (data) {
                taxReportRuleOrginal = JSON.parse(JSON.stringify(data));
                var taxPayerReportMappings = data;

                $scope.defaultTaxPayerReportMapping = (taxPayerReportMappings.filter(function (item) {
                    return item.isDefault === 1;
                }))[0];

                if($scope.defaultTaxPayerReportMapping){
                    $scope.defaultTaxPayerReportMapping.templateGroupId = $scope.defaultTaxPayerReportMapping.templateGroupId.toString();
                }

                $scope.taxPayerReportMappingExceptions = taxPayerReportMappings.filter(function (item) {
                    return item.isDefault !== 1;
                });

                $scope.taxPayerReportMappingExceptions.forEach(function (value) {
                    value.templateGroupId = value.templateGroupId.toString();
                });

                taxReportRuleOrginal.forEach(function (value) {
                    value.templateGroupId = value.templateGroupId.toString();
                });
            });


            //to refactor when i have time 
            ruleEngineService.getTaxRuleSetting().success(function (data) {
                taxRuleSettingOrginal = JSON.parse(JSON.stringify(data));
                var taxRuleSettingsGroups = _.groupBy(data, 'groupName');

                var taxRuleSetingsFormatted = [];
                for (var groupName in taxRuleSettingsGroups) {
                    if (taxRuleSettingsGroups.hasOwnProperty(groupName)) {
                        var taxRuleSettings = taxRuleSettingsGroups[groupName];
                        var taxRuleSettingGroup = [];
                        taxRuleSettingGroup.state = 0;
                        var subTaxRuleSettingGroups = _.groupBy(taxRuleSettings, 'name');
                        for (var subGroupName in subTaxRuleSettingGroups) {
                            if (subTaxRuleSettingGroups.hasOwnProperty(subGroupName)) {
                                var subTaxRuleSettings = subTaxRuleSettingGroups[subGroupName];
                                var taxRuleSettingItem = {};
                                taxRuleSettingItem.groupName = groupName;
                                taxRuleSettingItem.groupNameDesc = setRuleDisplayVal(groupName);
                                taxRuleSettingItem.name = subGroupName;
                                taxRuleSettingItem.nameDesc = setRuleDisplayVal(subGroupName);

                                taxRuleSettingItem.defaultTaxRuleSetting = (subTaxRuleSettings.filter(function (item) {
                                    return item.isDefault === 1;
                                }))[0];

                                taxRuleSettingItem.taxRuleSettingsExceptions = subTaxRuleSettings.filter(function (item) {
                                    return item.isDefault !== 1;
                                });
                                //authority
                                mappingAuthority(subGroupName);
                                taxRuleSettingItem.TempView = $scope.TempView;
                                taxRuleSettingItem.TempDefaultAction = $scope.TempDefaultAction;
                                taxRuleSettingItem.TempAction = $scope.TempAction;
                                taxRuleSettingGroup.push(taxRuleSettingItem);
                            }
                            taxRuleSettingGroup.original = JSON.parse(JSON.stringify(taxRuleSettingGroup));
                        }
                        taxRuleSetingsFormatted.push(taxRuleSettingGroup);
                    }
                }
                $scope.taxRuleSetingGroups = taxRuleSetingsFormatted;
                taxRuleSetingGroupsBk = angular.copy($scope.taxRuleSetingGroups);
            });

            templateGroupService.getall().success(function (data) {
                $scope.reportTypes = data;
            });

            $scope.taxPayerTypes = [{
                id: 0,
                name: '一般纳税人',
            }, {
                id: 1,
                name: '小规模税人',
            }];

            orgService.getOrgListLevel().success(function (data) {
                $scope.orgs = data;
            });
        }

        $scope.defaultTaxPayerTypeOption = {
            bindingOptions: {
                value: 'defaultTaxPayerReportMapping.taxPayerType',
                dataSource: 'taxPayerTypes',
                disabled: '!defaultRatePayerAction||state === 0',
                onItemClick: 'defaultTaxPayerReportMappingChanged',
            },
            valueExpr: 'id',
            displayExpr: 'name',
        };

        $scope.defaultReportTypeOption = {
            bindingOptions: {
                value: 'defaultTaxPayerReportMapping.templateGroupId',
                dataSource: {
                    deep: true,
                    dataPath: 'reportTypes'
                },
                disabled: '!defaultRatePayerAction||state === 0',
                onItemClick: 'defaultTaxPayerReportMappingChanged',
            },
            width: '300px',
            valueExpr: 'id',
            displayExpr: 'name',
        }

        $scope.defaultTaxPayerReportMappingChanged = function () {
            if ($scope.defaultTaxPayerReportMapping.editKey == null) {
                $scope.defaultTaxPayerReportMapping.editKey = +new Date();
            }
            ruleEngineOp.updateTaxPayerReportRuleOperation($scope.defaultTaxPayerReportMapping);
        };

        $scope.showOperateLogPop = function () {
            $scope.isShowLog = true;
        };

        $scope.editTaxPayerReportMapping = function () {
            $scope.taxPayerReportState = 1;
        };

        $scope.saveTaxPayerReportMapping = function () {
            var taxPayerReportMapping = [];
            $scope.taxPayerReportState = 1;
            taxPayerReportMapping.push($scope.defaultTaxPayerReportMapping);
            taxPayerReportMapping = taxPayerReportMapping.concat($scope.taxPayerReportMappingExceptions);
            var batchUpdateTaxRuleDto = {
                taxRuleSettingOperations: [],
                taxPayerReportRuleOperations: ruleEngineComparer.compareTaxPayerReportRule(taxReportRuleOrginal, taxPayerReportMapping)
            };
            console.log(batchUpdateTaxRuleDto);

            ruleEngineService.saveTaxRuleSettings(batchUpdateTaxRuleDto).success(function () {
                var temp = JSON.parse(JSON.stringify(taxPayerReportMapping))
                taxPayerReportMapping = JSON.parse(JSON.stringify(taxReportRuleOrginal));
                taxReportRuleOrginal = temp;
                $scope.taxPayerReportState = 0;
            });
        };

        $scope.cancelTaxPayerReportMapping = function () {

            taxReportRuleOrginalTemp = JSON.parse(JSON.stringify(taxReportRuleOrginal));
            $scope.defaultTaxPayerReportMapping = (taxReportRuleOrginalTemp.filter(function (item) {
                return item.isDefault === 1;
            }))[0];

            $scope.taxPayerReportMappingExceptions = taxReportRuleOrginalTemp.filter(function (item) {
                return item.isDefault !== 1;
            });
            $scope.taxPayerReportState = 0;
        };


        $scope.editTaxRuleSeting = function (taxRuleSetingGroup) {
            taxRuleSetingGroup.state = 1;
        };

        $scope.saveTaxRuleSeting = function (taxRuleSetingGroup) {
            taxRuleSetingGroup.state = 1;
            var taxRuleSettings = [];
            var taxRuleSettingsOrginal = [];
            taxRuleSetingGroup.forEach(function (taxRuleSetting) {
                taxRuleSettings.push(taxRuleSetting.defaultTaxRuleSetting);
                taxRuleSettings = taxRuleSettings.concat(taxRuleSetting.taxRuleSettingsExceptions);
            });

            taxRuleSetingGroup.original.forEach(function (taxRuleSetting) {
                taxRuleSettingsOrginal.push(taxRuleSetting.defaultTaxRuleSetting);
                taxRuleSettingsOrginal = taxRuleSettingsOrginal.concat(taxRuleSetting.taxRuleSettingsExceptions);
            });

            var batchUpdateTaxRuleDto = {
                taxRuleSettingOperations: ruleEngineComparer.compareTaxRuleSetting(taxRuleSettingsOrginal, taxRuleSettings),
                taxPayerReportRuleOperations: []
            };
            console.log(batchUpdateTaxRuleDto);
            ruleEngineService.saveTaxRuleSettings(batchUpdateTaxRuleDto).success(function () {
                taxRuleSetingGroup.original = JSON.parse(JSON.stringify(taxRuleSetingGroup));
                taxRuleSetingGroup.state = 0;
            });
        };

        $scope.cancelTaxRuleSeting = function (taxRuleSetingGroup) {
            var original = JSON.parse(JSON.stringify(taxRuleSetingGroup.original));
            //taxRuleSetingGroup = JSON.parse(JSON.stringify(taxRuleSetingGroup.original));
            taxRuleSetingGroup.forEach(function (item,index) {
                item.groupName = taxRuleSetingGroup.original[index].groupName;
                item.name = taxRuleSetingGroup.original[index].name;
                item.TempAction = taxRuleSetingGroup.original[index].TempAction;
                item.TempDefaultAction = taxRuleSetingGroup.original[index].TempDefaultAction;
                item.TempView = taxRuleSetingGroup.original[index].TempView;
                item.defaultTaxRuleSetting = taxRuleSetingGroup.original[index].defaultTaxRuleSetting;
                item.taxRuleSettingsExceptions = taxRuleSetingGroup.original[index].taxRuleSettingsExceptions;
            });
            
            taxRuleSetingGroup.original = original;
            taxRuleSetingGroup.state = 0;
        };

        init();

        //----------custom table---start---------------------
        //get all key code
        var getAllKeyCode = function () {
            KeyValueConfigService.getAll().success(function (data) {
                $scope.mentionLists = _.map(data, function (config) { return { code: '@' + config.keyCode, name: config.name, description:config.description } });
            });
        };

        var checkPermissionList = function () {
            var list = [];
            var userManageTemp = constant.adminPermission.systemConfiguration.ruleEnginee;
            list = _.values(userManageTemp);
            $scope.viewRatePayer = false;
            $scope.defaultRatePayerAction = false;
            $scope.specialRatePayerAction = false;
            $scope.LocalTax = false;
            //地方税-城市建设
            $scope.viewCityBuilding = false;
            $scope.defaultCityBuildingAction = false;
            $scope.specialCityBuildingAction = false;
            //地方教育
            $scope.viewLocalEducation = false;
            $scope.defaultLocalEducationAction = false;
            $scope.specialLocalEducationAction = false;
            //教育费附加税 

            $scope.viewEducationAttach = false;
            $scope.defaultEducationAttachAction = false;
            $scope.specialEducationAttachAction = false;
            //印花税
            $scope.viewStampTax = false;
            $scope.defaultStampTaxAction = false;
            $scope.specialStampTaxAction = false;
            //水利基金
            $scope.viewWaterFund = false;
            $scope.defaultWaterFundAction = false;
            $scope.specialWaterFundAction = false;
            $scope.$root.checkUserPermissionList(list).success(function (data) {
                $scope.viewRatePayer = data[userManageTemp.viewRatePayer];
                $scope.defaultRatePayerAction = data[userManageTemp.defaultRatePayerAction];
                $scope.specialRatePayerAction = data[userManageTemp.specialRatePayerAction];
                $scope.LocalTax = data[userManageTemp.LocalTax];
                //地方税-城市建设
                $scope.viewCityBuilding = data[userManageTemp.viewCityBuilding];
                $scope.defaultCityBuildingAction = data[userManageTemp.defaultCityBuildingAction];
                $scope.specialCityBuildingAction = data[userManageTemp.specialCityBuildingAction];
                //地方教育
                $scope.viewLocalEducation = data[userManageTemp.viewLocalEducation];
                $scope.defaultLocalEducationAction = data[userManageTemp.defaultLocalEducationAction];
                $scope.specialLocalEducationAction = data[userManageTemp.specialLocalEducationAction];
                //教育费附加税 
                $scope.viewEducationAttach = data[userManageTemp.viewEducationAttach];
                $scope.defaultEducationAttachAction = data[userManageTemp.defaultEducationAttachAction];
                $scope.specialEducationAttachAction = data[userManageTemp.specialEducationExtactAction];
                //印花税
                $scope.viewStampTax = data[userManageTemp.viewStampTax];
                $scope.defaultStampTaxAction = data[userManageTemp.defaultStampTaxAction];
                $scope.specialStampTaxAction = data[userManageTemp.specialStampTaxAction];
                //水利基金
                $scope.viewWaterFund = data[userManageTemp.viewWaterFund];
                $scope.defaultWaterFundAction = data[userManageTemp.defaultWaterFundAction];
                $scope.specialWaterFundAction = data[userManageTemp.specialWaterFundAction];
            });
        };

        // TODO: 为了保证正常运行,暂时通过hard code将判断标准改为支持中英双语
        var taxs = {
            CityBuildingTax: '城市维护建设税',
            LocalEducationAttach: '地方教育费附加',
            WaterFund: '水利基金',
            StampTax: '印花税',
            EducationAttach: '教育费附加'
        };
        var mappingAuthority = function (name) {
            //"CityBuildingTax":"城市维护建设税",
            //"LocalEducationAttach":"地方教育费附加",
            //"WaterFund":"水利基金",
            //"StampTax":"印花税",
            //"EducationAttach":"教育费附加"
            switch (name) {
                case 'CityBuildingTax':
                case taxs.CityBuildingTax:
                    $scope.TempView = $scope.viewCityBuilding;
                    $scope.TempDefaultAction = $scope.defaultCityBuildingAction;
                    $scope.TempAction = $scope.specialCityBuildingAction;
                    break;
                case 'LocalEducationAttach':
                case taxs.LocalEducationAttach:
                    $scope.TempView = $scope.viewLocalEducation;
                    $scope.TempDefaultAction = $scope.defaultLocalEducationAction;
                    $scope.TempAction = $scope.specialLocalEducationAction;
                    break;
                case 'WaterFund':
                case taxs.WaterFund:
                    $scope.TempView = $scope.viewWaterFund;
                    $scope.TempDefaultAction = $scope.defaultWaterFundAction;
                    $scope.TempAction = $scope.specialWaterFundAction;
                    break;
                case 'StampTax':
                case taxs.StampTax:
                    $scope.TempView = $scope.viewStampTax;
                    $scope.TempDefaultAction = $scope.defaultStampTaxAction;
                    $scope.TempAction = $scope.specialStampTaxAction;
                    break;
                case 'EducationAttach':
                case taxs.EducationAttach:
                    $scope.TempView = $scope.viewEducationExtact;
                    $scope.TempDefaultAction = $scope.defaultEducationAttachAction;
                    $scope.TempAction = $scope.specialEducationAttachAction;
                    break;
                default:
                    $scope.TempView = false;
                    $scope.TempDefaultAction = false;
                    $scope.TempAction = false;
            }

        };

        var setRuleDisplayVal = function (groupName) {
            switch (groupName) {
                case taxs.CityBuildingTax: return $translate.instant('CityBuildingTax');
                case taxs.LocalEducationAttach: return $translate.instant('LocalEducationAttach');
                case taxs.WaterFund: return $translate.instant('WaterFund');
                case taxs.StampTax: return $translate.instant('StampTax');
                case taxs.EducationAttach: return $translate.instant('EducationAttach');
                default: return '';

            }
        };
       
        //-----------custom table---end--------------------------
        (function initalization() {
            $scope.TempView = false;
            $scope.TempDefaultAction = false;
            $scope.TempAction = false;
            checkPermissionList();
            getAllKeyCode();
        })();
    }]);