import {Injectable, OnInit} from "@angular/core";
import {NzModalService} from 'ng-zorro-antd';
import {SERVER_API_URL, SERVER_API_URL_COMS} from '../../app.constants';
@Injectable()
export class CommonService implements OnInit {

    constructor(private modalSer:NzModalService) {
        // 定义发射事件
    }

    ngOnInit() {

    }

    exists(list, parentId,myId){
        for(let i=0; i<list.length; i++){
            if(list[i][myId] == parentId){
                return true;
            }
        }
        return false;
    }

    listToTree(myId,pId,list){

        const  nodes = [];
        for(let i=0; i<list.length; i++){
            list[i].checked = false;
            const row = list[i];
            if ( !this.exists(list, row[pId],myId) ){
                nodes.push(row);
            }
        }

        const toDo = [];
        for(let i=0; i<nodes.length; i++){
            toDo.push(nodes[i]);
        }
        while(toDo.length){
            const node = toDo.shift(); // the parent node
            for(let i=0; i<list.length; i++){
                const row = list[i];
                if (row[pId] == node[myId]){
                    if (node.children){
                        node.children.push(row);
                    } else {
                        node.children = [row];
                    }
                    toDo.push(row);
                }
            }
        }
        return nodes;
    }

    toQuery(data){
        let str = '';
        for (let key in data) {
            if (data.hasOwnProperty(key)) {
                const value = data[key];
                str += key + '=' + value + '&';
            }
        }
        str = str.substring(0, str.length - 1);
        return str;
    }

    /**
     * 删除确认函数
     * @param title  提示语
     * @param callback  回调函数
     */
    confirmThing(title,content,callback){
        this.modalSer.confirm({
            nzTitle: title,
            nzContent: '<b style="color: red;">'+content+'</b>',
            nzOkText: '确定',
            nzOkType: 'danger',
            nzOnOk: callback,
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel'),
        })
    }

    /**
     * 下载文件
     * @param url 文件URL
     */
    downloadFile(title,data: Response) {
        const blob = new Blob([data], {type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"});
        const url= window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.setAttribute("href", url);
        link.setAttribute("download", title);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}
