import {Component, OnInit} from '@angular/core';
import {Transfer} from '../service/transfer';
import {Api} from '../service/api';
import {fadeIn} from '../animations/fade-in';
import {Mqtt} from '../service/mqtt';
import {Load} from '../service/load';

@Component({
    selector: 'v-login',
    templateUrl: './login.page.html',
    styleUrls: ['./login.page.scss'],
    animations: [fadeIn]
})
export class LoginPage implements OnInit {
    req = {name: '', ps: ''};
    saveMimaCheck = false;

    constructor(private tf: Transfer, private api: Api, private load: Load, private mqtt: Mqtt) {
    }

    ngOnInit() {
        this.load.offLoad();

        if (window.localStorage.getItem('muchangUsername') != null) {
            this.req.name = window.localStorage.getItem('muchangUsername');
        }

        if (window.localStorage.getItem('muchangPassword') != null) {
            this.req.ps = window.localStorage.getItem('muchangPassword');
        }
    }

    login() {
        const req = {
            userName: this.req.name,
            password: this.req.ps
        };

        this.api.login.login([req, (data) => {
            if (data.code === 1) {
                window.localStorage.setItem('token', data.message);
                this.tf.transfer({url: '/index'});
                this.mqtt.getUserInfo();

                if(this.saveMimaCheck === true) {
                    window.localStorage.setItem('muchangUsername', this.req.name);
                    window.localStorage.setItem('muchangPassword', this.req.ps);
                }
            } else {
                this.api.presentMsgToast(data && data.message ? data.message : '登录失败');
            }
        }]);
    }
}
