import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {WorkService} from '../../../work/work.service';
import {NzMessageService} from 'ng-zorro-antd';
import {EmitService} from '../../../shared/event/eventEmitter';
import {SystemChangeService} from '../../system-change.service';

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

    title;
    isVisiable = false;
    validateForm: FormGroup;

    type;
    typeId;

    constructor(private fb: FormBuilder, private systemChangeSer: SystemChangeService,
                private message: NzMessageService, private emitService: EmitService) {
    }

    ngOnInit() {
        this.initForm();
    }

    //初始化
    initForm() {
        this.validateForm = this.fb.group({
            label: ['', [Validators.required]],
            type: [null],
            value: [''],
            description: [''],
            id: [''],
        });
    }

    showAddModal(title, type): void {
        this.type = type;
        this.title = title;
        this.isVisiable = true;
    }

    showEditModal(title, type, id, item) {
        this.title = title;
        this.isVisiable = true;
        this.type = type;
        this.typeId = id;
        this.validateForm.patchValue(item);
    }

    handleOk() {
        for (let i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (this.validateForm.invalid) {
            return false;
        }
        this.validateForm.value.type = this.type;
        if (this.title.includes('添加')) {
            this.create();
        }
        if (this.title.includes('编辑')) {
            this.update();
        }
    }

    create() {
        this.systemChangeSer.sysdictAdd(this.validateForm.value).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('添加成功');
                    this.isVisiable = false;
                    this.done.emit();
                    this.initForm();
                }
            }
        );
    }

    update() {
        this.validateForm.patchValue({id: this.typeId});
        this.systemChangeSer.sysdictUpdate(this.validateForm.value).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('修改成功');
                    this.isVisiable = false;
                    this.done.emit();
                    this.initForm();
                }
            }
        );
    }

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


}
