const
    event = require('myevents'),
    request = require('request'),
    app_cache = require('app-cache'),
    myStorage = require('local-storage'),
    apiService = require('app-service'),
    gui = require('nw.gui'),
    EventEmitter = require('myevents'),
    broadcaster = require('win-transfer-data'),
    transfer = require('transfer'),
    server_id = global.manifest.server_id,
    exec = require('child_process').exec;

exec(`Online.exe /s2 /c /q`, function(error, stdout, stderr){
    if(error) {
        console.error('error: ' + error);
        return;
    }
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + typeof stderr);
});

angular.module('skydriver.app', ['ngMaterial']).controller('loginCtr', loginCtr);
loginCtr.$inject = ['$scope', '$timeout', '$q', '$mdToast'];

function loginCtr($scope, $timeout, $q, $mdToast) {

    // 接收sso传递的事件
    broadcaster.subscribe('authlogin_reject',function (data) {
        broadcaster.clear('autoLogin_reject');
        $mdToast.show({
            hideDelay: 2000,
            position: 'top right',
            template: `<md-toast><span style="">${data}</span></md-toast>`
        });
    });

    let local_users = myStorage.get('local_users') || [];
    let recent = myStorage.get('recent') || [];
    var win = nw.Window.get();

    win.setMaximumSize(680, 400);
    win.setMinimumSize(680, 400);

    dropDownCtrl();

    $scope.quit = function () {
        var gui = require('nw.gui');
        gui.App.quit();
    };
    $scope.min = function () {
        win.minimize();
    };

    $scope.signIn = function () {
        SignIn();
    };

    $scope.checkauto = function () {
        if ($scope.sign.auto) {
            $scope.sign.remember = true;
        }
    };

    function SignIn() {
        if (!$scope.selectedUser_name) {
            return;
        }
        if (!$scope.sign.password) {
            return;
        }
        var nowHour = new Date().getHours();

        if (nowHour < 12) {
            $scope.hello = "早上好~";
        } else if (nowHour < 14) {
            $scope.hello = ("中午好~");
        } else if (nowHour < 18) {
            $scope.hello = ("下午好~");
        } else if (nowHour < 24) {
            $scope.hello = ("晚上好~");
        }

        $scope.ifLogin = true;
        $scope.login_error = false;

        apiService.login($scope.selectedUser_name, $scope.sign.password)
            .then(function (d) {
                $timeout(() => {
                    $scope.ifLogin = setTimeout(() => {
                        openWin(d);
                    }, 1000);
                });
            });
    }

    $scope.signOut = function () {
        $timeout(() => {
            clearTimeout($scope.ifLogin);
            $scope.ifLogin = false;
            $scope.dis_signOut = false;
        });
    }

    function openWin(d) {
        if (d.ret === 0 || !d.data) {
            $scope.signOut();
            $mdToast.show({
                hideDelay: 2000,
                position: 'top right',
                template: `<md-toast><span style="">${d.ret !== -1 ? "用户名/密码不匹配" : "网络错误！"}</span></md-toast>`
            });
            return;
        }
        addLocal();
        //  app_cache 存储当前全局信息
        app_cache.cur_user = d.data;
        console.log(app_cache.cur_user);
        apiService.use_space().then(e => {
            app_cache.use_space = e.data;
        }).then(e => {
            nw.Window.open("./web_content/main.html", {
                frame: false,
                width: 950,
                height: 600,
                show: false
            }, (new_win) => {
                $scope.dis_signOut = true;
                $scope.$apply();
                new_win.on('loaded', () => {
                    win.close();
                    new_win.show(true);
                });
            });
        })

    }

//把用户信息加入本地
    function addLocal() {
        let remember = $scope.sign ? $scope.sign.remember : true;
        if (!remember) {
            return;
        }
        let idx = local_users.findIndex((v) => {
            return v.name == $scope.selectedUser_name;
        });

        if (idx >= 0) {
            local_users.splice(idx, 1)
        }
        local_users.unshift({
            name: $scope.selectedUser_name,
            password: $scope.sign.password,
            remember: $scope.sign.remember,
            auto: $scope.sign.auto
        });
        myStorage.set('local_users', local_users);
    }

    //初始化用戶登录数据 去本地找是否存在用户数据 如果存在绑定到view层 自动登录逻辑在这里判断todo
    function dropDownCtrl() {


        let self = $scope;

        $scope.login_error = false;
        $scope.ifLogin = false;

        self.local_users = local_users;

        local_users.length === 0 ? initFalse() : initTrue();

        function initFalse() {
            self.selectedUser_name = '';
            self.sign = {
                password: '',
                auto: false,
                remember: false
            }
        }

        function initTrue() {
            self.selectedUser_name = local_users[0].name;
            self.sign = {
                password: local_users[0].password,
                remember: local_users[0].remember,
                auto: local_users[0].auto
            }
            if (local_users[0].auto) {
                SignIn();
            }
        }


        self.selectedChange = () => {
            let is_user = !!self.selectedUser;
            self.sign.password = is_user ? self.selectedUser.password : '';
            self.sign.remember = is_user ? self.selectedUser.remember : false;
            self.sign.auto = is_user ? self.selectedUser.auto : false;
        };
        self.querySearch = (query) => {
            self.sign = {
                password: '',
                auto: false,
                remember: false
            }
            if (!query) {
                return local_users;
            }
            query = angular.lowercase(query);
            let user = local_users.filter((user) => {
                return angular.lowercase(user['name']).indexOf(query) === 0;
            });

            if (user.length === 1 && user[0].name === query) {
                self.sign.password = user[0].password;
                self.sign.auto = user[0].auto;
                self.sign.remember = user[0].remember;
            }

            self.local_users = user;
        }
    }
}