import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {OverAllService} from '../../overAll/overAll.service';
import {FormBuilder} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';

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

    isVisiable = false;
    isOkLoading = false;
    title;
    itemId;   //监控项ID
    hostName;   //主机name
    itemObj;   //监控项对象
    conditionType = 'commonly';
    faultConditionList = [];   //故障阈值
    conditionList = [];    //危险阈值

    triggerConditionId;
    triggerFaultConditionId;

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

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

    ngOnInit() {
    }

    initForm() {
        this.faultConditionList = [];   //危险阀值list
        this.conditionList = [];    //故障list
        this.triggerObj = {
            condition: '',
            faultCondition: '',
            itemName: ''
        };
    }

    //危险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);
    }

    //新增
    showAddModal(title, itemId, hostName) {
        this.title = title;
        this.itemId = itemId;
        this.isVisiable = true;
        this.hostName = hostName;
        this.overAllSer.findItemDetail(this.itemId).subscribe(
            (res) => {
                this.itemObj = res.data[0];
            }
        );
    }

    //编辑
    showEditModal(title, itemId, hostId, hostName) {
        this.title = title;
        this.itemId = itemId;
        this.isVisiable = true;
        this.hostName = hostName;
        this.overAllSer.findItemDetail(this.itemId).subscribe(
            (res) => {
                this.itemObj = res.data[0];

                this.itemObj.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.itemObj.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, d.length),
                            };
                        } else {
                            data = {
                                equal: d[0],
                                value: d.substring(1, d.length),
                            };
                        }
                        arr.push(data);
                    });
                    if (value.priority == 2 || value.priority == 3) {     //危险
                        this.conditionList = arr;
                        this.triggerObj.condition = con;
                        this.triggerConditionId = value.triggerid;
                    }
                    if (value.priority == 4 || value.priority == 5) {     //故障
                        this.faultConditionList = arr;
                        this.triggerObj.faultCondition = con;
                        this.triggerFaultConditionId = value.triggerid;
                    }
                });
            }
        );
    }

    //阈值--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.itemObj.key_ + '.last()}' + res.equal + '' + res.value;
            });
            this.faultConditionList.forEach(res => {
                if (!res.and) {
                    res.and = '';
                }
                data.faultCondition += res.and + '{' + this.hostName + ':' + this.itemObj.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;
        }

        this.isOkLoading = true;

        if (this.title == '添加阈值') {
            if (this.conditionList.length == 0 && this.faultConditionList.length == 0) {
                this.isVisiable = false;
                this.initForm();
                return false;
            }else{
                this.createTrigger(data);
            }
        }
        if (this.title == '编辑阈值') {
            this.updateTrigger(data);
        }
    }

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

        return error;
    }

    //1.创建阈值
    createTrigger(data) {
        const res = {
            itemName: this.itemObj.name,
            faultCondition: data.faultCondition,
            condition: data.condition
        };
        this.overAllSer.createTrigger(res).subscribe(
            (response) => {
                if (response.errCode == 10000) {
                    this.message.success('创建阈值成功');
                    this.initForm();
                    this.done.emit();
                    this.isVisiable = false;
                } else {
                    this.message.error(response.errMsg);
                }
                this.isOkLoading = false;
            }
        );
    }

    //2.修改阈值
    updateTrigger(data) {
        const res = {
            faultCondition: {   //故障阈值
                itemName: this.itemObj.name,
                condition: data.faultCondition,
                triggerid: this.triggerFaultConditionId
            },
            condition: {   //危险阈值
                itemName: this.itemObj.name,
                condition: data.condition,
                triggerid: this.triggerConditionId
            }
        };
        this.overAllSer.updateTrigger(res).subscribe(res => {
            if (res.errCode == 10000) {
                this.message.success('修改阈值成功');
                this.initForm();
                this.done.emit();
                this.isVisiable = false;
            }
            this.isOkLoading = false;
        });
    }

    //取消
    handleCheckCancel() {
        this.isVisiable = false;
        this.initForm();
    }

}
