infrastructureModule.controller('landManageController', ['$log', '$scope', '$translate', '$timeout', 'orgService', 'landManageService',
    'SweetAlert', 'loginContext',
    function ($log, $scope, $translate, $timeout, orgService, landManageService, SweetAlert, loginContext) {
        //---------------land---manage-------------------
        $scope.pageStatus = {
            noData: 0,
            hasData: 1
        };
        var showAddLandDialog = function () {
            $scope.editLand = initLand();
            $scope.isEdit = false;
            $('#add-land').modal('show');
        };
        var showEditLandDialog = function () {
            $scope.editLand = angular.copy($scope.Land);
            $scope.isEdit = true;
            $('#add-land').modal('show');
        };
        var toDisplay = function () {
            $scope.Land.computeTaxWayText = $scope.Land.computeTaxWay === 1 ? $translate.instant('SpecialComputeTaxWay') : $translate.instant('GeneralComputeTaxWay');
            $scope.Land.isPrepaidText = $scope.Land.isPrepaid ? $translate.instant('Yes') : $translate.instant('No');
        };
        var addorUpdateLand = function () {
            //  $scope.editLand.updator = loginContext.userId;
            if ($scope.isEdit) {
                $scope.editLand.updater = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                landManageService.updateLand($scope.editLand).success(function (data) {
                    if (data.result) {
                        $scope.Land = $scope.editLand;
                        //toDisplay();
                        //initGrid();
                        //$scope.landLoadstatus = $scope.pageStatus.hasData;
                    } else {
                        SweetAlert.error($translate.instant('AddLandFail'), '');
                    }
                }).error(function (err) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                });
            } else
            {
                $scope.editLand.creator = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                landManageService.addLand($scope.editLand).success(function (data) {
                    if (data.result) {
                        $scope.Land = $scope.editLand;
                        $scope.Land.id = data.resultMsg;//new land id
                        toDisplay();
                        initGrid();
                        $scope.landLoadstatus = $scope.pageStatus.hasData;
                    } else {
                        SweetAlert.error($translate.instant('AddLandFail'), '');
                    }
                }).error(function (err) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                });
            }
          
        };
        var initLand = function () {
            return {
                id: '',
                //because organization selector need it
                organization: {
                    id: null,
                    name: ''
                },
                //in order to map the backend feild
                organizationID: '',
                organizationName: '',
                code: '',
                name: '',
                area: '',
                city: '',
                period: '',
                amount: null,
                computeTaxWay: 0,
                isPrepaid: false,
                creator: null,
                updater: null,
                isActive: 1
            };
        };
        var loadLandData = function () {
            landManageService.loadAll().success(function (data) {
                if (data.result) {
                    if (data.data && data.data.length > 0) {
                        $scope.landLoadstatus = $scope.pageStatus.hasData;
                        $scope.LandList = data.data;
                    } else {
                        $scope.landLoadstatus = $scope.pageStatus.noData
                    }

                } else {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                }
            }).error(function () {
                SweetAlert.error($translate.instant('CommonFail'), '');
            });
        };
        var showLand = function (land) {
            $scope.Land = land;
            toDisplay();
            var datagrid = $('#taxGrid').dxDataGrid("instance");
            datagrid.refresh();
            $('#detail-content').show();
        };
        var disableOrActiveLand = function () {
            $scope.Land.isActive = !$scope.Land.isActive
            var currentLand = initLand();
            currentLand.id = $scope.Land.id;
            currentLand.isActive = $scope.Land.isActive;
            currentLand.updater = $scope.Land.updater;
            landManageService.disableOrEnableLand(currentLand).success(function (res) {
                if (!res.result) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                }
            }).error(function () {
                SweetAlert.error($translate.instant('CommonFail'), '');
            });
        };
        //------------------taxation----basic-----------------------------------
        var getTaxData = function () {
            landManageService.loadAllTax($scope.Land.id)
                    .then(function (response) {
                        $scope.taxBasicData = response.data.data;
                        //return { data: response.data.data, totalCount: response.data.data.length };
                    }, function (response) {
                        return SweetAlert.error($translate.instant('CommonFail'), '');
                    });

        };
        var initGrid = function () {
            // getTaxData();
            // customStore(); CustomStore
            $scope.taxBasicSource = new DevExpress.data.DataSource({
                load: function (loadOptions) {
                    return landManageService.loadAllTax($scope.Land.id)
                    .then(function (response) {
                        return { data: response.data.data, totalCount: response.data.data.length };
                    }, function (response) {
                        return $q.reject($translate.instant('CommonFail'));
                    });
                },
                key: 'id',
                insert: function (values) {
                    values.landManageID = $scope.Land.id;
                    values.creator = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                    values.updater = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                    //validation
                    return landManageService.addTaxBasic(values);
                },
                //onInserted: function (values, key) {
                //    console.log('inserted');
                //    console.log(values);
                //    console.log(key);
                //},
                remove: function (key) {
                    return landManageService.deleteTaxBasic(key);
                },
                update: function (key, values) {
                    return landManageService.updateTaxBasic(values);
                },
                errorHandler: function (error) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                    return false;
                }
            });

            //loadAllTax
            $scope.gridOptions = {
                height:300,
                dataSource: $scope.taxBasicSource,
                paging: { pageSize: 6 },
                pager: {
                    showNavigationButtons: true
                },
                editing: {
                    mode: "form",
                    allowUpdating: true,
                    allowAdding: true,
                    allowDeleting: true,
                    form: {
                        colCount: 2,
                        items: [
                           'accountCode', 'accountName',
                           {
                               colSpan: 2,
                               dataField: "description",
                               editorType: "dxTextArea"
                               //editorOptions: {
                               //    height: 90,
                               //}
                           },
                        "isTaxpaying"
                        ]
                    }

                },
                //scrolling:{
                //    mode: 'standard',
                //    showScrollbar: 'Always'
                //},
                searchPanel: {
                    visible: true,
                    width: 240,
                    placeholder: "Search..."
                },
                onRowUpdating: function (e) {
                    // console.log(e.oldData);                    
                    e.newData = _.extend(e.oldData, e.newData);
                },
                showBorders: true,
                showRowLines: true,
                columns: [
                    //{ dataField: 'id', caption: 'ID', width: '3%' },
                    { dataField: 'accountCode', caption: $translate.instant('SubjectCode'), width: '25%', validationRules: [{ type: "required" }] },
                    { dataField: 'accountName', caption: $translate.instant('SubjectName'), width: '25%', validationRules: [{ type: "required" }] },
                    {
                        dataField: 'description', caption: $translate.instant('Description'), width: '37%',
                        editCellTemplate: function (cellElement, cellInfo) {
                            $('<div/>').dxTextArea({
                                value: cellInfo.value,
                                valueChangeEvent: "change",
                                onValueChanged: function (data) {
                                    cellInfo.setValue(data.value);
                                }
                            }).appendTo(cellElement);
                        }
                        //cellTemplate: function (cellElement, cellInfo) {
                        //    console.log(cellInfo.value);
                        //}
                    },
                    { dataField: 'isTaxpaying', dataType: 'boolean', caption: $translate.instant('IsCompute'), width: '13%' },
                ],
                onCellPrepared: function (e) {

                    if (e.rowType === "data" && e.column.command === "edit") {
                        var isEditing = e.row.isEditing,
                            $links = e.cellElement.find(".dx-link");

                        $links.text("");

                        if (isEditing) {
                            //$links.filter(".dx-link-save").addClass("dx-icon-save");
                            //$links.filter(".dx-link-cancel").addClass("dx-icon-revert");
                            $links.filter(".dx-link-save").addClass("fa").addClass("fa-floppy-o").addClass('action-icon');
                            $links.filter(".dx-link-cancel").addClass("fa").addClass("fa-undo").addClass('action-icon');
                        } else {
                            //$links.filter(".dx-link-edit").addClass("dx-icon-edit");
                            //$links.filter(".dx-link-delete").addClass("dx-icon-trash");
                            $links.filter(".dx-link-edit").addClass("fa").addClass("fa-pencil-square-o").addClass('action-icon');
                            $links.filter(".dx-link-delete").addClass("fa").addClass("fa-trash-o").addClass('action-icon');
                        }
                    }
                }
            };
        };

        var filterTax = function (value) {
            var dataGrid = $('#taxGrid').dxDataGrid("instance");
            if (value === -1)
                dataGrid.clearFilter();
            else
                dataGrid.filter(["isTaxpaying", "=", value]);
        };
        var initTaxation = function () {
            return {
                id: '',
                landManageID: '',
                accountCode: null,
                accountName: null,
                description: null,
                isTaxpaying: false,
                creator: null,
                updater: null
            }
        };

        //----------------------taxation----basic-end-------------------------------
        (function initialize() {
            $scope.addorUpdateLand = addorUpdateLand;
            $scope.disableOrActiveLand = disableOrActiveLand;
            $scope.showEditLandDialog = showEditLandDialog;
            $scope.showAddLandDialog = showAddLandDialog;
            loadLandData();
            //current land
            $scope.Land = {};
            $scope.editLand = {};
            $scope.initLand = initLand;
            $scope.ways = [
                { id: 0, name: $translate.instant('GeneralComputeTaxWay') },
                { id: 1, name: $translate.instant('SpecialComputeTaxWay') },
            ];
            $scope.wayOptions = {
                dataSource: $scope.ways,
                valueExpr: 'id',
                displayExpr: 'name',
                bindingOptions: {
                    value: "editLand.computeTaxWay"
                }
            };
            //show land detail
            $scope.showLand = showLand;
            initGrid();
            //taxation basic
            $scope.filterTax = filterTax;
            $scope.editTaxationBasic = {};
        })();
    }]);