import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AlarmService} from '../../alarm/alarm.service';
import {FindUserComponent} from '../../alarm/modal/find-user/find-user.component';
import {NzFormatEmitEvent, NzMessageService, NzTreeComponent, NzTreeNode} from 'ng-zorro-antd';
import {OverAllService} from '../../overAll/overAll.service';
import {SelectPersonComponent} from '../select-person/select-person.component';
import {WorkService} from '../../work/work.service';

@Component({
    selector: 'smart-alarm-modal',
    templateUrl: './alarm-modal.component.html',
    styles: [
            `
            .tree-div {
                border: 1px solid #dadada;
                height: 200px;
                overflow: auto;
                margin-top: 10px;
            }
        `
    ]
})
export class AlarmModalComponent implements OnInit {
    @ViewChild('smartFindUser') smartFindUser: FindUserComponent;
    @ViewChild('smartSelectPerson') smartSelectPerson: SelectPersonComponent;
    @ViewChild('nzTree') nzTree: NzTreeComponent;
    @Output() done = new EventEmitter<any>();

    title;
    tabNum = 0;
    isShow = false;
    isOkLoading = false;
    nodes;
    nodeList;
    actionid;  //告警Id
    isEvent = '2';

    groupList;
    sendOption = [];
    objList;

    selectTreeList = [];
    validateForm;

    selectModal = false;
    sendInfoList = [];   //发送方式
    eventTypeList;  //事件分类列表

    operatorList = [];   //负责人列表

    serviceid;   //业务id
    constructor(private alarmSer: AlarmService, private message: NzMessageService,
                private overAllSer: OverAllService, private workSer: WorkService,) {
    }

    ngOnInit() {
        this.initForm();
        this.getSendFun();
        this.getACtion();
        this.getGroup();
        this.getZabbixObj();
        this.getEventType();
    }

    //初始化
    initForm() {
        this.selectModal = false;
        this.tabNum = 0;
        this.isEvent = '2';
        this.selectTreeList = [];
        this.sendInfoList = [];
        this.operatorList = [];   //负责人列表
        this.validateForm = {
            name: null,
            alertGroupId: null,
            warn: 0,
            serious: 0,
            mediaTypeIds: [],
            def_longdata: '问题 {TRIGGER.NAME} 开始于: {EVENT.TIME} {EVENT.DATE}\n' +
                '主机: {HOST.NAME}\n' +
                '严重程度: {TRIGGER.SEVERITY}\n',
            r_longdata: '' +
                '问题 {TRIGGER.NAME} 恢复于: {EVENT.TIME} {EVENT.DATE} \n' +
                '主机: {HOST.NAME}\n' +
                '严重程度: {TRIGGER.SEVERITY}',
            sendInfos: null,
            event: {
                eventTypeId: null,   //事件分类id
                operators: null,   //事件负责人
                title: null,  //事件标题
            }
        };
    }

    //获取事件分类
    getEventType() {
        const data = {
            type: 0
        };
        this.workSer.findParamsByType(data).subscribe(
            (res) => {
                this.eventTypeList = res.data;
            }
        );
    }

    //获取告警目标
    getACtion() {
        this.overAllSer.findGroup().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    const dataSet = res.data;
                    dataSet.forEach(res => {
                        res.title = res.name;
                        res.key = res.groupid;
                    });
                    this.nodeList = dataSet;
                    this.toNode(dataSet);
                } else {
                    this.message.info(res.errMsg);
                }
            }
        );
    }

    //获取告警分组
    getGroup() {
        this.alarmSer.alertGroupFind().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.groupList = res.data;
                }
            }
        );
    }

    toNode(data) {
        this.nodes = data.map(res => {
            return new NzTreeNode(res);
        });
    }

    //下级
    mouseAction(name: string, event: NzFormatEmitEvent) {
        if (event.node.children.length > 0) {
            return false;
        }
        const index = <any>event.node.key - 1;
        const data = {
            'groupids': [event.node.origin.groupid],
            'hostExtend': {
                'superiorHostid': null
            }
        };
        this.overAllSer.findDetail(data).subscribe(
            (res) => {
                if (res.data) {
                    const dataSet = res.data;
                    dataSet.forEach(e => {
                        e.title = e.name;
                        e.key = e.hostid;
                        e.isLeaf = true;
                        if (this.selectTreeList.includes(e.key)) {
                            e.checked = true;
                        }
                    });
                    event.node.addChildren(dataSet);
                } else {
                    event.node.addChildren([]);
                    this.message.info('该分组下无资源');
                }

            }
        );
        setTimeout(_ => {
        }, 1000);
    }

    //选择树节点
    selectCheckTree(node) {
        if (node.isChecked) {
            this.selectTreeList.push(node.origin.hostid);
        } else {
            const index = this.selectTreeList.indexOf(node.origin.hostid);
            this.selectTreeList.splice(index, 1);
        }
    }

    //获取发送方式
    getSendFun() {
        this.alarmSer.mediaTypeFind({}).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.sendOption = res.data;
                }
            }
        );
    }

    //获取发送对象 zabbix
    getZabbixObj() {
        this.alarmSer.zUserFind({}).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.objList = res.data;
                }
            }
        );
    }

    //添加发送方式
    addOption() {
        const data = {
            mediaType: null,
            receiver: ''
        };
        this.sendInfoList.push(data);
    }

    //删除发送方式
    deleteOption(index) {
        this.sendInfoList.splice(index, 1);
    }

    //新增告警
    showAddModal(title,serviceid) {
        this.serviceid = serviceid;
        this.title = title;
        this.isShow = true;
    }

    //编辑告警
    showEditModal(title, id) {
        this.title = title;
        this.isShow = true;
        this.actionid = id;
        this.alarmSer.getAction(id).subscribe(
            (res) => {
                this.viewData(res.data);
            }
        );
    }

    //回显数据
    viewData(data) {
        this.validateForm.name = data.name;
        this.validateForm.alertGroupId = data.alertGroupId;
        this.validateForm.serious = data.serious;
        this.validateForm.warn = data.warn;
        //事件负责人回显
        if (data.event) {
            this.isEvent = '1';
            this.validateForm.event.title = data.event.title;
            this.validateForm.event.eventTypeId = data.event.eventTypeId;
            this.operatorList = data.event.operators.map(e => {
                const d = {
                    username: e.username,
                    userId: e.userId
                };
                return d;
            });
        }

        //发送方式回显
        if (data.sendInfos && data.sendInfos.length > 0) {
            this.sendInfoList = data.sendInfos.map(e => {
                const d = {
                    mediaType: e.mediaType,
                    receiver: e.receiver
                };
                return d;
            });
        }

        //恢复信息
        if (data.r_longdata) {
            this.selectModal = true;
        }

        //
        this.selectTreeList = data.hostIds;
        this.nodeList.forEach(e => {
            if (data.hostIds.includes(e.key)) {
                e.checked = true;
            }
        });
        this.toNode(this.nodeList);
    }

    //取消
    handleEditCancel() {
        this.initForm();
        this.isShow = false;
    }

    //tab切换
    tabsChange(index) {
        this.tabNum = index;
    }

    //选择处理人弹窗
    selectPerson() {
        this.smartSelectPerson.showModal('选择事件负责人', null);
    }

    //选择事件负责人done
    getUser(e) {
        const arr = [];
        e.forEach(res => {
            const data = {
                username: res.name,
                userId: res.id
            };
            arr.push(data);
        });
        this.operatorList = arr;
    }

    deleteOperator(index) {
        this.operatorList.splice(index, 1);
    }

    //保存
    handEditleOk() {

        if (!this.check()) {
            return false;
        }
        this.isOkLoading = true;
        const optionArr = [];
        this.sendOption.forEach(res => {
            if (res.checked) {
                optionArr.push(res.value);
            }
        });

        this.validateForm.warn = this.validateForm.warn == true ? 1 : 0;
        this.validateForm.serious = this.validateForm.serious == true ? 1 : 0;
        const data = {
            name: this.validateForm.name,
            alertGroupId: this.validateForm.alertGroupId,
            warn: this.validateForm.warn,
            serious: this.validateForm.serious,
            mediaTypeIds: optionArr,
            sendInfos: this.sendInfoList,
            def_longdata: this.validateForm.def_longdata,
            r_longdata: this.validateForm.r_longdata,
            r_shortdata: this.validateForm.r_shortdata,
            hostIds: this.selectTreeList,
            event: null,
            serviceid:this.serviceid,
        };
        if(this.isEvent == "1"){
            data.event = {
                eventTypeId: this.validateForm.event.eventTypeId,   //事件分类id
                operators: this.operatorList,   //事件负责人
                title: this.validateForm.event.title,  //事件标题
            }
        }

        if (this.title == '添加告警' || this.title == "添加告警推送") {
            this.create(data);
        }
        if (this.title == '编辑告警') {
            this.update(data);
        }
    }

    //校验
    check() {
        if (!this.validateForm.name) {
            this.message.error('请输入告警名称');
            return false;
        }
        if (this.sendInfoList.length == 0) {
            this.message.error('请选择发送对象');
            return false;
        }
        if (this.title != "添加告警推送" && this.selectTreeList.length == 0) {
            this.message.error('请选择告警目标');
            return false;
        }

        if (!this.validateForm.alertGroupId) {
            this.message.error('请选择告警分组');
            return false;
        }

        if (!this.validateForm.def_longdata) {
            this.message.error('请输入发送信息');
            return false;
        }
        if (this.isEvent == '1') {
            if (!this.validateForm.event.title) {
                this.message.error('请输入事件标题');
                return false;
            }
            if (!this.validateForm.event.eventTypeId) {
                this.message.error('请选择事件分类');
                return false;
            }
            if (this.operatorList.length == 0) {
                this.message.error('请选择事件负责人');
                return false;
            }
        }

        let number = true;
        this.sendInfoList.map(e => {
            if (!e.mediaType) {
                number = false;
            }
            if (!e.receiver) {
                number = false;
            }
        });

        if (!number) {
            this.message.error('请输入发送对象');
            return false;
        }

        return true;
    }

    //创建
    create(data) {
        this.alarmSer.actionCreate(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isShow = false;
                    this.initForm();
                    this.done.emit();
                    this.message.success('创建告警成功');
                } else {
                    this.message.error(res.errMsg);
                }
                this.isOkLoading = false;
            }
        );
    }

    //修改
    update(data) {
        data.actionid = this.actionid;
        this.alarmSer.actionUpdate(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isShow = false;
                    this.initForm();
                    this.done.emit();
                    this.message.success('编辑告警成功');
                } else {
                    this.message.error(res.errMsg);
                }
                this.isOkLoading = false;
            }
        );
    }

}
