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;
    nzSize = 'large';
    hostId;   //主机ID
    hostName;   //主机name
    itemId;  //监控项id
    interfaceList: any[];
    valueMapList = [];
    validateForm: FormGroup;
    checkList;  //监测点分类
    interval;    //间隔时长
    conditionType = 'commonly';
    faultConditionList = [

    ];   //危险阀值list
    conditionList = [

    ];    //故障list
    tabNum: number;
    triggerObj = {
        condition: '',
        faultCondition: '',
        itemName: ''
    };
    triggerConditionId;
    triggerFaultConditionId;

    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, [Validators.required]],
            key_: [null, [Validators.required]],
            value_type: [null, [Validators.required]],
            type: [null, [Validators.required]],
            units: [null],
            // formula: [null, [Validators.required]],
            history: ['3600'],
            trends: [null],
            valuemapid: ['0'],
            delay: [null, [Validators.required]],
            snmp_oid: [null],
            snmp_community: ['public'],
            applications: [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();
    }

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

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

                data.triggers.forEach((value) => {
                    let str = value.expression;
                    let equal = [];
                    let arr = [];
                    let con = '';
                    let a = str.split(' ');
                    a.forEach((e) => {   // 符号数组
                        let index1 = e.indexOf('}');
                        if (e == 'and' || e == 'or') {
                            equal.push(e);
                        }
                        if (index1 > -1) {
                            let f = e.substring(index1 + 1, e.length);
                            con += '{' + this.hostName + ':' + this.validateForm.value.key_ + '.last()}' + f + ' ';
                        } else {
                            con += e + ' ';
                        }
                    });
                    let c = str.replace(/and/g, '').replace(/or/g, '').split('  ');
                    c.forEach((val, index) => {
                        let index1 = val.indexOf('}');
                        let d = val.substring(index1 + 1, val.length);
                        let data;
                        if (index > 0) {
                            data = {
                                and: ' ' + equal[index - 1] + ' ',
                                equal: d[0],
                                value: d.substring(1, c.length),
                            };
                        } else {
                            data = {
                                equal: d[0],
                                value: d.substring(1, c.length),
                            };
                        }
                        arr.push(data);
                    });
                    if (value.priority == 2 || value.priority == 3) {     //危险
                        this.faultConditionList = arr;
                        this.triggerObj.condition = con;
                        this.triggerConditionId = value.triggerid;
                    }
                    if (value.priority == 4 || value.priority == 5) {     //故障
                        this.conditionList = arr;
                        this.triggerObj.faultCondition = con;
                        this.triggerFaultConditionId = value.triggerid;
                    }
                });

            }
        );

        //主机接口
        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) {
            this.message.error('请输入必填信息');
            return false;
        }
        this.validateForm.value.applications = [this.validateForm.value.applications];
        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.done.emit();
                    this.tabNum = 1;
                } else {
                    this.message.error(res.errMsg);
                }
            },
            (err) => {
                this.message.error('系统错误');
            }
        );
    }

    //修改监控项
    update() {
        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;
                } else {
                    this.message.error(res.errMsg);
                }
            },
            (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);
                }
            }
        );
    }

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

    //故障add
    addcondition() {
        const demo = {
            and: ' and ',
            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 => {
                if(!res.and){
                    res.and = "";
                }
                data.condition +=  res.and + '{' + this.hostName + ':' + this.validateForm.value.key_ + '.last()}' + res.equal + '' + res.value ;
            });
            this.faultConditionList.forEach(res => {
                if(!res.and){
                    res.and = "";
                }
                data.faultCondition +=  res.and + '{' + this.hostName + ':' + this.validateForm.value.key_ + '.last()}' + res.equal + '' + res.value ;
            });
        } else {           //高级
            data.condition = this.triggerObj.condition;
            data.faultCondition = this.triggerObj.faultCondition;
        }
        if(!this.checkFun()){
            this.message.error("请输入阈值");
            return false;
        }
        if(this.conditionList.length == 0 && this.faultConditionList.length == 0){
            this.isCheck = false;
            this.initForm();
            return false;
        }
        if (this.title == '添加监测点') {
            this.createTrigger(data);
        }
        if (this.title == '编辑监测点') {
            this.updateTrigger(data);
        }
    }

    //校验是否填值
    checkFun(){
        let error = true;
        this.conditionList.map(e=>{
            if(e.value.length > 0){
                console.log(e.value)
            }else{
                error = false;
            }
        });
        this.faultConditionList.map(e=>{
            if(e.value.length > 0){
                console.log(e.value)
            }else{
                error = false;
            }
        });

        return error;
    }

    //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.initForm();
                    this.isCheck = false;
                } else {
                    this.message.error(response.errMsg);
                }
            }
        );
    }

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

    //阈值--end

}
