import {Component, OnInit, ViewChild} from '@angular/core';
import {BasicEditComponent} from '../../modal/basic-edit/basic-edit.component';
import {CreateGroupComponent} from '../../modal/create-group/create-group.component';
import {OverAllService} from '../overAll.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {AlarmModalComponent} from '../../modal/alarm-modal/alarm-modal.component';
import {BasiCheckComponent} from '../../modal/basi-check/basi-check.component';
import {JhiMainComponent} from '../../layouts';
import {FormBuilder} from '@angular/forms';
import {color} from '../../app.constants';
import {PauseComponent} from '../../modal/pause/pause.component';
import {TreeNodeInterface} from '../basic/basic.component';
import {Router} from '@angular/router';
import {DiscoveryComponent} from '../../modal/discovery/discovery.component';
import {StrategyComponent} from '../../modal/strategy/strategy.component';
import {WorkService} from '../../work/work.service';
import {CommonService} from '../../shared/common/common.service';
import {UploadComponent} from '../../work/modal/upload/upload.component';

@Component({
    selector: 'smart-template',
    templateUrl: './template.component.html',
    styles: []
})
export class TemplateComponent implements OnInit {
    //组件
    @ViewChild('basicEdit') basicEdit: BasicEditComponent;
    @ViewChild('smartCheck') smartCheck: BasiCheckComponent;
    @ViewChild('smartCreateGroup') smartCreateGroup: CreateGroupComponent;
    @ViewChild('smartPause') smartPause: PauseComponent;
    @ViewChild('smartAlarmModal') smartAlarmModal: AlarmModalComponent;
    @ViewChild('smartDiscovery') smartDiscovery: DiscoveryComponent;
    @ViewChild('smartStrategy') smartStrategy: StrategyComponent;
    @ViewChild('smartUpload') smartUpload:UploadComponent;

    color = color;
    isDownload = false;

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

    selectedValue;
    isCheck = false;
    allChecked = false;
    hostId;

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

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

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

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

    //模版
    templateList = [];
    indeterminate;

    isClone = false;

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

    dataSet: any[];
    expandDataCache = {};

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

    ngOnInit(): void {
        this.getTemplateGroup();
    }

    //获取模版组
    getTemplateGroup() {
        this.isLoading = true;
        this.overAllSer.getTemplateGroups().subscribe(
            (res) => {
                this.dataSet = res.data;
                this.isLoading = false;
                for (let i = 0; i < this.dataSet.length; i++) {
                    this.dataSet[i].host = i;
                    this.dataSet[i].checked = false;
                }
                this.toTree(null);
            }
        );
    }

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

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

    //添加模版
    showTempAddModal() {
        this.smartStrategy.showAddModal('添加模版');
    }

    //编辑模版
    showTempEditModal(item) {
        this.smartStrategy.showEditModal('编辑模版', item.templateid);
    }

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

    //添加自动发现
    showDiscoveryAddModal(item) {
        this.smartDiscovery.showAddModal(item.templateid, '添加自动发现');
    }

    //goto 自动发现页面
    goToDiscovery(item) {
        this.router.navigate(['app/main/discoveryList'], {
            queryParams: {
                templateid: item.templateid,
                name: item.name,
                hostName: item.host
            }
        });
    }

    //goto 监控项列表
    goToItem(item) {
        this.router.navigate(['app/main/itemList'], {
            queryParams: {
                templateid: item.templateid,
                name: item.name,
                hostName: item.host
            }
        });
    }

    //goto阈值列表
    goToTri(item) {
        this.router.navigate(['app/main/triList'], {
            queryParams: {
                templateid: item.templateid,
                name: item.name,
                hostName: item.host
            }
        });
    }

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

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

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

    handleOk(e) {
        this.getTemplateGroup();
        this.smartStrategy.getTemplateGroup();
    }

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

    //根据设备类型查询主机资源
    getChildrenType(item) {
        if (item.list) {
            if (item.expand) {
                item.expand = false;
            } else {
                item.expand = true;
            }
            return false;
        }
        this.isLoading = 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.isLoading = false;
            }
        );
    }

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

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

    //批量删除资源
    batchDeleteConfirm() {
        if (this.batchDelList.length == 0) {
            this.message.info('请选择需要删除的设备');
            return false;
        }
        this.commonSer.confirmThing('删除','确认要删除所选模版吗？',()=>{
            const data = {
                templateids: this.batchDelList
            };
            this.overAllSer.deleteTemplates(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.message.success('删除成功');
                        this.batchDelList = [];
                        this.getTemplateGroup();
                    } else {
                        this.message.error(res.errMsg);
                    }
                }
            );
        })
    }

    //删除单个模版
    showDeleteConfirm(item) {
        this.commonSer.confirmThing('删除','确认删除该模版吗？',()=>{
            const data = {
                templateids: []
            };
            data.templateids.push(item.templateid);
            this.overAllSer.deleteTemplates(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.message.info('删除成功');
                        this.getTemplateGroup();
                    } else {
                        this.message.info(res.errMsg);
                    }
                }
            );
        });
    }

    //克隆单个模版
    cloneTemp(item) {
        this.commonSer.confirmThing('克隆','确认克隆该模版吗？',()=>{
            this.isClone = true;
            const data = {
                templateid: Number(item.templateid)
            };
            this.overAllSer.cloneTemplates(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.message.info('克隆成功');
                        this.getTemplateGroup();
                    } else {
                        this.message.info(res.errMsg);
                    }
                    this.isClone = false;
                }
            );
        });
    }

    //导入资产
    showUploadModal(){
        this.smartUpload.showModal("上传XML模版");
    }

    //下载模版
    download(){
        this.isDownload = true;
        const data = {
            ids:this.batchDelList
        };
        this.overAllSer.exportTemplates(data).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.workSer.downloadTemplate('templateExport',res.data).subscribe(
                        (data)=>{
                            this.isDownload = false;
                            this.commonSer.downloadFile('XML模版.xml',data)
                        }
                    )
                }else{
                    this.isDownload = false;
                    this.message.error(res.errMsg);
                }
            }
        )
    }
}
