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

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

    title;
    isVisiable = false;
    validateForm: FormGroup;

    type;
    typeId;

    constructor(private fb: FormBuilder, private workSer: WorkService,
                private message: NzMessageService, private emitService: EmitService) {
    }

    ngOnInit() {
        this.initForm();
    }

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

    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 == '添加计划分类' || this.title == '添加事件分类') {
            this.create();
        }
        if( this.title == '编辑事件分类' || this.title == '编辑计划分类' ){
            this.update();
        }
    }

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

    update() {
        const data = {
            id: this.typeId,
            name: this.validateForm.value.name
        };
        this.workSer.updateTypeByparams(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('修改成功');
                    this.isVisiable = false;
                    this.done.emit();
                    this.initForm();
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

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

}
