import {Component, OnInit} from '@angular/core';
import {FormGroup, Validators, FormBuilder} from '@angular/forms';
import {LoginService} from '../../../services/login.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {ADMIN_INFO_OBJECT, TOKEN, INIT_FLAG, LOGINTYPE, DATA} from '../../../services/local-storage.namespace';
import {LocalStorageService} from '../../../services/local-storage.service';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';


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

  loginForm: FormGroup; // 登录表单

  constructor(private store: LocalStorageService, // 数据请求
              private router: Router,  // 路由
              private form: FormBuilder, // 表单校验
              private http: HttpClient, // http请求
              private loginService: LoginService,
              private message: NzMessageService,
              private modal: NzModalService) {
  }

  ngOnInit() {
    this.loginForm = this.form.group({
      loginName: [null, [Validators.required]],
      password: [null, [Validators.required]],
    });
  }

  /**
   * 登录
   */
  submitLogin() {
    // tslint:disable-next-line:forin
    for (const i in this.loginForm.controls) {
      this.loginForm.controls[i].markAsDirty();
      this.loginForm.controls[i].updateValueAndValidity();
    }
    if (this.loginForm.status == null || this.loginForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写用户和密码',
      });
      return;
    }
    this.loginService.userLogin(this.loginForm.value, data => {
      if (data['return_code'] === '000000') {
        data['return_data']['object']['menuList'] = data['return_data']['object']['menuList'].filter(o => o.showOnMobile == 0);
        this.store.set(ADMIN_INFO_OBJECT, data['return_data']['object']);
        this.store.set(TOKEN, data['return_data']['uniqueCode']);
        this.store.set(INIT_FLAG, true);
        this.store.set(LOGINTYPE, data['return_data']['type']);
        this.router.navigateByUrl('/admin/index').then();
      } else {
          this.message.error(data['return_msg']);
      }
    });

  }
}
