app.controller('joinerManageCtrl', ['$scope', "$state", '$stateParams', '$http', '$timeout', 'uiGridConstants', 'i18nService', 'toaster', 'md5', 'QRCodeOptions', function ($scope, $state, $stateParams, $http, $timeout, uiGridConstants, i18nService, toaster, MD5, QRCodeOptions) {
    i18nService.setCurrentLang("zh-cn");
    var agentId = $stateParams.agentId;
    $scope.gridOptions = {
        data: 'myData',
        showGridFooter: true, //是否显示grid footer
        // rowHeight: 80,
        //-------- 分页属性 ----------------
        paginationPageSizes: [10, 20, 50, 100], //每页显示个数可选项
        paginationCurrentPage: 1, //当前页码
        paginationPageSize: 10, //每页显示个数
        totalItems: 0,// 总数量
        useExternalPagination: true,//是否使用分页按钮
        //过滤
        // enableFiltering: true,
        columnDefs: [],
        //---------------api---------------------
        onRegisterApi: function (gridApi) {
            $scope.gridApi = gridApi;
            gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                if ($scope.setPagingData) {
                    $scope.getPagedDataAsync(newPage, pageSize);
                }
            });
        }
    };
    //查询条件
    var condition = $scope.condition = {
        searchKey: "",
        agentId: agentId
    };
    //枚举常量
    $scope.enum = {};
    //事件
    $scope.event = {
        search: function () {
            $scope.getPagedDataAsync(1, $scope.gridOptions.paginationPageSize);
        }
    };
    function setColumnDefs() {
        $scope.gridOptions.columnDefs = [
            {field: 'name', displayName: '商家名称'},
            {
                field: 'devTotalNum', minWidth: '200',
                displayName: '设备数量',
                cellTemplate: '
'
            },
            {field: 'tel', displayName: '联系方式'},
            {
                field: 'dateTimeAdded',
                displayName: '注册时间',
                cellTemplate: ''
            },
            {
                field: 'lineCoins', minWidth: '150',
                displayName: '今日线下投币',
                cellTemplate: ''
            },
            {
                field: 'payIncome', minWidth: '150',
                displayName: '今日在线收入',
                cellTemplate: ''
            },
            {
                field: 'todayRechargeIncome', minWidth: '80',
                displayName: '今日扫码充值',
            },
            {
                field: 'todayChargeCardIncome', minWidth: '80',
                displayName: '今日卡充值',
            },
            {
                field: 'userCount', minWidth: '80',
                displayName: '用户总数',
            },
            {
                field: 'userCountAddedThisMonth', minWidth: '80',
                displayName: '本月新增用户',
            },
            {
                field: 'balance',
                displayName: '商家余额',
                cellTemplate: ''
            },
            {
                field: 'agentInfo',
                displayName: '代理商',
            },
            {
                field: 'detail',
                displayName: '详细信息',
                cellTemplate: '{{row.entity.detail}}
'
            },
        ];
        $scope.showBalance = function (entity) {
            if (entity.detail) {
                var detail = {}
                try {
                    detail = JSON.parse(entity.detail)
                } catch (e) {
                }
                return '¥' + (detail.balance || "0.00")
            }
            return '未知'
        }
        var operCol = {
            field: 'operation',
            displayName: '操作',
            enableFiltering: false,
            enableSorting: false,
            enableHiding: false,//禁止在列选择器中隐藏
            enableColumnMenu: false,// 是否显示列头部菜单按钮
            minWidth: 168,
            cellTemplate: '' +
                '' +
                '
'
        };
        $scope.gridOptions.columnDefs.push(operCol)
        var fields = $scope.gridOptions.columnDefs;
        for (var index in fields) {
            var item = fields[index];
            if (item && item['minWidth'] == null) {
                item['minWidth'] = 100;
            }
        }
    }
    $scope.setPagingData = function (data, curPage, pageSize) {
        var firstRow = (curPage - 1) * pageSize;
        var pagedData = data.data.dataList;
        $scope.myData = pagedData;
        $scope.gridOptions.totalItems = data.data.total;
    };
    $scope.getPagedDataAsync = function (curPage, pageSize, searchText) {
        if ($scope.gridOptionsLoading) {
            return;
        }
        var params = {
            pageSize: pageSize,
            pageIndex: curPage
        };
        if (condition.searchKey != "") {
            params.searchKey = condition.searchKey
        }
        if (condition.agentId) {
            params.agentId = condition.agentId
        }
        $scope.gridOptionsLoading = true;
        $http.get('/dealer/getJoinerDetailList', {
            params: params
        }).then(function (data) {
            $scope.gridOptionsLoading = false;
            $scope.setPagingData(data.data, curPage, pageSize);
        }).catch(function (data) {
            toaster.pop("error", "提示", "获取数据列表失败");
        });
    };
    function initDataGrid() {
        //首次加载表格
        $scope.getPagedDataAsync($scope.gridOptions.paginationCurrentPage, $scope.gridOptions.paginationPageSize);
    }
    setColumnDefs();
    initDataGrid();
    //展示详情
    $scope.showInfoDetail = function (title, content) {
        $scope.infoDetail = {title: title, content: JSON.parse(content)};
        $("#detailInfoPanel").modal();
    };
    $scope.closeDetailInfoPanel = function () {
        $("#detailInfoPanel").modal("hide");
    };
    //添加
    $scope.add = function () {
        //重置表单状态
        $scope.dealerForm.$setPristine();
        $scope.dealerForm.$setUntouched();
        $scope.dialogName = "代理商开户";
        $scope.dialogData = {};
        $("#dealerPanel").modal();
    };
    //编辑
    $scope.edit = function () {
        //重置表单状态
        $scope.dealerForm.$setPristine();
        $scope.dealerForm.$setUntouched();
        $scope.dialogName = "编辑经销商信息";
        var rows = $scope.gridApi.selection.getSelectedRows();
        if (rows.length == 0) {
            toaster.pop("info", "提示", "请选择数据!");
            return;
        }
        if (rows.length > 1) {
            toaster.pop("info", "提示", "只能选中编辑一条数据");
            return;
        }
        var item = rows[0];
        $scope.dialogData = $.extend({}, item);
        $("#dealerPanel").modal();
    };
    //提交表单保存
    $scope.saveData = function () {
        //表单未校验通过不能提交
        if ($scope.dealerForm.$invalid) {
            return;
        }
        var url = "/manager/editDealer";
        $http({
            method: 'POST',
            url: url,
            data: {
                id: $scope.dialogData.id,
                name: $scope.dialogData.name,
                tel: $scope.dialogData.tel,
                openId: $scope.dialogData.openId
            }
        }).then(function (response) {
            $('#dealerPanel').modal('hide');//弹窗消失
            $scope.getPagedDataAsync($scope.gridOptions.paginationCurrentPage, $scope.gridOptions.paginationPageSize);
        }, function (response) {
            toaster.pop("error", "提示", "保存失败!");
        });
    };
    //查看经销商
    $scope.checkDevice = function (entity) {
        $state.go('app.dev.joinDevManage', {
            dealerId: entity.id,
        }, {
            reload: true
        });
    };
    //编辑密码 默认123456
    $scope.editPassword = function () {
        //重置表单状态
        $scope.passwordForm.$setPristine();
        $scope.passwordForm.$setUntouched();
        var rows = $scope.gridApi.selection.getSelectedRows();
        if (rows.length == 0) {
            toaster.pop("info", "提示", "请选择数据!");
            return;
        }
        if (rows.length > 1) {
            toaster.pop("info", "提示", "只能选中编辑一条数据");
            return;
        }
        var item = rows[0];
        $scope.passwordData = $.extend({password: 123456}, item);
        $("#passwordPanel").modal();
    };
    //修改密码提交
    $scope.savePassword = function () {
        //表单未校验通过不能提交
        if ($scope.passwordForm.$invalid) {
            return;
        }
        var url = "/manager/editDealerPassword";
        var password = MD5.createHash($scope.passwordData.password + '');
        $http({
            method: 'POST',
            url: url,
            data: {
                id: $scope.passwordData.id,
                password: password
            }
        }).then(function (response) {
            $('#passwordPanel').modal('hide');//弹窗消失
            $scope.getPagedDataAsync($scope.gridOptions.paginationCurrentPage, $scope.gridOptions.paginationPageSize);
        }, function (response) {
            toaster.pop("error", "提示", "修改密码失败!");
        });
    };
    //解锁经销商的登录限制,如密码输错后导致的锁
    $scope.unlock = function () {
        var rows = $scope.gridApi.selection.getSelectedRows();
        if (rows.length == 0) {
            toaster.pop("info", "提示", "请选择数据!");
            return;
        }
        if (rows.length > 1) {
            toaster.pop("info", "提示", "只能选中编辑一条数据");
            return;
        }
        var item = rows[0];
        var url = "/manager/unlockDealer";
        $http({
            method: 'POST',
            url: url,
            data: {
                id: item.id
            }
        }).then(function (response) {
            toaster.pop("info", "提示", "解锁成功!")
            $scope.getPagedDataAsync($scope.gridOptions.paginationCurrentPage, $scope.gridOptions.paginationPageSize);
        }, function (response) {
            toaster.pop("error", "提示", "解锁失败!");
        });
    }
    $scope.editDefaultJoiner = function () {
        $http.get('/dealer/getDefaultJoiner', {
            params: {}
        }).then(function (data) {
            $scope.dialogData = data.data.payload
        }).catch(function (data) {
            toaster.pop("error", "提示", "获取数据失败");
        });
        $("#editDefaultJoinerForm").modal();
    };
    $scope.saveDefaultJoiner = function () {
        if ($scope.editDefaultJoinerForm.$invalid) {
            return;
        }
        var url = "/dealer/editDefaultJoiner";
        $http({
            method: 'POST',
            url: url,
            data: $scope.dialogData
        }).then(function (response) {
            $('#editDefaultJoinerForm').modal('hide');//弹窗消失
        }, function (response) {
            toaster.pop("error", "提示", "保存失败!");
        });
    };
}]);