import {Injectable, OnInit} from '@angular/core';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {SERVER_API_URL, SERVER_API_URL_COMS} from '../../app.constants';
import {DatePipe} from '@angular/common';
import {WorkService} from '../../work/work.service';

declare var ActiveXObject: ActiveXObject;

interface ActiveXObject {
    new(type: string): ActiveXObject;

    SendKeys(key: string): void;
}

@Injectable()
export class CommonService implements OnInit {

    constructor(private modalSer: NzModalService, private datePipe: DatePipe,
                private message: NzMessageService, private workSer: WorkService) {
        // 定义发射事件
    }

    ngOnInit() {

    }

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

    /**
     * list一层数组转为树形结构的数组
     * @param myId   父级字段名
     * @param pId   子级字段名
     * @param list
     * @returns {any[]}
     */
    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;
    }

    /**
     * JSON格式数据转化为字符串 接口调用
     * @param data  json格式的数据
     * @returns {string}
     */
    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 ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
        console.log('ie:' + ie);
        console.log('ieVer:' + ieVer);
        if (ie && ieVer < 10) {
            this.message.error('No blobs on IE<10');
            return;
        }
        if (ieVer > -1) {
            window.navigator.msSaveBlob(blob);
        } else {
            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);
        }
    }

    /**
     * 部分区域全屏
     * @param element  全屏区域
     * @param method  全屏方法
     * @returns {any}
     */
    showInFullScreen(element, method) {
        let usablePrefixMethod;
        const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
        if (ieVer > -1) {
            if (typeof (<any>window).ActiveXObject !== 'undefined') {
                //这的方法 模拟f11键，使浏览器全屏
                const wscript = new ActiveXObject('WScript.Shell');
                if (wscript != null) {
                    wscript.SendKeys('{F11}');
                }
            }
        }
        ['webkit', 'moz', 'ms', 'o', ''].forEach((prefix) => {
                if (usablePrefixMethod) {
                    return;
                }
                if (prefix === '') {
                    // 无前缀，方法首字母小写
                    // method = method.slice(0, 1).toLowerCase() + method.slice(1)
                }
                let typePrefixMethod = typeof element[prefix + method];
                if (typePrefixMethod + '' !== 'undefined') {
                    if (typePrefixMethod === 'function') {
                        usablePrefixMethod = element[prefix + method]();
                    } else {
                        usablePrefixMethod = element[prefix + method];
                    }
                }
            }
        );
        return usablePrefixMethod;
    }

    /**
     * 根据type 查询时间段
     * @param timeType  0：最近一小时  1：今天  2：昨天(最近一天)  3：最近三天  4：最近一周  5：最近一个月  6：最近一年
     */
    getTimeByType(timeType) {
        const nowDate = new Date().getTime();
        let day1, day2; //当作变量使用
        let obj = {startTime: null, endTime: null};
        switch (timeType) {
            case'0': {   //最近一小时
                day1 = nowDate - 1 * 60 * 60 * 1000;
                obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd HH:mm:ss');
                obj.endTime = this.datePipe.transform(nowDate, 'yyyy-MM-dd HH:mm:ss');
                break;
            }
            case'1': {   //今天
                obj.startTime = this.datePipe.transform(nowDate, 'yyyy-MM-dd') + ' 00:00:00';
                obj.endTime = this.datePipe.transform(nowDate, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'2': {   //昨天
                day1 = nowDate - 1 * 24 * 60 * 60 * 1000;
                obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                obj.endTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'3': {   //最近三天
                day1 = nowDate - 3 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                obj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'4': {  //最近一周
                day1 = nowDate - 7 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                obj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'5': {  //最近一个月
                day1 = nowDate - 30 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                obj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'6': {  //最近一年
                day1 = nowDate - 365 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                obj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'7': {
                break;
            }
        }
        return obj;
    }

    //内存单位换算
    unitConversion(unit) {
        let res;
        let Gbps = 1000 * 1000 * 1000;
        let Mbps = 1000 * 1000;
        let kbps = 1000;
        let size = Math.abs(unit);
        if (size / Gbps > 1) {
            res += (size / Gbps).toFixed(2) + 'Gbps';
        } else if (size / Mbps > 1) {
            res += (size / Mbps).toFixed(2) + 'Mbps';
        } else if (size / kbps > 1) {
            res += (size / kbps).toFixed(2) + 'kbps';
        } else {
            res += (size) + 'bps';
        }
        return res;
    }

    /**
     * 文件预览
     */
    previewFile(fileUrl) {
        this.workSer.getPreview().subscribe(
            (res) => {
                console.log(res.fileUrl + '?url=' + res.url + fileUrl);
                const previewUrl = res.fileUrl + '?url=' + encodeURIComponent(res.url + fileUrl);
                window.open(previewUrl);
            }
        );
    }
}
