import {Component, OnInit, Output, ViewChild} from '@angular/core';
import {BusinessComponent} from '../modal/business/business.component';
import {BusinessService} from '../business.service';
import {TreeNodeInterface} from '../../overAll/basic/basic.component';
import {NzMessageService} from 'ng-zorro-antd';
import {color, pageSize} from '../../app.constants';
import {CommonService} from '../../shared/common/common.service';
import {WebModalComponent} from '../../modal/web-modal/web-modal.component';
import {AlarmModalComponent} from '../../modal/alarm-modal/alarm-modal.component';

@Component({
    selector: 'smart-b-config',
    templateUrl: './b-config.component.html',
    styles: []
})
export class BConfigComponent implements OnInit {
    @ViewChild('smartBusiness') smartBusiness: BusinessComponent;
    @ViewChild('smartWebModal') smartWebModal: WebModalComponent;
    @ViewChild('smartAlarmModal') smartAlarmModal: AlarmModalComponent;

    sid;  //节点id
    color = color;
    allChecked = false;
    contractId;
    searchName;

    isLoading = false;   //加载中

    //分页
    pageNum = 1;
    pageCount = pageSize;
    totalNum;

    searchStatus = false;
    searchList;

    constructor(private busineSer: BusinessService, private message: NzMessageService,
                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.serviceid === d.serviceid);
                    target.expand = false;
                    this.collapse(array, target, false);
                });
            } else {
                return;
            }
        }
    }

    convertTreeToList(root: any, index: string, serviceid: string): TreeNodeInterface[] {
        const stack = [];
        const array = [];
        const hashMap = {};
        if (root.index == 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.children) {
                for (let i = node.children.length - 1; i >= 0; i--) {
                    stack.push({...node.children[i], level: node.level + 1, expand: true, parent: node});
                }
            }
        }
        return array;
    }

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

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

    ngOnInit() {
        this.getList();
    }

    //查询业务树
    getList() {
        this.isLoading = true;
        const data = {
            'sid': this.sid,
        };
        this.busineSer.findChild(data).subscribe(
            (res) => {
                this.isLoading = false;
                if (res.errCode == 10000) {
                    this.dataSet = res.data;
                    this.dataSet.forEach((e, index) => {
                        e.index = index;
                        e.checked = false;
                        e.children = [];
                        e.info = '';
                    });
                    this.toTree(null, null);
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    /**
     * 获取下级
     * @param item  当前节点
     * @param data  当前节点的根节点
     */
    getChildren(item, data) {
        if (item.children.length > 0) {
            if (item.expand) {
                item.expand = false;
            } else {
                item.expand = true;
            }
            return false;
        }
        this.isLoading = true;
        const obj = {
            'sid': item.serviceid,
        };
        this.busineSer.findChild(obj).subscribe(
            (res) => {
                if (res.data) {
                    res.data.forEach(e => {
                        e.children = [];
                        e.info = '';
                    });
                    this.dataSet.forEach(e => {
                        if (e.serviceid == item.serviceid) {
                            e.children = res.data;
                        }
                    });
                    this.setDateSet(this.dataSet, item, res.data);
                    this.toTree(data.index, item.serviceid);
                } else {
                    this.message.info('该分组下无资源');
                }
                this.isLoading = false;
            }
        );
    }

    setDateSet(array, data, insertArr) {
        if (array.length > 0) {
            const target = array.find(a => a.serviceid === data.serviceid);
            if (target) {
                target.children = insertArr;
            } else {
                array.forEach(o => {
                    this.setDateSet(o.children, data, insertArr);
                });
            }
        } else {
            return;
        }
    }

    //删除单个资源
    showDeleteConfirm(item) {
        this.commonSer.confirmThing('删除', '确定删除该服务', () => {
            const data = {
                serviceids: []
            };
            data.serviceids.push(item.serviceid);
            this.busineSer.deleteService(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.message.success('删除成功');
                        this.getList();
                    } else {
                        this.message.error(res.errMsg);
                    }
                }
            );
        });
    }

    //网站检测列表
    showWebModal(item) {
        this.contractId = item.serviceid;
        if (item.trigger) {
            this.message.info('已绑定阈值');
            return false;
        }
        this.smartWebModal.showModal();
    }

    //关联网站
    contract(e) {
        this.busineSer.relatedHttptest(this.contractId, e.httptestid).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('关联网站成功');
                    this.getList();
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    //告警时间
    getTime(item) {
        this.busineSer.selectAlarmsClock(item.serviceid).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    if (res.data.now) {
                        item.now = res.data.now.time;
                    }
                    if (res.data.last) {
                        item.last = res.data.last.time;
                    }
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    //添加业务
    showAddModal(item) {
        this.smartBusiness.showModal('添加业务', item);
    }

    //编辑业务
    showEditModal(item) {
        this.smartBusiness.showEditModal('编辑业务', item);
    }

    //添加告警推送
    showAlarmModal(item) {
        this.smartAlarmModal.showAddModal('添加告警推送',item.serviceid);
    }

    //编辑告警推送
    showEditAlarmModal(item){
        this.smartAlarmModal.showEditModal("编辑告警推送",item.serviceAction.actionId)
    }

    //查询
    reset() {
        this.searchStatus = true;
        this.pageNum = 1;
        this.search();
    }

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

    //翻页
    change(e){
        this.pageNum = e;
        this.search();
    }

    search(){
        this.isLoading = true;
        const data = {
            pageNum:this.pageNum,
            pageCount:this.pageCount,
            search:this.searchName
        }
        this.busineSer.findPage(data).subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.searchList = res.data.data;
                    this.totalNum = res.data.totalNum;
                }
                this.isLoading = false;
            }
        )
    }
}
