starter.controller('ScheduleCtrl', function ($rootScope, $scope, $state, $cordovaCalendar, global, Schedule, Tool) {
    $scope.goBack = function () {
        global.goBack();
    }

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

    $scope.toadd = function () {
        $state.go('schedule-create', {
            id: -1
        });
    }

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

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

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

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

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

    function getscheduledata() {
        if (global.user.token != "") {
            if ($scope.schedules == undefined) {
                $scope.loading = true;
            }
            Schedule.schedule.get({'type': 'receive'}, function (res) {
                $scope.schedules = 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;
            getscheduledata();
        }
    })

    $scope.$on("$destroy", function () {
        enter = null;
    })
//  function getscheduledata() {
//      if (global.user.token != "") {
//          Schedule.getReceive().then(function (data) {
//              data_unover = [];
//              data_over = [];
//              _.each(data, function (item) {
//                  var isover = false;
//                  var currentDateTime = new Date();
//                  if ((item.end_date != null && new Date(Date.parse(item.end_date)) < currentDateTime) ||
//                          (item.repeat_type == 0 && item.start_date != null && new Date(Date.parse(item.start_date)) < currentDateTime)) {
//                      isOver = true;
//                  } else {
//                      isOver = false;
//                  }
//                  if (isOver) {
//                      //已过期
//                      data_over.push(item);
//                  } else {
//                      //未过期
//                      data_unover.push(item);
//                  }
//
//              });
//
//              data_unover = _.sortBy(data_unover, 'execute_dd'); //升序
//              data_over = _.sortBy(data_over, 'execute_dd').reverse(); //降序
//              data = [];
//              _.each(data_unover, function (item) {
//                  data.push(item);
//              });
//              _.each(data_over, function (item) {
//                  data.push(item);
//              });
//              $scope.Schedule = data;
//          }, function (error) {
//              alert(JSON.stringify(error));
//          });
//      }
//  }
})

.controller('SchedulePostedCtrl', function ($rootScope, $scope, $state, global, Schedule, Tool) {
    global.fetch_user().then(function () {
        getscheduledata();
    })

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

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

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

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

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

    function getscheduledata() {
        if (global.user.token != "") {
            if ($scope.schedules == undefined) {
                $scope.loading = true;
            }
            Schedule.schedule.get({'type': 'release'}, function (res) {
                $scope.schedules = 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;
            getscheduledata();
        }
    })

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

.controller('ScheduleCreateCtrl', function ($rootScope, $scope, $state, $ionicHistory, $cordovaDatePicker, $cordovaCalendar, global, Schedule, Member, showPopup, Tool) {
    var id = $state.params['id'];
    var isModified = false;
    $scope.repeatfreqWeekDayHt = {
        "1": false,
        "2": false,
        "3": false,
        "4": false,
        "5": false,
        "6": false,
        "0": false
    }

    $scope.repeatfreqMonthDayHt = {
        "1": false,
        "2": false,
        "3": false,
        "4": false,
        "5": false,
        "6": false,
        "7": false,
        "8": false,
        "9": false,
        "10": false,
        "11": false,
        "12": false,
        "13": false,
        "14": false,
        "15": false,
        "16": false,
        "17": false,
        "18": false,
        "19": false,
        "20": false,
        "21": false,
        "22": false,
        "23": false,
        "24": false,
        "25": false,
        "26": false,
        "27": false,
        "28": false,
        "29": false,
        "30": false,
        "31": false
    }
    
    $scope.data = {
        content: null,
        start_date: getDateTimeYMDHM(1),
        start_date_title: null,
        repeat_type: 0,
        freq: '',
        repeat_freq_title: '不重复',
        end_date: null,
        repeat_end_date_type: 1,
        notification_type: 1,
        schedulemembers: []
    }

    $scope.popup = {
        isPopup: false
    }

    if (id > 0) {
        $scope.data = Tool.cloneObj(Schedule.scheduleDetails);
        $scope.data.freq = $scope.data.freq.split(',');
        if ($scope.data.repeat_type == 2) {
            setRepeatByFreq($scope.data.freq, $scope.repeatfreqWeekDayHt);
        } else if ($scope.data.repeat_type == 3) {
            setRepeatByFreq($scope.data.freq, $scope.repeatfreqMonthDayHt);
        }
        $scope.data.repeat_freq_title = Schedule.getRepeatFreqTitle($scope.data.repeat_type, $scope.data.freq);
        if ($scope.data.end_date == null) {
            $scope.data.repeat_end_date_type = 1;
        } else {
            $scope.data.repeat_end_date_type = 2;
        }
        var content_old = $scope.data.content;
        var date_old = $scope.data.start_date;
    }

    $scope.data.start_date_title = Schedule.getDateTimeTitle($scope.data.start_date);
    $scope.warningHt = Schedule.notificationType;
    $scope.repeatHt = Schedule.repeatType;
    $scope.weekDayHt = Schedule.weekDay;

    $scope.repeatfreqstyleunactive = {
        "border": "1px solid #ddd",
        "background-color": "#fff"
    }

    $scope.repeatfreqstyleactive = {
        "border": "1px solid #ddd",
        "background-color": "red"
    }

    $scope.goBack = function () {
        if (id < 0 && ($scope.data.content != null || $scope.data.schedulemembers.length > 0)) {
            showPopup.confirm('是否取消创建?', '是', '否').then(function (res) {
                if (res)
                    global.goBack();
            });
        } else {
            global.goBack();
        }
    }

    $scope.selectmember = function () {
        Member.resourcemember = [];
        _.each($scope.data.schedulemembers, function (user) {
            Member.resourcemember.push(user);
        })
        Member.titlename = '选择成员'
        Member.disabled = false;
        $state.go('selectmember');
    }

    //选择重复 重复类型（0:永不,1:每天 2:每周,3:每月,4:每年）
    showPopup.modalTemplate('templates/modal-selectrepeatid.html', 'slide-in-right', $scope).then(function (modal) {
        $scope.repeat_id_modal = modal;
    });

    $scope.showRepeatIdModal = function () {
        $scope.repeat_id_modal.show();
        $rootScope.commons.modal = $scope.repeat_id_modal;
    }

    $scope.closeRepeatIdModal = function () {
        //0:永不,1:每天 2:每周,3:每月,4:每年
        if ($scope.data.repeat_type == "2") {
            $scope.data.freq = getFreqByRepeat($scope.repeatfreqWeekDayHt);
        } else if ($scope.data.repeat_type == "3") {
            $scope.data.freq = getFreqByRepeat($scope.repeatfreqMonthDayHt);
        }
        $scope.data.repeat_freq_title = Schedule.getRepeatFreqTitle($scope.data.repeat_type, $scope.data.freq);
        $rootScope.commons.modal.hide();
    }

    $scope.changeRepeatId = function (repeat_type) {
        //0:永不,1:每天 2:每周,3:每月,4:每年
        if (repeat_type == "1") {
            $scope.data.freq = 1;
        } else if (repeat_type == "2") {
            $scope.repeatfreqWeekDayHt[new Date().getDay()] = true;
        } else if (repeat_type == "3") {
            $scope.repeatfreqMonthDayHt[new Date().getDate()] = true;
        }
        $scope.data.repeat_type = repeat_type;
    }

    $scope.changeDayRepeatfreqIdColor = function (freq) {
        $scope.data.freq = freq;
    }

    $scope.changeWeekDayRepeatfreqIdColor = function (freq) {
        if (!(_.compact($scope.repeatfreqWeekDayHt).length == 1 && $scope.repeatfreqWeekDayHt[freq]))
            $scope.repeatfreqWeekDayHt[freq] = !$scope.repeatfreqWeekDayHt[freq];
    }

    $scope.changeMonthDayRepeatfreqIdColor = function (freq) {
        if (!(_.compact($scope.repeatfreqMonthDayHt).length == 1 && $scope.repeatfreqMonthDayHt[freq]))
            $scope.repeatfreqMonthDayHt[freq] = !$scope.repeatfreqMonthDayHt[freq];
    }

    //选择结束重复（null：一直重复）
    showPopup.modalTemplate('templates/modal-selectrepeatenddd.html', 'slide-in-right', $scope).then(function (modal) {
        $scope.repeat_end_dd_modal = modal;
    });

    $scope.showRepeatendddModal = function () {
        $scope.repeat_end_dd_modal.show();
        $rootScope.commons.modal = $scope.repeat_end_dd_modal;
    }

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

    $scope.changeRepeatendddId = function (repeat_end_date_type) {
        $scope.data.repeat_end_date_type = repeat_end_date_type;
        $scope.data.end_date = null;
        $scope.closeRepeatendddModal();
    }

    //选择提醒 提醒类型(0:不提醒,1:事件发生时,2:提前5分钟,3:提前15分钟,4:提前30分钟,5:提前1小时,6:提前2小时,7:提前5小时)
    showPopup.modalTemplate('templates/modal-selectwarningid.html', 'slide-in-right', $scope).then(function (modal) {
        $scope.warning_id_modal = modal;
    });

    $scope.showWarningIdModal = function () {
        $scope.warning_id_modal.show();
        $rootScope.commons.modal = $scope.warning_id_modal;
    }

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

    $scope.changeWarningId = function (notification_type) {
        $scope.data.notification_type = notification_type;
        $scope.closeWarningIdModal();
    }

    $scope.addSchedule = function () {
        if (Schedule.checkSchedule($scope.data)) {
            showPopup.showLoading(1, '正在提交');
            if (id < 0) {
                createSchdule();
            } else {
//              if (isModified) { // todo :edit change is modified
                Schedule.deleteEvent(content_old, date_old);
                createSchdule();
//              }
            }
        }
    }

    $scope.chooseDate = function () {
        var options = {
            mode: 'date',
            date: $scope.data.end_date != null ? new Date($scope.data.end_date) : new Date(),
            androidTheme: 3
        };
        $cordovaDatePicker.show(options).then(function (date) {
            if (date == undefined) return;
            $scope.data.end_date = date;
            $scope.data.repeat_end_date_type = 2;
            $scope.closeRepeatendddModal();
        }, function (cancel) {
            $scope.data.end_date = null;
            $scope.data.repeat_end_date_type = 1;
        });
    }

    $scope.chooseStartddDate = function () {
        var options = {
            mode: 'datetime',
            date: new Date($scope.data.start_date),
            androidTheme: 3
        };
        $cordovaDatePicker.show(options).then(function (date) {
            if (date == undefined) return;
            $scope.data.start_date = date;
            $scope.data.start_date_title = Schedule.getDateTimeTitle($scope.data.start_date);
        });
    }

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

    var enter = $scope.$on("$ionicView.enter", function () {
        selectMember();
    });

    $scope.$on("$destroy", function () {
        if ($rootScope.commons.modal)
            $rootScope.commons.modal = null;
        $scope.repeat_end_dd_modal.remove();
        $scope.warning_id_modal.remove();
        $scope.repeat_id_modal.remove();
        enter = null;
        watch();
    })

    function createSchdule() {
        if ($scope.data.repeat_end_date_type == 1)
            $scope.data.end_date = null;
        var data = _.pick($scope.data, 'content', 'start_date', 'repeat_type', 'freq', 'end_date', 'notification_type', 'schedulemembers');
        if (data.freq.length > 0)
            data.freq = data.freq.join(',');
        data.schedulemembers = _.map(data.schedulemembers, function (user) {
            return user.user_id;
        })
        if (id < 0) {
            Schedule.schedule.save(data, function (data) {
                $rootScope.commons.refresh = true;
                Schedule.createEventWithOptions($scope.data.content, $scope.data.start_date, $scope.data.end_date, $scope.data.repeat_type, $scope.data.freq, $scope.data.notification_type);
                showPopup.hideLoading();
                $ionicHistory.goBack();
            })
        } else {
            data.id = id;
            Schedule.schedule.update(data, function (data) {
                $rootScope.commons.refresh = true;
                Schedule.createEventWithOptions($scope.data.content, $scope.data.start_date, $scope.data.end_date, $scope.data.repeat_type, $scope.data.freq, $scope.data.notification_type);
                showPopup.hideLoading();
                $ionicHistory.goBack();
            })
        }
    }

    function getFreqByRepeat(repeat) {
        var freq = []
        _.each(repeat, function (value, key) {
            if (value) freq.push(parseInt(key));
        })
        return freq;
    }

    function setRepeatByFreq(freq, repeat) {
        _.each(freq, function (f) {
            repeat[f] = !repeat[f];
        })
    }

    function selectMember() {
        if (Member.selectedemplst.length > 0) {
            $scope.data.schedulemembers = [];
            console.log(Member.selectedemplst);
            _.each(Member.selectedemplst, function (item) {
                $scope.data.schedulemembers.push({
                    user_id: item.user_id,
                    username: item.username,
                    deptname: item.depname,
                    degree: item.degree
                })

            });
            $scope.sel_member_names = Schedule.getMemberTitle($scope.data.schedulemembers);
            Member.selectedemplst = [];
        }
    }

    function getDateTimeYMDHM(add_hours) {
        var date = new Date()
        date.setHours(date.getHours() + add_hours);
        date.setMinutes(0);
        return date;
    }
})

.controller('ScheduleDetailsCtrl', function ($rootScope, $scope, $state, $ionicHistory, $ionicPopover, Schedule, global, showPopup, Tool) {
    var id = $state.params['id'];
    $scope.popup = {
        isPopup: false,
    }
    var view = $ionicHistory.backView();

    global.fetch_user().then(function () {
        if (view) {
            $scope.details = Schedule.scheduleDetails;
//              $scope.execute_dd_title = Schedule.getDateTimeTitle(res.execute_dd);
            $scope.scheduleMemberNames = Schedule.getMemberTitle($scope.details.schedulemembers);
            $scope.repeat_req_title = Schedule.getRepeatFreqTitle($scope.details.repeat_type, $scope.details.freq);
            $scope.isShowRemoveMember = _.find($scope.details.schedulemembers, function (user) {
                return user.user_id == global.user.usrid;
            });
            $scope.isOver = false;
            if ($scope.details.end_date != null && new Date() > new Date($scope.details.end_date))
                $scope.isOver = true;
        } else {
            getscheduledetails();
        }
    });

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

    $scope.deleteSchedule = function () {
        $scope.popover.hide();
        $scope.popup.isPopup = true;
        showPopup.confirm('是否删除该日程?', '是', '否').then(function (res) {
            if (res) {
                Schedule.deleteEvent($scope.details.content, $scope.details.start_date);
                Schedule.schedule.delete({'id': id}, function () {
                    $rootScope.commons.refresh = true;
                    $ionicHistory.goBack();
                });
            }
        });
    }

    $scope.deleteMember = function () {
        $scope.popup.isPopup = true;
        showPopup.confirm('退出后，你将不再参与该日程', '是', '否').then(function (res) {
            if (res) {
                Schedule.deleteEvent($scope.details.content, $scope.details.start_date);
                Schedule.schedulemenber.delete({'schedule_id': id}).then(function () {
                    $rootScope.commons.refresh = true;
                    $ionicHistory.goBack();
                });
            }
        });
    }

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

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

    function getscheduledetails() {
        if (global.user.token != "") {
            if ($scope.details == undefined) {
                $scope.loading = true;
            }
            Schedule.schedule.get({'id': id}, function (res) {
                Schedule.scheduleDetails = _.clone(res);
                console.log(res);
                $scope.details = res;
//              $scope.execute_dd_title = Schedule.getDateTimeTitle(res.execute_dd);
                $scope.scheduleMemberNames = Schedule.getMemberTitle(res.schedulemembers);
                $scope.repeat_req_title = Schedule.getRepeatFreqTitle(res.repeat_type, res.freq);
                $scope.isShowRemoveMember = _.find(res.schedulemembers, function (user) {
                    return user.user_id == global.user.usrid;
                });
                $scope.isOver = false;
                if ($scope.details.end_date != null && new Date() > new Date($scope.details.end_date))
                    $scope.isOver = true;
//              //是否过期
//              var currentDateTime = new Date();
//              var executeddTime = new Date(Date.parse($scope.data.execute_dd));
//              if (($scope.data.end_date != null && new Date(Date.parse($scope.data.end_date)) < currentDateTime) && currentDateTime > executeddTime ||
//                      ($scope.data.repeat_type == 0 && $scope.data.start_date != null && new Date(Date.parse($scope.data.start_date)) < currentDateTime)) {
//                  $scope.isOver = true;
//              } else {
//                  $scope.isOver = false;
//              }
            }, 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) {
            if (view == null)
                $rootScope.commons.refresh = false;
            getscheduledetails();
        }
    });

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