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, pageSize} from '../../app.constants';
import {JhiMainComponent} from '../../layouts';
import {CommonService} from '../../shared/common/common.service';

export interface TreeNodeInterface {
    host: any;
    hostid: any;
    serviceid: any;
    name: string;
    level: number;
    expand: boolean;
    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;

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

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

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

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

    //搜索
    searchName;
    searchData;
    status;

    pageNum = 1;
    pageCount = pageSize;
    totalNum;

    selectedValue = 'group';

    groupList = [];  //分组列表
    groupid = null;
    equipmentTypeid = null;

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

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

    showInFullScreen() {
        this.main.fullScreen();
    }

    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.hostid]) {
            hashMap[node.hostid] = true;
            array.push(node);
        }
    }

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

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

    select(e) {
        this.groupid = null;
        this.equipmentTypeid = null;
        if (e == 'group') {
            this.getGroup();
        } else {
            this.getType();
        }
    }

    //获取资源分组
    getGroup() {
        this.overAllSer.findGroup().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.groupList = res.data;
                    this.search();
                }
            }
        );
    }

    //获取设备类型
    getType() {
        this.overAllSer.findType().subscribe(
            (res) => {
                this.loading = false;
                if (res.errCode == 10000) {
                    this.groupList = res.data;
                    this.search();
                } else {
                    this.message.info(res.errMsg);
                }
            }
        );
    }

    changeStatus(status) {
        this.loading = true;
        if (this.status == status) {
            this.status = null;
        } else {
            this.status = status;
        }
        this.pageNum = 1;
        this.search();
    }

    /*
    //waringName:（值为:正常，禁用，告警，严重）
     */
    search() {
        this.loading = true;
        this.pageNum = 1;
        this.searchRe();
    }

    changeGroup(e) {
        this.loading = true;
        this.pageNum = 1;
        this.groupid = e;
        this.equipmentTypeid = null;
        this.searchRe();
    }

    changeEquiment(e){
        this.loading = true;
        this.pageNum = 1;
        this.groupid = null;
        this.equipmentTypeid = e;
        this.searchRe();
    }

    searchRe() {
        const data = {
            pageNum: this.pageNum,
            pageCount: this.pageCount,
            obj: {
                name: this.searchName,
                waringName: this.status,
                equipmentTypeid: this.equipmentTypeid,
                groupids: []
            }
        };
        if(this.groupid){
            data.obj.groupids.push(this.groupid)
        }else{
            data.obj.groupids = [];
        }
        this.overAllSer.findHostPageNew(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.dataSet = res.data.data;
                    this.totalNum = res.data.totalNum;
                }
                this.loading = false;
            }
        );
    }

    //翻页
    change(event) {
        this.loading = true;
        this.pageNum = event;
        this.searchRe();
        console.log(this.groupid);
    }

    //backList
    backList() {
        this.findOpStatus();
    }

    //查询设备状态
    findOpStatus() {
        this.overAllSer.findHostCountByStatusByHost().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.green = res.data.normal;
                    this.gray = res.data.disable;
                    this.yellow = res.data.waring;
                    this.red = res.data.serious;
                    this.deviceNo = res.data.total;
                } else {
                    this.message.info(res.Msg);
                }
            }
        );
    }

    //添加资源
    showBasicEditModal() {
        this.basicEdit.showModal();
    }

    //编辑资源 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);
                }

            }
        );
    }

    //删除单个资源
    showDeleteConfirm(item) {
        this.commonSer.confirmThing('删除', '确认删除该资源吗?', () => {
            this.loading = true;
            const data = {
                hostids: []
            };
            data.hostids.push(item.hostid);
            this.overAllSer.deleteHostPost(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.message.info('删除成功');
                        this.searchRe();
                    } else {
                        this.message.info(res.errMsg);
                    }
                }
            );
        });
    }

    //批量删除资源
    batchDeleteConfirm() {
        if (this.batchDelList.length == 0) {
            this.message.info('请选择需要删除的设备');
            return false;
        }

        this.commonSer.confirmThing('删除', '确认要删除所选设备吗？', () => {
            this.loading = true;
            const data = {
                hostids: this.batchDelList
            };
            this.overAllSer.deleteHostPost(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.message.info('删除成功');
                        this.batchDelList = [];
                        this.searchRe();
                    } else {
                        this.message.error(res.errMsg);
                    }
                }
            );
        });
    }

    //添加分组
    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: () => {
                this.loading = true;
                const data = {groupid: []};
                data.groupid.push(item.groupid);
                this.overAllSer.deleteGroup(data).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.info('删除成功');
                            this.searchRe();
                        } else {
                            this.message.info(res.errMsg);
                        }
                    }
                );
            },
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //添加告警
    showAlarm() {
        this.smartAlarmModal.showAddModal('添加告警', null);
    }

    handleOk(e) {
        this.loading = true;
        this.searchRe();
    }

    //根据设备类型查询主机资源
    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) {
        this.router.navigate(['app/main/basic-detail'], {
            queryParams: {
                hostId: item.hostid,
            }
        });
    }

    //临时暂停
    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: () => {
                this.loading = true;
                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.searchRe();
                        } 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: () => {
                this.loading = true;
                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.searchRe();
                        } else {
                            this.message.info(res.errMsg);
                        }
                    }
                );
            },
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //资产页面
    goTOInventory(id) {
        this.router.navigate(['app/main/assetsDetail'], {
            queryParams: {
                invertoryId: id
            }
        });
    }
}
