import {logs, promisify} from "./util";
import Config from "./config";

export const downloadFile = (url) => {
  let data = {tempFilePath: Config.get('imgUrl') + url}
  // #ifndef MP
  return data
  // #endif
  // #ifdef MP
  return promisify(uni.downloadFile, {
    url: Config.get('imgUrl') + url, //请求地址
  }).then(res => {
    if (res.statusCode == 200) {
      logs(`✔ 下载文件成功！`)
      return res
    } else {
      logs(`✘ 下载文件失败！ statusCode 非200`)
      return data
    }
  }, err => {
    logs(`✘ 下载文件失败！${err}`)
    return data
  })
  // #endif
}


export const getFileSystemManager = (url) => {
  return new Promise((resolve, reject) => {
    uni.getFileSystemManager().readFile({
      filePath: url,
      success(res) {
        return resolve(res)
      },
      fail(err) {
        return reject(err.errMsg)
      }
    })
  })
}
export const chooseFile = (data) => {
  let op = {}
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    op = {
      size: 1, //选择总数量
      isDown: true,//是否下钻（true 筛选当前目录以下的所有文件，fales 只筛选当前目录文件）
      types: [{
        name: '升级包',
        value: ["bin"]
      },]
    }
    if (data.count) op.size = data.count
    const AfDocument = uni.requireNativePlugin('Aq-ChooseFile')
    AfDocument.openMode(op, ({code, res}) => {
      if (code == 'success') {
        let data = []
        res.forEach((item, index) => {
          data.push({
            path: item.path,
            size: item.sizeHolp,
            name: item.name,
            type: item.type,
          })
        })
        resolve({
          tempFiles: data,
        })
      } else {
        reject(`选择文件出错`)
      }
    })
    // #endif
    // #ifdef MP-WEIXIN ||MP-QQ
    op = Object.assign({}, data)
    return promisify(uni.chooseMessageFile, op).then(res => {
      resolve(res)
    }, err => {
      reject(`选择文件出错 error:${err}`)
    })
    // #endif
  })


}

export const readerBin = (file) => {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    let environment = plus.android.importClass("android.os.Environment");
    // const sdRoot = environment.getExternalStorageDirectory(); //文件夹根目录
    const File = plus.android.importClass("java.io.File");
    const BufferedReader = plus.android.importClass("java.io.BufferedReader");
    const FileReader = plus.android.importClass("java.io.FileReader");
    // let readFr = new File(sdRoot + file.path);
    let readFr = new File(file.path);
    console.log('readFr', readFr)
    let reader = new BufferedReader(new FileReader(readFr))
    console.log('reader', reader)
    resolve(reader)
    // #endif
    // #ifdef MP
    const fs = uni.getFileSystemManager()
    fs.readFile({
      filePath: file.path,
      success(res) {
        // console.log('reader', reader.data)
        resolve(res.data)
      }
    })
    // #endif
  })
}
