starter.controller('PayCtrl', function ($rootScope, $scope, $state, $ionicPopover, global, Member, Pay, Tool) {
    beforeEnter = $scope.$on("$ionicView.beforeEnter", function (event, data) {
        global.fetch_user().then(function () {
            if ($scope.recordlist == undefined) getpaydata();
            set_step_data();
        });
    });

    Member.selectedemplst = [];

    $scope.goBack = function () {
        global.goBack();
    };

    $scope.toman = function () {
        $state.go('payman');
    };

    $scope.torecord = function (record) {
        if (record) {
            Pay.recordItem = _.clone(record);
            $state.go('pay-record', {
                id: record.id
            });
        } else {
            $scope.popover.hide();
            $state.go('pay-record', {
                id: -1
            });
        }
    };

    $scope.addpaybill = function () {
        $scope.popover.hide();
        $state.go('pay-bill', {
            type: 0,
            id: -1
        })
    };

    $scope.toauditstep = function () {
        $scope.popover.hide();
        Member.customerop = null;
        if ($scope.is_have_step) {
            $state.go('auditstep', {
                "id": 0
            });
        } else {
            Member.selectedemplst.push({
                "user_id": global.user.usrid,
                "username": global.user.usrname
            });
            Member.dialogresult = 1;
            Member.customerop = 1;
            $state.go('auditstep', {
                "id": -1
            });
        }
    };

    $ionicPopover.fromTemplateUrl('templates/paymenu.html', {
        scope: $scope
    }).then(function (popover) {
        $scope.popover = popover;
    });

    $scope.doRefresh = function () {
        global.refresh = true;
        getpaydata();
    };

    $scope.loadMore = function () {
        if ($scope.recordlist != undefined && $scope.recordlist.next != null) {
            Tool.get($scope.recordlist.next).then(function (data) {
                _.each(data.results, function (item) {
                    $scope.recordlist.results.push(item);
                });
                $scope.recordlist.next = data.next;
                $scope.recordlist.previous = data.previous;
            }).finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.loading = false;
            });
        } else {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }
    };

    $scope.moreCanBeLoaded = function () {
        return $scope.recordlist != undefined && $scope.recordlist.next != null;
    };

    function getpaydata() {
        if (global.user.token != "") {
            if ($scope.recordlist == undefined) {
                $scope.loading = true;
            }
            Pay.record.get(function (res) {
                Pay.recordList = _.clone(res.results);
                $scope.recordlist = res;
                $scope.roleid = global.user.roleid;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }

    enter = $scope.$on("$ionicView.enter", function (event, data) {
        if (data.fromCache && $rootScope.commons.refresh) {
            $rootScope.commons.refresh = false;
            getpaydata();
        }
    });

    $scope.is_have_step = false;

    function set_step_data() {
        Pay.auditstep.query({"userid": global.user.usrid}, function (data) {
            Pay.personstepdata = data;
            $scope.is_have_step = data.length > 0;
        }, function (err) {
            alert(JSON.stringify(err));
        })
    }

    $scope.$on("$destroy", function () {
        enter = null;
        Pay.auditstepdata = [];
        $scope.popover.remove();
    });
})

.controller('TypeSetCtrl', function ($rootScope, $scope, $state, $ionicHistory, global, showPopup, Pay, Tool) {
    $scope.ordering = false;
    global.fetch_user().then(function () {
        gettypedata();
    });

    $scope.toaddtype = function () {
        $state.go("addtype", {
            "id": -1
        });
    };

    $scope.toedittype = function (item) {
        Pay.typeItem = _.clone(item);
        $state.go("addtype", {
            "id": item.id
        });
    };

    $scope.reorderItem = function (item, fromIndex, toIndex) {
        $scope.types.splice(fromIndex, 1);
        $scope.types.splice(toIndex, 0, item);
    };

    $scope.ok = function () {
        $scope.ordering = !$scope.ordering;
        if (!$scope.ordering) {
            var data = [];
            for (var i = 0; i < $scope.types.length; i++) {
                data.push({
                    'id': $scope.types[i].id,
                    'ordering': i
                });
            }
            Pay.type.patch(data, function (data) {
                $scope.doRefresh();
            })
        }
    };

    $scope.doRefresh = function () {
        global.refresh = true;
        gettypedata();
    }

    function gettypedata() {
        if (global.user.token != "") {
            if ($scope.types == undefined) {
                $scope.loading = true;
            }
            Pay.type.get(function (res) {
                $scope.types = res;
                Pay.typeList = res;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }

    enter = $scope.$on("$ionicView.enter", function (event, data) {
        if (data.fromCache && $rootScope.commons.refresh) {
            $rootScope.commons.refresh = false;
            gettypedata();
        }
    });

    $scope.$on("$destroy", function () {
        enter = null;
    });
})

.controller('AuditStepSetCtrl', function ($rootScope, $scope, $state, $ionicPopover, $timeout, $location, $ionicScrollDelegate, $ionicHistory, global, showPopup, Member, Pay) {
    $ionicPopover.fromTemplateUrl('templates/add.html', {
        scope: $scope
    }).then(function (popover) {
        $scope.popover = popover;
    });
    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        getPayStepMflist();
    });

    $scope.sortchars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'];
    $scope.sortchar = 'A';
    $scope.is_show_middle = false;
    $scope.is_show_delete = false;

    $scope.sortByChar = function (char, id) {
        $scope.sortchar = char;
        $scope.is_show_middle = true;
        $location.hash(id);
        $ionicScrollDelegate.anchorScroll();
        $timeout(function () {
            $scope.is_show_middle = false;
        }, 200);
    };

    $scope.displayremove = function () {
        $scope.is_show_delete = !$scope.is_show_delete;
        $scope.popover.hide();
    };

    $scope.ok = function () {
        $scope.popover.hide();
        $scope.is_show_delete = false;
        var data = {"U": [], "D": delete_data, "C": []};
        if (delete_data.length > 0) {
            Pay.auditstep.patch(data, function (data) {
                console.log(data);
            }, function (err) {
                // alert('delete error');
            }).$promise.finally(function (f) {
                delete_data = [];
            });
            Pay.auditstepdata = _.filter(Pay.auditstepdata, function (item) {
                return !_.contains(delete_data, item.id);
            });
        }
    };

    $scope.toadd = function () {
        Member.resourcemember = [];
        Member.selectedemplst = [];
        Member.disabled = true;
        Member.resourcemember = _.map(_.pluck(Pay.auditstepdata, 'create_user'), function (m) {
            return {"user_id": m.id, "username": m.username};
        });
        Member.showall = false;
        Member.showgroup = false;
        Member.customerop = 1;
        Member.titlename = "选择添加的成员";
        Member.routename = "auditstep";
        Member.routeparams = {
            "id": -1
        };

        $scope.popover.hide();
        $state.go('selectmember');
    };

    var delete_data = [];
    $scope.removeItem = function (user, _char) {
        var ids = _.pluck(_.filter(Pay.auditstepdata, function (item) {
            return item.create_user.id == user.id;
        }), 'id');
        delete_data = delete_data.concat(ids);
        for (var i = 0; i < $scope.resultdata.length; i++) {
            if ($scope.resultdata[i].sortchar == _char) {
                for (var j = 0; j < $scope.resultdata[i].persons.length; j++) {
                    if ($scope.resultdata[i].persons[j].emp.id == user.id) {
                        $scope.resultdata[i].persons.splice(j, 1);
                        if ($scope.resultdata[i].persons.length == 0) {
                            $scope.resultdata.splice(i, 1);
                        }
                        break;
                    }
                }
                break;
            }
        }
    };

    $scope.toedit = function (usrid) {
        Member.customerop = null;
        $state.go('auditstep', {
            "id": usrid
        });
    };

    $scope.doRefresh = function () {
        getPayStepMflist();
    };

    function getPayStepMflist() {
        if ($scope.resultdata == undefined) {
            showPopup.showLoading(1, '正在加载', false);
        }
        Pay.auditstep.query(function (data) {
            Pay.auditstepdata = angular.copy(data);
            $scope.resultdata = [];
            var chars = _.map(data, function (item) {
                return _.indexOf($scope.sortchars, getCamelChar(item.create_user.username)) >= 0 ? getCamelChar(item.create_user.username) : '#';
            });
            chars = _.sortBy(_.uniq(chars));
            for (var i = 0; i < chars.length; i++) {
                var d = {
                    "sortchar": chars[i],
                    "persons": []
                };
                var users = _.map(_.uniq(_.map(_.pluck(data, 'create_user'), JSON.stringify)), JSON.parse);
                for (var j = 0; j < users.length; j++) {
                    var char = _.indexOf($scope.sortchars, getCamelChar(users[j].username)) >= 0 ? getCamelChar(users[j].username) : '#';
                    if (char == chars[i]) {
                        var p = {"emp": users[j], "checknames": ""};
                        var steps = _.sortBy(_.filter(data, function (v) {
                            return v.create_user.id == users[j].id && !v.is_teller;
                        }), 'ordering');
                        var newsteps = steps.length > 3 ? steps.slice(0, 3) : steps;
                        p.checknames = _.pluck(_.pluck(newsteps, 'verifier'), 'username').join('→');
                        if (steps.length > 3) p.checknames += '...';
                        d.persons.push(p)
                    }
                }
                $scope.resultdata.push(d);
            }
            var index = _.pluck($scope.resultdata, 'sortchar').indexOf('#');
            if (index >= 0) {
                var item = $scope.resultdata[index];
                $scope.resultdata.splice(index, 1);
                $scope.resultdata.push(item);
            }
            showPopup.hideLoading();
        }, function (err) {
            showPopup.hideLoading();
        }).$promise.finally(function (f) {
            $scope.$broadcast('scroll.refreshComplete');
        });
    }

    function getCamelChar(str) {
        return pinyin.getCamelChars(str).toUpperCase().charAt(0)
    }
})

.controller('AddTypeCtrl', function ($rootScope, $scope, $state, $ionicHistory, global, showPopup, Pay, Tool) {
    var icon = {icon: null}, iconcolor = null, isModified = false;
    $scope.typeid = $state.params['id'];
    $scope.data = {
        "name": "",
        "icon": "",
        "icon_color": "",
        "ordering": 0
    };
    $scope.iconcolordata = [{
        'background': "#FCB232",
        'isacitve': false
    }, {
        'background': "#F89E79",
        'isacitve': false
    }, {
        'background': "#FB7B7A",
        'isacitve': false
    }, {
        'background': "#F393C3",
        'isacitve': false
    }, {
        'background': "#DF9FF3",
        'isacitve': false
    }, {
        'background': "#C08CCE",
        'isacitve': false
    }, {
        'background': "#609BF5",
        'isacitve': false
    }, {
        'background': "#4BB1FB",
        'isacitve': false
    }, {
        'background': "#89cff0",
        'isacitve': false
    }, {
        'background': "#68D3C9",
        'isacitve': false
    }, {
        'background': "#87CC79",
        'isacitve': false
    }, {
        'background': "#4AD592",
        'isacitve': false
    }, {
        'background': "#C8BEBD",
        'isacitve': false
    }, {
        'background': "#CBA7AB",
        'isacitve': false
    }, {
        'background': "#868CA6",
        'isacitve': false
    }, {
        'background': "#8299CF",
        'isacitve': false
    }, {
        'background': "#A0C7E6",
        'isacitve': false
    }, {
        'background': "#90B1B6",
        'isacitve': false
    }];

    $scope.icondata = [{
        'background': "#fff",
        'icon': "ion-android-bus",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-ios-cart",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-ios-telephone",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-ios-home",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-fork",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "icon-money",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-android-film",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-umbrella",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-ios-game-controller-b",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-android-print",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-tshirt",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-ios-medkit",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-outlet",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-android-bicycle",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-ios-pulse-strong",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-trophy",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-android-favorite",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-ios-cloud-download",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-plane",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-android-bar",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-nuclear",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-film-marker",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-icecream",
        'isacitve': false
    }, {
        'background': "#fff",
        'icon': "ion-flag",
        'isacitve': false
    }];

    global.fetch_user().then(function () {
        if ($scope.typeid > 0) {
            $scope.data = Tool.cloneObj(Pay.typeItem);
            iconcolor = _.find($scope.iconcolordata, function (item) {
                if (item.background == $scope.data.icon_color) {
                    item.isacitve = true;
                    return item;
                }
            });
            iconcolor = iconcolor.background;
            icon = _.find($scope.icondata, function (item) {
                if (item.icon == $scope.data.icon) {
                    item.isacitve = true;
                    item.background = $scope.data.icon_color;
                    return item;
                }
            });
        } else {
            $scope.data.ordering = Pay.typeList.length;
            $scope.iconcolordata[0].isacitve = true;
            $scope.icondata[0].background = '#FCB232';
            $scope.icondata[0].isacitve = true;
            iconcolor = $scope.iconcolordata[0].background;
            icon.icon = $scope.icondata[0].icon;
        }
    });

    if ($scope.typeid > 0) {
        watch = $scope.$watch('data', function (n, o) {
            if (n == o)
                return;
            isModified = true;
        }, true);
    }

    $scope.selecticon = function (iconitem) {
        _.find($scope.icondata, function (item) {
            if (item.isacitve) {
                item.isacitve = false;
                item.background = '#fff';
                return item;
            }
        });
        iconitem.isacitve = true;
        iconitem.background = iconcolor;
        icon = iconitem;
    };

    $scope.selectcolor = function (coloritem) {
        _.find($scope.iconcolordata, function (item) {
            if (item.isacitve) {
                item.isacitve = false;
                return item;
            }
        });
        coloritem.isacitve = true;
        icon.background = coloritem.background;
        iconcolor = coloritem.background;
    };

    $scope.ok = function () {
        if ($scope.data.name == "") {
            return showPopup.PopupWindow(0, '类型名称不能为空！');
        }
        $scope.data.icon = icon.icon;
        $scope.data.icon_color = iconcolor;
        var type = null;
        if ($scope.typeid > 0) {
            if (isModified) {
                type = _.find(Pay.typeList, function (item) {
                    if (item.id != $scope.typeid && item.name == $scope.data.name) {
                        showPopup.PopupWindow(0, '类型名称不能重复！');
                        return item;
                    }
                });
                if (!type) {
                    showPopup.showLoading(1, '正在上传');
                    Pay.type.update($scope.data, function () {
                        $rootScope.commons.refresh = true;
                        showPopup.hideLoading();
                        $scope.back();
                    });
                }
            } else {
                $scope.back();
            }
        } else {
            type = _.find(Pay.typeList, function (item) {
                if (item.name == $scope.data.name) {
                    showPopup.PopupWindow(0, '类型名称不能重复！');
                    return item;
                }
            });
            if (!type) {
                showPopup.showLoading(1, '正在上传');
                Pay.type.save($scope.data, function () {
                    $rootScope.commons.refresh = true;
                    showPopup.hideLoading();
                    $scope.back();
                });
            }
        }
    };

    $scope.deltype = function () {
        showPopup.confirm('确定删除该类型吗?', '确定', '取消').then(function (res) {
            if (res) {
                showPopup.showLoading(1, '正在删除');
                Pay.type.delete({'id': $scope.typeid}, function () {
                    $rootScope.commons.refresh = true;
                    showPopup.hideLoading();
                    $scope.back();
                });
            }
        });
    };

    $scope.back = function () {
        $ionicHistory.goBack();
    };

    $scope.$on('$destroy', function () {
        if ($scope.typeid > 0) {
            watch();
        }
    })
})

.controller('AuditStepCtrl', function ($rootScope, $scope, $state, $ionicHistory, $timeout, global, Member, showPopup, Pay, Tool) {
    $scope.create_users = [];
    $scope.step_users = [];
    $scope.teller = null;
    $scope.op_id = 0;
    var beforeEnter = $scope.$on("$ionicView.enter", function () {
        $scope.op_id = $state.params['id'];
        if ($scope.op_id != 0) Tool.removeBackView(['selectmember', 'selectsinglemember', 'auditstep']);
        var back = $ionicHistory.backView();
        if ($scope.op_id > 0) {
            $scope.titlename = "编辑审批步骤";
            if (Member.customerop == null) {
                $scope.create_users = [_.find(Pay.auditstepdata, function (item) {
                    return item.create_user.id == $scope.op_id;
                }).create_user];
                setusers(Pay.auditstepdata, $scope.op_id);
            } else seteditdata();
        } else if ($scope.op_id < 0) {
            $scope.titlename = "添加审批步骤";
            setdata();
            if (back.stateName == 'pay' && Member.customerop == null && Pay.personstepdata.length > 0) setusers(Pay.personstepdata, Pay.personstepdata[0].create_user.id);
        } else if ($scope.op_id == 0) { //修改当前登录人的审批步骤
            $scope.titlename = "编辑审批步骤";
            if (Member.customerop == null) {
                if (Pay.personstepdata.length == 0) {
                    Pay.auditstep.query({"userid": global.user.usrid}, function (data) {
                        $scope.step_data = angular.copy(data);
                        $scope.create_users.push({"id": global.user.usrid, "username": global.user.usrname});
                        setusers(data, global.user.usrid);
                    });
                } else {
                    $scope.create_users = [{"id": global.user.usrid, "username": global.user.usrname}];
                    setusers(Pay.personstepdata, Pay.personstepdata[0].create_user.id);
                }
            } else setdata();
            $scope.showbar = true;
        }
        $scope.is_current_user = (global.user.usrid == formatusers($scope.create_users)[0].user_id && back.stateName == "pay");
    });

    $scope.$on("$destroy", function () {
        Pay.personstepdata = [];
        Member.selectedemplst = [];
        Member.unenabledata = [];
        beforeEnter = null;
    });

    $scope.add_teller = function () {
        set_member_option(false, $scope.teller == null ? [] : [$scope.teller], 3, "选择出纳人员", "selectsinglemember");
    };

    $scope.add_step_user = function () {
        set_member_option(true, $scope.step_users, 2, "选择审批人", "selectsinglemember");
    };

    $scope.add_create_user = function () {
        set_member_option(false, $scope.create_users, 1, "选择添加的成员", "selectmember");
        Member.unenabledata = formatusers(_.pluck(Pay.auditstepdata, "create_user"));
    };

    $scope.ok = function () {
        if ($scope.step_users.length == 0) {
            showPopup.PopupWindow(0, "请选择审批人！", false);
            return;
        }
        if ($scope.teller == null) {
            showPopup.PopupWindow(0, "请选择出纳人！", false);
            return;
        }
        showPopup.showLoading(1, '正在提交', false);
        if ($scope.op_id >= 0) {//edit
            Pay.auditstep.patch({"C": [], "D": [], "U": get_upload_data()}, function (data) {
                showPopup.hideLoading();
                $ionicHistory.goBack();
            }, function (err) {
                showPopup.hideLoading();
                // alert(JSON.stringify(err))
                $ionicHistory.goBack();
            })
        } else if ($scope.op_id < 0) { //add
            Pay.auditstep.save(get_upload_data(), function (data) {
                showPopup.hideLoading();
                $ionicHistory.goBack();
            }, function (err) {
                alert(JSON.stringify(err));
            })
        }
    };

    $scope.goback = function () {
        $ionicHistory.goBack();
    };

    $scope.toSeeList = function () {
        $state.go("seestepmflist");
    };

    function set_member_option(is_disabled, data, op, titlename, route) {
        Member.selectedemplst = [];
        Member.disabled = is_disabled;
        Member.resourcemember = formatusers(data);
        Member.customerop = op;
        Member.titlename = titlename;
        $state.go(route);
    }

    function seteditdata() {
        $scope.titlename = "编辑审批步骤";
        if (Member.customerop == null) $scope.create_users = Member.selectedemplst;
        setdata();
    }

    function setdata() {
        if (Member.customerop == 1) { //申请
            if (Member.dialogresult == 1) $scope.create_users = Member.selectedemplst;
        } else if (Member.customerop == 2) { //审核
            if (Member.selectedemplst.length > 0) $scope.step_users.push(Member.selectedemplst[0])
        } else if (Member.customerop == 3) {//出纳
            if (Member.selectedemplst.length > 0) $scope.teller = Member.selectedemplst[0]
        }
    }

    function get_upload_data() {
        var data = [];
        _.each($scope.create_users, function (c_user) {
            data = data.concat(_.map($scope.step_users, function (s_user, index) {
                return {"create_user": getuserid(c_user), "verifier": getuserid(s_user), "is_teller": false, "ordering": index + 1};
            }));
            data.push({"create_user": getuserid(c_user), "verifier": getuserid($scope.teller), "is_teller": true, "ordering": $scope.step_users.length + 1})
        });
        return data;
    }

    function getuserid(user) {
        return _.has(user, 'id') ? user.id : user.user_id;
    }

    function setusers(data, userid) {
        $scope.step_users = _.pluck(_.sortBy(_.filter(data, function (item) {
            return item.create_user.id == userid && !item.is_teller;
        }), "ordering"), 'verifier');
        $scope.teller = _.find(data, function (item) {
            return item.create_user.id == userid && item.is_teller;
        }).verifier;
    }

    function formatusers(data) {
        return _.map(data, function (item) {
            return {"user_id": _.has(item, 'id') ? item.id : item.user_id, "username": item.username}
        })
    }
})

.controller('SeeStepMfListCtrl', function ($rootScope, $scope, $state, $ionicHistory, $cordovaDatePicker, $timeout, global, Pay, Member, showPopup) {
    doRefresh();
    $scope.usestep = function (step) {
        Member.customerop = null;
        Pay.personstepdata = _.filter($scope.step_data_copy, function (item) {
            return item.create_user.id == step.create_user.id;
        });
        $ionicHistory.goBack();
    };

    $scope.doRefresh = function () {
        doRefresh();
    };

    function doRefresh() {
        if ($scope.step_datas == undefined) showPopup.showLoading(1, '正在加载', false);
        Pay.auditstep.query(function (data) {
            $scope.step_datas = [];
            $scope.step_data_copy = angular.copy(data);
            var users = _.map(_.uniq(_.map(_.pluck(data, 'create_user'), JSON.stringify)), JSON.parse);
            _.each(users, function (user) {
                if (user.id != global.user.usrid) {
                    var step_users = _.pluck(_.sortBy(_.filter(data, function (item) {
                        return item.create_user.id == user.id && !item.is_teller;
                    }), 'ordering'), 'verifier');
                    var step_usernames = _.pluck(step_users, 'username').join('→');
                    var teller = _.find(data, function (item) {
                        return item.create_user.id == user.id && item.is_teller;
                    }).verifier;
                    $scope.step_datas.push({"create_user": user, "step_users": step_users, "teller": teller, "step_usernames": step_usernames})
                }
            })
        }, function (err) {
            showPopup.hideLoading();
            alert(JSON.stringify(err));
        }).$promise.finally(function () {
            $scope.$broadcast('scroll.refreshComplete');
            showPopup.hideLoading();
        });
    }

    $scope.goback = function () {
        $ionicHistory.goBack();
    };
})

.controller('PayRecordCtrl', function ($rootScope, $scope, $state, $cordovaDatePicker, $timeout, $ionicModal, $ionicHistory, $q, ImageManage, global, showPopup, Pay, Tool) {
    showPopup.modalTemplate('templates/modal-paytype.html', 'slide-in-right', $scope).then(function (modal) {
        $scope.select_pay_type = modal;
    });
    $scope.recordid = $state.params['id'];
    $scope.titleArr = ['新建', '编辑'];
    $scope.popup = {
        isPopup: false
    };
    $scope.record = {
        "amount": null,
        "pay_type": null,
        "type_modal": null,
        "spend_date": null,
        "description": null,
        "files": []
    };
    var isModified = false;

    Pay.type.get(function (res) {
        $scope.types = res;
        Pay.typeList = res;
        _.each($scope.types, function (type) {
            type.color = {
                'color': type.icon_color
            };
            type.selected = false;
        });
    }, function (err) {
        alert(JSON.stringify(err));
    });

    if ($scope.recordid > 0) {
        $scope.record = Tool.cloneObj(Pay.recordItem);
        $scope.record.amount = parseFloat($scope.record.amount);
    }

    $scope.ok = function () {
        if ($scope.record.amount == null) {
            showPopup.PopupWindow(0, "请填写金额", false);
            return
        } else if ($scope.record.type_modal == null) {
            showPopup.PopupWindow(0, "请选择消费类型", false);
            return
        } else if ($scope.record.spend_date == null) {
            showPopup.PopupWindow(0, "请选择消费日期", false);
            return
        }
        showPopup.showLoading(1, '正在提交', true);
        if ($scope.recordid > 0) {
            if (isModified) {
                Pay.record.update($scope.record, function () {
                    $rootScope.commons.refresh = true;
                    _.each($scope.deleteimage_list, function (imageID) {
                        Pay.recordfile.delete({id: imageID});
                    });
                    var imagefiles = [];
                    _.each($scope.record.files, function (image) {
                        if (!image.id)
                            imagefiles.push(image.file_full_path);
                    });
                    if (imagefiles.length > 0) {
                        postimg(imagefiles, $scope.recordid);
                    } else {
                        showPopup.hideLoading();
                        $ionicHistory.goBack();
                    }
                });
            }
        } else {
            Pay.record.save($scope.record, function (data) {
                $rootScope.commons.refresh = true;
                var imagefiles = [];
                _.each($scope.record.files, function (image) {
                    if (!image.id)
                        imagefiles.push(image.file_full_path);
                });
                if (imagefiles.length > 0) {
                    postimg(imagefiles, data.id);
                } else {
                    showPopup.hideLoading();
                    $ionicHistory.goBack();
                }
            }, function (err) {
                alert('post Record error' + err);
            });
        }
    }

    $scope.selectSpendDate = function (spend_date) {
        var options = {
            mode: 'date',
            date: spend_date ? new Date(spend_date) : new Date(),
            androidTheme: 3
        };
        $cordovaDatePicker.show(options).then(function (date) {
            if (date == undefined) return;
            $scope.record.spend_date = date;
        });
    }

    $scope.selectPayType = function () {
        $scope.select_pay_type.show();
        $rootScope.commons.modal = $scope.select_pay_type;
    }


    $scope.cancel = function (op) {
        $rootScope.commons.modal.hide();
    }

    $scope.checkType = function (type) {
        $scope.pay_type = type.id;
        $scope.record.type_modal = type;
        $rootScope.commons.modal.hide();
    }

    $scope.deleteRecord = function () {
        showPopup.confirm("是否删除该消费记录？", '是', '否').then(function (res) {
            if (res) {
                Pay.record.delete({id: $scope.recordid}, function () {
                    $rootScope.commons.refresh = true;
                    $ionicHistory.goBack();
                });
            }
        });
    }

    $scope.addphoto = function () {
        if ($scope.record.files.length < 5) {
            $scope.popup.optionsPopup = showPopup.showSelectImgPopup(Camera, ImagePicker, $scope);
            $scope.popup.isPopup = true;
        } else {
            showPopup.PopupWindow(0, "上传图片数量需小于等于5！", false);
        }
    };

    var ImagePicker = function () { //打开相册
        $scope.popup.optionsPopup.close();
        ImageManage.ImagePicker_getPictures(5).then(function (result) {
            _.each(result, function (imageUrl) {
                $scope.record.files.push({
                    "file_thumbnail_path": imageUrl,
                    "file_full_path": imageUrl
                });
            })
        });
    };

    var Camera = function () {
        $scope.popup.optionsPopup.close();
        ImageManage.Camera_getPicture(true).then(function (result) {
            $scope.record.files.push({
                "file_thumbnail_path": result,
                "file_full_path": result
            });
        });
    };

    function postimg(imgfiles, id) {
        ImageManage.uploadImage(imgfiles, 'pay', id, 'payrecordfile').then(function (res) {
            $q.all(res).then(function (data) {
                showPopup.hideLoading();
                $ionicHistory.goBack();
            })
        }, function (err) {
            alert(JSON.stringify(error));
            showPopup.PopupWindow(0, 'upload image fail');
        })
    }

    $scope.deleteimage_list = [];
    $scope.shouBigImage = function (imageUrl) {
        $scope.Url = imageUrl;
        $rootScope.commons.bigImage = true;
    };

    $rootScope.commons.bigImage = false;
    $scope.hideBigImage = function () {
        $rootScope.commons.bigImage = false;
    };

    $scope.deleteimage = function () {
        var img = _.find($scope.record.files, function (image) {
            return image.file_full_path == $scope.Url;
        });
        if (img) {
            $scope.record.files.splice(_.indexOf($scope.record.files, img), 1);
            if (img.id)
                $scope.deleteimage_list.push(img.id);
        }
        $rootScope.commons.bigImage = false;
    };

    if ($scope.recordid > 0) {
        watch = $scope.$watch('record', function (n, o) {
            if (n == o)
                return;
            isModified = true;
        }, true);
    }

    $scope.$on("$destroy", function () {
        $scope.select_pay_type.remove();
        if ($scope.recordid > 0) {
            watch();
        }
    });
})

.controller('PayBillCtrl', function ($rootScope, $scope, $state, $ionicHistory, $ionicModal, global, showPopup, Pay, Tool) {
    $scope.select_record = showPopup.modalTemplate('templates/modal-selectrecord.html', 'slide-in-right', $scope);
    var isFirst = false;
    $scope.type = $state.params['type'];
    $scope.billid = $state.params['id']
    $scope.titleArr = ['新建', '编辑'];
    $scope.amountSum = 0;
    $scope.bill = {
        "title": null,
        "note": null,
        "status": null,
        "record": [],
        "record_old": []
    }
    $scope.records = [];

    global.fetch_user().then(function () {
        Pay.auditstep.get({userid: global.user.usrid}, function (data) {
            $scope.checkusrdata = data;
        });
        if ($scope.billid < 0) {
            $scope.recordlist = Tool.cloneObj(Pay.recordList);
            $scope.select_record.then(function (modal) {
                $scope.select_record = modal;
                $rootScope.commons.modal = modal;
                $scope.select_record.show();
            });
            isFirst = true;
        } else {
            $scope.select_record.then(function (modal) {
                $scope.select_record = modal;
                $rootScope.commons.modal = modal;
            });
            $scope.bill = Tool.cloneObj(Pay.detailItem);
            $scope.recordlist = Tool.cloneObj(Pay.recordList);
            $scope.records = $scope.bill.record;
            $scope.bill.record_old = _.map($scope.bill.record, function (record) {
                return record.id;
            });
            _.each($scope.records.reverse(), function (record) {
                record.selected = true;
                $scope.recordlist.splice(0, 0, record);
            });
            $scope.amountSum = $scope.bill.total_amount;
        }
    });

    $scope.selectRecord = function (recorditem) {
        if (recorditem.selected) {
            $scope.amountSum = parseFloat($scope.amountSum) + parseFloat(recorditem.amount);
        } else {
            $scope.amountSum = parseFloat($scope.amountSum) - parseFloat(recorditem.amount);
        }
        $scope.amountSum = $scope.amountSum.toFixed(2);
    };

    $scope.toEditRecord = function () {
        $scope.select_record.show();
        $rootScope.commons.modal = $scope.select_record;
    };

    $scope.cancel = function (op) {
        if (op == 'm') {
            if (isFirst) {
                $ionicHistory.goBack();
            }
            $rootScope.commons.modal.hide();
            $rootScope.commons.modal = undefined;
        } else {
            $ionicHistory.goBack();
        }

    };

    $scope.ok = function (op) {
        if (op == 'bill') {
            if ($scope.bill.title == null) {
                showPopup.PopupWindow(0, "请填写标题", false);
                return;
            }
            $scope.bill.record = _.map($scope.records, function (item) {
                return item.id;
            });
            showPopup.showLoading(1, '正在提交', false);
            if ($scope.billid < 0) {
                Pay.billdetail.save($scope.bill, function (data) {
                    showPopup.hideLoading();
                    $state.go('paybilldetails', {
                        id: data.id
                    });
                }, function (err) {
                    alert(JSON.stringify(err))
                });
            } else {
                $scope.bill = _.pick($scope.bill, 'id', 'title', 'note', 'status', 'record', 'record_old');
                Pay.billdetail.update($scope.bill, function (data) {
                    showPopup.hideLoading();
                    $state.go('paybilldetails', {
                        id: data.id
                    });
                }, function (err) {
                    alert(JSON.stringify(err))
                });
            }
        } else {
            $scope.records = _.filter($scope.recordlist, function (item) {
                return item.selected;
            });
            $rootScope.commons.modal.hide();
        }
    }

    $scope.$on("$destroy", function () {
        $scope.select_record.remove();
    });
})

.controller('BillListCtrl', function ($rootScope, $scope, $state, global, Pay) {
    var type = $state.params['type'];
    global.fetch_user().then(function () {
        getpaylistdata();
    });

    $scope.doRefresh = function () {
        global.refresh = true;
        getpaylistdata();
    };

    $scope.loadMore = function () {
        if ($scope.bills != undefined && $scope.bills.next != null) {
            Tool.get($scope.bills.next).then(function (data) {
                _.each(data.results, function (item) {
                    $scope.bills.results.push(item);
                });
                $scope.bills.next = data.next;
                $scope.bills.previous = data.previous;
            }).finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.loading = false;
            });
        } else {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }
    };

    $scope.moreCanBeLoaded = function () {
        return $scope.bills != undefined && $scope.bills.next != null;
    };

    function getpaylistdata() {
        if (global.user.token != "") {
            if ($scope.bills == undefined) {
                $scope.loading = true;
            }
            Pay.bill.get({type: type}, function (data) {
                $scope.bills = data;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }
})

.controller('BillApproveCtrl', function ($rootScope, $scope, $state, global, Pay) {
    var type = $state.params['type'];
    global.fetch_user().then(function () {
        getpaylistdata();
    });

    $scope.doRefresh = function () {
        global.refresh = true;
        getpaylistdata();
    };

    $scope.loadMore = function () {
        if ($scope.bills != undefined && $scope.bills.next != null) {
            Tool.get($scope.bills.next).then(function (data) {
                _.each(data.results, function (item) {
                    $scope.bills.results.push(item);
                });
                $scope.bills.next = data.next;
                $scope.bills.previous = data.previous;
            }).finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.loading = false;
            });
        } else {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }
    };

    $scope.moreCanBeLoaded = function () {
        return $scope.bills != undefined && $scope.bills.next != null;
    };

    function getpaylistdata() {
        if (global.user.token != "") {
            if ($scope.bills == undefined) {
                $scope.loading = true;
            }
            Pay.bill.get({type: type}, function (data) {
                $scope.bills = data;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }
})

.controller('BillApprovedCtrl', function ($rootScope, $scope, $state, global, Pay, Member, Tool) {
    var type = $state.params['type'];
    $scope.centerdata = [
        {"key": null, "name": "全部状态", "check": true},
        {"key": 0, "name": "已驳回", "check": false},
        {"key": 1, "name": "已支付", "check": false},
        {"key": 2, "name": "未支付", "check": false},
        {"key": 3, "name": "处理中", "check": false}];
    var beforeenter = $scope.$on('$ionicView.beforeEnter', function () {
        $scope.user_id = Member.selectedemplst.length > 0 ? Member.selectedemplst[0].user_id : 0;
    });
    global.fetch_user().then(function () {
        getpaylistdata(null, null, null, null);
    });

    $scope.doRefresh = function () {
        global.refresh = true;
        getpaylistdata();
    };

    $scope.loadMore = function () {
        if ($scope.bills != undefined && $scope.bills.next != null) {
            Tool.get($scope.bills.next).then(function (data) {
                _.each(data.results, function (item) {
                    $scope.bills.results.push(item);
                });
                $scope.bills.next = data.next;
                $scope.bills.previous = data.previous;
            }).finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.loading = false;
            });
        } else {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }
    };

    $scope.moreCanBeLoaded = function () {
        return $scope.bills != undefined && $scope.bills.next != null;
    };

    $scope.selectClick = function (date, status, user_id) {
        var year = date == null ? date : (date.length > 4 ? date.substr(0, 4) : date);
        var month = date == null ? date : (date.length == 4 ? null : date.substr(5, date.length - 5));
        getpaylistdata(status == null ? status : parseInt(status), year, month, user_id);
    };

    $scope.setUser = function () {
        $scope.user_id = 0;
    };

    function getpaylistdata(status, year, month, create_user) {
        if (global.user.token != "") {
            if ($scope.bills == undefined) {
                $scope.loading = true;
            }
            Pay.bill.get({"type": type, "status": status, "year": year, "month": month, "create_user": create_user}, function (data) {
                $scope.bills = data;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }

    $scope.$on('$destroy', function () {
        beforeenter = null;
        Member.selectedemplst = [];
    });
})

.controller('BillPayCtrl', function ($rootScope, $scope, $state, global, Pay) {
    var type = $state.params['type'];
    global.fetch_user().then(function () {
        getpaylistdata();
    });

    $scope.doRefresh = function () {
        global.refresh = true;
        getpaylistdata();
    };

    $scope.toAnalyse = function () {
        $state.go('pay-analyse');
    }

    $scope.loadMore = function () {
        if ($scope.bills != undefined && $scope.bills.next != null) {
            Tool.get($scope.bills.next).then(function (data) {
                _.each(data.results, function (item) {
                    $scope.bills.results.push(item);
                });
                $scope.bills.next = data.next;
                $scope.bills.previous = data.previous;
            }).finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.loading = false;
            });
        } else {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }
    };

    $scope.moreCanBeLoaded = function () {
        return $scope.bills != undefined && $scope.bills.next != null;
    };

    function getpaylistdata() {
        if (global.user.token != "") {
            if ($scope.bills == undefined) {
                $scope.loading = true;
            }
            Pay.bill.get({type: type}, function (data) {
                $scope.bills = data;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }
})

.controller('PayBillDetailsCtrl', function ($rootScope, $scope, $state, $ionicPopup, $ionicHistory, $cordovaDialogs, global, Pay, showPopup, Tool) {
    showPopup.modalTemplate('templates/modal-stepReject.html', 'slide-in-right', $scope).then(function (modal) {
        $scope.step_reject = modal;
    });
    $scope.index = null;
    var paybillid = $state.params["id"];
    Tool.removeBackView('pay-bill');

    global.fetch_user().then(function () {
        $scope.user = global.user.usrid;
        getbilldata();
    });

    $scope.toedit = function () {
        $state.go('pay-bill', {
            type: 1,
            id: paybillid
        });
    }

    $scope.deleteBill = function () {
        $cordovaDialogs.confirm('是否撤销该报销单', '提示', ['是', '否']).then(function (buttonIndex) {
            if (buttonIndex == 1) {
                showPopup.showLoading(1, '撤销中');
                Pay.billdetail.delete({id: paybillid}, function () {
                    showPopup.hideLoading();
                    $ionicHistory.goBack();
                });
            }
        });
    }

    $scope.audit = function (op) {
        $scope.data = {};
        if (op == 0) {
            setPopup('驳回', '请输入驳回理由(必填)', op);
        } else if (op == 1) {
            setPopup('同意', '请输入备注(选填)', op);
        } else if (op == 2) {
            showPopup.showLoading(1, '提交中');
            Pay.billdetail.update({id: paybillid, status: 2}, function (data) {
                getbilldata();
                showPopup.hideLoading();
            });
        }
    }

    $scope.ok = function () {
        console.log($scope.index);
        $scope.data.ordering = $scope.index;
        postHistory($scope.data);
        $scope.cancel();
    }

    $scope.cancel = function () {
        $rootScope.commons.modal.hide();
    }

    $scope.changeIndex = function (index) {
        $scope.index = index;
    }

    function getbilldata() {
        if (global.user.token != "") {
            if ($scope.bill == undefined) {
                $scope.loading = true;
            }
            Pay.billdetail.get({id: paybillid}, function (res) {
                $scope.loading = false;
                $scope.bill = res;
                Pay.detailItem = _.clone(res);
                console.log(res);
                $scope.billhistorydata = [];
                _.each(res.history, function (item) {
                    var historyitem = {};
                    historyitem.date = item.create_date;
                    historyitem.title = item.create_user.username;
                    historyitem.profilePicture = "../../../img/panda.png";
                    historyitem.text = item.content;
                    historyitem.icon = item.status == 0 ? "ion-ios-undo assertive" : "ion-ios-checkmark balanced"
                    $scope.billhistorydata.push(historyitem);
                });
                if (!$scope.bill.verifier.is_teller) {
                    $scope.billhistorydata.push({
                        icon: 'ion-load-c task-create-member-p',
                        title: $scope.bill.status == 0 ? $scope.user == $scope.bill.create_user.id ? '等待我处理' : '当前处理人:' + $scope.bill.create_user.username : $scope.user == $scope.bill.verifier.verifier_id ? '等待我处理' : '当前处理人:' + $scope.bill.verifier.verifier__username,
                        profilePicture: "../../../img/panda.png"
                    });
                }
                $scope.billhistorydata.reverse();
            })
        }
    }

    function setPopup(title, placeholdertext, op) {
        $cordovaDialogs.prompt(placeholdertext, title, ['确定', '取消']).then(function (result) {
            var input = result.input1;
            var btnIndex = result.buttonIndex;
            if (btnIndex == 1) {
                if (input == '' && op == 0) {
                    $cordovaDialogs.alert('请填写驳回理由', '提示', '确定');
                } else {
                    $scope.data = {
                        status: op,
                        content: input == '' ? null : input,
                        pay_bill_id: paybillid,
                        ordering: null
                    }
                    if (op == 1) {
                        postHistory($scope.data);
                    } else if (op == 0) {
                        $scope.step = getStep($scope.bill.step);
                        if ($scope.step.length >= 1) {
                            $scope.step.reverse();
                            $scope.step.push({
                                ordering: 0,
                                verifier: {
                                    username: $scope.bill.create_user.username
                                }
                            });
                            $scope.index = $scope.step[0].ordering;
                            $scope.step_reject.show();
                            $rootScope.commons.modal = $scope.step_reject;
                        } else {
                            postHistory($scope.data);
                        }
                    }
                }
            }
        });
    }

    function postHistory(data) {
        showPopup.showLoading(1, '提交中');
        Pay.billhistory.save(data, function (data) {
            getbilldata();
            showPopup.hideLoading();
        })
    }

    function getStep(step) {
        return _.filter(step, function (item) {
            return item.is_approved;
        });
    }

    $scope.$on("$destroy", function () {
        $scope.step_reject.remove();
    });
})

.controller('PayAnalyseCtrl', function ($rootScope, $scope, $filter, $state, global, Pay) {
    global.fetch_user().then(function () {
        getanalysedata();
    });

    function getanalysedata() {
        if (global.user.token != "") {
            if ($scope.data == undefined) {
                $scope.loading = true;
            }
            Pay.analyse.get(function (res) {
                $scope.loading = false;
                $scope.data = res;
                _.each($scope.data.result, function (item) {
                    item.percentage = $filter('percentage')(item.count / $scope.data.count, 2, "%");
                })
            })
        }
    }
})