import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {
    AbstractControl, Form,
    FormBuilder,
    FormControl,
    FormGroup,
    Validators
} from '@angular/forms';
import {SystemService} from '../../system.service';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
    selector: 'smart-user',
    templateUrl: './user.component.html',
    styles: []
})
export class UserComponent implements OnInit {
    @Output() done = new EventEmitter<any>();

    title = '新增用户';
    isVisible = false;
    groupList:any[];
    validateForm:FormGroup;

    constructor(private fb:FormBuilder,private systemSer:SystemService,
                private message:NzMessageService) {
    }

    ngOnInit() :void{
       this.initForm();
    }

    initForm(){
        this.validateForm = this.fb.group({
            name:[null,[Validators.required,Validators.maxLength(10)]],
            loginName:[null,[Validators.required,Validators.maxLength(10)]],
            mobile:[null,[Validators.required,Validators.min(11),Validators.maxLength(11)]],
            gender:[null,[Validators.required]],
            email:[null,[Validators.email]],
            organizeId:[null,[Validators.required]],
            comments:[null,[Validators.required]],
            status:[null,[Validators.required]],
        })
    }

    showModal(data){
        this.groupList = data;
        this.isVisible = true;
    }

    handleCancel(){
        this.isVisible = false;
    }

    handleOk(){
        for(let i in this.validateForm.controls){
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        this.validateForm.value.gender = Number(this.validateForm.value.gender);
        this.validateForm.value.status = Number(this.validateForm.value.status);
        if(this.validateForm.invalid){
            return false;
        }
        this.systemSer.adduser(this.validateForm.value).subscribe(
            (res)=>{
                    if(res.errCode == 10000){
                        this.isVisible = false;
                        this.initForm();
                        this.done.emit();
                    }else{
                        this.message.error(res.errMsg);
                    }
            }
        )
    }
}
