starter.controller('NoticeCtrl', function ($rootScope, $scope, $state, $ionicHistory, _, global, Member, Notice, Tool) {
    var beoreenter = $scope.$on("$ionicView.beforeEnter", function () {
        global.fetch_user().then(function () {
            Notice.getCreateUsrsState().then(function (data) {
                $scope.createstate = data.state;
            });
            getnoticedata();
            $scope.roleid = global.user.roleid;
        }, function (err) {
            alert(JSON.stringify(err));
            $scope.loading = false;
        });
        Notice.getsavedata = Notice.getstructdata();
        Member.selectedemplst = [];
        $ionicHistory.clearHistory(); //清除所有的view
    });
    $scope.$on("$destroy", function () {
        beoreenter = null;
    });

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

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

    $scope.toper = function () {
        $state.go('power-set');
    };

    $scope.toadd = function () {
        Member.resourcemember = [];
        Member.selectedemplst = [];
        Member.showall = true;
        Member.showgroup = true;
        Member.titlename = "选择通知的成员";
        Member.routename = "postnotice";
        Member.routeparams = {
            "id": -1
        };
        $state.go('selectmember');
    };

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

    $scope.loadMore = function () {
        if ($scope.Notice != undefined && $scope.Notice.next != null) {
            Notice.getNext($scope.Notice.next).then(function (data) {
                console.log(data);
                _.each(data.results, function (item) {
                    $scope.Notice.results.push(item);
                })
                $scope.Notice.next = data.next;
                $scope.Notice.previous = data.previous;
            }).finally(function () {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
        } else {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        }
    }

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

    function getnoticedata() {
        if (global.user.token != "") {
            if ($scope.Notice == undefined) $scope.loading = true;
            Notice.getReceive().then(function (data) {
                data.results = _.sortBy(data.results, 'create_dd').reverse();
                $scope.Notice = data;
                console.log($scope.Notice);
            }, function (err) {
                alert(JSON.stringify(err));
            }).finally(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $scope.loading = false;
            });
        }
    }
})

.controller('NoticeDetailsCtrl', function ($rootScope, $scope, $state, $ionicSlideBoxDelegate, $ionicPopover, $ionicPopup, _, global, showPopup, Notice, General) {
    $scope.id = $state.params['id'];
    $scope.isScopeShow = false;
    $scope.activeIndex = 0;
    $scope.data = {
        notice_id: $scope.id,
        content: null
    };
    var isChange = false;

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

    $scope.change = function (index) {
        $scope.activeIndex = index;
        $ionicSlideBoxDelegate.slide(index);
    };

    $scope.lockSlide = function () {
        $ionicSlideBoxDelegate.enableSlide(false);
    };

    $scope.changeIndex = function (index) {
        if (!isChange) {
            isChange = true;
        }
        if ($scope.details.vote_selecttype == 1) {
            $scope.selectIndex = index;
        } else {
            var flag = false;
            _.each($scope.selectIndex, function (item) {
                if (item == index) {
                    $scope.selectIndex.splice($scope.selectIndex.indexOf(item), 1);
                    flag = true;
                }
            })
            if (!flag) {
                $scope.selectIndex.push(index);
            }
        }
    }

    $scope.result = function () {
        // type 0 admin 1 usr
        var type = null;
        if ($scope.isAdmin) {
            type = 0;
        } else {
            type = 1;
        }
        $scope.popover.hide();
        $state.go('notice-result', {
            id: $scope.id,
            type: type
        });
    }

    $scope.transfer = function (id) {
        $scope.popover.hide();
    }

    $scope.deleteNotice = function () {
        $scope.popover.hide();
        showPopup.confirm("是否删除改公告？", '是', '否').then(function (res) {
            if (res) {
                Notice.delete_NoticeMf($scope.id).then(function (data) {
                    $state.go('notice');
                }, function (error) {
                    alert('delete noticemf error:' + JSON.stringify(error))
                })
            }
        });
    }

    $scope.sendComment = function () {
        if ($scope.data.content != null && $scope.data.content != "") {
            $scope.data.create_dd = new Date();
            General.postComment($scope.data, 'notice').then(function (data) {
                $scope.data.content = 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) {
                        General.deleteComment(id, 'notice');
                    }
                }]
            });
            $scope.popup.isPopup = true;
        } else {
            //todo:对其进行回复
        }
    };

    $scope.giveUp = function (type) {
        // type 0:投票 1:反馈
        var title = ['是否放弃投票?', '是否放弃反馈?']
        showPopup.confirm(title[type], '是', '否').then(function (res) {
            if (res) {
                postGiveUp(type);
            }
        })
    };

    $scope.postVote = function () {
        if (isChange) {
            var data = {
                vote_selectindex: ''
            };
            $scope.usr_select_index = $scope.selectIndex;
            if ($scope.details.vote_selecttype == 0) {
                for (var i = 0; i < $scope.selectIndex.length; i++) {
                    if (i == $scope.selectIndex.length - 1) {
                        data.vote_selectindex += $scope.selectIndex[i];
                    } else {
                        data.vote_selectindex += $scope.selectIndex[i] + ';';
                    }
                }
            } else {
                data.vote_selectindex = $scope.selectIndex;
            }
            postRecordData(data);
        }
    }

    $scope.showbackpopup = function () {
        $scope.backData = {
            content: null
        };
        var backpopup = $ionicPopup.show({
            template: '<div class="popup-edit-comp" ><input type="text" ng-model="backData.content" ><label ></label></div>',
            title: '<div><h5>请输入反馈内容</h5></div>',
            scope: $scope,
            buttons: [{
                text: '取消',
                onTap: function () {
                    return false;
                }
            }, {
                text: '<b>提交</b>',
                type: 'button-positive',
                onTap: function (e) {
                    if (!$scope.backData.content) {
                        e.preventDefault();
                    } else {
                        return true;
                    }
                }
            }]
        }).then(function (res) {
            if (res) {
                postBackContent();
            }
        });
    };

    $scope.edit = function () {
        $scope.popover.hide();
        $state.go("postnotice", {
            "id": $scope.id
        })
    }

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

    $scope.shouBigImage = function (imageName, event) {
        if (event != undefined) {
            event.stopPropagation();
        }
        $scope.Url = imageName;
        $rootScope.commons.bigImage = true;
    };

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

    function postBackContent() {
        postRecordData({
            back_content: $scope.backData.content
        });
    }

    function postGiveUp(type) {
        // type 0 投票 1 反馈
        var data = {};
        if (type == 0) {
            data.vote_giveup = 1
        } else if (type == 1) {
            data.back_giveup = 1
        }
        postRecordData(data);
    }

    function postRecordData(data) {
        data.notice_id = $scope.id;
        data.user_id = global.user.usrid;
        Notice.postRecord(data).then(function (data) {
            $scope.record = data;
        })
    }

    function getDetails() {
        if ($scope.details == undefined) {
            $scope.loading = true;
        }
        Notice.getDetails($scope.id).then(function (data) {
            $scope.details = data;
            if ($scope.details.user == global.user.usrid) {
                $scope.isAdmin = true;
            }
            if ($scope.details.vote_enddd != null) {
                $scope.details.vote_enddd = new Date($scope.details.vote_enddd)
            }
            if ($scope.details.back_enddd != null) {
                $scope.details.back_enddd = new Date($scope.details.back_enddd)
            }
            $scope.datetime = new Date();
            if ($scope.details.vote_selectdata != null) {
                $scope.selectData = $scope.details.vote_selectdata.split(';');
            }
            if ($scope.details.vote_selecttype == 1) {
                $scope.selectIndex = 0;
            } else if ($scope.details.vote_selecttype == 0) {
                $scope.selectIndex = [];
            }
            Notice.getRecord($scope.id).then(function (data) {
                $scope.record = data;
                if ($scope.record != null) {
                    if ($scope.record.vote_selectindex != null) {
                        $scope.usr_select_index = $scope.record.vote_selectindex.split(';');
                    }
                }
                $scope.loading = false;
            });
            General.getComment($scope.id, 'notice').then(function (data) {
                $scope.commentData = data.reverse();
            });
            General.getRead($scope.id, 'notice').then(function (data) {
                $scope.readData = data.reverse();
            });
            General.getRead($scope.id, 'notice', 'unreads').then(function (data) {
                $scope.unreadData = data.reverse();
            });
        }).finally(function () {
            $scope.$broadcast('scroll.refreshComplete');
        });
    }

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        if (global.user.token == "") {
            global.fetch_user().then(function () {
                getDetails();
            }, function (err) {
                $scope.loading = false;
                alert(JSON.stringify(err));
            });
        } else {
            getDetails();
        }

        $scope.popup = {
            isPopup: false
        };
    });

    $scope.$on("$destroy", function () {
        $scope.popover.remove();
        beforeEnter = null;
        $rootScope.commons.bigImage = false;
    })
})

.controller('PowerSetCtrl', function ($rootScope, $scope, $state, $timeout, $location, $ionicScrollDelegate, $ionicPopover, _, global, Dept, Member, Notice) {
    $ionicPopover.fromTemplateUrl('templates/add.html', {
        scope: $scope
    }).then(function (popover) {
        $scope.popover = popover;
    });

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        $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', '#'];
        if (Member.selectedemplst.length > 0) {
            var add_usrs = _.pluck(Member.selectedemplst, 'user_id');
            // alert("add_usrs data:"+JSOM.stringify(add_usrs));
            Notice.post_NoticeCreateUsrs(add_usrs).then(function (data) {
                getCreateUsrs();
            }, function (error) {
                console.log(error);
            })
        } else {
            getCreateUsrs();
        }
        Member.cancelroutename = '';
        Member.cancelrouteparams = {};
    });

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

    $scope.isshowdelete = {
        showDelete: false
    };
    $scope.sortchar = 'A';
    $scope.Isshowmiddle = false;

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

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

    $scope.ok = function () {
        $scope.popover.hide();
        $scope.isshowdelete.showDelete = false;
        if (delete_data.length > 0) {
            Notice.delete_NoticeCreateUsrs(delete_data);
            for (var i = 0; i < $scope.empdata.length; i++) {
                _.each(delete_data, function (d) {
                    if (d == $scope.empdata[i].id) {
                        $scope.empdata.splice(i, 1)
                    }
                })
            }
        }
    };

    $scope.toadd = function () {
        Member.resourcemember = [];
        Member.selectedemplst = [];
        Member.disabled = true;
        Member.resourcemember = $scope.empdata;
        Member.showall = false;
        Member.showgroup = false;
        Member.titlename = "选择成员";
        Member.routename = "";
        $scope.popover.hide();
        $state.go('selectmember');
    };
    var delete_data = [];
    $scope.removeItem = function (id, _char) {
        delete_data.push(id);
        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].nid == id) {
                        $scope.resultdata[i].persons.splice(j, 1);
                        if ($scope.resultdata[i].persons.length == 0) {
                            $scope.resultdata.splice(i, 1)
                        }
                        break;
                    }
                }
                break;
            }
        }
    };

    function getCreateUsrs() {
        if ($scope.resultdata == undefined) {
            $scope.loading = true;
        }
        Notice.getCreateUsrs().then(function (data) {
            $scope.loading = false;
            $scope.empdata = data;
            $scope.resultdata = [];
            var chars = _.map($scope.empdata, function (emp) {
                var char = pinyin.getCamelChars(emp.name).toUpperCase().charAt(0);
                return _.contains($scope.sortchars, char) ? char : '#';
            });
            chars = _.sortBy(_.uniq(chars));
            for (var i = 0; i < chars.length; i++) {
                var d = {
                    "sortchar": chars[i],
                    "persons": []
                };
                $scope.resultdata.push(d);
                for (var j = 0; j < $scope.empdata.length; j++) {
                    var char = pinyin.getCamelChars($scope.empdata[j].name).toUpperCase().charAt(0);
                    var empchar = _.contains($scope.sortchars, char) ? char : '#';
                    if (empchar == chars[i]) {
                        d.persons.push({
                            "nid": $scope.empdata[j].id,
                            "username": $scope.empdata[j].name
                        });
                    }
                }
            }
            var index = _.pluck($scope.resultdata, 'sortchar').indexOf('#');
            if (index >= 0) {
                var item = $scope.resultdata[index];
                $scope.resultdata.splice(index, 1);
                $scope.resultdata.push(item);
            }
            Member.selectedemplst = [];
        }, function (err) {
            $scope.loading = false;
            alert(JSON.stringify(err))
        });
    }
})

.controller('PostNoticeCtrl', function ($rootScope, $scope, $state, $cordovaDatePicker, $timeout, $ionicHistory, $q, $ionicScrollDelegate, _, global, ImageManage, showPopup, Notice, Member, Tool, formatFilter) {
    $rootScope.commons.bigImage = false;
    var tmday = new Date((new Date() / 1000 + 86400) * 1000);
    $scope.isNew = (parseInt($state.params["id"]) < 0);
    $scope.selectdatas = [{
        name: '多选',
        id: 0
    }, {
        name: '单选',
        id: 1
    }];
    var deleteimages = {};

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        Tool.removeBackView('selectmember');
        $scope.usernames = "";
        if ($scope.isNew) { //add
            deleteimages = Notice.getsavedata.deleteimages;
            $scope.noticedata = Notice.getsavedata;
            $scope.noticedata.allid = Member.all;
            if (Member.dialogresult == 0) { //cancel
                $scope.noticedata.allid == 0 ? setreadusrs($scope.noticedata.readusrs) : $scope.usernames = "全部成员";
            } else {
                if (Member.all == 0 && Member.selectedemplst.length > 0) {
                    $scope.noticedata.readusrs = _.map(Member.selectedemplst, function (item) {
                        return _.pick(item, 'user_id', 'username');
                    });
                    setreadusrs(Member.selectedemplst);
                } else if (Member.all == 1) {
                    $scope.noticedata.readusrs = [];
                    $scope.usernames = "全部成员";
                }
            }
        } else { //edit
            deleteimages = Notice.getLoalDetails().deleteimages;
            $scope.noticedata = Notice.getLoalDetails();
            $scope.editvotedata = $scope.noticedata.selectitems;
            $scope.noticedata.disablededit.showadditem = (Tool.trim($scope.noticedata.vote_title).length == 0);
            $scope.noticedata.disablededit.showeditback = (Tool.trim($scope.noticedata.back_title).length == 0);
            if (Member.selectedemplst.length > 0) {
                $scope.noticedata.allid = Member.all;
                $scope.noticedata.readusrs = _.map(Member.selectedemplst, function (item) {
                    return _.pick(item, 'user_id', 'username');
                });
                setreadusrs(Member.selectedemplst)
            } else {
                if ($scope.noticedata.allid == 1) {
                    $scope.noticedata.readusrs = [];
                    $scope.usernames = "全部成员";
                } else {
                    setreadusrs($scope.noticedata.readusrs)
                }
            }
        }
        Member.routeparams = {};
        $scope.popup = {
            isSetPopup: false
        };
        $ionicScrollDelegate.resize();
    });

    $scope.$on("$destroy", function () {
        $rootScope.commons.modal = null;
        $rootScope.commons.fun = null;
        beforeEnter = null;
        Notice.getsavedata = Notice.getstructdata();
    });

    $scope.noticedata = [];
    $scope.imagePicker = function () {
        ImageManage.ImagePicker_getPictures(10).then(function (data) {
            if (data.length == 0) return;
            $scope.noticedata.noticefiles = $scope.noticedata.noticefiles.concat(_.map(data, function (imageUrl) {
                return {"file_thumbnail_path": imageUrl, "file_full_path": imageUrl};
            }));
        });
    };

    $scope.Camera = function () {
        ImageManage.Camera_getPicture().then(function (result) {
            $scope.noticedata.noticefiles.push({
                "file_thumbnail_path": result,
                "file_full_path": result
            });
        });
    };

    $scope.shouBigImage = function (imageName, event) {
        if (event != undefined) event.stopPropagation();
        $scope.Url = imageName;
        $rootScope.commons.bigImage = true;
    };

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

    $scope.deleteimage = function () {
        for (var i = 0; i < $scope.noticedata.noticefiles.length; i++) {
            if ($scope.noticedata.noticefiles[i].file_full_path == $scope.Url) {
                if (_.has($scope.noticedata.noticefiles[i], 'id')) {
                    deleteimages.oldimages.push($scope.noticedata.noticefiles[i]);
                }
                $scope.noticedata.noticefiles.splice(i, 1);
                break;
            }
        }
        $rootScope.commons.bigImage = false;
    };

    var tempdata = {};
    $scope.set_voteback = function (type, event) {
        type == 'vote' ? $scope.noticedata.setbtnstyle.vote = true : $scope.noticedata.setbtnstyle.back = true;
        tempdata = Tool.cloneObj($scope.noticedata);
        tempdata.selectitems = tempdata.vote_selectdata == "" ? [] : _.map(tempdata.vote_selectdata.split(';'), function (text) {
                return {'text': text};
            });
        showPopup.modalTemplate(formatFilter('templates/modal-{0}.html', type), 'slide-in-right', $scope).then(function (modal) {
            $rootScope.commons.fun = clear_change;
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        })
    };

    $scope.cancel = function (op) {
        $rootScope.commons.fun = null;
        if (op == 'notice') {
            $ionicHistory.goBack();
        } else {
            clear_change()
        }
    };

    function clear_change() {
        $scope.noticedata = Tool.cloneObj(tempdata);
        if (Tool.trim(tempdata.vote_title).length == 0) $scope.noticedata.setbtnstyle.vote = false;
        if (Tool.trim(tempdata.back_title).length == 0) $scope.noticedata.setbtnstyle.back = false;
        set_modal();
    }

    $scope.ok = function (op) {
        $rootScope.commons.fun = null;
        if (op == "notice") { //创建公告的首页-确定按钮
            if (Tool.trim($scope.noticedata.title).length == 0) {
                showPopup.PopupWindow(0, "标题不能为空！", false);
                return;
            }
            if (Tool.trim($scope.noticedata.content).length == 0) {
                showPopup.PopupWindow(0, "内容不能为空！", false);
                return;
            }
            showPopup.showLoading(1, '正在提交');
            $scope.noticedata.usrid = global.user.usrid;
            var temp_notice = Tool.cloneObj($scope.noticedata);
            temp_notice.readusrs = _.pluck(temp_notice.readusrs, 'user_id');
            if ($scope.isNew) {
                Notice.post_NoticeMf(temp_notice).then(function (data) {
                    if ($scope.noticedata.noticefiles.length > 0) {
                        postimg($scope.noticedata.noticefiles, data.id);
                    } else {
                        showPopup.hideLoading();
                        $ionicHistory.goBack();
                        $timeout(function () {
                            $state.go("notice-details", {
                                "id": data.id
                            })
                        });
                    }
                }, function (error) {
                    showPopup.hideLoading();
                    alert('post_NoticeMf error:  ' + JSON.stringify(error))
                });
            } else {
                temp_notice.del_files = _.pluck(deleteimages.oldimages, 'id');
                Notice.put_NoticeMf(temp_notice).then(function (data) {
                    postimgs = _.filter($scope.noticedata.noticefiles, function (img) {
                        return !_.has(img, 'id');
                    });
                    if (postimgs.length > 0) {
                        postimg(postimgs, $state.params['id']);
                    } else {
                        showPopup.hideLoading();
                        $ionicHistory.goBack();
                    }
                }, function (error) {
                    showPopup.hideLoading();
                    alert("put notice error: " + JSON.stringify(error))
                })
            }
        } else if (op == "vote") { //添加投票模态窗口-确定按钮
            if (Tool.trim($scope.noticedata.vote_title).length == 0) {
                showPopup.PopupWindow(0, '标题不能为空！', false);
                return;
            }
            var items = _.filter($scope.noticedata.selectitems, function (item) {
                return Tool.trim(item.text).length > 0;
            });

            var resultitems = _.uniq(_.pluck(items, 'text'));
            if (resultitems.length < items.length) {
                showPopup.PopupWindow(0, '选项不能重复！', false);
                return;
            }
            if (resultitems.length < 2) {
                showPopup.PopupWindow(0, '实际投票选项不能少于2项！', false);
                return;
            }
            $scope.noticedata.vote_selectdata = _.pluck($scope.noticedata.selectitems, 'text').join(';');
            set_modal();
            $timeout(function () {
                $scope.noticedata.showvoteDelete = true;
            }, 1000);
        } else if (op == "back") {
            if (Tool.trim($scope.noticedata.back_title).length == 0) {
                showPopup.PopupWindow(0, '问题内容不能为空！', false);
                return;
            }
            set_modal();
            $timeout(function () {
                $scope.noticedata.showbackDelete = true;
            }, 1000);
        }
    };

    $scope.checkend_dd = function (op) {
        var date = null;
        if ($scope.isNew) {
            date = tmday;
        } else {
            if (op == "vote") {
                date = $scope.noticedata.vote_enddd == null ? tmday : $scope.noticedata.vote_enddd;
            } else {
                date = $scope.noticedata.back_enddd == null ? tmday : $scope.noticedata.vote_enddd;
            }
        }
        var options = {
            mode: 'date',
            date: date,
            androidTheme: 3
        };
        $cordovaDatePicker.show(options).then(function (date) {
            $timeout(function () {
                if (date == undefined) return;
                op == "vote" ? $scope.noticedata.vote_enddd = date : $scope.noticedata.back_enddd = date;
            });
        });
    };

    $scope.addItem = function () {
        $timeout(function () {
            $scope.noticedata.selectitems.push({
                "text": ""
            });
        });
    };

    $scope.removeItem = function (index) {
        $scope.noticedata.selectitems.splice(index, 1);
    };

    //todo:选择要通知的成员
    $scope.toselect = function () {
        Member.resourcemember = [];
        Member.showall = true;
        Member.showgroup = true;
        Member.titlename = "选择通知的成员";
        Member.routename = "postnotice";
        Member.cancelroutename = "postnotice";
        Member.cancelrouteparams = {
            "id": $state.params['id']
        };
        Member.disabled = false;
        if ($scope.isNew) {
            Member.dialogresult == 0 ? setresourcedata($scope.noticedata.readusrs) : setresourcedata(Member.selectedemplst);
            Member.routeparams = {
                "id": -1
            };
        } else {
            Member.selectedemplst.length == 0 ? setresourcedata($scope.noticedata.readusrs) : setresourcedata(Member.selectedemplst);
            Member.routeparams = {
                "id": $state.params['id']
            };
        }
        Member.selectedemplst = [];
        $state.go('selectmember');
    };

    $scope.delete = function (op) {
        if (op == "vote") {
            $scope.noticedata.vote_title = "";
            $scope.noticedata.vote_selectdata = "";
            $scope.noticedata.vote_selecttype = 1;
            $scope.noticedata.vote_enddd = tmday;
            $scope.noticedata.selectitems = [];
            $scope.noticedata.setbtnstyle.vote = false;
            $scope.noticedata.showvoteDelete = false;
            $scope.noticedata.disablededit.showadditem = true;
        } else {
            $scope.noticedata.back_title = "";
            $scope.noticedata.back_enddd = tmday;
            $scope.noticedata.setbtnstyle.back = false;
            $scope.noticedata.showbackDelete = false;
            $scope.noticedata.disablededit.showeditback = true;
        }
        set_modal();
    };

    $scope.getaddress = function () {
        if (window.cordovaLinker) {
            var local = {
                NAME: "",
                Latitude: "",
                Longitude: "",
                Distance: ""
            };
            cordovaLinker.callMap(local, function (mapdata) {
                $scope.noticedata.address = mapdata.NAME
            });
        }
    };

    function setresourcedata(data) {
        Member.resourcemember = Member.resourcemember.concat(_.map(data, function (item) {
            if (_.has(item, 'user__username')) item.username = item.user__username;
            return item
        }));
    }

    function setreadusrs(data) {
        $scope.usernames = _.map(data, function (item) {
            return _.has(item, 'username') ? item.username : item.user__username;
        }).join('、');
    }

    function postimg(imgfiles, id) {
        ImageManage.uploadImage(_.pluck(imgfiles, 'file_full_path'), 'notice', id, 'noticefile').then(function (res) {
            $q.all(res).then(function (res1) {
                showPopup.hideLoading();
                $ionicHistory.goBack();
                $timeout(function () {
                    $state.go("notice-details", {
                        "id": id
                    })
                });
            })
        }, function (err) {
            showPopup.hideLoading();
            alert(JSON.stringify(error));
            showPopup.PopupWindow(0, 'upload image fail');
        })
    }

    function set_modal() {
        $rootScope.commons.modal.hide();
        $rootScope.commons.modal = null;
    }
})

.controller('NoticeResultCtrl', function ($rootScope, $scope, $state, $timeout, showPopup, Notice) {
    $scope.id = $state.params['id'];
    $scope.type = $state.params['type'];

    $scope.toResultDetails = function (type, index) {
        // type 0 未看 1 已看 2 未反馈 3 已反馈 4 放弃反馈 5 未投票 6 放弃投票 7 已投票
        // index 选项的下标
        showPopup.showLoading(1, '加载中');
        var data = Notice.getCountDetails();
        if (type == 7) {
            data.selectItem = $scope.selectData[index];
        }
        Notice.getUsrCount($scope.id, type, index).then(function () {
            $state.go('result-details', {
                type: type
            });
            showPopup.hideLoading();
        })
    }

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        if ($scope.details == undefined) {
            showPopup.showLoading(1, '加载中');
        }
        Notice.getCount($scope.id).then(function (data) {
            $scope.countData = data;
            $scope.details = Notice.getLoalDetails();
            if ($scope.details.vote_title != null) {
                $scope.selectData = $scope.details.vote_selectdata.split(';');
                $scope.usrvotecount = 0;
                for (var i = 0; i < $scope.countData.votecount.length; i++) {
                    $scope.usrvotecount += $scope.countData.votecount[i];
                }
                $scope.usrvotecount += $scope.countData.unvote;
                $scope.usrvotecount += $scope.countData.votegiveup;
            }
            showPopup.hideLoading();
        });
    });

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

.controller('NoticePostedCtrl', function ($scope, $state, Member, Notice) {
    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        if ($scope.createstate == undefined)
            $scope.createstate = 0; //默认不显示'+'标记
        Notice.getCreateUsrsState().then(function (data) {
            $scope.createstate = data.state;
        });
        Notice.getRelease().then(function (data) {
            $scope.Notice = _.sortBy(data.results, 'create_dd').reverse();
        });
        Notice.getsavedata = Notice.getstructdata();
        Member.selectedemplst = [];
    });

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

    $scope.toadd = function () {
        Member.resourcemember = [];
        Member.selectedemplst = [];
        Member.showall = true;
        Member.showgroup = true;
        Member.titlename = "选择通知的成员";
        Member.routename = "postnotice";
        Member.routeparams = {
            "id": -1
        };
        $state.go('selectmember');
    };

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

.controller('ResultDetailsCtrl', function ($scope, $state, Notice) {
    $scope.type = $state.params['type'];
    $scope.titleArr = ['未看', '已看', '未反馈', '已反馈', '放弃反馈', '未投票', '放弃投票', '已投票'];
    $scope.countDetails = Notice.getCountDetails();
});
