starter.controller('workatd-index', function ($rootScope, $interval, $scope, $state, $ionicModal, $ionicPlatform, $cordovaPreferences, $ionicPopup, $ionicActionSheet, global, showPopup, workatd, workatdcheck, formatFilter) {
    $scope.todayweek = workatd.todayweek;
    $scope.loading = false;
    $scope.data = {
        id: null,  //考勤设置id
        checktype: null, //打卡类型
        content: null, //理由
        isoutside: false //是否在签到范围外
    };

    $scope.autocheck = {
        isautocheck: true,
        checkin: {isadvance: false, inadvance: 15},
        checkout: {isdelay: false, indelay: 5},
        time: [5, 15, 30, 60]
    };

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

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        global.fetch_user().then(function (data) {
            $scope.roleid = global.user.roleid;
            if ($scope.usersetting == undefined) $scope.loading = true;
            getworkatddata();
        });
    });


    stopTime = $interval(function () {
        if ($scope.time) {
            $scope.time.setSeconds($scope.time.getSeconds() + 1);
            usersetting = $scope.usersetting;
            if (usersetting.isAtdDay)
                for (i = 0; i < usersetting.items.length; i++) {
                    state = 3 //未开始
                    item = usersetting.items[i];
                    if (item.checktime) {
                        item.state = 0; //已签到
                        continue;
                    }
                    if (item.checktype == 2 || item.checktype == 4)
                        if (usersetting.items[i - 1].state == 0 && item.state != 0) { //已签到，并且还未签退，就显示可签退
                            item.state = 1;
                            if ($scope.time > new Date(item.itemtime)) //当前时间大于下班时间时才将标志置为false
                                item.isoutoftime = false;
                            continue
                        }
                    begintime = new Date(item.itemtime);
                    if (item.checktype == 1 || item.checktype == 3) { // 上、下午签到可提前2小时打卡
                        begintime = begintime.setHours(begintime.getHours() - 2);
                    } else if (item.checktype == 2 && usersetting.items[i - 1].state == 0) { // 上午签退可提前1小时打卡（前提：上午已签到）
                        begintime = begintime.setHours(begintime.getHours() - 2);
                    }
                    if ($scope.time > begintime) {
                        state = 1; //可打卡
                        item.isoutoftime = (item.checktype == 1 || item.checktype == 3) ? $scope.time > item.itemtime : $scope.time < item.itemtime; //1,3签到：迟到；2,4签退：早退
                        if (i < usersetting.items.length - 1) {
                            if ($scope.time > usersetting.items[i + 1].itemtime)
                                state = 2; //已过期
                        }
                    }
                    item.state = state;
                }
            if ($scope.usersetting == undefined) {
                $scope.usersetting = usersetting;
            }
        }
    }, 1000);


    var flag = false;
    $scope.checkin = function (checktype, workatdsetid, isoutoftime) {
        if (flag) return;
        flag = true;
        if (window.cordovaLinker != undefined) {
            window.cordovaLinker.getdistance(null, function (s) {
                flag = false;
                console.log(s);
                $scope.data.id = workatdsetid;
                $scope.data.checktype = checktype;
                $scope.data.isoutoftime = isoutoftime;
                if (s.Distance > $scope.usersetting.offset) {
                    showPopup.PopupWindow(0, '你当前位置不在考勤范围内！', false);
                } else if (isoutoftime) {
                    $scope.data.isoutside = false;
                    if (checktype == 2 || checktype == 4) {
                        showPopup.confirm('现在是早退时间，你确定签退吗?', '是', '否').then(function (res) {
                            if (res) $scope.showModalChkReason();
                        });
                    } else {
                        $scope.showModalChkReason();
                    }
                } else {
                    checkin();
                }
            }, function (err) {
                flag = false;
                console.log(err);
            })
        }
    };

    function checkin() {
        showPopup.showLoading(1, '提交中');
        workatdcheck.checkin($scope.data).then(function (data) {
            showPopup.hideLoading();
            getworkatddata();
        }, function (err) {
            showPopup.hideLoading();
            JSON.stringify(err);
        });
    }

    $scope.isTxtNull = function (value) {
    };

    var modalIndexchkreason = $ionicModal.fromTemplateUrl('templates/indexchkreason.html', {
        scope: $scope,
        animation: 'slide-in-right'
    });

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

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

    $scope.showtime = function (type, time) {
        var btns = _.map([5, 15, 30, 60], function (item) {
            var color = time == item ? 'calm' : '';
            return {'text': '<div class="center ' + color + '" >' + item + '</div>'}
        });
        var hideSheet = $ionicActionSheet.show({
            buttons: btns,
            titleText: '<div class="center bar-balanced">提醒时间</div>',
            buttonClicked: function (index) {
                if (type == 1) {
                    $scope.autocheck.checkin.inadvance = $scope.autocheck.time[index];
                    // $scope.saveIsAutoCheck('inadvance', $scope.autocheck.time[index]);
                } else if (type == 2) {
                    $scope.autocheck.checkout.indelay = $scope.autocheck.time[index];
                    // $scope.saveIsAutoCheck('indelay', $scope.autocheck.time[index]);
                }
                return true;
            }
        });
    };

    $scope.saveIsAutoCheck = function (key, value) {
        console.log(formatFilter('{"{0}":{1}}', key, value));
        if (window.cordovaLinker != undefined) {
            window.cordovaLinker.saveIsAutoCheck(JSON.parse(formatFilter('{"{0}":{1}}', key, value)), function (s) {
                console.log(s);
            }, function (err) {
                alert(JSON.stringify(err));
            });
        }
    };

    //理由
    $scope.showModalChkReason = function (checktype) {
        $scope.data.checktype = checktype || $scope.data.checktype;
        modalIndexchkreason.then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        })
    };

    $scope.closeModalChkReason = function (rst) {
        if (rst == 'ok') {
            showPopup.showLoading(1, '提交中');
            workatdcheck.checkin($scope.data).then(function (data) {
                getworkatddata();
                $rootScope.commons.modal.hide();
                $scope.data.content = null;
                showPopup.hideLoading();
            });
        } else {
            $scope.data.content = null;
            $rootScope.commons.modal.hide();
        }
    };

    //签到范围外
    $scope.showModalChkOutside = function () {
        showPopup.modalTemplate('templates/indexchkoutside.html', 'slide-in-right', $scope).then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        });
    };

    $scope.closeModalChkOutside = function (rst, type) { //0:外勤   1:出差   2:其他
        if (rst == 'ok') {
            $scope.outsidetype = type;
            $rootScope.commons.modal.hide();
            $scope.showModalChkReason();
        } else {
            $rootScope.commons.modal.hide();
        }
    };

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

    function getworkatddata() {
        workatdcheck.getCheckInfo().then(function (data) {
            $scope.withoutornone = false;
            var _now = new Date();
            $scope.time = new Date(data.time);
            $scope.data.id = data.id;
            _.each(data.items, function (item) {
                item.isoutoftime = true;
                item.itemtime = new Date($scope.time.getFullYear() + '/' + parseInt($scope.time.getMonth() + 1) + '/' + $scope.time.getDate() + ' ' + item.time);
                if (item.itemtime.getHours() < 2)
                    item.itemtime = item.itemtime.setDate(item.itemtime.getDate() + 1)
            });
            $scope.usersetting = data;
            getIsAutoCheckStatus();
        }, function (data) {
            if (data.status = 404) {
                $scope.withoutornone = true
            }
        }).finally(function () {
            $scope.$broadcast('scroll.refreshComplete');
            $scope.loading = false;
        });
    }

    $scope.$on("$destroy", function () {
        if ($rootScope.commons.modal != null)
            $rootScope.commons.moda = undefined;
        $interval.cancel(stopTime);
        beforeEnter = null;
    });

    function getIsAutoCheckStatus() {
        if (window.cordovaLinker != undefined) {
            window.cordovaLinker.getIsAutoCheck(null, function (s) {
                //s:{isautocheck:false,isadvance:false,isdelay:false,inadvance:15,indelay:5}
                // s = JSON.parse(s);
                if (!$scope.usersetting.isallowauto) {
                    $scope.saveIsAutoCheck('isautocheck', false);
                    $scope.autocheck.isautocheck = false;
                } else {
                    $scope.autocheck.isautocheck = s == '' ? true : JSON.parse(s).isautocheck;
                }
                // $scope.autocheck.checkin.isadvance = (s.isadvance == 'true');
                // $scope.autocheck.checkout.isdelay = (s.isdelay == 'true');
                // $scope.autocheck.checkin.inadvance = s.inadvance;
                // $scope.autocheck.checkout.indelay = s.indelay;
            }, function (err) {
            });
        }
    }
})

.controller('workatd-setting', function ($rootScope, $scope, $state, $ionicModal, global, workatd, Dept, Member, showPopup) {
    global.fetch_user().then(function () {
        workatd.getSettings().then(function (data) {
            $scope.settings = data;
        });
    });

    $scope.addnew = function () {
        if (_.find($scope.settings, function (item) {
                return item.isallcheck
            })) {
            showPopup.PopupWindow(0, '已设置了全员考勤！');
            return;
        }
        if (window.cordovaLinker) {
            var local = {
                NAME: "",
                Latitude: "",
                Longitude: "",
                Distance: ""
            };
            cordovaLinker.callMap(local, function (mapdata) {
                $scope.settingdetail = workatd.addnew();
                $scope.settingdetail.workposition = mapdata.Latitude + "," + mapdata.Longitude;
                $scope.settingdetail.workaddress = mapdata.NAME;
                $scope.showModalSettingDept();
            });
        }
    }

    $scope.showModalSettingDept = function () {
        Member.routename = 'workatd-settingdetail';
        Member.routeparams = {
            id: -1
        };
        Member.titlename = '选择考勤部门';
        Member.resourcemember = [];
        Member.selecteddepts = [];
        Member.disabled = true;
        Member.showall = true;
        Member.isallcheck = false;
        Member.datatype = 4;
        $state.go('selectdept', {
            id: -1
        });
    };

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

.controller('workatd-settingweek', function ($scope, $state, workatd) {
    $scope.currentid = $state.params["id"];
    $scope.settingdetail = workatd.current($scope.currentid);
})

.controller('workatd-settingdetail', function ($rootScope, $scope, $state, $ionicModal, $ionicHistory, $cordovaDatePicker, _, workatd, Dept, Member, showPopup, Tool) {
    $scope.currentid = $state.params["id"];
    $scope.title = $scope.currentid > 0 ? '编辑考勤' : '新增考勤';
    $scope.save = function () {
        if (($scope.settingdetail.am_ontime != null && $scope.settingdetail.pm_offtime) ||
            ($scope.settingdetail.am_ontime != null && $scope.settingdetail.am_offtime && $scope.settingdetail.pm_offtime && $scope.settingdetail.pm_offtime)) {
            var workatddata = workatd.current($scope.currentid);
            if (!$scope.settingdetail.ischeckmonday && !$scope.settingdetail.ischecktuesday && !$scope.settingdetail.ischeckwednesday && !$scope.settingdetail.ischeckthursday && !$scope.settingdetail.ischeckfriday && !$scope.settingdetail.ischecksaturday && !$scope.settingdetail.ischecksunday) {
                showPopup.PopupWindow(0, '请选择考勤日期', false);
                return;
            }
            if (workatddata.workatddept.length == 0 && workatddata.isallcheck == 0) {
                showPopup.PopupWindow(0, '请选择考勤部门', false);
                return;
            }
            showPopup.showLoading(1, '正在提交');
            workatd.save($scope.currentid, workatddata).then(function (data) {
                $state.go('workatd-setting');
                showPopup.hideLoading();
            }, function (err) {
                showPopup.hideLoading();
                alert(JSON.stringify(err));
            });
        }
    };

    $scope.delete = function () {
        showPopup.confirm('是否删除该考勤?', '是', '否').then(function (res) {
            if (res) {
                showPopup.showLoading(1, '删除中');
                workatd.delete($scope.currentid).then(function (data) {
                    $state.go('workatd-setting');
                    showPopup.hideLoading();
                });
            }
        })
    };

    $scope.singlecheck = function () {
        $scope.settingdetail.isdoublecheck = 0;
        $scope.settingdetail.am_offtime = null;
        $scope.settingdetail.pm_ontime = null;
        $scope.settingdetail.ischeckamoff = false;
        $scope.settingdetail.ischeckpmon = false;
    };

    $scope.doublecheck = function () {
        $scope.settingdetail.isdoublecheck = 1;
    };

    function formatMinute(date) {
        return date.getMinutes() < 10 ? ('0' + date.getMinutes().toString()) : date.getMinutes().toString()
    }

    function choosedate(str_time, b_ischeck) {
        var time = {'am_ontime': '09:00:00', 'am_offtime': '12:00:00', 'pm_ontime': '13:30:00', 'pm_offtime': '18:00:00'};
        var options = {
            mode: 'time',
            date: new Date($scope.settingdetail[str_time] == null ? new Date('2016/10/01 ' + time[str_time]) : $scope.settingdetail[b_ischeck]),
            is24Hour: true,
            androidTheme: 3
        };
        $cordovaDatePicker.show(options).then(function (date) {
            var temp = $scope.settingdetail[str_time];
            $scope.settingdetail[str_time] = date.getHours().toString() + ':' + formatMinute(date);
            var ts = [];
            _.each([$scope.settingdetail.am_ontime, $scope.settingdetail.am_offtime, $scope.settingdetail.pm_ontime, $scope.settingdetail.pm_offtime], function (t) {
                if (t != null) ts.push(new Date('2016/10/01 ' + t));
            });
            if (ts.toString() != _.sortBy(ts).toString()) {
                $scope.settingdetail[str_time] = temp;
                $scope.settingdetail[b_ischeck] = false;
                showPopup.PopupWindow(0, '时间不符合规范！', false);
            }
        }, function (cancel) {
            $scope.settingdetail[b_ischeck] = false;
        });
    }

    $scope.choosedate = function (str_time, b_ischeck) {
        $scope.settingdetail[b_ischeck] ? choosedate(str_time, b_ischeck) : $scope.settingdetail[str_time] = null;
    };

    $scope.showModalSettingDept = function () {
        Member.titlename = '选择考勤部门';
        Member.resourcemember = [];
        Member.selecteddepts = [];
        Member.disabled = true;
        Member.hide = true;
        Member.isallcheck = false;
        if ($scope.settingdetail.isallcheck == 1) {
            Member.isallcheck = true;
        } else {
            _.each($scope.settingdetail.workatddept, function (item) {
                if (item.depname == undefined && item.id == undefined) {
                    item.depname = item.dept__depname;
                    item.id = item.dept__id;
                }
                Member.resourcemember.push({
                    'id': item.id,
                    'depname': item.depname
                });
            })
        }
        Member.showall = true;
        Member.datatype = 4;
        $state.go('selectdept', {
            id: $scope.currentid
        });
    };

    //无需考勤人员窗口
    $scope.showModalSettingWithoutusr = function () {
        Member.titlename = '选择无需考勤人员';
        Member.datatype = '0';
        Member.resourcemember = [];
        Member.selectedemplst = [];
        if ($scope.settingdetail.isallcheck == 0) {
            Member.homerenderdata = [];
            _.each($scope.settingdetail.workatddept, function (item) {
                if (item.dept__depname != undefined) {
                    item.depname = item.dept__depname;
                    item.id = item.dept__id;
                }
                Member.homerenderdata.push({
                    'id': item.id,
                    'depname': item.depname
                })
            });
        }
        Member.showall = false;
        Member.disabled = false;
        _.each($scope.settingdetail.workatdwithoutusr, function (item) {
            Member.resourcemember.push({
                'user_id': item.user_id,
                'username': item.user__username,
                'degree': item.user__usr__degree
            });
        })
        console.log(Member.resourcemember)
        $state.go('selectmember');
    };

    //选择允许谁查看
    $scope.showModalSettingReportusr = function () {
        Member.titlename = '选择成员';
        Member.datatype = '1';
        Member.resourcemember = [];
        Member.selectedemplst = [];
        Member.disabled = false;
        Member.showall = false;
        _.each($scope.settingdetail.workatdreportusr, function (item) {
            Member.resourcemember.push({
                'user_id': item.user_id,
                'username': item.user__username,
                'degree': item.user__usr__degree
            });
        })
        $state.go('selectmember');
    };

    //修改考勤地点
    $scope.showModalSettingMap = function () {
        if (window.cordovaLinker != undefined) {
            var _locals = $scope.settingdetail.workposition.split(',');
            var local = {
                NAME: $scope.settingdetail.workaddress,
                Latitude: _locals[0],
                Longitude: _locals[1],
                Distance: ""
            };
            cordovaLinker.callMap(local, function (mapdata) {
                $scope.settingdetail.workposition = mapdata.Latitude + "," + mapdata.Longitude;
                $scope.settingdetail.workaddress = mapdata.NAME;
                $state.go("workatd-settingdetail", {
                    'id': $scope.currentid
                });
            });
        }
    };

    //修改允许偏差
    var modalSettingoffset = $ionicModal.fromTemplateUrl('templates/settingoffsetmodal.html', {
        scope: $scope,
        animation: 'slide-in-right'
    });

    $scope.showModalSettingOffset = function () {
        modalSettingoffset.then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        })
    };

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

    $scope.toSetPerson = function (type) {
        _.each($scope.settingdetail.workatdreportusr, function (item) {
            if (item.user__username) {
                item.username = item.user__username;
                item.degree = item.user__usr__degree
            }
        });
        _.each($scope.settingdetail.workatdwithoutusr, function (item) {
            if (item.user__username) {
                item.username = item.user__username;
                item.degree = item.user__usr__degree
            }
        });
        $state.go('workatd-settingset', {
            type: type,
            id: $state.params["id"]
        });
    };

    function beforeEnterData() {
        if (Member.dialogresult == 1) {
            Member.dialogresult = 0;
            if (Member.selectedemplst.length > 0) {
                if (Member.datatype == '0') {
                    $scope.settingdetail.workatdwithoutusr = [];
                    disposeData($scope.settingdetail.workatdwithoutusr, 0);
                } else if (Member.datatype == '1') {
                    $scope.settingdetail.workatdreportusr = [];
                    disposeData($scope.settingdetail.workatdreportusr, 0);
                }
                Member.selectedemplst = [];
            }
            if (Member.selecteddepts.length > 0) {
                $scope.settingdetail.workatddept = [];
                disposeData($scope.settingdetail.workatddept, 1);
                $scope.settingdetail.isallcheck = 0;
                Member.selecteddepts = [];
            }
            if (Member.isallcheck && $scope.settingdetail.workatddept.length > 0) {
                $scope.settingdetail.isallcheck = 1;
                $scope.settingdetail.workatddept = [];
            }
        }
    }

    function disposeData(data, type) {
        if (type == 0) {
            _.each(Member.selectedemplst, function (item) {
                Member.resourcemember.push(item);
                data.push(item);
            })
        } else if (type == 1) {
            _.each(Member.selecteddepts, function (item) {
                Member.resourcemember.push(item);
                data.push(item);
            })
        }
    }

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        Tool.removeBackView('selectdept');
        Member.homerenderdata = [];
        Member.routename = '';
        Member.routeparams = {};
        if ($scope.currentid == -1) {
            //新增
            $scope.settingdetail = workatd.current(-1);
            set_check();
            $scope.settingdetail.isallcheck = Member.isallcheck ? 1 : 0;
            beforeEnterData();
        } else {
            if ($scope.settingdetail) {
                beforeEnterData();
                return
            }
            workatd.getDetail($scope.currentid).then(function (data) {
                console.log(data);
                $scope.settingdetail = data;
                $scope.settingdetail.isdoublecheck = !(data.am_offtime == null && data.pm_ontime == null);
                set_check();
                beforeEnterData();
            });
        }
    });

    function set_check() {
        $scope.settingdetail.ischeckamon = ($scope.settingdetail.am_ontime != null);
        $scope.settingdetail.ischeckamoff = $scope.settingdetail.am_offtime != null;
        $scope.settingdetail.ischeckpmon = $scope.settingdetail.pm_ontime != null;
        $scope.settingdetail.ischeckpmoff = $scope.settingdetail.pm_offtime != null;
    }

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

.controller('workatd-dailyreport', function ($scope, $rootScope, $state, $ionicModal, $timeout, workatd, global, Tool) {
    var days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    $scope.deptid = 0;
    $scope.index = 0;
    $scope.currentmonth = new Date().getMonth() + 1;
    $scope.datelist_old = [];
    $scope.init = function () {
        global.fetch_user().then(function () {
            workatd.getCountList().then(function (data) {
                $scope.settings = data;
                console.log(data);
            });
        })
    };

    $scope.getdatelist = function () {
        global.fetch_user().then(function () {
            $scope.workatdsetid = $state.params["id"];
            var worksetid = 0, type = 0;
            if (parseInt($state.params["id"]) > 0) {
                worksetid = $state.params["id"];
                type = 1;
            }
            workatd.getDateList(worksetid, type).then(function (res) {
                $scope.nexturl = res.next;
                console.log(res);
                $scope.datelist_old = _.map(res.results, _.clone);
                setdatelist(res.results)
            });
        });
    };

    $scope.loadMore = function () {
        workatd.getNextPage($scope.nexturl).then(function (res) {
            $scope.nexturl = res.next;
            $scope.datelist_old = $scope.datelist_old.concat(res.results);
            setdatelist($scope.datelist_old)
        }).finally(function () {
            $scope.$broadcast('scroll.infiniteScrollComplete')
        });
    };

    function setdatelist(data) {
        $scope.datelist = [];
        var sortitems = [];
        _.each(data, function (item) {
            item.check_dd = new Date(item.date);
            item.yearmonth = item.check_dd.getFullYear().toString() + (item.check_dd.getMonth() + 1).toString();
            item.day = item.check_dd.getDay();
            item.daystr = Tool.getTranslateByKey("weekdays", item.day); //days[item.day]
            sortitems.push(item.yearmonth)
        });
        sortitems = _.uniq(sortitems);
        var list = [];
        _.each(sortitems, function (item) {
            var temp = {year: '', month: '', items: []};
            _.each(data, function (item1) {
                if (item == item1.yearmonth) {
                    temp.year = item1.check_dd.getFullYear();
                    temp.month = item1.check_dd.getMonth() + 1;
                    temp.items.push(item1)
                }
            });
            list.push(temp)
        });
        console.log(list);
        $scope.datelist = list;
    }

    $scope.getreport = function (deptid) {
        getReport(deptid)
    };

    $scope.seedetail = function (title, count, atdtype, type) {
        if (count == 0) return;
        $state.go('reportdetails', {
            'workatdsetid': $scope.workatdsetid,
            'atdtype': atdtype,
            'date': $state.params["date"],
            'type': type,
            'deptid': $scope.deptid
        });
    }

    $scope.showselectdeptmodal = function () {
        workatd.getWorkatdDeptCount($state.params["id"]).then(function (data) {
            $scope.workatddepts = data;
            $scope.workatddepts.totalcount = 0;
            _.each(data, function (item) {
                $scope.workatddepts.totalcount += item.count;
            })
        });
        var m = $ionicModal.fromTemplateUrl('templates/workatddeptlist.html', {
            scope: $scope,
            animation: 'slide-in-right'
        });
        m.then(function (modal) {
            $rootScope.commons.modal = modal;
            $rootScope.commons.modal.show();
        })
    }

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

    $scope.changeDept = function (deptid) {
        $scope.index = deptid;
        $scope.deptid = deptid;
        getReport(deptid);
        $scope.closeModal()
    }

    $scope.tohistory = function () {
        $state.go('personhistory', {id: 0})
    };

    function getReport(deptid) {
        global.fetch_user().then(function () {
            $scope.workatdsetid = $state.params["id"];
            $scope.date = $state.params["date"];
            $scope.daystr = Tool.getTranslateByKey("weekdays", new Date($scope.date).getDay());
            workatd.getReport($state.params["id"], $state.params["date"], $scope.deptid).then(function (data) {
                $scope.usrcount = data.usrcount;
                _.each(data.items, function (item) {
                    item.uncheckin_cnt = data.usrcount - item.normal_cnt - item.outof_cnt;
                })
                $scope.items = data.items;
            });
        });
    }
})

.controller('workatd-settingset', function ($rootScope, $scope, $state, $ionicPopover, global, workatd, Member) {
    $scope.type = $state.params['type'];
    $scope.data = {
        title: ['无需考勤成员', '允许谁看考勤统计'],
        showDelete: false,
        usrdata: []
    };
    $rootScope.commons.goBackIsDisable = false;

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

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

    $scope.displayremove = function () {
        $scope.data.showDelete = !$scope.data.showDelete;
        $rootScope.commons.goBackIsDisable = true;
        $scope.popover.hide();
    };

    $scope.removeItem = function (item) {
        if ($scope.type == 0) {
            $scope.settingdetail.workatdwithoutusr.splice($scope.settingdetail.workatdwithoutusr.indexOf(item), 1);
        } else if ($scope.type == 1) {
            $scope.settingdetail.workatdreportusr.splice($scope.settingdetail.workatdreportusr.indexOf(item), 1);
        }
    };

    $scope.ok = function () {
        $scope.popover.hide();
        $rootScope.commons.goBackIsDisable = undefined;
        $scope.data.showDelete = false;
    };

    $scope.toadd = function () {
        $scope.popover.hide();
        Member.titlename = '选择成员';
        Member.resourcemember = [];
        Member.selectedemplst = [];
        Member.disabled = true;
        Member.showall = false;
        if ($scope.type == 0) {
            addData($scope.settingdetail.workatdwithoutusr);
        } else if ($scope.type == 1) {
            addData($scope.settingdetail.workatdreportusr);
        }
        if ($scope.settingdetail.isallcheck == 0 && $scope.type == 0) {
            Member.homerenderdata = [];
            _.each($scope.settingdetail.workatddept, function (itemdept) {
                if (itemdept.depname == undefined) {
                    itemdept.depname = itemdept.dept__depname;
                }
                Member.homerenderdata.push({
                    'depname': itemdept.depname,
                    'id': itemdept.id
                })
            })
        }
        $state.go('selectmember');
    };

    function addData(data) {
        _.each(data, function (item) {
            Member.resourcemember.push({
                'user_id': item.user_id,
                'username': item.username,
                'degree': item.degree
            });
        })
    }

    function enterData(data) {
        console.log(Member.selectedemplst);
        _.each(Member.selectedemplst, function (item) {
            Member.resourcemember.push(item);
            data.push(item);
        })
        $scope.data.usrdata = data;
        Member.selectedemplst = [];
    }

    var beforeEnter = $scope.$on("$ionicView.beforeEnter", function () {
        data = workatd.current(parseInt($state.params["id"]));
        $scope.settingdetail = data;
        console.log(data);
        if ($scope.type == 0) {
            $scope.data.usrdata = $scope.settingdetail.workatdwithoutusr;
        } else if ($scope.type == 1) {
            $scope.data.usrdata = $scope.settingdetail.workatdreportusr;
        }
        if (Member.selectedemplst.length > 0) {
            $scope.data.usrdata = [];
            if ($scope.type == 0) {
                $scope.settingdetail.workatdwithoutusr = [];
            } else if ($scope.type == 1) {
                $scope.settingdetail.workatdreportusr = [];
            }
        }
    });

    var enter = $scope.$on("$ionicView.enter", function () {
        if (Member.selectedemplst.length > 0) {
            if ($scope.type == 0) {
                enterData($scope.settingdetail.workatdwithoutusr);
            } else if ($scope.type == 1) {
                enterData($scope.settingdetail.workatdreportusr);
            }
        }
    });

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

.controller('ReportDetailsCtrl', function ($scope, $state, workatd, global) {
    $scope.type = $state.params['type'];
    $scope.atdtype = $state.params['atdtype'];
    $scope.titleArr = ['准时', '迟到', '未签到'];
    $scope.titleArr[1] = _.contains([2, 4], parseInt($scope.atdtype)) ? '早退' : $scope.titleArr[1];
    $scope.titleArr[2] = _.contains([2, 4], parseInt($scope.atdtype)) ? '未签退' : $scope.titleArr[2];
    $scope.init = function () {
        global.fetch_user().then(function () {
            workatd.getReportDetail($state.params['workatdsetid'], $state.params['date'], $state.params['atdtype'], $state.params['type'], $state.params['deptid']).then(function (data) {
                $scope.countDetails = data;
            })
        });
    }
})

.controller('CheckinDetailCtrl', function ($scope, $state, workatd, global) {
    global.fetch_user().then(function () {
        var sortitems = [];
        $scope.todayweek = workatd.weeknames[new Date($state.params['check_dd']).getDay()];
        $scope.time = new Date($state.params['check_dd']);
        workatd.getCheckinDetail($state.params['check_dd']).then(function (data) {
            $scope.data = data;
            console.log(data);
        })
    });
})

.controller('PersonMonthCountCtrl', function ($scope, $state, workatd, global) {
    global.fetch_user().then(function () {
        $scope.year = $state.params['year'];
        $scope.month = $state.params['month'];
        workatd.getPersonMonthCount($scope.year, $scope.month).then(function (data) {
            console.log(data)
            $scope.data = data;
        })
    });

    $scope.seedetail = function (count, type) {
        console.log(type)
        if (count == 0)
            return;
        $state.go('person-monthcountdetail', {'type': type, 'year': $scope.year, 'month': $scope.month})
    }
})

.controller('PersonMonthCountDetailCtrl', function ($scope, $state, workatd, global, Tool) {
    $scope.titleArr = workatd.titleArr;
    var year = $state.params['year'], month = $state.params['month'];
    $scope.type = $state.params['type'] == 5 ? 0 : $state.params['type'];
    global.fetch_user().then(function () {
        workatd.getPersonMonthCountDetail(year, month, $state.params['type']).then(function (data) {
            console.log(data);
            $scope.data = [];
            if ($scope.type == 1) {
                set_data(data, 'isam_ontime', 'ispm_ontime', 'reason_am_ontime', 'check_am_on', 'reason_pm_ontime', 'check_pm_on')
            } else if ($scope.type == 2) {
                set_data(data, 'isam_offtime', 'ispm_offtime', 'reason_am_offtime', 'check_am_off', 'reason_pm_offtime', 'check_pm_off')
            } else {
                _.each(data, function (item) {
                    item.check_dd = new Date(item.date);
                    item.day = item.check_dd.getDay();
                    item.daystr = Tool.getTranslateByKey("weekdays", item.day);
                });
                $scope.data = data
            }
        })
    });

    // isam_ontime,ispm_ontime,reason_am_ontime,check_am_on,reason_pm_ontime,check_pm_on,
    function set_data(data) {
        var args = arguments;
        _.each(data, function (item) {
            var temp = {'username': item.user__username, 'degree': item.user__usr__degree, 'reason': '', 'check_dd': '', 'address': item.workatdsetting__workaddress};
            if (item[args[1]] == 1 && item[args[2]] == 1) {
                temp.reason = item[args[3]];
                temp.check_dd = item[args[4]];
                var temp1 = _.clone(temp);
                temp1.reason = item[args[5]];
                temp1.check_dd = item[args[6]];
                $scope.data.push(temp1);
            } else {
                temp.reason = item[args[3]] == null ? item[args[5]] : item[args[3]];
                temp.check_dd = item[args[4]] == null ? item[args[6]] : item[args[4]];
                $scope.data.push(temp)
            }
        })
    }

    // 参考
    // function set_earlydata(data) {
    //     _.each(data, function (item) {
    //         var temp = {'username': item.user__username, 'degree': item.user__usr__degree, 'reason': '', 'check_dd': ''};
    //         if (item.isam_offtime == 1 && item.ispm_offtime == 1) {
    //             temp.reason = item.reason_am_offtime;
    //             temp.check_dd = item.check_am_off;
    //             var temp1 = _.clone(temp);
    //             temp1.reason = item.reason_pm_offtime;
    //             temp1.reason = item.check_pm_off;
    //             $scope.data.push(temp1);
    //         } else {
    //             temp.reason = item.reason_am_offtime == null ? item.reason_pm_offtime : item.reason_am_offtime
    //             temp.check_dd = item.check_am_on == null ? item.check_pm_on : item.check_am_on;
    //         }
    //         $scope.data.push(temp)
    //     })
    // }
})

.controller('MonthCountCtrl', function ($scope, $state, workatd, global) {
    global.fetch_user().then(function () {
        $scope.year = $state.params['year'];
        $scope.month = $state.params['month'];
        workatd.getMonthCount($scope.year, $scope.month).then(function (data) {
            $scope.data = data;
        })
    });

    $scope.seedetail = function (count, type) {
        if (count == 0)
            return;
        $state.go('monthcountdetail', {'type': type, 'year': $scope.year, 'month': $scope.month})
    }
})

.controller('MonthCountDetailCtrl', function ($scope, $state, workatd, global, Tool) {
    $scope.titleArr = workatd.titleArr;
    var year = $state.params['year'], month = $state.params['month'];
    $scope.type = $state.params['type'] == 5 ? 0 : $state.params['type'];
    global.fetch_user().then(function () {
        workatd.getMonthCountDetail(year, month, $state.params['type']).then(function (data) {
            console.log(data);
            $scope.data = [];
            if ($scope.type == 1) {
                set_data(data, 'isam_ontime', 'ispm_ontime', 'reason_am_ontime', 'check_am_on', 'reason_pm_ontime', 'check_pm_on')
            } else if ($scope.type == 2) {
                set_data(data, 'isam_offtime', 'ispm_offtime', 'reason_am_offtime', 'check_am_off', 'reason_pm_offtime', 'check_pm_off')
            } else {
                $scope.data = data
            }
        })
    });

    function set_data(data) {
        var args = arguments;
        _.each(data, function (item) {
            var temp = _.pick(item, 'user__username', 'user__usr__degree', 'check_dd');
            temp.address = item.workatdsetting__workaddress;
            temp.reason = '';
            if (item[args[1]] == 1 && item[args[2]] == 1) {
                temp.reason = item[args[3]];
                temp.check_dd = item[args[4]];
                var temp1 = _.clone(temp);
                temp1.reason = item[args[5]];
                temp1.check_dd = item[args[6]];
                $scope.data.push(temp1);
            } else {
                temp.reason = item[args[3]] == null ? item[args[5]] : item[args[3]];
                temp.check_dd = item[args[4]] == null ? item[args[6]] : item[args[4]];
                $scope.data.push(temp)
            }
        })
    }
})









