import {
    upLoadImg
} from '@/api/user.js';
import {
    upLoadArrayImage
} from '@/api/hotel.js';

// base64转file，dataurl为base64地址，filename为文件名称，自定义即可
export const dataURLtoFile = (dataurl, filename) => {
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {
        type: mime
    });
}
/**路径转为文件 */
export const getImageFileFromUrl=(url, imageName)=>{
    return new Promise((resolve, reject) => {
      let blob = null;
      let imgFile = null;
      let xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.setRequestHeader("Accept", "image/png");
      xhr.responseType = "blob";
      xhr.onload = () => {
        blob = xhr.response;
        imgFile = new File([blob], imageName, { type: "image/png" });
        resolve(imgFile);
      };
      xhr.onerror = e => {
        reject(e);
      };
      xhr.send();
    });
}


//获取当前时间  传1返回YYYY-MM-DD HH-MM-SS   传2返回YYYY-MM-DD
export const getCurrentDate = (val) => {
    const nowDate = new Date();
    const {
        year,
        month,
        day,
        hour,
        minute,
        second
    } = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth(),
        day: nowDate.getDay(),
        hour: nowDate.getHours(),
        minute: nowDate.getMinutes(),
        second: nowDate.getSeconds()
    }
    const YYYYMMDD = year + '-' + month + '-' + day;
    const HHMMSS = hour + ':' + minute + ':' + second;
    if (val == 1) {
        return YYYYMMDD + ' ' + HHMMSS;
    } else if (val == 2) {
        return YYYYMMDD
    }
}
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
export const ChangeDateType = (TM, TMformat) => {
    let result = TM;
    try {
        result = TM.format(TMformat);
    } catch (e) {
        //TODO handle the exception
    };
    return result;
}

/**现场图片提交 */
export const file_img_src = (base64_img, hotelId, type) => {
    const timestamp = Date.parse(new Date());
    let file = dataURLtoFile(base64_img, timestamp + ".png");
    let fd = new FormData();
    fd.append("file", file);
    fd.append("hotelId", hotelId);
    fd.append("bucket", type);
    return new Promise((resolve) => {
        upLoadImg(fd).then((res) => {
            if (res.code == 9000) {
                resolve(res.data);
            } else {
                resolve("");
            }
        });
    });
};

//遍历树状结构
export const treeForeach = (tree, func) => {
    let node, list = [...tree]
    while (node = list.shift()) {
      func(node)
      node.children && list.push(...node.children)
    }
  }