import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {OverAllService} from '../../../overAll.service';
import {BasicKeyComponent} from '../../../../modal/basic-key/basic-key.component';
import {NewTypeComponent} from '../../../../modal/new-type/new-type.component';
import {NzMessageService} from 'ng-zorro-antd';

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

    @ViewChild('basicKey') basicKey: BasicKeyComponent;
    @ViewChild('newType') newType: NewTypeComponent;
    @Output() done = new EventEmitter<any>();

    title;
    isCheck = false;
    isInterface = true;     //添加模版监测点的时候不需要主机接口
    nzSize = 'large';
    hostId;   //主机ID
    discoveryid;  //自动发现id
    itemId;  //监控项id
    valueMapList = [];
    validateForm: FormGroup;
    checkList;  //监测点分类
    interval;    //间隔时长

    tabNum: number;

    constructor(private overAllSer: OverAllService, private fb: FormBuilder,
                private message: NzMessageService) {
    }

    ngOnInit() {
        this.initForm();
    }

    initForm() {
        this.tabNum = 0;
        this.validateForm = this.fb.group({
            name: [null, [Validators.required]],
            key_: [null, [Validators.required]],
            hostid: [null],
            ruleid: [null],
            type: [null, [Validators.required]],
            value_type: [null, [Validators.required]],
            delay: [null, [Validators.required]],
            units: [null],
            history: ['3600'],
            trends: [null],
            applications: [null],
            status: [null],
            // snmp_oid: ['interfaces.ifTable.ifEntry.ifInOctets.1'],
            // snmp_community: ['public'],
        });
    }

    /**
     * 新增监控项原型
     * @param hostId  模版id
     * @param discoveryid  自动发现id
     * @param hostName  模版名称
     * @param title  标题
     */
    showAddModal(hostId,discoveryid, title) {
        this.title = title;
        this.isCheck = true;
        this.discoveryid = discoveryid;
        this.hostId = hostId;
        this.isInterface = true;

        this.getItemType();
    }

    /**
     *
     * @param hostId   模版id
     * @param discoveryid   自动发现id
     * @param itemId   监控项id
     * @param hostName    模版名称
     * @param title  标题
     */
    showEditModal(hostId, discoveryid,itemId, title) {
        this.title = title;
        this.hostId = hostId;
        this.itemId = itemId;
        this.isCheck = true;
        this.discoveryid = discoveryid;
        this.overAllSer.findItemById(itemId).subscribe(
            (res) => {
                const data = res.data[0];
                data.type += '';
                data.value_type += '';
                data.status =  data.status == 0 ? true : false;
                if (data.applications) {
                    data.applications = data.applications.map(e => {
                        return e.applicationid;
                    });
                }
                this.validateForm.patchValue(data);
            }
        );

        this.getItemType();
    }

    //获取监测点分类
    getItemType() {
        //监测点分类
        const data = {
            'hostids': [this.hostId]
        };
        this.overAllSer.findItemType(data).subscribe(
            (res) => {
                this.checkList = res.data;
            }
        );
    }

    //添加
    handleCheckOk() {
        const list = ['0', '1', '3', '4', '6', '10', '12', '13', '14', '16', '17'];
        if (list.indexOf(this.validateForm.value.type) > -1) {
            this.validateForm.get('type').setValidators(Validators.required);
        }
        for (let i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (this.validateForm.invalid) {
            this.message.error('请输入必填信息');
            return false;
        }
        this.validateForm.patchValue({
            applications:this.validateForm.value.applications,
            hostid:this.hostId,
            ruleid:this.discoveryid,
            status:this.validateForm.value.status ? 0 : 1
        });
        if (this.title == '添加监控项原型') {
            this.create();
        }
        if (this.title == '编辑监控项原型') {
            this.update();
        }
    }

    create() {
        this.overAllSer.createItemPrototype(this.validateForm.value).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('创建监控项原型成功');
                    this.done.emit();
                    this.tabNum = 1;
                    this.isCheck = false;
                }
            },
            (err) => {
                this.message.error('系统错误');
            }
        );
    }

    //修改监控项
    update() {
        this.validateForm.addControl('itemid', new FormControl(this.itemId));
        this.overAllSer.updateItemPrototype(this.validateForm.value).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('修改监控项原型成功');
                    this.done.emit();
                    this.tabNum = 1;
                    this.isCheck = false;
                }
            },
            (err) => {
                this.message.error('系统错误');
            }
        );
    }

    handleCheckCancel(): void {
        this.isCheck = false;
        this.initForm();
    }

    //键值查询
    showKeymodal() {
        this.basicKey.showKeyModal();
    }

    //新增分类
    showTypeModal() {
        this.newType.showModal('新建分类');
    }

    //添加分类
    addItemType(data) {
        const obj = {
            hostid: this.hostId,
            name: data
        };
        this.overAllSer.createItemType(obj).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('添加成功');
                    this.getItemType();
                }
            }
        );
    }

    getKey(keyValue): void {
        const d = {
            key_: keyValue
        };
        this.validateForm.patchValue(d);
    }

}
