import {Component, OnInit} from '@angular/core';
import {OverAllService} from '../../overAll/overAll.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageComponent, NzMessageService} from 'ng-zorro-antd';
import {LayoutService} from '../../layouts/layout.service';
import {LoginService} from '../../shared';

@Component({
    selector: 'smart-modify-password',
    templateUrl: './modify-password.component.html',
    styles: []
})
export class ModifyPasswordComponent implements OnInit {

    isVisible = false;
    title = '修改密码';
    validateForm: FormGroup;

    groupid;

    constructor(private fb: FormBuilder, private layoutSer: LayoutService,
                private message: NzMessageService,private loginService:LoginService) {}

    ngOnInit() {
        this.initForm();
    }

    showModal(): void {
        this.isVisible = true;
    }

    handleOk() {
        for (let i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (this.validateForm.invalid) {
            return false;
        }
        if(this.validateForm.value.password != this.validateForm.value.realPassword){
            this.message.error("两次输入密码不一致");
            return false;
        }
        this.update();
    }

    update() {
        let formData = new FormData();
        formData.append('password',this.validateForm.value.password);
        this.layoutSer.modifyPassword(formData).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('修改成功');
                    this.isVisible = false;
                    this.loginService.logout();
                    this.initForm();
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    handleCancel(): void {
        this.isVisible = false;
        this.initForm();
    }

    //初始化
    initForm() {
        this.validateForm = this.fb.group({
            password: [null, [Validators.required]],
            realPassword: [null, [Validators.required]],
        });
    }
}
