// 读取文件目录
// plus.io.PRIVATE_WWW: 应用私有资源目录常量
// plus.io.PRIVATE_DOC: 应用私有文档目录常量
// plus.io.PUBLIC_DOCUMENTS: 应用公共文档目录常量
// plus.io.PUBLIC_DOWNLOADS: 应用公共下载目录常量
const localPath = {
  PRIVATE_WWW: "_www/",
  PRIVATE_DOC: "_doc/",
  PUBLIC_DOCUMENTS: "_documents/",
  PUBLIC_DOWNLOADS: "_downloads/",
};

const VideoDirName = "Video";
const VideoPath = localPath.PRIVATE_DOC + VideoDirName;

function readAppDir(dirType = plus.io.PRIVATE_DOC) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    plus.io.requestFileSystem(
      dirType,
      (fs) => {
        resolve(fs.root.fullPath);
      },
      (e) => {
        console.log("Request file system failed: " + e.message);
        reject(e);
      }
    );
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
function createDir(dirName = VideoDirName, dirPath = localPath.PRIVATE_DOC) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    plus.io.resolveLocalFileSystemURL(
      dirPath,
      (entry) => {
        entry.getDirectory(
          dirName,
          { create: true, exclusive: false },
          (dir) => {
            console.log("CreateDir Success: " + dir.name);
            resolve(dir.fullPath);
          },
          (e) => {
            //失败操作
            console.log("CreateDir Failed: " + e.message);
            reject(e);
          }
        );
      },
      (e) => {
        //失败操作
        console.log("CreateDir Failed: " + e.message);
        reject(e);
      }
    );
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
//已下载列表 为了区别某些已下载但未下载完成的文件
function saveSuccessFileName(taskFileName) {
  let value = uni.getStorageSync('Download-Success')
  let ishas = false
  let list = value ? JSON.parse(value) : []
  for (let i = 0; i < list.length; i ++) {
    let name = list[i]
    if (name == taskFileName) {
       ishas = true
       break
    }
  }
  if (!ishas) {
    list.push(taskFileName)
	console.log("[Save Download-Success] ", taskFileName)
    uni.setStorageSync('Download-Success', JSON.stringify(list))
  }
}
function clearSuccessFileName(fileName) {
	let taskFileName = fileName
	if (!taskFileName.startsWith(VideoPath + "/")) {
	  taskFileName = VideoPath + "/" + taskFileName;
	}
    let value = uni.getStorageSync('Download-Success')
	let ishas = false
    let list = value ? JSON.parse(value) : []
	console.log(list)
	for (let i = 0; i < list.length; i ++) {
	  let name = list[i]
	  if (name == taskFileName) {
	    ishas = true
		list.splice(i, 1)
		console.log("Delete clear taskFileName ", taskFileName)
		console.log("[Download-Success]", list)
	    break
	  }
	}
	if (ishas) {
	  uni.setStorageSync('Download-Success', JSON.stringify(list))
	}
}
function checkSuccessFile(taskFileName) {
  let value = uni.getStorageSync('Download-Success')
  let ishas = false
  let list = value ? JSON.parse(value) : []
  for (let i = 0; i < list.length; i ++) {
    let name = list[i]
    if (name == taskFileName) {
      ishas = true
      break
    }
  }
  console.log("ishas ", ishas)
  return ishas
}
//获取视频的缓存路径
function getLocalVideoUrl(fileName, path) {
	  // #ifdef APP-PLUS
	  let taskFileName = fileName
	  if (!taskFileName.startsWith(VideoPath + "/")) {
	    taskFileName = VideoPath + "/" + taskFileName;
	  }
	  if (checkSuccessFile(taskFileName)) {
		  return path + VideoDirName + "/" + fileName
	  } else {
		  return ""
	  }
	  // #endif
	  // #ifdef !APP-PLUS
	  return ""
	  // #endif
}
async function getSuccessVideoFiles() {
  let array = []
  let videoFiles = await getVideoFiles()
  console.log('videoFiles ', videoFiles)
  let value = uni.getStorageSync('Download-Success')
  let list = value ? JSON.parse(value) : []
  for (let i = 0; i < videoFiles.length; i ++) {
    let file = videoFiles[i]
	file.is_checked=false
    for (let j = 0; j < list.length; j ++) {
      let taskFileName = list[j]
      if (file.localPath == taskFileName) {
        array.push(file)
      }
    }
  }
  array.sort(function (a, b) { return a.name.localeCompare(b.name, 'zh-CN') })
  return array
}
function sort(files) {
    return files
}
async function getVideoFiles() {
  return await dirFiles(VideoDirName);
}
function dirFiles(dirName, dirType = plus.io.PRIVATE_DOC) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    plus.io.requestFileSystem(dirType, (fs) => {
      let fullPath = fs.root.fullPath;
      plus.io.resolveLocalFileSystemURL(fullPath + dirName, (entry) => {
        //创建目录对象的读取对象
        let directoryReader = entry.createReader();
        //读取该目录所有文件和子目录，fs:文件或者目录对象数组
        directoryReader.readEntries(
          async (entries) => {
            let files = [];
			if (entries.length == 0) resolve(files);
            for (let i = 0; i < entries.length; i++) {
              let entry = entries[i]
              if (entry.isFile) {
                entry.file(
                  (file)=> {
                    files.push({
                      name: entry.name,
                      size: file.size,
                      time: file.lastModifiedDate,
                      fullPath: entry.fullPath,
                      localPath: entry.toURL(),
                    });
                    if (i == entries.length - 1) {
                      resolve(files);
                    }
                  },
                  (e) => {
                    if (i == entries.length - 1) {
                      resolve(files);
                    }
                  }
                )
              }
            }
          },
          (e) => {
            //失败操作
            console.log("Request dirFiles failed: " + e.message);
            reject(e);
          }
        );
      });
    });
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
// method: (String 类型 )网络请求类型 支持http协议的“GET”、“POST”，默认为“GET”请求。
// data: (String 类型 )POST请求时提交的数据 仅在网络请求类型method设置为"POST"时有效，"GET"请求时忽略此数据。
// filename: (String 类型 )下载文件保存的路径 保存文件路径仅支持以"_downloads/"、"_doc/"、"_documents/"开头的字符串。 文件路径以文件后缀名结尾（如"_doc/download/a.doc"）表明指定保存文件目录及名称，以“/”结尾则认为指定保存文件的目录（此时程序自动生成文件名）。 如果指定的文件已经存在，则自动在文件名后面加"(i)"，其中i为数字，如果文件名称后面已经是此格式，则数字i递增，如"download(1).doc"。 默认保存目录为（"_downloads"），并自动生成文件名称。
// priority: (Number 类型 )下载任务的优先级 数值类型，数值越大优先级越高，默认优先级值为0。
// timeout: (Number 类型 )下载任务超时时间 数值类型，单位为s(秒)，默认值为120s。 超时时间为服务器响应请求的时间（不是下载任务完成的总时间），如果设置为0则表示永远不超时。
// retry: (Number 类型 )下载任务重试次数 数值类型，默认为重试3次。
// retryInterval: (Number 类型 )下载任务重试间隔时间 数值类型，单位为s(秒)，默认值为30s。
function downloadVideo(url, filename = "", cb) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    if (!filename.startsWith(VideoPath + "/")) {
      filename = VideoPath + "/" + filename;
    }
    let opts =
      filename != ""
        ? { filename: filename, timeout: 3, retryInterval: 1 }
        : {};
    var dtask = plus.downloader.createDownload(url, opts, function (d, status) {
      if (status == 200) {
		console.log("下载成功：" + d.filename);
        resolve(d);
      } else {
        dtask.abort();
        reject(-1);
      }
    });
    dtask.addEventListener("statechanged", function (task, status) {
      if (!dtask) {
        return;
      }
      let progress = task.totalSize == 0 ? 0 : Math.round((task.downloadedSize / task.totalSize) * 100 * 100) / 100;
	  let progressInt = parseInt(progress)
	  console.log(progressInt)
      cb(task.state, progressInt);
      switch (task.state) {
        case 1: // 开始下载...
          break;
        case 2: // 已连接到服务器
          break;
        case 3: // 已接收到数据
          break;
        case 4: // 下载完成
          saveSuccessFileName(task.options.filename)
          break;
      }
    });
    dtask.start();
	cb(0, 0);
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
// DownloadState
// -1: (Number 类型 )枚举任务状态 非下载任务状态，泛指所有下载任务的状态，用于enumerate()和clear()操作时指定作用于所有下载任务。
function task_downloads() {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    var taskArray = new Array();
    plus.downloader.enumerate(function (tasks) {
      for (var i = tasks.length - 1; i >= 0; i--) {
        // var filename = tasks[i].filename;
        // var url = tasks[i].url;
        // var state = tasks[i].state;
        // var downloadedSize = tasks[i].downloadedSize;
        // var totalSize = tasks[i].totalSize;
        taskArray.push(tasks[i]);
      }
      resolve(taskArray);
    }, -1);
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
function getVideoInfo(filePath) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    plus.io.getVideoInfo({
      filePath: filePath,
      success: (videoInfo) => {
        //本地支持mp4 flv
        resolve({
          fullPath: filePath,
          videoInfo: videoInfo,
        });
      },
      fail: () => {},
      complete: () => {
        this.i++;
        //回调结束
        if (this.i == length) resolve();
      },
    });
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
function checkFile(fileName) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    let dirType = plus.io.PRIVATE_DOC;
    let filePath = VideoDirName + "/" + fileName;
    plus.io.requestFileSystem(dirType, (fs) => {
      let fullPath = fs.root.fullPath;
      plus.io.resolveLocalFileSystemURL(
        fullPath + "/" + filePath,
        (r) => {
          resolve(true);
        },
        (e) => {
          resolve(false);
        }
      );
    });
    // #endif
    // #ifdef !APP-PLUS
    resolve(false);
    // #endif
  });
}
function clearFinishTask(state = 4) {
	plus.downloader.clear(state);
}
function getFile(fileName, dirType = plus.io.PRIVATE_DOC) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    let filePath = VideoDirName + "/" + fileName;
    plus.io.requestFileSystem(dirType, (fs) => {
      let fullPath = fs.root.fullPath;
      plus.io.resolveLocalFileSystemURL(
        fullPath + "/" + filePath,
        (r) => {
          resolve(r);
        },
        (e) => {
          console.log("Get file failed: ", e.message);
          reject(e);
        }
      );
    });
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
function deleteFileWithPath(fullPath) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
	plus.io.resolveLocalFileSystemURL(fullPath, (entry) => {
	  entry.remove(
	    () => {
	      resolve(1);
	    },
	    (e) => {
	      console.log("Delete file failed: ", e);
	      reject(-1);
	    }
	  );
	});
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
function deleteFile(fileName, dirType = plus.io.PRIVATE_DOC) {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
	let filePath = VideoDirName + "/" + fileName;
    plus.io.requestFileSystem(dirType, (fs) => {
      let fullPath = fs.root.fullPath;
      plus.io.resolveLocalFileSystemURL(fullPath + "/" + filePath, (entry) => {
        entry.remove(
          () => {
            resolve(1);
          },
          (e) => {
            console.log("Delete file failed: ", e);
            reject(-1);
          }
        );
      });
    });
    // #endif
    // #ifdef !APP-PLUS
    resolve({});
    // #endif
  });
}
// }

export default {
  readAppDir,
  createDir,
  getVideoFiles,
  dirFiles,
  downloadVideo,
  task_downloads,
  clearFinishTask,
  getVideoInfo,
  getLocalVideoUrl,
  checkFile,
  checkSuccessFile,
  getFile,
  deleteFile,
  deleteFileWithPath,
  getSuccessVideoFiles,
  saveSuccessFileName,
  clearSuccessFileName,
};
