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;
    hostId;   //主机ID
    hostName;   //主机name
    itemId;  //监控项id
    interfaceList: any[];
    validateForm:FormGroup;
    checkList;  //监测点分类
    interval;    //间隔时长
    conditionType = 'commonly';
    faultConditionList = [
        {
            code: '1',
            equal: '=',
            value: '',
        }
    ];   //危险阀值list
    conditionList = [
        {
            code: '1',
            equal: '=',
            value: '',
        }
    ];    //故障list
    tabNum:number;
    triggerObj = {
        condition:'',
        faultCondition:'',
        itemName:''
    };
    constructor(private overAllSer: OverAllService, private fb: FormBuilder,
                private message: NzMessageService) {
    }

    ngOnInit() {
        this.initForm();
    }

    initForm(){
        this.tabNum = 0;
        this.validateForm = this.fb.group({
            hostid:[this.hostId],
            name:[null,[Validators.required]],
            interfaceid:[null,[Validators.required]],
            key_:[null,[Validators.required]],
            value_type:[null,[Validators.required]],
            type:[null,[Validators.required]],
            data_type:[null,[Validators.required]],
            units:[null],
            formula:[null,[Validators.required]],
            history:['3600'],
            trends:[null],
            valuemapid:[null],
            delay:[null,[Validators.required]],
            snmp_oid:[null],
            snmp_community:[null],
            delta:[null],
            applicationids:[null],
        });
        this.triggerObj = {
            condition:'',
            faultCondition:'',
            itemName:''
        };
    }

    //新增
    showAddModal(hostId,hostName){
        this.title = '添加监测点';
        this.isCheck = true;
        this.hostId = hostId;
        this.hostName = hostName;
        //主机接口
        this.overAllSer.findDetailed(this.hostId).subscribe(
            (res) => {
                this.interfaceList = res.data[0].interfaces;
            }
        );
        this.getItemType();
    }

    //编辑
    showEditModal(hostId,id){
        this.title = "编辑监测点";
        this.hostId = hostId;
        this.isCheck = true;
        this.itemId = id;
        this.overAllSer.findItemDetail(id).subscribe(
            (res) => {
                const data = res.data[0];
                data.type += '';
                data.interfaceid += "";
                data.value_type += "";
                data.data_type += "";
                this.validateForm.patchValue(data);
            }
        );

        //主机接口
        this.overAllSer.findDetailed(this.hostId).subscribe(
            (res) => {
                this.interfaceList = res.data[0].interfaces;
            }
        );
        this.getItemType();
    }

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

    //添加
    handleCheckOk() {
        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.applicationids = [this.validateForm.value.applicationids];
        this.validateForm.value.hostid = this.hostId;
        if(this.title == "添加监测点"){
            this.create();
        }
        if(this.title == "编辑监测点"){
            this.update();
        }
    }

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

    //修改监控项
    update(){
        this.validateForm.addControl('itemid',new FormControl(this.itemId));
        this.overAllSer.itemUpdata(this.validateForm.value).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isCheck = false;
                    this.initForm();
                    this.done.emit();
                }
                this.message.info(res.errMsg);
            },
            (err) => {
                this.message.info('系统错误');
            }
        );
    }

    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);
                }
            }
        );
    }

    //危险add
    addFault() {
        const demo = {
            and: '&',
            code: '1',
            equal: '=',
            value: '',
        };
        this.faultConditionList.push(demo);
    }

    //故障add
    addcondition() {
        const demo = {
            and: '&',
            code: '1',
            equal: '=',
            value: '',
        };
        this.conditionList.push(demo);
    }

    //危险delete
    deleteFault(index) {
        this.faultConditionList.splice(index, 1);
    }

    //故障delete
    deleteCondition(index) {
        this.conditionList.splice(index, 1);
    }

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

    //阈值--start
    saveTrigger(){
        const data = {
            condition:'',
            faultCondition:''
        };
        if (this.conditionType == 'commonly') {   //常规
            this.conditionList.forEach(res => {
                data.condition += '{' + this.hostName + ':' + this.validateForm.value.key_ + '.last()}' + res.equal + '' + res.value ;
            });
            this.faultConditionList.forEach(res => {
                data.faultCondition += '{' + this.hostName + ':' + this.validateForm.value.key_ + '.last()}' + res.equal + '' + res.value;
            });
        } else {           //高级
            data.condition = this.triggerObj.condition;
            data.faultCondition = this.triggerObj.faultCondition;
        }
        if(this.title == "添加监测点"){
            this.createTrigger(data);
        }
        if(this.title == "编辑监测点"){
            this.updateTrigger(data);
        }
    }
    //1.创建阈值
    createTrigger(data){
        const res = {
            itemName:this.validateForm.value.name,
            faultCondition:data.faultCondition,
            condition:data.condition
        };
        this.overAllSer.createTrigger(res).subscribe(
            (response)=>{
                if(response.errCode == 10000){
                    this.message.success("创建阈值成功");
                    this.done.emit();
                    this.initForm();
                    this.isCheck = false;
                }else{
                    this.message.error(response.errMsg);
                }
            }
        )
    }

    //2.修改阈值
    updateTrigger(data){
        const res = {
            triggerid:'',
            itemName:this.validateForm.value.name,
            faultCondition:data.faultCondition,
            condition:data.condition
        };
        this.overAllSer.updateTrigger(data).subscribe(res=>{
            if(res.errCode == 10000){
                this.message.success("修改阈值成功");
                this.done.emit();
                this.initForm();
                this.isCheck = false;
            }else{
                this.message.error(res.errMsg);
            }
        })
    }
    //阈值--end

}
