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';

@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 = [];  //设备类型列表

    validateForm;
    groupList = [];

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

    templatesResoure = [];

    //加密
    otherHost;

    isBasicEdit = false;
    tabNum: number;    //tabs面板的序列号
    macroList1: any[];
    macroList2: any[];      //配置宏数组
    interfaceslist: any[];   //接口list
    macroTYpe = 'macro';      //宏tabs
    mainHost = 'hostType1';      //主机tabs
    constructor(private fb: FormBuilder, private overAllSer: OverAllService,
                public message: NzMessageService) {
    }

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

    //获取分组
    getGroup(){
        this.groupList = [];
        this.overAllSer.findGroup().subscribe(
            (res) => {
                for (let i = 0; i < res.data.length; i++) {
                    const gObj = {
                        label: res.data[i].name, value: res.data[i].groupid, checked: false
                    };
                    this.groupList.push(gObj);
                }
            }
        );
    }

    //新增
    showModal(hostId, name, gId): void {
        this.isBasicEdit = true;
        this.modalTitle = '添加资源';
        this.hostId = hostId;
    }

    //编辑
    editModal(hostId, name, gId): void {
        this.isBasicEdit = true;
        this.hostId = hostId;
        this.modalTitle = '编辑资源';
        this.overAllSer.findDetailed(this.hostId).subscribe(
            (res) => {
                const data = res.data[0];
                this.validateForm.name = data.name;
                this.validateForm.host = data.host;
                this.validateForm.ipmi_authtype = data.ipmi_authtype + '';
                this.validateForm.ipmi_username = data.ipmi_username + '';
                this.validateForm.ipmi_privilege = data.ipmi_privilege + '';
                this.validateForm.ipmi_password = data.ipmi_password + '';
                this.validateForm.tls_psk_identity = data.tls_psk_identity + '';
                this.validateForm.tls_issuer = data.tls_issuer + '';
                this.validateForm.tls_subject = data.tls_subject + '';
                this.validateForm.tls_psk = data.tls_psk + '';
                this.validateForm.inventoryExtend = data.inventoryExtend;
                // this.validateForm.inventoryExtend.invertoryname = data.inventoryExtend.invertoryname;
                // this.validateForm.inventoryExtend.mac = data.inventoryExtend.mac;
                // this.validateForm.inventoryExtend.storageLocation = data.inventoryExtend.storageLocation;
                // this.validateForm.inventoryExtend.maintenanceExpiration = data.inventoryExtend.maintenanceExpiration;
                this.validateForm.hostExtend.equipmentTypeid = data.hostExtend.equipmentTypeid +'';
                this.validateForm.hostExtend.secondLevelTypeid = data.hostExtend.secondLevelTypeid +'';
                this.validateForm.hostExtend.serviceid = data.hostExtend.serviceid +'';

                this.validateForm.groups = data.groups;
                if(data.parentTemplates){
                    let tempArr = [];
                    tempArr = data.parentTemplates.map(res=>{
                        return res.templateid;
                    });
                    this.validateForm.templates = tempArr;
                    this.templatesResoure = tempArr;
                }
                this.interfaceslist = data.interfaces;
                this.interfaceslist.forEach(res => {
                    res.main = res.main + '';
                    res.type = res.type + '';
                });

                if (data.macros) {
                    this.macroList1 = data.macros;
                }

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

    //确定
    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;
        }

        //获取分组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.interfaceslist.forEach(res=>{
           if(res.bulk){
               res.bulk = '1';
           }else{
               res.bulk = '0';
           }
        });

        this.validateForm.groups = groupArr;
        if (this.modalTitle == '编辑资源') {
            this.update();
        } else {
            this.create();
        }
    }

    //创建
    create() {
        if (this.macroTYpe == 'macroExpand') {
            this.validateForm.macros = this.macroList2;
        }
        this.overAllSer.createHost(this.validateForm).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isBasicEdit = false;
                    this.initForm();
                    this.getGroup();
                    this.done.emit();
                }
                this.message.info(res.errMsg);
            },
            (err) => {
                this.message.info('系统错误');
            }
        );
    }

    //更新
    update() {

        //比较监控模版是否发生变化
        const clearArr = [];
        this.templatesResoure.forEach(res=>{
            if( this.validateForm.templates.indexOf(res) == -1 ){
                clearArr.push(res);
            }
        });
        this.validateForm.clearTemplateids = clearArr;

        if (this.macroTYpe == 'macroExpand') {
            this.validateForm.macros = this.macroList2;
        }
        this.validateForm.hostid = this.hostId;
        this.validateForm.interfaces = this.interfaceslist;
        this.validateForm.macros = this.macroList1;
        this.overAllSer.updateHost(this.validateForm).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isBasicEdit = false;
                    this.done.emit();
                    this.initForm();
                    this.getGroup();
                }
                this.message.info(res.errMsg);
            },
            (err) => {
                this.message.info('系统错误');
            }
        );
    }

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

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

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

    //getTree
    getTree(){
        this.overAllSer.findTree().subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.hostTypeList = res.data;
                }else{
                    this.message.info(res.errMsg);
                }
            }
        )
    }

    //
    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 = {
            main: '0',
            ip: '',
            dns: '',
            type: '1',
            port: '10050',
            useip: 1,
            bulk: false,
        };
        this.interfaceslist.push(demo);
    }

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

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

        }
    }

    //只能一个默认
    changeMain(index) {
        this.interfaceslist.forEach(res => {
            res.main = '0';
        });
        this.interfaceslist[index].main = '1';
    }

    //新增宏
    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);
    }

    //初始化Form信息
    initForm() {
        this.templatesResoure = [];
        this.macroList1 = [      //配置宏数组
            {
                macro: '{$SNMP_COMMUNITY}',
                value: 'public',
            }
        ];
        this.macroList2 = [      //配置宏数组
            {
                macro: '{$SNMP_COMMUNITY}',
                value: 'public',
            }
        ];
        this.interfaceslist = [   //接口list
            {
                main: '1',
                ip: '',
                dns: '',
                type: '1',
                port: '10050',
                useip: 1,
                bulk: false,
            }
        ];
        this.tabNum = 0;
        this.validateForm = {
            groups: [],
            hostExtend: {
                equipmentTypeid: null,
                secondLevelTypeid: null,
                serviceid: ''
            },
            macros: this.macroList1,
            interfaces: this.interfaceslist,  //接口
            inventoryExtend: {
                serialnoA: null,
                invertoryname: null,
                mac: null,
                storageLocation: null,
                maintenanceExpiration: null
            },
            templates: null,
            name: null,
            host: null,
            ipmi_authtype: null,
            ipmi_username: null,
            ipmi_privilege: null,
            ipmi_password: null,
            tls_psk_identity: null,
            tls_issuer: null,
            tls_subject: null,
            tls_psk: null,
        };
    }
}
