import {Component, AfterViewInit, Renderer, ElementRef, OnInit} from '@angular/core';
import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
import {Router} from '@angular/router';
import {JhiEventManager} from 'ng-jhipster';

import {LoginService} from './login.service';
import {StateStorageService} from '../auth/state-storage.service';

import {
    AbstractControl,
    FormBuilder,
    FormGroup,
    Validators
} from '@angular/forms';
import {EmitService} from '../event/eventEmitter';
import {NzNotificationService} from 'ng-zorro-antd';
import {LocalStorageService} from 'ngx-webstorage';
import {OverAllService} from '../../overAll/overAll.service';
import {SystemService} from '../../system/system.service';
import {Base64} from 'js-base64';
import {LayoutService} from '../../layouts/layout.service';

@Component({
    selector: 'jhi-login-modal',
    templateUrl: './login.component.html',
    styles: [
        `
            :host ::ng-deep .ant-spin-nested-loading > div > .ant-spin{
                left: 0;
                top:-6px;
            }
        `
    ]
})
export class JhiLoginModalComponent implements OnInit {
    validateForm: FormGroup;
    systemName;

    isSpinning = false;
    authenticationError: boolean;
    credentials: any;

    userInfo: any = {};

    constructor(
        private fb: FormBuilder,
        private eventManager: JhiEventManager,
        private loginService: LoginService,
        private stateStorageService: StateStorageService,
        private elementRef: ElementRef,
        private renderer: Renderer,
        private router: Router,
        public activeModal: NgbActiveModal,
        public emitService: EmitService,
        public notification: NzNotificationService,
        public $localStorage: LocalStorageService,
        public overAll: OverAllService,
        private sysSer: SystemService,
        private layoutSer: LayoutService,
    ) {
        this.credentials = {};
        this.emitService.eventEmit.subscribe((value: any) => {
            if (value == 'logout') {
                this.router.navigate(['login']);
            } else {
                // this.token = false;
            }
        });
    }

    submitForm() {
        for (let i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (this.validateForm.invalid) {
            return false;
        }
        this.getEncodepassword();
    }

    getEncodepassword() {
        const data = {
            userName: this.validateForm.value.loginName,
            password: Base64.encode(this.validateForm.value.password)
        };
        this.isSpinning = true;
        this.layoutSer.encodePassword(data).subscribe(
            (res) => {
                this.validateForm.patchValue({password: res.data});
                this.login();
            }
        );
    }

    ngOnInit(): void {
        this.validateForm = this.fb.group({
            loginName: [null, [Validators.required]],
            password: [null, [Validators.required]],
            rememberMe: [true]
        });
        this.overAll.getSystem().subscribe(
            (res) => {
                this.systemName = res.main.name;
            }
        );
    }

    cancel() {
        this.credentials = {
            loginName: null,
            password: null,
            rememberMe: true
        };
        this.authenticationError = false;
        this.activeModal.dismiss('cancel');
    }

    //登录
    login() {
        this.loginService.login(this.validateForm.value).then((res) => {
            if (res) {
                this.getUserInfo();
            } else {
                this.isSpinning = false;
                this.notification.create('error', '登录失败', '用户名或密码错误', {nzDuration: 2000});
            }
        }).catch(() => {
            this.isSpinning = false;
            this.authenticationError = true;
        });
    }

    //查询登录用户信息
    getUserInfo() {
        const d = {
            token: this.$localStorage.retrieve('accessToken')
        };
        this.sysSer.getUserInfo(d).subscribe(
            (res) => {
                this.userInfo.userName = res.data.name;
                this.userInfo.userId = res.data.id;
                this.userInfo.gender = res.data.gender;
                this.userInfo.roles = res.data.roles;
                this.userInfo.isAdmin = res.data.isAdmin;
                this.getOrgInfo();
            }
        );
    }

    //查询登录用户部门
    getOrgInfo() {
        this.sysSer.findOrganizationByUserId(this.userInfo.userId).subscribe(
            (res) => {
                this.isSpinning = false;
                this.router.navigate(['app/main/home']);
                this.notification.create('success', '登录成功', '', {nzDuration: 2000});
                if (res.data) {
                    this.userInfo.organizationId = res.data.id;
                    this.userInfo.organizationName = res.data.name;
                }
                this.$localStorage.store('userInfo', this.userInfo);
            }, (error1 => {
                this.router.navigate(['app/main/home']);
                this.notification.create('success', '登录成功', '', {nzDuration: 2000});
                this.$localStorage.store('userInfo', this.userInfo);
            })
        );
    }

    //重置密码
    requestResetPassword() {
        this.activeModal.dismiss('to state requestReset');
        this.router.navigate(['/reset', 'request']);
    }
}
