starter.controller('TaskCtrl', function ($rootScope, $scope, $state, _, global, Task) {
    $scope.nexturl = null;
    $scope.goBack = function () {
        global.goBack();
    };

    $scope.toadd = function () {
        $state.go('task-create');
    };

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

    $scope.todetails = function (item) {
        $state.go('task-details', {
            id: item.id
        });
    };

    $scope.totansfer = function () {
        $state.go('transfer');
    };

    $scope.loadMore = function () {
        if ($scope.nexturl != null) {
            gettaskdata();
        }
    };

    function gettaskdata() {
        if (global.user.token != "") {
            Task.task($scope.nexturl).get({'type': 'received'}, function (res) {
                var olddata = [];
                if ($scope.nexturl != null) {
                    olddata = _.map($scope.Task, _.clone);
                }
                $scope.nexturl = res.next;
                res.results = _.sortBy(res.results, 'create_date').reverse();
                res.results = _.sortBy(res.results, 'is_completed');
                $scope.Task = res.results;
                $scope.Task = olddata.concat($scope.Task);
            }, function (err) {
                $scope.loading = false;
                $scope.$broadcast('scroll.infiniteScrollComplete');
                alert(JSON.stringify(err));
            }).$promise.finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.loading = false;
            });
        }
    }

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        if ($scope.Task == undefined) $scope.loading = true;
        global.fetch_user().then(function () {
            gettaskdata();
            $scope.roleid = global.user.roleid;
        }, function (err) {
            alert(JSON.stringify(err));
            $scope.loading = false;
        });
    });

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

.controller('TaskManCtrl', function ($rootScope, $scope, $ionicModal, Task, global) {
    var modal = $ionicModal.fromTemplateUrl('templates/taskruleset-modal.html', {
        scope: $scope,
        animation: 'slide-in-right'
    });

    var old_data = null;
    $scope.openModal = function () {
        modal.then(function (m) {
            $rootScope.commons.modal = m;
            $rootScope.commons.modal.show();
            $scope.itemdata = _.clone(old_data);
        })
    };

    $scope.init = function () {
        global.fetch_user().then(function (data) {
            Task.taskpreferences.get({'key': 'task_rule'}, function (data) {
                old_data = _.clone(data);
            }, function (err) {
                old_data = {'key': 'task_rule', 'value': 1};
            }).$promise.finally(function () {
                $scope.itemdata = _.clone(old_data);
            });
        });
    };

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

    $scope.$on('$destroy', function () {
        $rootScope.commons.modal.remove();
    });

    $scope.ok = function () {
        $scope.closeModal();
        if (old_data.value == $scope.itemdata.value)
            return;
        Task.taskpreferences.save($scope.itemdata, function (data) {
            old_data = _.clone(data);
            $scope.itemdata = _.clone(old_data);
        });
    };
})

.controller('PostedTaskCtrl', function ($rootScope, $scope, $state, $ionicHistory, $ionicScrollDelegate, Task, Member, global) {
    $scope.nexturl = null;
    var taskall = [];
    $scope.totalcount = 0;
    $scope.Ishidded = true;
    $scope.headerion = {
        leftion: true,
        rightion: true
    };
    $scope.leftdata = [{
        id: 0,
        name: '最新发布',
        check: true,
        key: 'create_date'
    }, {
        id: 1,
        name: '最近更新',
        check: false,
        key: 'last_modified'
    }, {
        id: 2,
        name: '截止时间',
        check: false,
        key: 'end_dd'
    }];
    $scope.rightdata = [{
        id: 0,
        name: '全部成员',
        check: true,
        key: ''
    }, {
        id: 1,
        name: '选择单个成员',
        check: false
    }];
    $scope.title = [{
        id: 0,
        name: '最新发布'
    }, {
        id: 1,
        name: '全部成员'
    }];

    var beforeenter = $scope.$on('$ionicView.beforeEnter', function () {
        $rootScope.goBackRoute = 'postedtask';
        if ($scope.Task == undefined) $scope.loading = true;
        global.fetch_user().then(function () {
            if (Member.selectedemplst.length > 0) {
                $scope.rightdata[1].name = '选择单个成员(' + Member.selectedemplst[0].username + ')';
                $scope.title[1].name = Member.selectedemplst[0].username;
                getdata(Member.selectedemplst[0].user_id);
                Member.selectedemplst = [];
            } else {
                //打开的selecetmemer 页面但是点了取消
                if ($scope.rightdata[1].name.length > 6) {
                    setrightcheck(false, true);
                } else {
                    setrightcheck(true, false);
                    getdata();
                }
            }
        });
    });

    $scope.leftdisplay = function () {
        setdisplay('rightion', 'leftion');
    };
    $scope.rightdisplay = function () {
        setdisplay('leftion', 'rightion');
    };

    $scope.toadd = function () {
        $state.go('task-create');
    };

    $scope.backhide = function () {
        $scope.headerion = {
            leftion: true,
            rightion: true
        };
        $scope.Ishidded = !$scope.Ishidded;
    };

    $scope.change = function (op, item) {
        if (op == 'f') {
            if ($scope.title[0].name != item.name) {
                $scope.title[0].name = item.name;
                $scope.Task = _.sortBy($scope.Task, item.key).reverse();
                $scope.Task = _.sortBy($scope.Task, 'is_completed');
                $scope.rightdata[0].key = item.key;
            }
        } else {
            if ($scope.rightdata[1].id == item.id) {
                setrightcheck(false, true);
                Member.titlename = "选择单个成员";
                Member.routename = 'postedtask';
                Member.selectedemplst = [];
                $state.go('selectsinglemember');
            } else {
                $scope.nexturl = null;
                getdata();//all
                $scope.title[1].name = "全部成员";
                $scope.rightdata[1].name = '选择单个成员';
                setrightcheck(true, false);
            }
        }
        $scope.backhide();
    };

    $scope.todetails = function (item) {
        $state.go('task-details', {
            id: item.id
        });
    };

    $scope.loadMore = function () {
        if ($scope.nexturl != null) getdata();
    };

    function setrightcheck(allcheck, singlecheck) {
        $scope.rightdata[0].check = allcheck;
        $scope.rightdata[1].check = singlecheck;
    }

    function getdata(usrid) {
        var data = {'type': 'posted'};
        if (usrid != undefined)
            data.usrid = usrid;
        Task.task($scope.nexturl).get(data, function (res) {
            $scope.totalcount = res.count;
            var olddata = [];
            if ($scope.nexturl != null) {
                olddata = _.map($scope.Task, _.clone);
            }
            $scope.nexturl = res.next;
            $scope.Task = _.sortBy(res.results, 'is_completed');
            $scope.Task = olddata.concat($scope.Task);
            $scope.loading = false;
        }, function (err) {
            console.log(err);
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }).$promise.finally(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
            $ionicScrollDelegate.resize();
            $scope.loading = false;
        });
    }

    function setdisplay(key1, key2) {
        // $scope.headerion[key1] = $scope.headerion[key1] ? true : false;
        if (!$scope.Ishidded) {
            $scope.headerion[key1] = !$scope.headerion[key1];
        } else {
            $scope.Ishidded = !$scope.Ishidded;
        }

        if (!$scope.headerion[key2] && !$scope.Ishidded) {
            $scope.backhide();
        } else {
            $scope.headerion[key2] = !$scope.headerion[key2];
        }
    }

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

.controller('TaskCreateCtrl', function ($rootScope, $scope, $state, $ionicHistory, $ionicPopup,
                                        $cordovaDatePicker, $timeout, $q, _, Task, Member, showPopup, ImageManage, Tool, formatFilter) {
    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        $scope.popup = {
            isPopup: false
        };
        if (Member.selectedemplst.length > 0) {
            _.each(Member.selectedemplst, function (item) {
                item.is_leader = 'F';
                $scope.task.task_members.push(item);
            });
            Member.selectedemplst = [];
        } else {
            if (!$scope.task) {
                init_task();
            }
        }
    });

    $scope.goback = function () {
        if ($scope.task.content != null && $scope.task.content != '' || $scope.task.task_members.length > 0) {
            showPopup.confirm('是否取消创建?', '是', '否').then(function (res) {
                if (res) {
                    $ionicHistory.goBack()
                }
            })
        } else {
            $ionicHistory.goBack();
        }
    };

    $scope.selectmember = function () {
        $scope.isremove = false;
        Member.titlename = '选择任务成员';
        Member.routename = '';
        Member.resourcemember = $scope.task.task_members;
        $state.go('selectmember');
    };

    $scope.remove = function (user, index) {
        $scope.task.task_members.splice(index, 1);
        if ($scope.task.task_members.length == 0) $scope.isremove = false;
    };

    $scope.isremove = false;
    $scope.changeRemove = function (flag) {
        $scope.isremove = !flag;
    };

    $scope.showModal = function () {
        showPopup.modalTemplate('templates/modal-selectadmin.html', 'slide-in-right', $scope).then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        });
    };

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

    $scope.changeAdmin = function (item, index) {
        $scope.isremove = false;
        $scope.closeModal();
        $scope.task.task_members.splice(index, 1);
        $scope.task.task_members.splice(0, 0, item);
    };

    $scope.addTask = function () {
        if (Task.check($scope.task)) {
            showPopup.showLoading(1, '正在提交', true, $scope.image_list.length > 0 ? 20000 : 10000);
            var task = Tool.cloneObj($scope.task);
            task.leader = task.task_members[0].user_id;
            task.task_members[0].is_leader = 'T';
            task.task_members = _.map(task.task_members, function (m) {
                return {'user': m.user_id, 'is_leader': m.is_leader}
            });
            Task.task(null).save(task, function (data) {
                if ($scope.image_list.length == 0) {
                    showPopup.hideLoading();
                    godetail(data.id);
                    init_task();
                    return;
                }
                ImageManage.uploadImage($scope.image_list, 'task', data.id, 'taskfile').then(function (res) {
                    $q.all(res).then(function (res1) {
                        showPopup.hideLoading();
                        godetail(data.id);
                        init_task();
                    }, function (err) {
                        showPopup.hideLoading();
                        alert(JSON.stringify(err));
                    });
                }, function (err) {
                    showPopup.hideLoading();
                    showPopup.PopupWindow(1, 'get upload token fail!');
                });
            }, function (err) {
                console.log(err);
                showPopup.hideLoading()
            });
        }
    };

    var flag = true;
    $scope.chooseDate = function () {
        if (flag) {
            flag = false;
            var options = {
                mode: 'date',
                date: $scope.task.end_dd == null ? new Date() : $scope.task.end_dd,
                androidTheme: 3
            };
            $cordovaDatePicker.show(options).then(function (date) {
                if (date == undefined) return;
                $scope.task.end_dd = date;
                flag = true;
            }, function (cancel) {
                flag = true;
            });
        }
    };

    $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 () {
        $scope.image_list.splice(_.indexOf($scope.image_list, $scope.Url), 1);
        $rootScope.commons.bigImage = false;
    };

    $scope.image_list = [];
    $scope.addphoto = function () {
        if ($scope.image_list.length == $rootScope.commons.upload_maxcount) {
            showPopup.PopupWindow(0, formatFilter('最多可上传{0}张！', $rootScope.commons.upload_maxcount), false);
            return;
        }
        $scope.popup.optionsPopup = showPopup.showSelectImgPopup(Camera, ImagePicker, $scope);
        $scope.popup.isPopup = true;
    };

    var ImagePicker = function () { //打开相册
        $scope.popup.optionsPopup.close();
        ImageManage.ImagePicker_getPictures($rootScope.commons.upload_maxcount - $scope.image_list.length).then(function (promises) {
            $q.all(promises).then(function (res) {
                $scope.image_list = $scope.image_list.concat(res);
            }, function (error) {
                alert(error);
            });
        });
    };

    var Camera = function () {
        $scope.popup.optionsPopup.close();
        ImageManage.Camera_getPicture().then(function (result) {
            $scope.image_list.push(result);
        });
    };

    function godetail(id) {
        $ionicHistory.goBack();
        $timeout(function () {
            $state.go('task-details', {
                id: id
            })
        });
        Member.resourcemember = [];
    }

    function init_task() {
        $scope.task = {
            content: null,
            end_dd: null,
            create_date: null,
            is_completed: 0,
            task_members: []
        };
        $scope.image_list = [];
    }

    $scope.$on("$destroy", function () {
        beforeEnter = null;
        if ($rootScope.commons.modal != null) $rootScope.commons.modal.remove();
        Member.resourcemember = [];
    })
})

.controller('TaskDetailsCtrl', function ($rootScope, $scope, $state, $stateParams, $ionicSlideBoxDelegate,
                                         $ionicPopup, $ionicScrollDelegate, $timeout, $cordovaDatePicker, $ionicHistory, $q, showPopup, global, ImageManage, Member, Tool, Task, formatFilter) {
    $scope.activeIndex = 0;
    $scope.change = function (index) {
        $scope.activeIndex = index;
    };

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

    $scope.taskcomments = [];
    $scope.taskhistory = [];
    $scope.childtask = init_childtask();
    $scope.postcommentdata = init_comment();
    $scope.data = {};
    $scope.childtasks = [];
    $scope.lockSlide = function () {
        $ionicSlideBoxDelegate.enableSlide(false);
    };

    var beforeenter = $scope.$on('$ionicView.beforeEnter', function () {
        if ($scope.task == undefined) $scope.loading = true;
        global.fetch_user().then(function () {
            getTaskDetails();
            getTaskComments();
            gettaskhistory();
        }, function (err) {
            alert(JSON.stringify(err));
        });
        $scope.popup = {
            isPopup: false
        };
    });

    $scope.deletecomment = function (comment, index) {
        if (comment.create_user.id == global.user.usrid) {
            $scope.popup.optionsPopup = $ionicPopup.show({
                template: '<div class="center customer-op" rj-close-back-drop><h4>用户操作</h4></div>',
                scope: $scope,
                buttons: [{
                    text: '删除',
                    type: 'button-positive',
                    onTap: function (e) {
                        $scope.taskcomments.splice(index, 1);
                        Task.taskcomment(null).delete({'id': comment.id}, function (res) {

                        });
                    }
                }]
            });
            $scope.popup.isPopup = true;
        }
    };

    $scope.closeModal = function (op) {
        if (op == 'select') {//选择负责人
            $rootScope.commons.modal.hide();
            return;
        }
        showPopup.confirm('是否取消创建?', '是', '否').then(function (res) {
            if (res) {
                $rootScope.commons.modal.hide();
            }
        });
    };

    // Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function () {
        beforeenter = null;
        if ($rootScope.commons.modal != null) $rootScope.commons.modal.remove();
    });

    //子任务复选框
    $scope.changecheck = function (childtask) {
        childtask.parent = $scope.task.id;
        marktask(childtask, childtask.is_completed);
    };

    $scope.tocomment = function () {
        $scope.postcommentdata = init_comment();
        $scope.image_list = [];
        $rootScope.commons.bigImage = false;
        showPopup.modalTemplate('templates/modal-taskcomment.html', 'slide-in-up', $scope).then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        })
    };

    var addchildmodal = null;
    $scope.toaddchildtask = function () {
        $scope.childtask = init_childtask();
        showPopup.modalTemplate('templates/modal-addchildtask.html', 'slide-in-up', $scope).then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
            addchildmodal = _.clone(modal);
        });
    };

    $scope.addchildtask = function () {
        if (Tool.trim($scope.childtask.content).length == 0) {
            showPopup.PopupWindow(0, '请输入任务内容！', false);
            return;
        }
        showPopup.showLoading(1, '正在提交', true);
        var leader = $scope.childtask.leader;
        if ($scope.childtask.leader != null) {
            $scope.childtask.leader = $scope.childtask.leader.id;
        }
        Task.task(null).save($scope.childtask, function (data) {
            showPopup.hideLoading();
            data.leader = leader;
            $scope.childtasks.splice(0, 0, data);
            $scope.nexturl.history = null;
            gettaskhistory();
            $rootScope.commons.modal.hide();
        }, function (error) {
            showPopup.hideLoading();
            alert("add childtask error:" + JSON.stringify(error));
        });
    };

    var flag_end_dd = true;
    $scope.checkend_dd = function () {
        if (flag_end_dd) {
            flag_end_dd = false;
            var options = {
                mode: 'date',
                date: new Date($scope.childtask.end_dd == null ? new Date() : $scope.childtask.end_dd),
                androidTheme: 3
            };
            $cordovaDatePicker.show(options).then(function (date) {
                $timeout(function () {
                    if (date == undefined) return;
                    $scope.childtask.end_dd = date;
                });
                flag_end_dd = true;
            });
        }
    };

    $scope.setTask = function () {
        Task.taskdetail = $scope.task;
        Task.taskdetail.childtasks = $scope.childtasks;
        Member.selectedemplst = [];
        $state.go('task-set', {
            id: $stateParams.id,
            isheader: $scope.Isheader ? 1 : 0
        });
    };

    $scope.postcomment = function () {
        if ($scope.postcommentdata.content == '') {
            showPopup.PopupWindow(0, '请输入评论内容！', false);
            return;
        }
        showPopup.showLoading(1, '正在提交', true, $scope.image_list.length > 0 ? 20000 : 10000);
        Task.taskcomment(null).save({'task_id': $stateParams.id}, $scope.postcommentdata, function (data) {
            $scope.taskcomments.splice(0, 0, data);
            if ($scope.image_list.length == 0) {
                showPopup.hideLoading();
                $rootScope.commons.modal.hide();
                return;
            }
            ImageManage.uploadImage($scope.image_list, 'task', data.id, 'taskcommentfile').then(function (res) {
                $q.all(res).then(function (res1) {
                    data.task_comment_files = _.sortBy(_.map(res1, function (item) {
                        return JSON.parse(item.response);
                    }), 'id');
                    showPopup.hideLoading();
                    $rootScope.commons.modal.hide();
                })
            }, function (err) {
                alert('upload image error' + err);
                showPopup.hideLoading();
            });
        }, function (err) {
            alert('commnet fail!');
        });
    };

    $scope.toeditchildtask = function (id) {
        if (($scope.data.leader.id == global.user.usrid) || ($scope.data.create_user.id == global.user.usrid)) {
            Task.taskdetail = $scope.task;
            Task.taskdetail.childtasks = $scope.childtasks;
            $state.go('editchildtask', {
                'id': id
            });
        }
    };

    $scope.checkheader = function () {
        showPopup.modalTemplate('templates/modal-selectadmin.html', 'slide-in-right', $scope).then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        });
    };

//标记任务完成或未完成
    $scope.marktask = function (completeid) {
        if (completeid == 1) {
            if (_.findWhere($scope.childtasks, {is_completed: false}) == undefined) {
                marktask($scope.data, completeid);
                return;
            }
            showPopup.confirm('还有未完成的子任务,确定要完成吗?', '确定', '取消').then(function (res) {
                if (res) {
                    marktask($scope.data, completeid);
                }
            });
        } else {
            marktask($scope.data, completeid);
        }
    };

    $scope.changeAdmin = function (user) {
        $scope.childtask.leader = user.user;
        $rootScope.commons.modal.hide();
        $rootScope.commons.modal = addchildmodal;
    };
    $scope.image_list = [];
    $scope.imagePicker = function () { //打开相册
        if (!check_image()) return;
        ImageManage.ImagePicker_getPictures($rootScope.commons.upload_maxcount).then(function (data) {
            $scope.image_list = $scope.image_list.concat(data);
        });
    };
    $scope.Camera = function () {
        if (!check_image()) return;
        ImageManage.Camera_getPicture().then(function (result) {
            $scope.image_list.push(result);
        });
    };
    $scope.shouBigImage = function (imageName, event) { //传递一个参数（图片的URl）
        if (event != undefined) {
            event.stopPropagation();
        }
        $scope.Url = imageName;
        $rootScope.commons.bigImage = true;
    };

    $scope.stopPropagation = function (event) {
        if (event != undefined) {
            event.stopPropagation();
        }
    }

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

    $scope.deleteimage = function () {
        $scope.image_list.splice(_.indexOf($scope.image_list, $scope.Url), 1);
        $rootScope.commons.bigImage = false;
    };

    $scope.nexturl = {'comment': null, 'history': null};
    $scope.loadMore = function (type) {
        if (type == 'history') {
            gettaskhistory();
        } else {
            getTaskComments();
        }
    };

    function check_image() {
        if ($scope.image_list.length >= 10) {
            showPopup.PopupWindow(0, formatFilter('最多可上传{0}张', $rootScope.commons.upload_maxcount), false);
            return false
        }
        return true;
    }

    function getTaskDetails() {
        Task.task(null).get({'id': $stateParams.id}, function (data) {
            $scope.data = Tool.cloneObj(data);
            var members = _.filter(data.task_members, function (item) {
                return data.leader.id != item.user.id;
            });
            data.membernames = _.map(members, function (m) {
                if (data.leader.id != m.user.id) return m.user.username;
            }).join('、');
            $scope.task = data;
            $scope.Isheader = ($scope.task.create_user.id == global.user.usrid);
            if ((data.create_user.id == global.user.usrid) || (data.leader.id == global.user.usrid)) {
                $scope.is_disabledmark = false;
            } else {
                Task.taskpreferences.get({'key': 'task_rule'}, function (data) {
                    $scope.is_disabledmark = Boolean(data.value);
                });
            }
        }, function (err) {
            console.log(err)
        }).$promise.finally(function (res) {
            $scope.loading = false;
        });
        //get child task
        Task.taskchild.get({'id': $stateParams.id}, function (res) {
            $scope.childtasks = _.sortBy(res.results, 'is_completed');
        })
    }

    function marktask(data, is_completed) {
        var task = Tool.cloneObj(data);
        task.leader = task.leader.id;
        task = _.omit(task, 'create_user', 'childtasks', 'task_files');
        task.task_members = _.map(task.task_members, function (item) {
            return {'is_leader': item.is_leader, 'user': item.user.id};
        });
        task.is_completed = is_completed;
        showPopup.showLoading(1, '', false);
        Task.task(null).update({'id': task.id}, task, function (data) {
            $scope.nexturl.history = null;
            gettaskhistory();
            $scope.childtasks = _.sortBy($scope.childtasks, 'is_completed');
            if (data.parent == null) $scope.task.is_completed = is_completed;
        }, function (err) {
            showPopup.PopupWindow(0, 'mark task fail!', false);
        }).$promise.finally(function (res) {
            showPopup.hideLoading();
        })
    }

    function init_childtask() {
        var childtask = {
            content: '',
            end_dd: null,
            is_completed: 0,
            leader: null,
            parent: parseInt($stateParams.id),
            task_members: []
        };
        return childtask;
    }

    function init_comment() {
        return {"content": ''};
    }

    function getTaskComments() {
        Task.taskcomment($scope.nexturl.comment).get({'task_id': $stateParams.id}, function (res) {
            if ($scope.nexturl.comment != null)
                $scope.taskcomments = $scope.taskcomments.concat(res.results);
            else
                $scope.taskcomments = res.results;
            $scope.nexturl.comment = res.next;
        }).$promise.finally(function (f) {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    }

    function gettaskhistory() {
        Task.taskhistory($scope.nexturl.history).get({'task_id': $stateParams.id}, function (res) {
            if ($scope.nexturl.history != null)
                $scope.taskhistory = $scope.taskhistory.concat(res.results);
            else
                $scope.taskhistory = res.results;
            $scope.nexturl.history = res.next;
        }).$promise.finally(function (f) {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    }
})

.controller('TaskSetCtrl', function ($rootScope, $scope, $state, $cordovaDatePicker, $ionicHistory,
                                     $timeout, $q, _, global, showPopup, Task, Member, ImageManage, Tool, formatFilter) {
    var id = $state.params['id'];
    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        $scope.popup = {
            isPopup: false,
            isSetPopup: false
        };
        if (Member.selectedemplst.length > 0) {
            _.each(Member.selectedemplst, function (item) {
                item.is_leader = 'F';
                $scope.task.task_members.push(item)
            });
            Member.selectedemplst = [];
            update_task();
        } else {
            $scope.task = Tool.cloneObj(Task.taskdetail);
            $scope.user = global.user;
            $scope.task.task_members = _.sortBy(_.map($scope.task.task_members, function (item) {
                return {'user_id': item.user.id, 'username': item.user.username, 'is_leader': item.is_leader};
            }), 'is_leader').reverse();
            $scope.contentdata = $scope.task.content;
        }
        //获取是否为发布人
        $scope.Isheader = Boolean($state.params['isheader']);
    });

    $scope.showModal = function (type) {
        $scope.isremove = false;
        var templateurl = type == 'select' ? 'templates/modal-selectadmin.html' : 'templates/modal-content.html';
        showPopup.modalTemplate(templateurl, 'slide-in-right', $scope).then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
            if (type == "content") $rootScope.commons.fun = clear_change;
        })
    };

    $scope.closeModal = function (type, flag) {
        $rootScope.commons.fun = null;
        $rootScope.commons.modal.hide();
        if (flag) clear_change();
    };

    function clear_change() {
        $scope.task.content = Task.taskdetail.content;
        $scope.task.task_files = Tool.cloneObj(Task.taskdetail.task_files);
        $scope.image_list = [];
        if ($rootScope.commons.bigImage) {
            $rootScope.commons.bigImage = false;
        } else {
            $rootScope.commons.modal.hide();
            $rootScope.commons.modal = null;
        }
    }

    $scope.selectmember = function () {
        $scope.isremove = false;
        Member.resourcemember = $scope.task.task_members;
        Member.routename = '';
        Member.titlename = '选择任务成员';
        $state.go('selectmember');
    };

    $scope.remove = function (_user, index) {
        if ($scope.task.task_members.length == 1) {
            showPopup.PopupWindow(0, '负责人不能为空', false);
            $scope.isremove = false;
            return;
        }
        $scope.task.task_members.splice(index, 1);
        update_task();
    };

    $scope.isremove = false;
    $scope.changeRemove = function (flag) {
        $scope.isremove = !flag;
    };

    $scope.changeAdmin = function (_user, index) {
        $scope.isremove = false;
        $scope.task.task_members.splice(index, 1);
        $scope.task.task_members.splice(0, 0, _user);
        _.each($scope.task.task_members, function (item) {
            item.is_leader = 'F';
        });
        _user.is_leader = 'T';
        $scope.task.leader.id = _user.user_id;
        update_task();
    };

    $scope.updatecontent = function () {
        if ($scope.image_list.length > 0) {
            showPopup.showLoading(1, '', false, 20000);
            ImageManage.uploadImage($scope.image_list, 'task', $scope.task.id, 'taskfile').then(function (res) {
                $q.all(res).then(function (res1) {
                    $scope.image_list = [];
                    $scope.task.task_files = _.sortBy($scope.task.task_files.concat(_.map(res1, function (item) {
                        return JSON.parse(item.response);
                    })), 'id');
                });
                update_task();
            })
        } else {
            update_task();
        }
        $rootScope.commons.fun = null;
    };

    var flag = true;
    $scope.chooseDate = function () {
        if (flag) {
            flag = false;
            var options = {
                mode: 'date',
                date: $scope.task.end_dd == null ? new Date() : new Date($scope.task.end_dd),
                androidTheme: 3
            };
            $cordovaDatePicker.show(options).then(function (date) {
                if (date == undefined) return;
                $scope.task.end_dd = date;
                update_task();
                flag = true;
            }, function (cancel) {
                flag = true;
            });
        }
    };

    $scope.deleteTask = function () {
        if ($scope.Isheader) {
            $scope.popup.isPopup = true;
            showPopup.confirm('是否删除该任务?', '是', '否').then(function (res) {
                if (res) {
                    showPopup.showLoading(1, '', false);
                    Task.task(null).delete({'id': $scope.task.id}, function (data) {
                        $ionicHistory.goBack(-2);
                    }, function (err) {
                        showPopup.PopupWindow(0, 'delete task fail!', false);
                    }).$promise.finally(function (f) {
                        showPopup.hideLoading();
                    });
                }
            })
        } else {
            //任务成员退出任务
            $scope.task.task_members.splice(_.findIndex($scope.task.task_members, {'user_id': global.user.usrid}), 1);
            update_task();
            $ionicHistory.goBack(-2);
        }
    };

    $scope.image_list = [];
    $scope.del_image_list = [];
    $scope.shouBigImage = function (imageName) {
        $scope.Url = imageName;
        $rootScope.commons.bigImage = true;
    };

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

    $scope.deleteimage = function () {
        if (_.indexOf($scope.image_list, $scope.Url) >= 0) {
            $scope.image_list.splice(_.indexOf($scope.image_list, $scope.Url), 1);
        } else {
            var index = _.findIndex($scope.task.task_files, {'file_full_path': $scope.Url});
            $scope.del_image_list.push($scope.task.task_files[index].id);
            $scope.task.task_files.splice(index, 1);
        }
        $rootScope.commons.bigImage = false;
    };

    $scope.addphoto = function () {
        if (($scope.image_list.length + $scope.task.task_files.length) == $rootScope.commons.upload_maxcount) {
            showPopup.PopupWindow(0, formatFilter('最多可上传{0}张！', $rootScope.commons.upload_maxcount), false);
            return;
        }
        $scope.popup.optionsPopup = showPopup.showSelectImgPopup(Camera, ImagePicker, $scope);
        $scope.popup.isSetPopup = true;
    };

    function ImagePicker() { //打开相册
        $scope.popup.optionsPopup.close();
        ImageManage.ImagePicker_getPictures($rootScope.commons.upload_maxcount - ($scope.image_list.length + $scope.task.task_files.length)).then(function (data) {
            if (data.length == 0) return;
            $scope.image_list = $scope.image_list.concat(data);
        });
    }

    function Camera() {
        $scope.popup.optionsPopup.close();
        ImageManage.Camera_getPicture().then(function (result) {
            $scope.image_list.push(result);
        });
    }

    function update_task() {
        var task = Tool.cloneObj($scope.task);
        task.task_files = $scope.del_image_list;
        task.leader = task.leader.id;
        task = _.omit(task, 'create_user', 'childtasks', 'membernames');
        task.task_members = _.map(task.task_members, function (item) {
            return {'is_leader': item.is_leader, 'user': item.user_id};
        });
        showPopup.showLoading(1, '', false);
        Task.task(null).update({'id': task.id}, task, function (data) {
            if ($rootScope.commons.modal != null) {
                $rootScope.commons.modal.hide();
                $rootScope.commons.modal = null;
            }
        }, function (err) {
            showPopup.PopupWindow(0, 'update task fail!', false);
        }).$promise.finally(function (f) {
            showPopup.hideLoading();
        });
    }

    $scope.$on("$destroy", function () {
        beforeEnter = null;
        if ($rootScope.commons.modal != null) $rootScope.commons.modal.remove();
        Member.resourcemember = [];
        $rootScope.commons.fun = null;
    })
})

.controller('EditChildTaskCtrl', function ($scope, $state, $stateParams, $cordovaDatePicker, $timeout, $ionicHistory, $rootScope, Task, Member, showPopup, formatFilter, Tool) {
    $scope.data = _.pick(Task.taskdetail, 'childtasks', 'task_members');
    $scope.task = _.find($scope.data.childtasks, function (c) {
        return parseInt(c.id) == parseInt($stateParams.id)
    });
    $scope.task.task_members = $scope.data.task_members;
    $scope.childcontent = $scope.task.content;
    $scope.openmodal = function (type) {
        if (type == 'childcontent') $rootScope.commons.fun = clear_change;
        showPopup.modalTemplate(formatFilter('templates/modal-{0}.html', type), 'slide-in-right', $scope).then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        })
    };

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

    // Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function () {
        if ($rootScope.commons.modal != null) {
            $rootScope.commons.modal.remove();
            $rootScope.commons.modal = null;
        }
    });

    $scope.checkend_dd = function () {
        var options = {
            mode: 'date',
            date: $scope.task.end_dd == null ? new Date() : $scope.task.end_dd,
            androidTheme: 3
        };
        $cordovaDatePicker.show(options).then(function (date) {
            $timeout(function () {
                if (date == undefined) return;
                $scope.task.end_dd = date;
                showPopup.showLoading(1, '', false);
                Task.task(null).update({'id': $scope.task.id}, set_task(), function (data) {
                    $rootScope.commons.modal.hide();
                }, function (err) {
                    showPopup.PopupWindow(0, 'fail', false);
                }).$promise.finally(function (f) {
                    showPopup.hideLoading();
                });
            });
        });
    };

    $scope.changeAdmin = function (user) {
        var task = set_task();
        task.leader = user.user.id;
        showPopup.showLoading(1, '', false);
        Task.task(null).update({'id': task.id}, task, function (data) {
            $scope.task.leader = data.leader;
        }, function (err) {
            showPopup.PopupWindow(0, 'fail', false);
        }).$promise.finally(function (f) {
            $scope.closeModal();
            showPopup.hideLoading();
        });
    };

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

    $scope.ok = function () {
        if ($scope.task.content == '') {
            showPopup.PopupWindow(0, '请输入任务内容！', false);
            return;
        }
        showPopup.showLoading(1, '', false);
        Task.task(null).update({'id': $scope.task.id}, set_task(), function (data) {
            $scope.closeModal();
        }, function (err) {
            showPopup.PopupWindow(0, 'fail', false);
        }).$promise.finally(function (f) {
            showPopup.hideLoading();
        });
    };

    $scope.deletechildTask = function () {
        showPopup.confirm('是否删除该任务?', '是', '否').then(function (res) {
            if (res) {
                showPopup.showLoading(1, '', false);
                Task.task(null).delete({'id': $stateParams.id}, function (data) {
                    $scope.data.childtasks.splice(_.indexOf($scope.data.childtasks, $scope.task), 1);
                    $ionicHistory.goBack();
                }, function (err) {
                    showPopup.PopupWindow(0, 'fail', false);
                }).$promise.finally(function (f) {
                    showPopup.hideLoading();
                });
            }
        })
    };

    function clear_change() {
        $scope.task.content = $scope.childcontent;
        $rootScope.commons.modal.hide();
        $rootScope.commons.modal.remove();
        $rootScope.commons.modal = null;
    }

    function set_task() {
        var task = Tool.cloneObj($scope.task);
        task.leader = task.leader.id;
        task.task_members = [];
        return task;
    }
})
