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

@Component({
    selector: 'smart-basi-check',
    templateUrl: './basi-check.component.html',
    styles: [
            `.tag-button[disabled],
        .tag-button {
            width: 80%;
            height: 30px;
            color: rgba(0, 0, 0, 0.65);
            background-color: #fff;
            border-color: #d9d9d9;
        }

        :host ::ng-deep .ant-tabs-nav .ant-tabs-tab-disabled {
            color: rgba(0, 0, 0, .65);
        }
        `
    ]
})
export class BasiCheckComponent implements OnInit {
    @ViewChild('basicKey') basicKey: BasicKeyComponent;
    @ViewChild('newType') newType: NewTypeComponent;
    @Output() done = new EventEmitter<any>();

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

    tabNum: number;
    triggerObj = {
        condition: '',
        faultCondition: '',
        itemName: ''
    };

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

    ngOnInit() {
        this.initForm();
        this.getValuemap();
    }

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

    //新增
    showAddModal(hostId, hostName,title) {
        this.title = title;
        this.isCheck = true;
        this.hostId = hostId;
        this.hostName = hostName;
        if(this.title == '添加监测点'){
            //主机接口
            this.overAllSer.findInterface(this.hostId).subscribe(
                (res) => {
                    this.interfaceList = res.data;
                }
            );
            this.isInterface = true;
        }
        if(this.title == '添加模版监测点'){
            this.isInterface = false;
            this.validateForm.get('interfaceid').clearValidators();
        }

        this.getItemType();
    }

    //映射值
    getValuemap() {
        // this.overAllSer.findValuemap().subscribe(
        //     (res) => {
        //         if (res.errCode == 10000) {
        //             this.valueMapList = res.data;
        //         } else {
        //             this.message.error(res.errMsg);
        //         }
        //     }
        // );
    }

    //编辑
    showEditModal(hostId, id, hostName,templateid,title) {
        this.title = title;
        this.hostId = hostId;
        this.templateid = templateid;
        this.isCheck = true;
        this.itemId = id;
        this.hostName = hostName;
        if(this.title == '编辑模版监测点'){
            this.isInterface = false;
            this.validateForm.get('interfaceid').clearValidators();
        }
        this.overAllSer.findItemDetail(id).subscribe(
            (res) => {
                const data = res.data[0];
                data.type += '';
                data.interfaceid += '';
                data.value_type += '';
                if(data.applications){
                    data.applications = data.applications.map(e=>{
                        return e.applicationid;
                    });
                }
                this.validateForm.patchValue(data);
            }
        );

        //主机接口
        this.overAllSer.findInterface(this.hostId).subscribe(
            (res) => {
                this.interfaceList = res.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.value.hostid = this.hostId;
        this.isOkLoading = true;
        if (this.title == '添加监测点' || this.title == "添加模版监测点") {
            this.create();
        }
        if (this.title == '编辑监测点' || this.title == "编辑模版监测点") {
            this.update();
        }
    }

    create() {
        this.overAllSer.create(this.validateForm.value).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('创建监测点成功');
                    this.done.emit();
                    this.tabNum = 1;
                    this.initForm();
                    this.isCheck = false;
                } else {
                    this.message.error(res.errMsg);
                }
                this.isOkLoading = false;
            },
            (err) => {
                this.message.error('系统错误');
            }
        );
    }

    //修改监控项
    update() {
        this.validateForm.patchValue({
            templateid:this.templateid
        })
        this.validateForm.addControl('itemid', new FormControl(this.itemId));
        this.overAllSer.itemUpdata(this.validateForm.value).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('修改监测点成功');
                    this.done.emit();
                    this.tabNum = 1;
                    this.initForm();
                    this.isCheck = false;
                } else {
                    this.message.error(res.errMsg);
                }
                this.isOkLoading = 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();
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

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