/*jshint esversion: 6 */
import {
    Loading,
    Message
} from 'element-ui';
import {
    saveAs
} from 'file-saver';
import { ACCESS_TOKEN, ACCESS_USER, HTTP_STATUS } from "../constant/user";

/**
 * 添加请求头
 * @param {} headers 
 * @returns 
 */
function addHeaders(headers) {
    let headers_target = {
        'Content-Type': 'application/json', // 指定提交方式为表单提交
        'x-requested-with': 'XMLHttpRequest'
    };
    headers_target = Object.assign(headers_target, headers);
    let token = sessionStorage.getItem("token");
    if (token) {
        headers_target[ACCESS_TOKEN] = token;
    }
    let user = sessionStorage.getItem("user");
    if (user) {
        headers_target[ACCESS_USER] = JSON.parse(user).account;
    }
    return headers_target;
}

let get = (url, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "GET",
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.code == 9000) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));

    })
};
let post = (url, data, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "POST",
            body: typeof data == "object" ? JSON.stringify(data) : data,
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.code == 9000) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
};

let delete_util = (url, data, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "DELETE",
            body: typeof data == "object" ? JSON.stringify(data) : data,
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.code == 9000) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
};

let fileUpload = (url, formData, headers = {}) => {
    let headers_target = { 'x-requested-with': 'XMLHttpRequest' };
    headers_target = Object.assign(headers_target, headers);
    let token = sessionStorage.getItem("token");
    if (token) {
        headers_target[ACCESS_TOKEN] = token;
    }
    let user = sessionStorage.getItem("user");
    if (user) {
        headers_target[ACCESS_USER] = JSON.parse(user).account;
    }
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "POST",
            body: formData,
            headers: new Headers(headers_target)
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.code == 9000) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
};

//下载文件 type传文件类型 例如：doc,xls...
let fileDownload = (url, filename, type, headers = {}) => {
    fetch(url, {
        method: "GET",
        // body: JSON.stringify(data),
        headers: new Headers(addHeaders(headers))
    }).then(res => res.blob().then(blob => {
        filename = `${filename}.${type}`
        let a = document.createElement('a');
        let url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    }));
}

//下载文件 type传文件类型 例如：doc,xls...
let fileDownload1 = (url, param, filename, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "POST",
            body: typeof param == "object" ? JSON.stringify(param) : param,
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            let tmp = res.headers.get('content-disposition');
            if (filename == null && tmp != null) {
                // 解码
                filename = decodeURIComponent(tmp.split('filename=')[1]);
            }
            return res.blob();
        }).then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            resolve();
        }).catch(err => {
            console.log(err);
        });
    });

}

//此方法是 用于标识文字段落中一些特殊的信息  用不同的颜色来区分
let getReplaceColor = (color_dict, content) => { //  color_dict: 需要颜色区分的文字以及颜色集合   content:被替换的主体
    for (let i = 0; i < color_dict.length; i++) {
        let color_tmp = color_dict[i][1];
        let replaceString =
            '<span style="color: ' + color_tmp + ';">' + color_dict[i][0] + "</span>";
        content = content.replace(color_dict[i][0], replaceString);
    }
    return content;
}

// 此方法是把平行数据整理成树状结构
let getTreeData = (data, id, parentId, children, firstId) => { // 调用时，字段名以字符串的形式传参，如treeData(data, 'id', 'parentId', 'children',0) firstId代表第一层的parentId
    data.forEach(item => {
        item['label'] = item.name;
    });
    let cloneData = JSON.parse(JSON.stringify(data))
    return cloneData.filter(father => {
        let branchArr = cloneData.filter(child => father[id] == child[parentId]);
        branchArr.length > 0 ? father[children] = branchArr : ''
        return father[parentId] == firstId // 如果第一层不是parentId=0，请自行修改
    })
}
//此方法是 用于获取给定字符在字符串中出现的最后一个位置的下标
let lastIndexOf = (str, c) => {
    let x = str.indexOf(c);
    if (x == -1) {
        return x;
    }
    for (let i = 0; i < str.length - x; i++) {
        let index = str.indexOf(c, x + 1);
        if (index == -1) {
            break;
        }
        x = index;
    }
    return x;
}

//加载动画
let loading;
const startLoading = () => {
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    //增加关闭按钮
    const delBtn = document.createElement("button");
    delBtn.innerHTML = "关闭";
    document.querySelector('.el-loading-spinner').appendChild(delBtn);
    delBtn.onclick = endLoading;
}
const endLoading = () => {
    loading.close();
}





// 下载方法
let download = (url, filename) => {
    getBlob(url).then((blob) => {
        saveAsFiles(blob, filename);
    });
}
/**
 * 获取 blob
 * @param  {String} url 目标文件地址
 * @return {Promise}
 */
let getBlob = (url) => {
    return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();

        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
            if (xhr.status === 200) {
                resolve(xhr.response);
            }
        };

        xhr.send();
    });
}
/**
 * 保存
 * @param  {Blob} blob
 * @param  {String} filename 想要保存的文件名称
 */
let saveAsFiles = (blob, filename) => {
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
    } else {
        const link = document.createElement("a");
        const body = document.querySelector("body");

        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);

        link.click();
        body.removeChild(link);

        window.URL.revokeObjectURL(link.href);
    }
}

//获取前几日的日期
let getTime_extent = (n) => {
    let now = new Date();
    let preDate = now.getTime() - (n * 24 * 60 * 60 * 1000);
    let preDay = new Date(preDate);
    let pre_year = preDay.getFullYear();
    let pre_month = preDay.getMonth() + 1;
    let pre_date = preDay.getDate();
    let pre_newMonth = (pre_month < 10) ? "0" + pre_month : pre_month;
    let pre_newDate = (pre_date < 10) ? "0" + pre_date : pre_date;
    let pre_rq = pre_year + '-' + pre_newMonth + '-' + pre_newDate;
    let pre_rq_start = pre_year + '-' + pre_newMonth + '-' + pre_newDate + ' ' + '00:00:00';
    let pre_rq_end = pre_year + '-' + pre_newMonth + '-' + pre_newDate + ' ' + '23:59:59';
    return {
        pre_rq,
        pre_rq_start,
        pre_rq_end
    }
}

//转换图片格式
let base64DataURLToArrayBuffer = (dataURL) => {
    const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
    if (!base64Regex.test(dataURL)) {
        return false;
    }
    const stringBase64 = dataURL.replace(base64Regex, "");
    let binaryString;
    if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
    } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
    }
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes.buffer;
}
let imageToBase64 = (file, that) => {
    var reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
        that.img_Base64 = reader.result;
    }
    reader.onerror = function (error) {
        console.log('Error: ', error)
    }
}

//文件上传限制格式
let format_file = () => {
    return ".TXT,.DOC,.XLS,.PPT,.DOCX,.XLSX,.PPTX,.pdf,.JPG,.PNG,.TIFF,.SWF,.rar,.zip,.EXE,.FLV,.RMVB,.rm,.MP4,.MVB,.avi,.WMA,.MP3"
}
//视频播放格式
let arr_video_format = () => {
    return ["FLV", "RMVB", "MP4", "MVB", "avi", "rm"]
}
//音频播放格式
let arr_sound_format = () => {
    return ["WMA", "MP3"]
}
//人物机构字段确认状态后缀名
let rw_jg_IsConfirm = () => {
    return '_DOUBT'
}

let dataURItoBlob = (dataURI) => {
    let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
    let byteString = atob(dataURI.split(',')[1]); //base64 解码
    let arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    let intArray = new Uint8Array(arrayBuffer); //创建视图

    for (let i = 0; i < byteString.length; i++) {
        intArray[i] = byteString.charCodeAt(i);
    }
    return new Blob([intArray], {
        type: mimeString
    });
}
//64位转换为file,并下载
let dataUrlToblob = (data, isDownload) => {
    let out = dataURItoBlob(data.path);
    if (isDownload == 1) {
        saveAs(out, data.name + '.docx')
    } else if (isDownload == 0) {
        return out;
    }

}

let isDuringDate = (beginDateStr, endDateStr) => {
    let curDate = new Date(),
        beginDate = new Date(beginDateStr),
        endDate = new Date(endDateStr);
    console.log(12131221);
    if (curDate < beginDate) {
        //时间还没到
        return '1';
    }
    if (endDate < curDate) {
        //时间已过
        return '2';
    }
    if (curDate >= beginDate && curDate <= endDate) {
        //可以考试
        return '3';
    }
}

let dateChangeFormat = (format, date) => {
    date = new Date(date);
    const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString(),
    };
    Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
            format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
    });
    return format;
}
let getCookie = (name) => {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return (arr[2]);
    else
        return null;
}
let setCookie = (c_name, value, b) => {
    let s = new Date();
    s.setDate(s.getDate() + b);
    document.cookie = c_name + "=" + escape(value) + ((b == null) ? "" : ";expires=" + s.toGMTString());
}
let delCookie = (name) => {
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let s = getCookie(name);
    if (s != null)
        document.cookie = name + "=" + s + ";expires=" + exp.toGMTString();
}

/**
 * 添加param
 * @param {*} param 
 * @returns 
 */
const addParam = (param) => {
    let url = "";
    let keys = Object.getOwnPropertyNames(param);
    keys.forEach(function (key, index) {
        if (param[key] != undefined) {
            if (index == 0) {
                url += "?";
            }
            url += key + "=" + param[key];
            if (index != keys.length - 1) {
                url += "&";
            }
        }
    });
    return url;
}

let get_exame = (url, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "GET",
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.state.code == 90001) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));

    })
};

let post_exame = (url, data, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "POST",
            body: typeof data == "object" ? JSON.stringify(data) : data,
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.state.code == 90001) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
};

let delete_util_exame = (url, data, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "DELETE",
            body: typeof data == "object" ? JSON.stringify(data) : data,
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.state.code == 90001) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
};

let fileUpload_PUT = (url, formData, headers = {}) => {
    let headers_target = { 'x-requested-with': 'XMLHttpRequest' };
    headers_target = Object.assign(headers_target, headers);
    let token = sessionStorage.getItem("token");
    if (token) {
        headers_target[ACCESS_TOKEN] = token;
    }
    let user = sessionStorage.getItem("user");
    if (user) {
        headers_target[ACCESS_USER] = JSON.parse(user).account;
    }
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "PUT",
            body: formData,
            headers: new Headers(headers_target)
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.code == 9000) {
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
};

let post_technique = (url, data, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "POST",
            body: typeof data == "object" ? JSON.stringify(data) : data,
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.status == 'success') {
                // resolve(JSON.parse(result.data));
                resolve(result.data);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
}

let post_technique_entity = (url, data, headers = {}) => {
    return new Promise((resolve, reject) => {
        fetch(url, {
            method: "POST",
            body: typeof data == "object" ? JSON.stringify(data) : data,
            headers: new Headers(addHeaders(headers))
        }).then(res => {
            if (res.status == 200) {
                return res.text();
            } else {
                console.log(res.statusText);
                reject(HTTP_STATUS);
            }
        }).then(res => {
            let result = JSON.parse(res);
            if (result.success == 'true') {
                // resolve(JSON.parse(result.data));
                resolve(result.result);
            } else {
                console.log(result);
                reject(result);
            }
        }).catch(err => reject(err));
    })
};


export {
    get,
    post,
    delete_util,
    fileUpload,
    fileDownload,
    getReplaceColor,
    getTreeData,
    lastIndexOf,
    startLoading,
    endLoading,
    getTime_extent,
    download,
    format_file,
    arr_video_format,
    arr_sound_format,
    dataUrlToblob,
    isDuringDate,
    dateChangeFormat,
    getCookie,
    setCookie,
    delCookie,
    fileDownload1,
    imageToBase64,
    rw_jg_IsConfirm,
    addParam,
    get_exame,
    post_exame,
    delete_util_exame,
    fileUpload_PUT,
    post_technique,
    post_technique_entity
}