import {getPageList} from "@/api/ordinary_user";
import {doGetFaceServerLog} from "@/api/old_api_pengwenbing";
import {
  doGetWaringServerLog,
} from "@/api/user_manage";

//批量导出图片-下载图片blob数据
function 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();
  });
}

//批量导出图片-将blob文件转成文件
function saveAs(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);
  }
}


//批量导出图片-处理入口
function steakPhoto(url, filename) {
  getBlob(url).then(blob => {
    saveAs(blob, filename);
  });
}

/*******************************************************************************************************************************/

//批量导出图片-白名单-操作入口
export function downloadPhotosWhiteList(page,number) {
  let data = JSON.parse(JSON.stringify(page))
  data.pageSize = number
  data.pageNum = 1
  getPageList(data).then(res => {
    let list = res.data.list;
    let index = 0;
    function doSteak() {
      setTimeout(() => {
        if(index < list.length) {
          steakPhoto(list[index].avatar, `${list[index].name}-${list[index].idNumber}`);
          ++index;
          doSteak()
        }
      },500)
    }
    doSteak()
  })
}

//批量导出图片-进出记录-操作入口
export function downloadPhotosPassRecords(page,number) {
  let data = JSON.parse(JSON.stringify(page))
  data.pageSize = number
  data.pageNum = 1
  doGetFaceServerLog(data).then(res => {
    let list = res.data.list;
    let index = 0;
    function doSteak() {
      setTimeout(() => {
        if(index < list.length) {
          steakPhoto(list[index].photo, `${list[index].name}-${list[index].cardid}-${list[index].phone}-${list[index].faceTime}`);
          ++index;
          doSteak()
        }
      },500)
    }
    doSteak()
  })
}
//批量导出图片-进出异常预警-操作入口
export function downloadPhotosWarningPassRecords(page,number) {
  let data = JSON.parse(JSON.stringify(page))
  data.pageSize = number
  data.pageNum = 1
  doGetWaringServerLog(data).then(res => {
    let list = res.data.list;
    let index = 0;
    function doSteak() {
      setTimeout(() => {
        if(index < list.length) {
          steakPhoto(list[index].photo, `${list[index].name}-${list[index].cardid}-${list[index].phone}-${list[index].faceTime}`);
          ++index;
          doSteak()
        }
      },500)
    }
    doSteak()
  })
}



