import {AfterViewChecked, AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {TopologyService} from '../topology.service';
import {NzMessageService, NzModalService, UploadFile} from 'ng-zorro-antd';
import {DomSanitizer} from '@angular/platform-browser';
import * as $ from 'jquery';
import {TopologyComponent} from '../model/topology/topology.component';
import {CheckComponent} from '../model/check/check.component';
import {DeviceComponent} from '../model/device/device.component';
import {SelectGroupComponent} from '../../modal/select-group/select-group.component';

declare let editor: any;
declare var layui: any;

@Component({
    selector: 'smart-ne-topology',
    templateUrl: './ne-topology.component.html',
    styles: [
            `
            .layui-side-scroll {
                width: initial;
            }

            .layui-layout-right {
                color: #666666;
            }

            .layui-header span {
                margin-right: 15px;
                cursor: pointer;
            }

            .tips {
                position: absolute;
                top: 10px;
                left: 20px;
                color: #ca0814;
                font-size: 20px;
            }

            .checkList {
                position: absolute;
                top: 10px;
                right: 20px;
                color: #666666;
                font-size: 20px;
            }

            .layui-form-label {
                width: 110px;
            }

            .minus {
                vertical-align: middle;
                color: red;
                font-size: 15px;
                margin-left: 12px;
                cursor: pointer;
            }
        `
    ]
})
export class NeTopologyComponent implements OnInit, AfterViewInit {
    @ViewChild('topologyCanvas') topologyCanvas: ElementRef;
    @ViewChild('smartTopology') smartTopology: TopologyComponent;
    @ViewChild('smartCheck') smartCheck: CheckComponent;
    @ViewChild('smartSelectGroup') smartSelectGroup: SelectGroupComponent;

    dataSet;
    isVisible = false;
    image;

    topoId;
    name;
    refreshRete;
    options;

    checkJson = [];
    fileList: UploadFile[] = [];

    constructor(private topologySer: TopologyService, private message: NzMessageService,
                private sanitizer: DomSanitizer, private modalSer: NzModalService) {
    }

    ngOnInit() {
        this.getList();
        this.getTypeList();
    }

    //一级分类
    getTypeList(){
        this.topologySer.findTreeWithWeb().subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.options = res.data;
                    layui.use('form', function() {
                        let form = layui.form;
                        form.render("select");
                    });
                }else{
                    this.message.error(res.errMSg);
                }
            }
        )
    }

    ngAfterViewInit() {
        layui.use('element', () => {
            let element = layui.element;
            element.init();
        });
        this.loadCanvas();

    }

    //新增拓扑图
    addTopo() {
        this.smartTopology.showAddMOodal();
    }

    //编辑拓扑图
    editTopo() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.smartTopology.showEditModal(this.topoId);
    }

    //添加监测点
    addCheck() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.smartCheck.showAddModal();
    }

    //添加设备
    addDevice() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.smartSelectGroup.showAddModal('添加设备');
    }

    //获取设备图片
    setImg(e) {
        console.log(e);
        editor.utils.addNode(e[0].icon, '图片');
    }

    //获取列表
    getList() {
        this.topologySer.findAll().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.dataSet = res.data;
                } else {
                    this.message.create('error', res.errMsg);
                }
            }
        );
    }

    //编辑
    update() {
        const json = {
            topology: editor.saveTopology(),
            check: this.checkJson
        };
        let data = {
            id: this.topoId,
            json: JSON.stringify(json),
            refreshRete: this.refreshRete,
            name: this.name
        };
        this.topologySer.update(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('编辑成功');
                    editor.utils.editTopology();
                    this.getList();
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    //查询单个
    getDetail(id) {
        this.topologySer.findItem(id).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    if (res.data.json.length > 0) {
                        let json = JSON.parse(res.data.json);
                        editor.loadTopologyByJson(JSON.parse(json.topology), 'img/backimg.png');
                        this.checkJson = json.check;
                    } else {
                        editor.utils.clearTopology();
                        this.checkJson = [];
                    }
                    this.name = res.data.name;
                    this.refreshRete = res.data.refreshRete;
                    this.topoId = res.data.id;
                    editor.utils.editTopology();
                    this.findItemStatus();
                }
            }
        );
    }

    //查询监控点状态
    findItemStatus() {
        const data = {
            httpTestIds: this.checkJson.map(e => {
                return e.id;
            })
        };
        this.topologySer.findElementStatus(data).subscribe(
            (res) => {

            }
        );
    }

    //删除拓扑图
    deleteTopo() {
        if (!this.topoId) {
            this.message.warning('请选择需要删除的拓扑图');
            return false;
        }
        this.modalSer.confirm({
                nzTitle: '删除',
                nzContent: '<b style="color: red;">确认删除该拓扑图吗？</b>',
                nzOkText: '确定',
                nzOkType: 'danger',
                nzOnOk: () => {
                    this.topologySer.delete(this.topoId).subscribe(
                        (res) => {
                            if (res.errCode == 10000) {
                                this.topoId = null;
                                this.message.success('删除成功');
                                this.getList();
                            } else {
                                this.message.error(res.errMsg);
                            }
                        }
                    );
                },
                nzCancelText: '取消',
                nzOnCancel: () => console.log('Cancel')
            }
        );
    }

    //设置监测点
    setCheckList(event) {
        console.log(event);
        this.checkJson.push(JSON.parse(event));
    }

    //删除监测点
    deleteCheck(index) {
        this.checkJson.splice(index, 1);
    }

    //load
    loadCanvas() {
        // 节点树中每个节点的拖放动作定义给拓扑图编辑器
        let nodes = $('[topo-div-type=\'topo-node\']');
        let nodeLength = nodes.length;
        for (let i = 0; i < nodeLength; i++) {
            let text = $(nodes[i]).find('span').eq(0).text();
            editor.drag(nodes[i], document.getElementById('topology-canvas'), text);
        }
        editor.loadTopology('', 'img/backimg.png');
    }

    //添加图片-----start
    showAddImg() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.isVisible = true;
    }

    beforeUpload = (file: UploadFile): boolean => {
        const isLt2M = file.size / 1024 < 300;
        if (!isLt2M) {
            this.message.error('图标必须小于300kb!');
        } else {
            this.fileList.push(file);
        }
        return false;
    };

    handleCancel() {
        this.isVisible = false;
        this.fileList = [];
    }

    handleOk() {
        if (this.fileList.length == 0) {
            this.message.warning('请选择图片');
            return false;
        }
        const formData = new FormData();
        this.fileList.forEach((file: any) => {
            formData.append('file', file);
        });
        this.topologySer.addPic(formData).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisible = false;
                    editor.utils.addNode(res.data, 'text');
                    this.fileList = [];
                } else {
                    this.message.error('添加失败');
                }
            }
        );
    }

//    end

}
