import {Injectable} from "@angular/core";
import {AlertController, ToastController} from "@ionic/angular";
import {File} from "@ionic-native/file/ngx";
import {FileOpener} from "@ionic-native/file-opener/ngx";
import {environment} from "../environments/environment";

@Injectable()

export class CommonService{
    constructor(public toastCtrl:ToastController,public alertCtrl:AlertController,
                private file: File, private fileOpener: FileOpener){}



    /**
     * 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;
    }

    /**
     * JSON格式对象转为form表单的格式，用来接口传递数据
     * @param json   需要转化的json
     * @returns {FormData}   formData数据
     */
    toFormData(json){
        let formData = new FormData();
        for(let k in json){
            formData.append(k,json[k])
        }
        return formData;
    }

    /**
     * 提示信息 位置：居中，延时2s
     * @param message  提示文字
     * @param callback  提示信息之后执行的方法
     */
    async toast(message, callback?) {
        let toast = await this.toastCtrl.create({
            message: message,
            showCloseButton:false,
            duration: 2000,
            position:'middle',
        });
        await toast.present();
        if (callback) {
            callback();
        }
    }

    /**
     * alert弹窗
     * @param message  弹窗内的文字
     * @param callback  如果有回调方法 就有确定、取消两个按钮，没有回调方法 则只有确认一个按钮
     */
    async alert(message, callback?) {
        if (callback) {
            let alert = await this.alertCtrl.create({
                header: '提示',
                message: message,
                buttons: ['取消', {
                    text: "确定",
                    handler: data => {
                        callback();
                    }
                }]
            });
           await alert.present();
        } else {
            let alert = await this.alertCtrl.create({
                header: '提示',
                message: message,
                buttons: ["确定"]
            });
            await alert.present();
        }
    }

    /**
     * 下载文件
     * @param url 文件URL
     */
    downloadFile(fileID,fileName) {
        const xhr = new XMLHttpRequest();
        const fileType = this.getFileMimeType(fileName);
        const url = encodeURI(environment.domain + '/wisdomgroup/modules/common/file/download/' + fileID);
        xhr.open('GET',url);
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.responseType = "blob";
        xhr.addEventListener("loadstart",(ev)=>{
        })
        xhr.addEventListener("progress",(ev)=>{
            let progress = Math.round(100.0 * ev.loaded / ev.total);
            // alert(progress);
        })
        xhr.addEventListener("load",(ev)=>{
            const blob = xhr.response;
            if(blob){
                let path = this.file.externalDataDirectory;
                this.file.writeFile(path,fileName,blob,{   //写入文件
                    replace:true
                }).then(
                    ()=>{
                        this.fileOpener.open(path + fileName, fileType).catch((err) => {
                            this.alert('打开文件失败！'+err);
                        })
                    }).catch((err)=>{
                        this.toast("下载文件失败！")
                })
            }
        });

        xhr.addEventListener("loadend", (ev) => {
            // 结束下载事件
        });
        xhr.addEventListener("error", (ev) => {
            this.alert('下载文件失败！');
        });
        xhr.addEventListener("abort", (ev) => {
        });
        xhr.send();
    }

    //获取文件类型
    getFileMimeType(fileName: string): string {
        let fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
        let mimeType: string = '';

        switch (fileType) {
            case 'txt':
                mimeType = 'text/plain';
                break;
            case 'docx':
                mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                break;
            case 'doc':
                mimeType = 'application/msword';
                break;
            case 'pptx':
                mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
                break;
            case 'ppt':
                mimeType = 'application/vnd.ms-powerpoint';
                break;
            case 'xlsx':
                mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                break;
            case 'xls':
                mimeType = 'application/vnd.ms-excel';
                break;
            case 'zip':
                mimeType = 'application/x-zip-compressed';
                break;
            case 'rar':
                mimeType = 'application/octet-stream';
                break;
            case 'pdf':
                mimeType = 'application/pdf';
                break;
            case 'jpg':
                mimeType = 'image/jpeg';
                break;
            case 'png':
                mimeType = 'image/png';
                break;
            default:
                mimeType = 'application/' + fileType;
                break;
        }
        return mimeType;
    }

    /**
     * 定义全局的log日志  开发模式 打印log  生产环境 关闭
     * @param message   日志信息
     */
    log(message){
        if(environment.domain === ""){    //开发环境时
            console.log(message);
        }
    }

}