import { Router, ActivatedRoute, Params } from '@angular/router';
import { AppEnvironment } from '@environments/AppEnvironment';
import { Component, OnInit } from '@angular/core';
import { Http } from '@global/http/http';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable } from 'rxjs';

@Component({
    selector: 'app-login',
    templateUrl: './login.page.html',
    styleUrls: ['./login.page.less']
})
export class Login implements OnInit {

    /**
     * 构造方法
     * @param {Http} $http
     * @param {NzNotificationService} $notice
     * @memberof Login
     */
    constructor(private $http: Http, private $notice: NzNotificationService, private $avtiveRoute: ActivatedRoute, private $router: Router) { }

    /**
     * 登录用户名
     *
     * @private
     * @type {string}
     * @memberof Login
     */
    private loginname: string = '';

    /**
     * 密码
     *
     * @private
     * @type {string}
     * @memberof Login
     */
    private password: string = '';

    /**
     * 生命周期
     *
     * @memberof Login
     */
    ngOnInit(): void {

    }

    /**
     * 登录
     *
     * @memberof Login
     */
    public handleSubmit() {
        if (!this.loginname) {
            this.$notice.error('错误', '用户名不能为空！');
        }
        if (!this.password) {
            this.$notice.error('错误', '密码不能为空！');
        }
        let param: any = {
            loginname: this.loginname,
            password: this.password
        };
        this.$http.post(AppEnvironment.RemoteLogin, param).then((response: any) => {
            this.$notice.success('', '登录成功');
            const data = response;
            localStorage.setItem(AppEnvironment.AppName + '-token', data.token);
            localStorage.setItem(AppEnvironment.AppName + '-user', JSON.stringify(data.user));
            let queryParams: any = this.$avtiveRoute.snapshot.queryParams;
            if (queryParams && queryParams.RU) {
                window.location.href = queryParams.RU;
            } else {
                this.$router.navigate(['']);
            }
        }).catch((error: any) => {
            this.$notice.error('错误', '登录失败！');
        });
    }

}
