starter.controller('DailyCtrl', function ($rootScope, $scope, $state, global, Daily, Tool) {
    $scope.goBack = function () {
        global.goBack();
    }

    global.fetch_user().then(function () {
        getdailydata();
    });

    $scope.toman = function () {
        $state.go('daily-man');
    }

    $scope.towrite = function () {
        $state.go('daily-edit', {
            'flag': 0
        });
    }

    $scope.totransfer = function (id) {
        $state.go('transfer', {
            module: 'daily',
            id: id
        });
    }

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

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

    $scope.moreCanBeLoaded = function () {
        return $scope.dailys != undefined && $scope.dailys.next != null ? true : false;
    }

    function getdailydata() {
        if (global.user.token != "") {
            if ($scope.dailys == undefined) {
                $scope.loading = true;
            }
            Daily.dailymf.get(function (res) {
                $scope.dailys = res;
                console.log($scope.dailys);
                $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;
            getdailydata();
        }
    });

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

.controller('DailyReadCtrl', function ($scope, $state, $ionicSlideBoxDelegate, Daily, global, Tool) {
    $scope.index = 0;

    global.fetch_user().then(function () {
        getsummaryata();
    });

    $scope.select = function (index) {
        $ionicSlideBoxDelegate.slide(index);
        $scope.index = $ionicSlideBoxDelegate.currentIndex();
    }

    $scope.toMonthCount = function (item) {
        $state.go('daily-readMonthCount', {
            'daily_dd': item.daily_date
        });
    }

    $scope.toDayCount = function (date) {
        $state.go('daily-readDay', {
            'daily_dd': date
        })
    }

    $scope.isMonth = function (item) {
        var date = new Date(item.daily_date);
        return date.getMonth() == new Date().getMonth() ? false : true;
    }

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

    $scope.loadMore = function () {
        if ($scope.summary != undefined && $scope.summary.next != null) {
            Tool.get($scope.summary.next).then(function (data) {
                data.results = initialize(data.results);
                _.each(data.results, function (value, key) {
                    var item = _.pick($scope.summary.results, key);
                    if (item[key]) {
                        _.each(value, function (i) {
                            $scope.summary.results[key].push(i);
                        })
                    } else {
                        $scope.summary.results[key] = value;
                    }
                });
                console.log($scope.summary.results);
                $scope.summary.next = data.next;
                $scope.summary.previous = data.previous;
            }).finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.loading = false;
            });
        } else {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }
    }

    $scope.moreCanBeLoaded = function () {
        return $scope.summary != undefined && $scope.summary.next != null ? true : false;
    }

    function getsummaryata() {
        if (global.user.token != "") {
            if ($scope.summary == undefined) {
                $scope.loading = true;
            }
            Daily.dailysummary.get(function (res) {
                console.log(res.results);
                res.results = initialize(res.results);
                $scope.summary = res;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }

    function initialize(data) {
        _.each(data, function (item) {
            var date = new Date(item.daily_date);
            item.month = date.getFullYear() + '-' + (date.getMonth() + 1);
        });
        return _.groupBy(data, 'month');
    }
})

.controller('DailyDetailsCtrl', function ($rootScope, $scope, $state, $ionicPopover, $ionicPopup, $ionicHistory, global, Daily, showPopup) {
    $scope.id = $state.params['id'];
    $scope.cssstyle = true;
    $scope.comments = {};
    $scope.reads = {};
    $scope.data = {
        daily_mf: $scope.id,
        comment: null
    }
    var view = $ionicHistory.backView();

    $scope.popup = {
        isPopup: false
    }

    global.fetch_user().then(function () {
        if (view) {
            $scope.loading = true;
            $scope.daily = Daily.daily;
            Daily.dailyread.get({mf_id: $scope.id}, function (data) {
                $scope.comments = data;
                $scope.loading = false;
            });
            Daily.readview.query({mf_id: $scope.id}, function (data) {
                $scope.reads = data;
            });
        } else {
            getdailydata();
        }
    });

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

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

    $scope.sendComment = function () {
        if ($scope.data.comment != null && $scope.data.comment != "") {
            Daily.dailyread.save($scope.data, function (data) {
                $scope.comments.results.splice(0, 0, data);
                $scope.data.comment = null;
            })
        }
    }

    $scope.popupMessageOpthins = function (id, usrid) {
        if (usrid == global.user.usrid) {
            $scope.popup.optionsPopup = $ionicPopup.show({
                template: '<div class="center" style="height:20px;width:100%;line-height:20px;margin-top:10px;" rj-close-back-drop><h4>用户操作</h4></div>',
                scope: $scope,
                buttons: [{
                    text: '删除',
                    type: 'button-positive',
                    onTap: function (e) {
                        Daily.dailyread.delete({id: id}, function () {
                            var comment = _.find($scope.comments.results, function (item) {
                                if (item.id === parseInt(id))
                                    return item;
                            });
                            if (comment != undefined)
                                $scope.comments.results.splice($scope.comments.results.indexOf(comment), 1);
                        });
                    }
                }]
            });
            $scope.popup.isPopup = true;
        }
    }

    $scope.transfer = function () {
        $scope.popover.hide();
        $state.go('transfer', {
            module: 'daily',
            id: $scope.id
        });
    }

    $scope.remove = function () {
        $scope.popover.hide();
        showPopup.confirm('是否删除该汇报?', '是', '否').then(function (res) {
            if (res) {
                Daily.dailymf.delete({id: $scope.id}, function () {
                    $rootScope.commons.refresh = true;
                    $ionicHistory.goBack();
                });
            }
        });
    }

    $scope.edit = function () {
        $scope.popover.hide();
        $state.go('daily-edit', {
            'flag': $scope.id
        })
    }

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

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

    $scope.moreCanBeLoaded = function () {
        return $scope.comments != undefined && $scope.comments.next != null ? true : false;
    }

    function getdailydata() {
        if ($scope.daily == undefined) {
            $scope.loading = true;
        }
        Daily.dailymf.get({id: $scope.id}, function (res) {
            Daily.daily = _.clone(res);
            $scope.daily = res;
        }, function (err) {
            alert(JSON.stringify(err));
        }).$promise.finally(function () {
            $scope.$broadcast('scroll.refreshComplete');
            $scope.loading = false;
        });
        Daily.dailyread.get({mf_id: $scope.id}, function (data) {
            $scope.comments = data;
        });
        Daily.readview.query({mf_id: $scope.id}, function (data) {
            $scope.reads = data;
        });
    }

    enter = $scope.$on('$ionicView.enter', function (event, data) {
        if (data.fromCache && $rootScope.commons.refresh) {
            if (view == null)
                $rootScope.commons.refresh = false;
            getdailydata();
        }
    });

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

.controller('DailyPermissionCtrl', function ($rootScope, $scope, $ionicPopover, $state, global, Daily) {
    var deletes = {C: [], D: [], U: []};

    global.fetch_user().then(function () {
        getpermissiondata();
    });

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

    $scope.isshowdelete = {
        showDelete: false
    }

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

    $scope.ok = function () {
        $scope.popover.hide();
        if (deletes.D.length > 0) {
            deletes.D = deletes.D.join(',');
            Daily.dailypermission.patch(deletes, function () {
                deletes.D = [];
            });
        }
        $scope.isshowdelete.showDelete = false;
    }

    $scope.toadd = function () {
        $scope.popover.hide();
        $state.go('additem');
    }

    $scope.remove = function (item) {
        _.each(item.permissions, function (permission) {
            deletes.D.push(permission.id);
        });
        $scope.userlist.results.splice(_.indexOf($scope.userlist.results, item), 1);
    }

    $scope.toSelectDeptOrItem = function (item) {
        Daily.permissionUser = _.clone(item);
        $state.go('selectdeptoritem', {
            "id": item.user_id
        });
    }

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

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

    $scope.moreCanBeLoaded = function () {
        return $scope.userlist != undefined && $scope.userlist.next != null ? true : false;
    }

    function getpermissiondata() {
        if (global.user.token != "") {
            if ($scope.userlist == undefined) {
                $scope.loading = true;
            }
            Daily.dailypermission.get(function (res) {
                $scope.userlist = res;
                Daily.permissionUsers = res.results;
            }, 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;
            getpermissiondata();
        }
    });

    $scope.$on('$destroy', function () {
        enter = null;
        $scope.popover.remove();
    })
})

.controller('SelectDeptOrItemCtrl', function ($rootScope, $scope, $state, $stateParams, $ionicHistory, Daily, Dept, showPopup, Tool) {
    var userId = $stateParams.id;
    $scope.cancel = function () {
        $ionicHistory.goBack();
    }
    $scope.leftbtn = [{
        text: '取消',
        click: 'cancel'
    }, {
        text: '上一层',
        click: 'up'
    }];
    $scope.index = 0;
    $scope.deptlst = [];
    $scope.emplst = [];
    $scope.deptid = null;
    $scope.selecteditems = Tool.cloneObj(Daily.permissionUser);
    var selecteditems_old = [];
    _.each($scope.selecteditems.depts, function (dept) {
        selecteditems_old.push(dept.permission);
    });
    _.each($scope.selecteditems.users, function (user) {
        selecteditems_old.push(user.permission);
    });

    var patchs = {C: [], D: [], U: []};
    $scope.selectcount = '';
    $scope.isUp = false;
    $scope.loading = true;
    Dept.getDep().then(function (data) {
        d = _.find(data, function (dept) {
            return dept.parent == null;
        });
        data = _.filter(data, function (item) {
            return item.level == 1;
        });
        $scope.deptlst = data;
        setdeptrighticon($scope.deptlst);
        getemp(d.id);
        $scope.loading = false;
    });

    $scope.tochilddept = function (dept) {
        getChildDept(dept.id);
    }

    function getemp(id, childdepts) {
        Dept.getEmp(id).then(function (data) {
            $scope.emplst = data;
            setitem();
        });
    }

    function getChildDept(did) {
        Dept.getEmp(did).then(function (data) {
            $scope.emplst = data;
            $scope.deptlst = Dept.getChildDept(did);
            setdeptrighticon($scope.deptlst);
            setitem();
            deptid = did;
            if (did == 1) {
                $scope.index = 0;
            } else {
                $scope.index = 1;
            }
        });
    }

    function setitem() {
        _.each($scope.deptlst, function (cd) {
            cd.selected = false;
            _.each($scope.selecteditems.depts, function (dept) {
                if (cd.id == dept.id)
                    cd.selected = true;
            });
            cd.isShow = Dept.getChildDept(cd.id).length == 0 ? false : true;
        });
        _.each($scope.emplst, function (e) {
            e.selected = false;
            _.each($scope.selecteditems.users, function (user) {
                if (e.user_id == user.user_id)
                    e.selected = true;
            });
        });
    }

    function setdeptrighticon(deptlst) {
        _.each(deptlst, function (d) {
            d.isShow = Dept.getChildDept(d.id).length == 0 ? false : true;
        })
    }

    $scope.up = function () {
        var dept = _.find(Dept.all(), function (d) {
            return d.id == parseInt(deptid);
        });
        getChildDept(dept.parent);
    }

    $scope.change = function (selitem, op) {
        var type = op == 'd' ? true : false;
        if (op == 'd') {
            setSelectItem(selitem, type, $scope.selecteditems.depts);
        } else {
            setSelectItem(selitem, type, $scope.selecteditems.users);
        }
        if ($scope.selecteditems.all) {
            $scope.selecteditems.all = false;
            if ($scope.selecteditems.permissions.length == 1 && $scope.selecteditems.permissions[0].flag == 0) {
                patchs.D = $scope.selecteditems.permissions[0].id.toString();
            }
        }
    }

    function setSelectItem(selectItem, type, array) {
        if (selectItem.selected) {
            selectItem.permission = {
                'user_id': userId,
                'flag': type ? 1 : 2,
                'value': type ? selectItem.id : selectItem.user_id
            };
            array.push(selectItem);
        } else {
            var item = _.find(array, function (item) {
                return type ? item.id == selectItem.id : item.user_id == selectItem.user_id;
            });
            array.splice(_.indexOf(array, item), 1);
        }
    }

    $scope.ok = function () {
        selecteditems = [];
        _.each($scope.selecteditems.depts, function (dept) {
            selecteditems.push(dept.permission);
        });
        _.each($scope.selecteditems.users, function (user) {
            selecteditems.push(user.permission);
        });

        rst = _.diff(selecteditems, selecteditems_old);
        if (patchs.D.length > 0) {
            if (rst.D.length > 0) {
                rst.D = rst.D + ',' + patchs.D;
            } else {
                rst.D = patchs.D;
            }
        }
        if (rst.C.length > 0 || rst.U.length > 0 || rst.D.length > 0) {
            showPopup.showLoading(1, '正在提交');
            Daily.dailypermission.patch(rst, function () {
                $rootScope.commons.refresh = true;
                showPopup.hideLoading();
                $ionicHistory.goBack();
            })
        } else {
            $ionicHistory.goBack();
        }
    }

    $scope.selectAll = function () {
        if ($scope.selecteditems.all) {
            if ($scope.selecteditems.permissions.length == 1 && $scope.selecteditems.permissions[0].flag == 0) {
                $ionicHistory.goBack();
            } else {
                showPopup.showLoading(1, '正在提交');
                var data = {C: [], D: [], U: []};
                data.C.push({
                    'user_id': userId,
                    'flag': 0,
                    'value': 0
                });
                data.D = _.map($scope.selecteditems.permissions, function (permission) {
                    return permission.id;
                }).join(',');
                Daily.dailypermission.patch(data, function () {
                    $rootScope.commons.refresh = true;
                    showPopup.hideLoading();
                    $ionicHistory.goBack();
                })
            }
        }
    }
})

.controller('DailyTemplateCtrl', function ($rootScope, $scope, $state, Daily, global) {
    $scope.gosetmoban = function (template) {
        Daily.currentTemplate = template;
        $state.go('daily-templateEdit', {
            "id": template.id
        });
    }

    global.fetch_user().then(function () {
        gettemplatedata();
    });

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

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

    $scope.moreCanBeLoaded = function () {
        return $scope.templates != undefined && $scope.templates.next != null ? true : false;
    }

    function gettemplatedata() {
        if (global.user.token != "") {
            if ($scope.templates == undefined) {
                $scope.loading = true;
            }
            Daily.template.get(function (res) {
                $scope.templates = 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;
            gettemplatedata();
        }
    });

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

.controller('DailyTemplateScopeCtrl', function ($rootScope, $scope, $stateParams, $ionicHistory, $state, Dept, Daily) {
    $scope.leftbtn = [{
        text: '取消',
        click: 'cancel'
    }, {
        text: '上一层',
        click: 'up'
    }];
    $scope.isNew = $stateParams.id == -1;
    // Daily.templateData = {items: [], depts: []}
    $scope.deptsAll = [];
    $scope.index = 0;
    $scope.actived = false;
    $scope.cancel = function () {
        $ionicHistory.goBack();
    }
    $scope.depts = [];
    if (!$scope.isNew) {
        $scope.selecteddepts = _.map(Daily.templateData.depts, function (dept) {
            return {'id': dept.dept_id, 'depname': dept.dept_name}
        });
    } else {
        $scope.selecteddepts = []
    }

    $scope.selecteddepts_old = _.map($scope.selecteddepts, _.clone)
    $scope.selectdeptcount = '';
    $scope.showupbtn = false;
    var resourcedept = [];
    $scope.isUp = false;
    $scope.loading = true;
    function setdept(data) {
        $scope.depts = data;
    }

    Dept.getDep().then(function (data) {
        $scope.deptsAll = data;
        Daily.templatedept.get(function (res) {
            _.each($scope.deptsAll, function (dept) {
                dept.selected = _.find($scope.selecteddepts, function (d) {
                    return d.id == dept.id && !$scope.isNew;
                }) == undefined ? false : true; //selected the existing dept
                if (!dept.selected) {
                    dept.isdisabled = _.find(res.results, function (d) {
                        return d.dept_id == dept.id;
                    }) == undefined ? false : true;//部门是否已设置模板
                }
                dept.isshow = Dept.getChildDept(dept.id).length > 0;
            });
            $scope.loading = false;
        });

        depts_lvl_1 = _.filter($scope.deptsAll, function (item) {
            return item.level == 1;
        });
        setdept(depts_lvl_1);
    });

    $scope.change = function (dept) {
        if (dept.selected) {
            $scope.selecteddepts.push(dept);
            Daily.templateDepts.push(dept);
        } else {
            $scope.selecteddepts.splice(_.indexOf($scope.selecteddepts, dept), 1);
            Daily.templateDepts.splice(_.indexOf(Daily.templateDepts, dept), 1);
        }
    }

    $scope.ok = function () {
        depts = _.pluck($scope.selecteddepts, 'depname');
        dept_names = depts.join(',');
        dept_ids = _.pluck($scope.selecteddepts, 'id');
        if ($scope.isNew) {
            Daily.template.save({'name': dept_names, 'dept_ids': dept_ids}, function (dept) {
                $rootScope.commons.refresh = true;
                $state.go('custom-form', {id: dept.id});
            })
        } else {
            Daily.template.update({'id': $stateParams.id, 'name': dept_names, 'dept_ids': dept_ids}, function (dept) {
                $rootScope.commons.refresh = true;
                $ionicHistory.goBack();
            })
        }
    }

    var activedept = {};
    $scope.tochilddept = function (dept) {
        activedept = dept;
        if (dept.isshow) {
            getChildDept(dept);
        } else {
            activedept.selected = !activedept.selected;
            $scope.change(activedept);
        }
    }

    function getChildDept(dept) {
        var childdepts = Dept.getChildDept(dept.id);
        $scope.index = dept.level < 1 ? 0 : 1;
        if (childdepts.length > 0) {
            setdept(childdepts);
        }
    }

    $scope.up = function () {
        dept = _.find($scope.deptsAll, function (dept) {
            return dept.id == activedept.parent;
        });
        getChildDept(dept);
        activedept = dept
    }
})

.controller('DailyTemplateEditCtrl', function ($rootScope, $scope, $ionicHistory, $state, $stateParams, global, Dept, Daily, showPopup) {
    Daily.templateId = $stateParams.id;

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

    global.fetch_user().then(function (data) {
        gettemplatedata();
    });

    $scope.delete = function () {
        showPopup.confirm('是否删除该日报模板?', '是', '否').then(function (res) {
            if (res) {
                Daily.template.delete({id: $stateParams.id}, function () {
                    $rootScope.commons.refresh = true;
                    $ionicHistory.goBack();
                });
            }
        });
    }

    $scope.defineform = function () {
        $state.go('custom-form', {
            id: $stateParams.id
        });
    }

    $scope.toSetDept = function () {
        $state.go('daily-templateScope', {
            "id": $stateParams.id
        });
    }

    function gettemplatedata() {
        if (global.user.token != "") {
            Daily.template.get({'id': Daily.templateId}, function (res) {
                $scope.template = res;
                Daily.templateData = res;
            }, function (err) {
                alert(JSON.stringify(err));
            });
        }
    }

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

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

.controller('FormFieldTypeCtrl', function ($scope, $state, $ionicHistory, global, showPopup, Daily) {
    $scope.template_field = {};
    $scope.index = $state.params['id'];
    $scope.isNew = $scope.index == -1;
    $scope.showadd = false;
    $scope.template_field.required = false;
    $scope.selecttexts = [{text: ""}];
    $scope.template_field_active = {};
    if (!$scope.isNew && Daily.templateData.items[$scope.index]) {
        $scope.template_field = Daily.templateData.items[$scope.index];
    }

    watch = $scope.$watch('template_field', function (n, o) {
        if (n == o)
            return;
        $scope.template_field.isModified = true; //TODO:check
    }, true);

    global.fetch_user().then(function () {
        Daily.templatefield.get(function (res) {
            $scope.template_fields = res.results;
            if ($scope.isNew) {
                if ($scope.template_fields.length > 1) {
                    $scope.template_field_active = $scope.template_fields[1]
                }
            } else {
                $scope.template_field_active = _.find($scope.template_fields, function (r_field) {
                    return r_field.id == $scope.template_field.daily_template_field_id;
                })
            }

            if ($scope.template_field && $scope.template_field.extra)
                $scope.selecttexts = JSON.parse($scope.template_field.extra)
        })
    });

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

    $scope.add = function () {
        $scope.selecttexts.push({text: ""});
    }

    $scope.change = function (item) {
        $scope.template_field_active = item;
    }

    $scope.ok = function () {
        if ($scope.template_field.name == '' || $scope.template_field.name == undefined) {
            showPopup.PopupWindow(0, '名称不能为空！', false);
            return;
        }

        if ($scope.template_field.showlist)
            if ($scope.selecttexts.length == 0) {
                showPopup.PopupWindow(0, '请添加选项！', false);
                return;
            } else {
                $scope.template_field.extra = $scope.selecttexts;
            }
        exists = _.find(Daily.templateData.items, function (f) {
            return f.name == $scope.template_field.name && f != $scope.template_field;
        });

        if (exists) {
            showPopup.PopupWindow(0, '名称不能重复！', false);
            return;
        }

        if ($scope.template_field_active) {
            $scope.template_field.daily_template_field_id = $scope.template_field_active.id;
            $scope.template_field.t__type = $scope.template_field_active.type;
        }

        d = _.filter($scope.selecttexts, function (item) {
            return item.text != "";
        });
        if (d.length > 0) {
            $scope.template_field.extra = JSON.stringify(d)
        }

        if ($scope.isNew) {
            $scope.template_field.daily_template_id = Daily.templateId;
            Daily.templateData.items.push($scope.template_field);
        }

        $ionicHistory.goBack();
    }

    $scope.delete = function () {
        Daily.templateData.items.splice($scope.index, 1);
        $ionicHistory.goBack();
    }

    $scope.remove = function (index) {
        $scope.selecttexts.splice(index, 1);
    }

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

.controller('CustomFormCtrl', function ($rootScope, $scope, $ionicHistory, $state, global, Daily, showPopup, Tool) {
    $scope.fieldItems = [];
    $scope.fieldItems_old = [];

    $scope.mobanitems = null;
    $scope.addmobanitems = null;
    Daily.templateId = $state.params['id'];
    $scope.isNew = Daily.templateId == -1;

    global.fetch_user().then(function (data) {
        Daily.templateitem.get({'daily_template_id': Daily.templateId}, function (res) {
            Daily.templateData.items = res.results;
            $scope.fieldItems = Daily.templateData.items;
            $scope.fieldItems_old = _.map($scope.fieldItems, _.clone);
        })
    });

    $scope.ok = function () {
        if (Daily.templateData.items.length == 0) {
            showPopup.PopupWindow(0, '请添加字段！', false);
            return;
        }
        showPopup.showLoading(1, '正在上传');
        Daily.templateData.description = Daily.get_description();
        Daily.template.update({'id': Daily.templateId, 'description': Daily.templateData.description});
        var fieldItems = _.map($scope.fieldItems, function (item) {
            return _.omit(item, 't__type');
        });
        rst = _.diff(fieldItems, $scope.fieldItems_old);
        Daily.templateitem.patch(rst, function () {
            $rootScope.commons.refresh = true;
            Tool.removeBackView('daily-templateScope');
            showPopup.hideLoading();
            $ionicHistory.goBack();
        });
    }

    $scope.cancel = function () {
        Daily.templateData.items = [];
        Tool.removeBackView('daily-templateScope');
        $ionicHistory.goBack();
    }

    $rootScope.commons.fun = $scope.cancel;

    $scope.tohref = function (item) {
        var index = _.indexOf(Daily.templateData.items, item);
        return '#/fieldtype/' + index;
    }

    $scope.preview = function () {
        Daily.previewData = {
            'daily_tfs': Daily.templateData.items
        }
        $state.go('daily-edit', {
            'flag': -1
        });
    }
})

.controller('AddItemCtrl', function ($rootScope, $scope, $state, $ionicHistory, Dept, Daily, showPopup) {
    $scope.isUp = false;
    $scope.leftbtn = [{
        text: '取消',
        click: 'cancel'
    }, {
        text: '上一层',
        click: 'up'
    }];
    $scope.index = 0;
    $scope.deptlst = [];
    $scope.emplst = [];
    $scope.selectedemplst = [];
    var deptid = 0;
    $scope.selectcount = '';
    Dept.getDep().then(function (data) {
        d = _.find(data, function (dept) {
            return dept.parent == null;
        });
        data = _.filter(data, function (item) {
            return item.level == 1;
        });
        $scope.deptlst = data;
        setdeptrighticon($scope.deptlst);
        getemp(d.id);
    });

    $scope.changedept = function (dept) {
        getdept_emp(dept.id);
    }

    $scope.change = function (emp) {
        if (emp.selected) {
            $scope.selectedemplst.push(emp);
        } else {
            $scope.selectedemplst.splice(_.indexOf($scope.selectedemplst, emp), 1);
        }
    }

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

    $scope.up = function () {
        var dept = _.find(Dept.all(), function (d) {
            return d.id == parseInt(deptid);
        });
        getdept_emp(dept.parent);
    }

    $scope.ok = function () {
        showPopup.showLoading(1, '提交中');
        var data = [];
        _.each($scope.selectedemplst, function (item) {
            data.push({'user': item.user_id, 'flag': 0, 'value': 0});
        });
        Daily.dailypermission.save(data, function () {
            $rootScope.commons.refresh = true;
            showPopup.hideLoading();
            $ionicHistory.goBack();
        });
    }

    function getdept_emp(did) {
        Dept.getEmp(did).then(function (data) {
            $scope.emplst = data;
            $scope.deptlst = Dept.getChildDept(did);
            setdeptrighticon($scope.deptlst);
            setitem();
            deptid = did;
            if (did == 1) {
                $scope.index = 0;
            } else {
                $scope.index = 1;
            }
        });
    }

    function getemp(id) {
        Dept.getEmp(id).then(function (data) {
            $scope.emplst = data;
            setitem();
        });
    }

    function setitem() {
        _.each($scope.emplst, function (e) {
            e.selected = false;
            e.disabled = false;
            _.each(Daily.permissionUsers, function (p) {
                if (p.user_id == parseInt(e.user_id)) {
                    e.disabled = true;
                    e.selected = true;
                }
            });
            _.each($scope.selectedemplst, function (e1) {
                if (e1.user_id == e.user_id) {
                    e.selected = true;
                }
            });
        });
    }

    function setdeptrighticon(deptlst) {
        _.each(deptlst, function (d) {
            d.isShow = Dept.getChildDept(d.id).length == 0 ? false : true;
        })
    }
})

.controller('DailyEditCtrl', function ($rootScope, $scope, $stateParams, $state, $ionicHistory, $q, global, ImageManage, showPopup, Daily, Tool) {
    $scope.flag = $stateParams.flag;
    $scope.change = 1;
    $scope.index = 14;
    $scope.coke = 11;
    $scope.image_list = [];
    $scope.deleteimage_list = [];
    $scope.popup = {
        isPopup: false
    };
    var isModified = false;

    $scope.changeDate = function (id) {
        $scope.index = id;
        $scope.change = 15 - id;
        $scope.closeModal();
    }

    global.fetch_user().then(function () {
        if ($scope.flag == 0) {
            Daily.templatedept.get(function (td) {
                dept = _.find(td.results, function (d) {
                    return d.dept_id == global.user.deptno;
                });
                Daily.templateitem.get({'daily_template_id': dept.daily_template_id}, function (res) {
                    Daily.templateData.items = res.results;
                    _.each(Daily.templateData.items, function (item) {
                        item.daily_template_item = item.id
                    });
                    Daily.previewData = {
                        'daily_tfs': res.results
                    };
                    $scope.item = Daily.previewData;
                    $scope.item.files = [];
                })
            });
            $scope.newDate = Daily.getDate();
        } else if ($scope.flag == -1) {
            $scope.item = Daily.previewData;
            $scope.item.files = [];
            $scope.newDate = Daily.getDate();
        } else {
            $scope.item = Tool.cloneObj(Daily.daily);
        }
    });

    $scope.goBack = function () {
        if ($scope.flag == 0) {
            back = _.find($scope.item.daily_tfs, function (item) {
                return item.text !== undefined && item.text != '';
            });
            showConfirm(isModified, '是否退出写日报?');
        } else if ($scope.flag > 0) {
            showConfirm(isModified, '是否放弃当前编辑?');
        } else {
            $ionicHistory.goBack();
        }
    }

    $scope.addDaily = function () {
        if (Daily.checkDaily($scope.item.daily_tfs)) {
            showPopup.showLoading(1, '正在提交');
            if ($scope.flag == 0) {
                date = $scope.newDate[$scope.change].day;
                Daily.dailymf.save({'daily_dd': date}, function (res) {
                    var id = res.id;
                    data = _.map($scope.item.daily_tfs, function (it) {
                        return _.extend(_.pick(it, 'text', 'daily_template_item'), {'daily_mf': id});
                    });
                    Daily.dailytf.save(data, function (res) {
                        $rootScope.commons.refresh = true;
                        var imagefiles = [];
                        _.each($scope.item.files, function (image) {
                            if (!image.id)
                                imagefiles.push(image.file_full_path);
                        });
                        if (imagefiles.length > 0) {
                            postimg(imagefiles, id);
                        } else {
                            showPopup.hideLoading();
                            $ionicHistory.goBack();
                        }
                    });
                });
            } else if ($scope.flag > 0) {
                if (isModified) {
                    data = _.map($scope.item.daily_tfs, function (it) {
                        return _.pick(it, 'id', 'text', 'daily_template_item', 'daily_mf')
                    });
                    Daily.dailytf.update(data, function (res) {
                        $rootScope.commons.refresh = true;
                        _.each($scope.deleteimage_list, function (file) {
                            Daily.dailyfile.delete({id: file});
                        });
                        var imagefiles = [];
                        _.each($scope.item.files, function (image) {
                            if (!image.id)
                                imagefiles.push(image.file_full_path);
                        });
                        if (imagefiles.length > 0) {
                            postimg(imagefiles, $scope.flag);
                        } else {
                            showPopup.hideLoading();
                            $ionicHistory.goBack();
                        }
                    });
                } else {
                    showPopup.hideLoading();
                    $ionicHistory.goBack();
                }
            } else {
                showPopup.hideLoading();
                $ionicHistory.goBack();
            }
        }
    }

    showPopup.modalTemplate('templates/modal-selectDate.html', 'slide-in-right', $scope).then(function (modal) {
        $scope.select_date_modal = modal;
    });

    $scope.showModal = function () {
        $scope.select_date_modal.show();
        $rootScope.commons.modal = $scope.select_date_modal;
    }

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

    $scope.shouBigImage = function (imageName) { //传递一个参数（图片的URl）
        $scope.Url = imageName; //$scope定义一个变量Url，这里会在大图出现后再次点击隐藏大图使用
        $rootScope.commons.bigImage = true; //显示大图
    }

    $rootScope.commons.bigImage = false; //初始默认大图是隐藏的
    $scope.hideBigImage = function () {
        $rootScope.commons.bigImage = false;
    }

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

    $scope.addphoto = function () {
        $scope.popup.optionsPopup = showPopup.showSelectImgPopup(Camera, ImagePicker, $scope);
        $scope.popup.isPopup = true;
    }

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

    $scope.$on("$destroy", function () {
        if ($rootScope.commons.modal)
            $rootScope.commons.modal = null;
        $scope.select_date_modal.remove();
        if ($scope.flag > 0) {
            watch();
        }
    });

    function ImagePicker() { //打开相册
        $scope.popup.optionsPopup.close();
        ImageManage.ImagePicker_getPictures(10).then(function (data) {
            _.each(data, function (imageUrl) {
                $scope.item.files.push({
                    "file_thumbnail_path": imageUrl,
                    "file_full_path": imageUrl
                });
            });
        });
    }

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

    function postimg(imgfiles, id) {
        ImageManage.uploadImage(imgfiles, 'daily', id, 'dailyfile').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');
        })
    }

    function showConfirm(flag, content) {
        if (flag) {
            showPopup.confirm(content, '是', '否').then(function (res) {
                if (res)
                    $ionicHistory.goBack();
            });
        } else {
            $ionicHistory.goBack();
        }
    }
})

.controller('DailyReadMonthCountCtrl', function ($rootScope, $scope, $state, global, Daily, showPopup) {
    var daily_dd = $state.params['daily_dd'];
    var date = new Date(daily_dd);
    $scope.year = date.getFullYear();
    $scope.month = date.getMonth() + 1;

    global.fetch_user().then(function () {
        if (global.user.token != "") {
            Daily.mouthsummary.get({'daily_dd': daily_dd}, function (res) {
                $scope.monthView = res;
            }, function (err) {
                alert(JSON.stringify(err));
            });
            Daily.dailydeptview.query(function (res) {
                $scope.index = res[0].id;
                if (res[0].id == 1 && res[0].parent == null)
                    res[0].depname = '全体成员';
                $scope.depts = res;
            })
        }
    });

    $scope.changeindex = function (dept) {
        $scope.index = dept.id;
        var data = {'dept': dept.id, 'daily_dd': daily_dd};
        if (dept.parent == null)
            data = _.omit(data, 'dept');
        Daily.mouthsummary.get(data, function (res) {
            $scope.monthView = res;
            $scope.closeModal();
        })
    }

    showPopup.modalTemplate('templates/modal-selectdept.html', 'slide-in-right', $scope).then(function (modal) {
        $scope.select_dept_modal = modal;
    });

    $scope.showModal = function () {
        $scope.select_dept_modal.show();
        $rootScope.commons.modal = $scope.select_dept_modal;
    }

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

    $scope.$on("$destroy", function () {
        if ($rootScope.commons.modal)
            $rootScope.commons.moda = null;
        $scope.select_dept_modal.remove();
    })
})

.controller('DailyReadDayCtrl', function ($rootScope, $scope, $state, global, Daily, Tool) {
    var daily_dd = $state.params['daily_dd'];
    var date = new Date(daily_dd);
    $scope.month = date.getMonth() + 1;
    $scope.day = date.getDate();

    global.fetch_user().then(function () {
        getdailydata();
    });

    $scope.totransfer = function (id) {
        $state.go('transfer', {
            module: 'daily',
            id: id
        });
    }

    $scope.lookCount = function () {
        $state.go('daily-readDayCount', {
            'daily_dd': daily_dd
        });
    }

    $scope.shouBigImage = function (imageName, event) { //传递一个参数（图片的URl）
        $scope.Url = imageName; //$scope定义一个变量Url，这里会在大图出现后再次点击隐藏大图使用
        $rootScope.commons.bigImage = true; //显示大图
        event.stopPropagation();
    }

    $rootScope.commons.bigImage = false; //初始默认大图是隐藏的
    $scope.hideBigImage = function () {
        $rootScope.commons.bigImage = false;
    }

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

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

    $scope.moreCanBeLoaded = function () {
        return $scope.dailys != undefined && $scope.dailys.next != null ? true : false;
    }

    function getdailydata() {
        if (global.user.token != "") {
            if ($scope.dailys == undefined) {
                $scope.loading = true;
            }
            Daily.dailyview.get({'daily_dd': daily_dd}, function (res) {
                $scope.dailys = res;
            }, function (err) {
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }
})

.controller('DailyReadDayCountCtrl', function ($scope, $state, global, Daily) {
    var daily_dd = $state.params['daily_dd'];
    var date = new Date(daily_dd);
    $scope.year = date.getFullYear();
    $scope.month = date.getMonth() + 1;
    $scope.day = date.getDate();

    global.fetch_user().then(function () {
        if (global.user.token != "") {
            Daily.todaysummary.get({'daily_dd': daily_dd}, function (res) {
                console.log(res);
                $scope.toDayView = res;
            }, function (err) {
                alert(JSON.stringify(err));
            });
        }
    });

    $scope.lookDeptCount = function (flag, users, dept, isSubmit) {
        if (isSubmit != 0) {
            Daily.toDayViewUsers = users;
            $state.go('daily-readDayDeptCount', {
                'flag': flag,
                'daily_dd': daily_dd,
                'dept': dept
            });
        }
    }
})

.controller('DailyReadDayDeptCountCtrl', function ($scope, $state, Daily) {
    var daily_dd = $state.params['daily_dd'];
    $scope.flag = $state.params['flag'];
    $scope.dept = $state.params['dept'];
    var date = new Date(daily_dd);
    $scope.year = date.getFullYear();
    $scope.month = date.getMonth() + 1;
    $scope.day = date.getDate();

    $scope.users = Daily.toDayViewUsers;
});
