import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {
    FormBuilder,
    FormGroup,
    Validators
} from '@angular/forms';
import {OverAllService} from '../../overAll/overAll.service';
import {NzMessageService} from 'ng-zorro-antd';
import {WorkService} from '../../work/work.service';
import {EmitService} from '../../shared/event/eventEmitter';

@Component({
    selector: 'smart-basic-edit',
    templateUrl: './basic-edit.component.html',
    styles: []
})
export class BasicEditComponent implements OnInit {
    @Output() done = new EventEmitter<string>();
    modalTitle;    //modal标题
    nzSize = 'large';
    hostId;    //主机ID
    style = {
        display: 'block',
        height: '30px',
        lineHeight: '30px'
    };
    radioValue;

    tempList = [];  //模版列表
    hostTypeList = [];  //设备类型列表
    hostTypeChildrenList = [];  //设备类型列表
    parentTypeList = [];//父级分类
    typeList = [];//子级分类
    validateForm;
    groupList = [];

    //折叠面板
    panel1 = {name: '配置IPMI', active: true};
    panel2 = {name: '配置宏', active: true};

    templatesResoure = [];
    tempArr = [];

    //加密
    otherHost;

    isBasicEdit = false;
    isOkLoading = false;
    tabNum = 0;    //tabs面板的序列号
    macroList1: any[];
    macroList2: any[];      //配置宏数组
    interfaceslist: any[];   //接口list
    macroTYpe = 'macro';      //宏tabs
    mainHost = 'hostType1';      //主机tabs

    isInVentory = false;
    isYesInVentory = 'primary';
    isNOInVentory = 'default';
    inventoryParentId;
    equipmentTypeid;

    constructor(private fb: FormBuilder, private overAllSer: OverAllService,
                private emitService: EmitService,
                public message: NzMessageService, private workSer: WorkService) {
        this.emitService.eventEmit.subscribe((value: any) => {
            if (value == 'add') {
                this.getGroup();
            }
        });

    }

    ngOnInit() {
        this.tabNum = 0;
        this.initForm();
        this.getTemplate();
        this.getTree();
        this.getParentType();
        this.getGroup();
    }

    //获取分组
    getGroup() {
        this.groupList = [];
        this.overAllSer.findGroup().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    res.data.data.forEach(e => {
                        e.label = e.name;
                        e.value = e.id;
                        e.checked = false;
                    });
                    this.groupList = res.data.data;
                }
            }
        );
    }

    //新增
    showModal(): void {
        this.tabNum = 0;
        this.isBasicEdit = true;
        this.modalTitle = '添加资源';
    }

    //父级分类
    getParentType() {
        this.workSer.findByParentType().subscribe(
            (res) => {
                const data = res.data;
                this.parentTypeList = data;
            }
        );
    }

    //通过父级分类查询子级分类
    getTypeByParent(parentid) {
        this.workSer.findByParentidCount(parentid).subscribe(
            (res) => {
                const data = res.data;
                this.typeList = data;
            }
        );
    }

    //编辑
    editModal(hostId): void {
        this.isBasicEdit = true;
        this.tabNum = 0;
        this.hostId = hostId;
        this.modalTitle = '编辑资源';
        this.overAllSer.findDetailed(this.hostId).subscribe(
            (res) => {
                const data = res.data;
                this.validateForm.name = data.name;
                this.validateForm.host = data.host;

                //分组对象
                if (data.groups) {
                    this.validateForm.groups = data.groups;
                    for (let i = 0; i < this.validateForm.groups.length; i++) {
                        for (let j = 0; j < this.groupList.length; j++) {
                            if (this.validateForm.groups[i].groupid == this.groupList[j].value) {
                                this.groupList[j].checked = true;
                            } else {
                                this.groupList[j].checked = false;
                            }
                        }
                    }
                    for (let i = 0; i < this.groupList.length; i++) {
                        for (let j = 0; j < this.validateForm.groups.length; j++) {
                            if (this.validateForm.groups[j].groupid == this.groupList[i].value) {
                                this.groupList[i].checked = true;
                            }
                        }
                    }
                }

                //模版对象
                if (data.parentTemplates) {
                    this.tempArr = data.parentTemplates.map(e => {
                        return e.id;
                    });
                }

                //接口对象
                if (data.interfaces) {
                    this.interfaceslist = data.interfaces;
                    this.interfaceslist.forEach(res => {
                        res.type = res.type + '';
                    });
                }

                //主机对象
                this.hostTypeChildrenList = [];
                if (data.hostExtend) {
                    this.validateForm.hostExtend = data.hostExtend;
                    this.hostTypeList.forEach(res => {
                        if (this.validateForm.hostExtend.equipmentTypeid == res.id) {
                            this.hostTypeChildrenList = res.childs;
                        }
                    });
                }

                //宏对象
                if (data.macros) {
                    data.macros.forEach(e => {
                        this.macroList1.push({'macro': e.macro, 'value': e.value});
                    });
                }

                //资产对象
                if (data.inventory) {
                    this.validateForm.inventoryExtend = data.inventory;
                    this.inventoryParentId = data.inventory.typeparentid;
                    this.isInVentory = true;
                    this.isYesInVentory = 'default';
                    this.isNOInVentory = 'primary';
                }

            }
        );
    }

    //确定
    handEditleOk() {
        if (!this.validateForm.hostExtend.equipmentTypeid) {
            this.message.info('请选择选择设备类型');
            return false;
        }
        if (!this.validateForm.hostExtend.secondLevelTypeid) {
            this.message.info('请选择选择二级类型');
            return false;
        }
        if (!this.validateForm.name) {
            this.message.info('请输入显示名');
            return false;
        }
        if (!this.validateForm.host) {
            this.message.info('请输入IP地址');
            return false;
        }
        if (this.isInVentory) {
            if (!this.validateForm.inventoryExtend.name) {
                this.message.info('请输入资产名称');
                return false;
            }
        }

        //获取分组id
        const groupArr = [];
        for (let i = 0; i < this.groupList.length; i++) {
            if (this.groupList[i].checked == true) {
                const groupid = {'groupid': this.groupList[i].value};
                groupArr.push(groupid);
            }
        }
        this.validateForm.groups = groupArr;
        this.tempArr.forEach(res => {
            const d = {
                id: res
            };
            this.validateForm.templates.push(d);
        });
        this.isOkLoading = true;
        if (this.modalTitle == '编辑资源') {
            this.update();
        } else {
            this.create();
        }
    }

    //创建
    create() {
        const interfaceArr = [];
        this.interfaceslist.forEach(res => {
            const a = {
                ip: res.ip,
                type: res.type,
                port: res.port,
            };
            interfaceArr.push(a);
        });
        this.validateForm.interfaces = interfaceArr;
        if (this.macroTYpe == 'macroExpand') {
            this.validateForm.macros = this.macroList2;
        }
        if (!this.isInVentory) {
            this.validateForm.inventoryExtend = null;
        }
        this.overAllSer.createHost(this.validateForm).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isBasicEdit = false;
                    this.initForm();
                    this.done.emit();
                    this.message.success('创建成功');
                }
                this.isOkLoading = false;
            },
            (err) => {
                this.message.info('系统错误');
            }
        );
    }

    //更新
    update() {
        const interfaceArr = [];
        this.interfaceslist.forEach(res => {
            const a = {
                ip: res.ip,
                type: res.type,
                port: res.port,
                hostid: this.hostId,
                interfaceid: res.interfaceid
            };
            interfaceArr.push(a);
        });
        this.validateForm.interfaces = interfaceArr;
        //比较监控模版是否发生变化
        if (!this.isInVentory) {
            this.validateForm.inventoryExtend = null;
        }
        if (this.macroTYpe == 'macroExpand') {
            this.validateForm.macros = this.macroList2;
        }
        this.validateForm.hostid = this.hostId;
        this.validateForm.macros = this.macroList1;
        this.validateForm.id = this.hostId;
        this.overAllSer.updateHost(this.validateForm).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isBasicEdit = false;
                    this.done.emit();
                    this.initForm();
                    this.message.success('修改成功');
                }
                this.isOkLoading = false;
            },
            (err) => {
                this.message.info('系统错误');
            }
        );
    }

    //取消
    handleEditCancel(): void {
        this.isBasicEdit = false;
        this.isOkLoading = false;
        this.initForm();
    }

    //tabs切换
    tabsChange(num) {
        this.tabNum = num;
    }

    //获取模版
    getTemplate() {
        this.overAllSer.templates().subscribe(
            (res) => {
                this.tempList = res.data;
            }
        );
    }

    //获取设备类型
    getTree() {
        this.overAllSer.findTree().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.hostTypeList = res.data;
                }
            }
        );
    }

    //二级类型的list
    getChildren(item) {
        this.hostTypeChildrenList = [];
        this.validateForm.hostExtend.secondLevelTypeid = null;
        this.hostTypeList.forEach(res => {
            if (item == res.id) {
                this.hostTypeChildrenList = res.childs;
            }
        });
    }

    //接口add
    addInterfaces() {
        const demo = {
            ip: '',
            type: '2',
            port: '10050',
        };
        this.interfaceslist.push(demo);
    }

    //接口delete
    deleteInterfaces(index) {
        this.interfaceslist.splice(index, 1);
    }

    // 1 agent:161 2 SNMP:161   3 IPMI:12345  4 JMX:6999
    changePort(index) {
        switch (this.interfaceslist[index].type) {
            case '1': {
                this.interfaceslist[index].port = '10050';
                break;
            }
            case '2': {
                this.interfaceslist[index].port = '161';
                break;
            }
            case '3': {
                this.interfaceslist[index].port = '12345';
                break;
            }
            case '4': {
                this.interfaceslist[index].port = '6999';
                break;
            }

        }
    }

    //新增宏
    addMacro1() {
        const data = {
            macro: '{$SNMP_COMMUNITY}',
            value: 'public',
        };
        this.macroList1.push(data);
    }

    //移除宏
    deleteMacro1(index) {
        this.macroList1.splice(index, 1);
    }

    //新增主机宏
    addMacro2() {
        const data = {
            macro: '{$SNMP_COMMUNITY}',
            value: 'public',
        };
        this.macroList2.push(data);
    }

    //移除主机宏
    deleteMacro2(index) {
        this.macroList2.splice(index, 1);
    }

    //登记资产
    checkChange(e) {
        if (e == 'yes') {
            this.isInVentory = true;
            this.isYesInVentory = 'default';
            this.isNOInVentory = 'primary';
        }
        if (e == 'no') {
            this.isInVentory = false;
            this.isYesInVentory = 'primary';
            this.isNOInVentory = 'default';
        }
    }

    //初始化Form信息
    initForm() {
        this.isInVentory = false;
        this.isYesInVentory = 'primary';
        this.isNOInVentory = 'default';
        this.templatesResoure = [];
        this.macroList1 = [      //配置宏数组
            {
                macro: '{$SNMP_COMMUNITY}',
                value: 'public',
            }
        ];
        this.macroList2 = [      //配置宏数组
            {
                macro: '{$SNMP_COMMUNITY}',
                value: 'public',
            }
        ];
        this.interfaceslist = [   //接口list
            {
                ip: '',
                type: '2',
                port: '10050',
            }
        ];
        this.tabNum = 0;
        this.validateForm = <any>{
            groups: [],
            hostExtend: {
                equipmentTypeid: null,
                secondLevelTypeid: null,
            },
            macros: this.macroList1,
            interfaces: null,  //接口
            inventoryExtend: {
                serialnoA: null,
                invertoryname: null,
                mac: null,
                storageLocation: null,
                maintenanceExpiration: null,
                name: null,
                person: null,
                ip: null,
                usedcount: null,
                stock: null,
                lendcount: null,
                repaircount: null,
                scrapcount: null,
            },
            templates: [],
            name: null,
            host: null,
        };
    }
}
