import {Component, OnInit, ViewChild} from '@angular/core';
import {OverAllService} from '../overAll.service';
import {NzModalService} from 'ng-zorro-antd';
import {NzMessageService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {
    FormBuilder,
    FormGroup,
    Validators
} from '@angular/forms';
import {BasicEditComponent} from '../../modal/basic-edit/basic-edit.component';
import {BasiCheckComponent} from '../../modal/basi-check/basi-check.component';
import {CreateGroupComponent} from '../../modal/create-group/create-group.component';
import {PauseComponent} from '../../modal/pause/pause.component';
import {AlarmModalComponent} from '../../modal/alarm-modal/alarm-modal.component';
import {color} from '../../app.constants';

export interface TreeNodeInterface {
    host: any;
    name: string;
    age: number;
    level: number;
    expand: boolean;
    address: string;
    children?: TreeNodeInterface[];
}

@Component({
    selector: 'jhi-basic',
    templateUrl: './basic.component.html',
    styles: [
        `:host ::ng-deep .table-dropdown a{
           font-weight: 300;
        }`
    ]
})
export class BasicComponent implements OnInit {
    //组件
    @ViewChild('basicEdit') basicEdit: BasicEditComponent;
    @ViewChild('smartCheck') smartCheck: BasiCheckComponent;
    @ViewChild('smartCreateGroup') smartCreateGroup: CreateGroupComponent;
    @ViewChild('smartPause') smartPause:PauseComponent;
    @ViewChild('smartAlarmModal') smartAlarmModal:AlarmModalComponent;

    color = color;

    //表格信息
    loading = false;
    frontPagination = true;

    selectedValue;
    isCheck = false;
    allChecked = false;
    interfaceList: any[];
    hostId;
    deviceNo;     //设备监控数

    isKey = false;
    keyList: any[];
    keyType = '1';

    //批量删除list
    batchDelList = [];

    //设备状态
    red;
    yellow;
    green;
    gray;

    //搜索
    searchStatus = false;
    searchName;
    searchData;

    constructor(private fb: FormBuilder, private overAllSer: OverAllService, private router: Router,
                private modalService: NzModalService, private message: NzMessageService,
                ) {
    }

    dataSet: any[];
    expandDataCache = {};
    ckeckObj: object;

    collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
        if ($event === false) {
            if (data.children) {
                data.children.forEach(d => {
                    const target = array.find(a => a.host === d.host);
                    target.expand = false;
                    this.collapse(array, target, false);
                });
            } else {
                return;
            }
        }
    }

    convertTreeToList(root: any, groupId: string,index): TreeNodeInterface[] {
        const stack = [];
        const array = [];
        const hashMap = {};
        if(root.host == index){
            stack.push({...root, level: 0, expand: true});
        }else{
            stack.push({...root, level: 0, expand: false});
        }
        while (stack.length !== 0) {
            const node = stack.pop();

            this.visitNode(node, hashMap, array);
            if (node.list) {
                for (let i = node.list.length - 1; i >= 0; i--) {
                    stack.push({...node.list[i], level: node.level + 1, expand: true, parent: node, gId: groupId, checked: false});
                }
            }
        }

        return array;
    }

    visitNode(node: TreeNodeInterface, hashMap: object, array: TreeNodeInterface[]): void {
        if (!hashMap[node.host]) {
            hashMap[node.host] = true;
            array.push(node);
        }
    }

    ngOnInit(): void {
        this.selectedValue = 'group';
        this.select();
        this.findSize();
        this.findOpStatus();
    }

    //搜索
    search(status){
        this.loading = true;
        this.searchStatus = true;
        this.frontPagination = false;
        const data = {
            search:{
                status:status,
                name:this.searchName
            }
        }
        this.overAllSer.find(data).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.searchData = res.data;
                }
                this.loading = false;
            }
        )
    }

    //backList
    backList(){
        this.searchStatus = false;
        this.frontPagination = true;
    }

    //查询设备状态
    findOpStatus(){
        this.overAllSer.findHostCountByStatus(0).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                        this.green = res.data.size;
                }else{
                    this.message.info(res.Msg);
                }
            }
        )
        this.overAllSer.findHostCountByStatus(1).subscribe(
            (res)=>{
                this.gray = res.data.size;
            }
        )
        this.overAllSer.findWarningByAll(1).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.yellow = res.data.size;
                }else{
                    this.message.info(res.Msg);
                }
            }
        )
        this.overAllSer.findWarningByAll(0).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.red = res.data.size;
                }else{
                    this.message.info(res.Msg);
                }
            }
        )
    }

    //添加资源  ,name-分组名称，id-分组id
    showBasicEditModal(item) {
        this.basicEdit.showModal(item.hostId, item.name, item.id);
    }

    //编辑资源 name--分组名称，gId-当前分组的id
    editBasicModal(item) {
        this.basicEdit.editModal(item.hostid, item.name, item.gId);
    }

    //添加监测点
    showBasicCheckModal(hostid,host) {
        this.smartCheck.showAddModal(hostid,host);
    }

    //列表
    findList() {
        const data = {};
        this.overAllSer.find(data).subscribe(
            (res) => {
                if (res.data) {
                    this.dataSet = res.data;
                } else {
                    this.message.info(res.errMsg);
                }

            }
        );
    }

    //选择分组
    select() {
        this.loading = true;
        this.searchStatus = false;
        this.frontPagination = true;
        this.findOpStatus();
        if (this.selectedValue == 'group') {
            this.overAllSer.getgroups({}).subscribe(
                (res) => {
                    this.loading = false;
                    if (res.errCode == 10000) {
                        this.dataSet = res.data;
                        // this.dataSet = this.dataSet.filter(d => d.list);     //过滤无list的
                        for (let i = 0; i < this.dataSet.length; i++) {
                            this.dataSet[i].host = i;
                            this.dataSet[i].checked = false;
                        }
                        this.toTree(null);
                    } else {
                        this.message.info(res.errMsg);
                    }
                }
            );
        } else if (this.selectedValue == 'type') {
            this.overAllSer.findType().subscribe(
                (res) => {
                    this.loading = false;
                    if (res.errCode == 10000) {
                        this.dataSet = res.data;
                        // this.dataSet = this.dataSet.filter(d => d.list);     //过滤无list的
                        for (let i = 0; i < this.dataSet.length; i++) {
                            this.dataSet[i].host = i;
                            this.dataSet[i].checked = false;
                        }
                        this.toTree(null);
                    } else {
                        this.message.info(res.errMsg);
                    }
                }
            );
        } else if (this.selectedValue == 'all') {
            this.findList();
        }
    }

    toTree(index) {
        this.dataSet.forEach(item => {
            this.expandDataCache[item.host] = this.convertTreeToList(item, item.id, index);
        });
    }

    //删除单个资源
    showDeleteConfirm(data) {
        this.modalService.confirm({
            nzTitle: '删除',
            nzContent: '<b style="color: red;">确认删除该资源吗？</b>',
            nzOkText: '确定',
            nzOkType: 'danger',
            nzOnOk: () => {
                this.overAllSer.deleteHostGet(data.hostid).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.info('删除成功');
                            this.select();
                        } else {
                            this.message.info(res.errMsg);
                        }
                    }
                );
            },
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //批量删除资源
    batchDeleteConfirm(){
        if(this.batchDelList.length == 0){
            this.message.info('请选择需要删除的设备');
            return false;
        }
        this.modalService.confirm({
            nzTitle: '删除',
            nzContent: '<b style="color: red;">确认要删除所选设备吗？</b>',
            nzOkText: '确定',
            nzOkType: 'danger',
            nzOnOk: () => {
                const data = {
                    hostids:this.batchDelList
                }
                this.overAllSer.deleteHostPost(data).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.info('删除成功');
                            this.batchDelList = [];
                            this.select();
                        } else {
                            this.message.info(res.errMsg);
                        }
                    }
                );
            },
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //添加分组
    showGroupModal() {
        this.smartCreateGroup.showModal('添加分组');
    }

    //编辑分组
    updateGroup(item){
        this.smartCreateGroup.showEditModal('修改分组',item);
    }

    //删除分组
    showDeleteGroupConfirm(item) {
        this.modalService.confirm({
            nzTitle: '删除',
            nzContent: '<b style="color: red;">确认删除该分组吗？</b>',
            nzOkText: '确定',
            nzOkType: 'danger',
            nzOnOk: () => {
                const data = {params: []};
                data.params.push(item.groupid);
                this.overAllSer.deleteGroup(data).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.info('删除成功');
                            this.select();
                        } else {
                            this.message.info(res.errMsg);
                        }
                    }
                );
            },
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //添加告警
    showAlarm(item){
        this.smartAlarmModal.showModal(item);
    }

    handleOk(e) {
        this.select();
    }

    //获取下级list
    getChildren(item) {
        if(item.list){
            if(item.expand){
                item.expand = false;
            }else{
                item.expand = true;
            }
            return false;
        }
        this.loading = true;
        const data = {
            'groupids': [item.groupid],
            'hostExtend': {
                'superiorHostid': null
            }
        };
        this.overAllSer.findDetail(data).subscribe(
            (res) => {
                if(res.data){
                    this.dataSet[item.host].list = res.data;
                    this.toTree(item.host);
                }else{
                    this.message.info('该分组下无资源');
                }
                this.loading = false;
            }
        );
    }

    //根据设备类型查询主机资源
    getChildrenType(item){
        if(item.list){
            if(item.expand){
                item.expand = false;
            }else{
                item.expand = true;
            }
            return false;
        }
        this.loading = true;
        const data = {
            type:item.equipmentTypeid
        };
        this.overAllSer.findHostByType(data).subscribe(
            (res) => {
                if(res.data){
                    this.dataSet[item.host].list = res.data;
                    this.toTree(item.host);
                }else{
                    this.message.info('该分组下无资源');
                }
                this.loading = false;
            }
        );
    }

    //查看详情
    goDetail(item){
        let type = 0;
        if(item.hostExtend){
            if(item.hostExtend.equipmentType == '交换机'){
                type = 1;
            }
        }
        this.router.navigate(['app/main/basic-detail'],{
            queryParams:{
                hostId:item.hostid,
                type:type,
                name:item.name,
                hostName:item.host
            }
        })
    }

    //监控设备数
    findSize() {
        this.overAllSer.findSize().subscribe(
            (res) => {
                this.deviceNo = res.data.size;
            }
        );
    }

    //临时暂停
    showTempStop(item){
        this.smartPause.showModal(item.hostid,'基础资源');
    }

    //选择
    selectChecked(event,item){
        if(event){
            if(item.hostid){
                this.batchDelList.push(item.hostid);
            }
        }else{
            if(item.hostid){
                const index = this.batchDelList.indexOf(item.hostid);
                this.batchDelList.splice(index,1)
            }
        }
    }

    //开启or停止监控
    openHost(item){
        this.modalService.confirm({
            nzTitle: '监控',
            nzContent: '确定开启监控设备'+item.name + '？',
            nzOkText: '确定',
            nzCancelText: '取消',
            nzOnOk: () => {
                let params1 = 0;
                if(item.status == 0){
                    params1 = 1;
                }
                const params2 = item.hostid;
                this.overAllSer.stopOrOpen(params1,params2).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.info('修改成功');
                            this.select();
                        } else {
                            this.message.info(res.errMsg);
                        }
                    }
                );
            },
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //批量开启or停止监控
    openBatchHost(status,operation){
        if(this.batchDelList.length == 0){
            this.message.info('请选择需要'+ operation +'的设备');
            return false;
        }
        this.modalService.confirm({
            nzTitle: '监控',
            nzContent: '确定批量'+operation+'监控设备?',
            nzOkText: '确定',
            nzCancelText: '取消',
            nzOnOk: () => {
                const data = {
                    status:status,
                    hostids:this.batchDelList
                }
                this.overAllSer.batchStopOrOpen(data).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.info('修改成功');
                            this.batchDelList = [];
                            this.findOpStatus();
                            this.select();
                        } else {
                            this.message.info(res.errMsg);
                        }
                    }
                );
            },
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //资产页面
    goTOInventory(id){

    }
}
