import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {AlarmService} from '../../alarm.service';
import {
    FormBuilder,
    FormControl,
    FormGroup,
    ValidationErrors,
    Validators
} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';

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

    title;
    isVisible = false;
    groupId;

    validateForm: FormGroup;
    name;
    description;

    constructor(private alarmSer:AlarmService,private fb:FormBuilder,
                private message:NzMessageService) {
    }

    ngOnInit() {
        this.initForm();
    }

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

    //新增告警组
    addModal() {
        this.title = '新增告警组';
        this.isVisible = true;
    }

    //编辑告警组
    editModal(arr) {
        this.title = '编辑告警组';
        this.groupId = arr.id;
        this.isVisible = true;
        this.validateForm.patchValue(arr);
    }

    //取消
    handleCancel() {
        this.isVisible = false;
        this.initForm();
    }

    //确定
    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.title == '编辑告警组'){
            this.update();
        }else{
            this.create();
        }
    }

    create(){
        this.alarmSer.alertGroupCreate(this.validateForm.value).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.isVisible = false;
                    this.add.emit();
                    this.initForm();
                }
            }
        )
    }

    update(){
       const data = {
           id:this.groupId,
           name:this.validateForm.value.name,
           description:this.validateForm.value.description
       };
        this.alarmSer.alertGroupUpdate(data).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.isVisible = false;
                    this.add.emit();
                    this.initForm();
                }
                this.message.info(res.errMsg);
            }
        )
    }

}
