/**
 * io读写方法
 *
 */

import {
  createFileWithPlusIO,
  SYNCHRONIZE_DATA_PAD,
  setSm2,
  readFileContent,
  readFilesInDirectory,
  checkFileExists,
  FILE_ENUM,
} from "./systemCofig";
import moment from "moment";
import lodash from "lodash";

import store from "../store/index";

import { Base64 } from "js-base64";

//日志类型
export const LOG_TYPE_ENUM = {
  login: "登录",
  add: "新增",
  photo: "拍照",
  edit: "编辑",
  sign: "签字",
  darf: "草稿",
  delete: "删除",
  sys: "同步",
  updatePassword: "修改密码",
};

// 生成日志
export const getLogContent = (type, detail = "", module = "其他模块") => {
  const now_user = store.state.now_user;
  let timeStr = moment().format("yyyy-MM-DD HH:mm:ss");
  return {
    level: "秘密",
    module,
    detail,
    type,
    time: timeStr,
    ...now_user,
  };
};

/**
 * 新增日志
 * @param {*} content   字符串格式  写入文件
 * @returns
 */
export const addLog = (content) => {
  return new Promise((resolve, reject) => {
    const now_user = store.state.now_user;
    let fileName = `${now_user.user}.txt`;
    const temp = content.filter((item) => item.user == now_user.user);

    const fileContent = Base64.encode(JSON.stringify(temp)); // 方便验证

    // store 更新日志
    store.commit("SET_LOG_LIST", content);

    createFileWithPlusIO(
      `${SYNCHRONIZE_DATA_PAD}/日志文件/${now_user.user}`,
      fileName,
      fileContent
    )
      .then((res) => {
        resolve();
      })
      .catch((error) => reject(error));
  });
};

// 读取日志
export const readLogData = () => {
  const now_user = store.state.now_user;
  const isAdmin = now_user.isAdmin;

  const directoryPath = isAdmin
    ? `${SYNCHRONIZE_DATA_PAD}/日志文件`
    : `${SYNCHRONIZE_DATA_PAD}/日志文件/${now_user.user}`;
  return new Promise((resolve, reject) => {
    readFilesInDirectory(directoryPath)
      .then((res) => {
        console.log("readFilesInDirectory", res);
        const temp = res.map((element) => {
          return JSON.parse(Base64.decode(element));
        });

        resolve(lodash.flattenDeep(temp));
      })
      .catch((error) => reject(error));
  });
};

// 写入草稿文件
export const writeDarf = (content) => {
  return new Promise((resolve, reject) => {
    const now_user = store.state.now_user;
    let fileName = `${now_user.user}.txt`;
    let fileContent =
      content.length == 0 ? "" : Base64.encode(JSON.stringify(content));

    createFileWithPlusIO(
      `${SYNCHRONIZE_DATA_PAD}/草稿文件`,
      fileName,
      fileContent
    ).then((res) => {
      resolve();
    });
  });
};

// 读取草稿文件
export const readDarfData = () => {
  const now_user = store.state.now_user;
  const directoryPath = `${SYNCHRONIZE_DATA_PAD}/草稿文件/${now_user.user}.txt`;

  return new Promise((resolve, reject) => {
    checkFileExists(`${SYNCHRONIZE_DATA_PAD}/草稿文件`, `${now_user.user}.txt`)
      .then((fileEntry) => {
        // 文件存在，
        return readFileContent(fileEntry)
          .then((res) => {
            if (!res.length) {
              resolve({});
            } else {
              resolve(JSON.parse(Base64.decode(res)));
            }
          })
          .catch((error) => {
            reject(error);
          });
      })
      .catch((error) => {
        reject(error);
      });
  });
};

/**
 * // 写入【巡检数据】文件
 * @param {*} content   写入内容
 * @param {*} isEncryption  是否加密
 * @returns
 */
export const writeInspectionData = (content, userName) => {
  return new Promise((resolve, reject) => {
    let fileName = `list.txt`;
    const fileContent = Base64.encode(JSON.stringify(content));

    createFileWithPlusIO(
      `${SYNCHRONIZE_DATA_PAD}/巡检数据/${userName}`,
      fileName,
      fileContent
    ).then((res) => {
      // store 更新 巡检数据. 缓存数据置为空,让接口重新读取文件数据
      // store.commit("SET_ALL_DATA", []);
      resolve();
    });
  });
};

// 读取【巡检数据】文件
export const readInspectionData = () => {
  const now_user = store.state.now_user;
  const isAdmin = now_user.isAdmin;
  const directoryPath = isAdmin
    ? `${SYNCHRONIZE_DATA_PAD}/巡检数据`
    : `${SYNCHRONIZE_DATA_PAD}/巡检数据/${now_user.user}`;

  return new Promise((resolve, reject) => {
    readFilesInDirectory(directoryPath)
      .then((res) => {
        console.log("readInspectionData", res);
        const temp = res.map((element) => {
          return JSON.parse(Base64.decode(element));
        });

        resolve(lodash.flattenDeep(temp));
      })
      .catch((error) => reject(error));
  });
};
/**
 * // 写入【设备上架】文件
 * @param {*} content   写入内容
 * @param {*} isEncryption  是否加密
 * @returns
 */
export const writeDeviceData = (content, userName) => {
  return new Promise((resolve, reject) => {
    let fileName = `list.txt`;
    const fileContent = Base64.encode(JSON.stringify(content));

    createFileWithPlusIO(
      `${SYNCHRONIZE_DATA_PAD}/设备上架/${userName}`,
      fileName,
      fileContent
    ).then((res) => {
      // store 更新 设备上架. 缓存数据置为空,让接口重新读取文件数据
      store.commit("SET_DEVICEDATA", []);
      resolve();
    });
  });
};
// 读取【设备上架】文件
export const readDeviceData = () => {
  const now_user = store.state.now_user;
  console.log("now_user", now_user);
  const isAdmin = now_user.isAdmin;
  // const directoryPath = isAdmin
  //   ? `${SYNCHRONIZE_DATA_PAD}/设备上架`
  //   : `${SYNCHRONIZE_DATA_PAD}/设备上架/${now_user.user}`;
  const directoryPath = `${SYNCHRONIZE_DATA_PAD}/设备上架/${now_user.user}`;
  console.log("directoryPath", directoryPath);

  return new Promise((resolve, reject) => {
    readFilesInDirectory(directoryPath)
      .then((res) => {
        console.log("directoryPathres", res);
        const temp = res.map((element) => {
          return JSON.parse(Base64.decode(element));
        });

        resolve(lodash.flattenDeep(temp));
      })
      .catch((error) => reject(error));
  });
};

// 复制文件夹中的所有数据到另一个文件夹
/**
 *
 * @param {*} sourceDirectoryPath  复制内容文件夹路径  -- 源路径
 * @param {*} targetDirectoryPath  复制到新的文件夹路径 -- 目标路径
 */
export function copyDirectory(sourceDirectoryPath, targetDirectoryPath) {
  return new Promise((resolve, reject) => {
    // 请求文件系统
    plus.io.requestFileSystem(
      plus.io.PUBLIC_DOCUMENTS,
      function (fs) {
        // 获取源文件夹路径的目录条目
        fs.root.getDirectory(
          sourceDirectoryPath,
          { create: false },
          function (sourceDirEntry) {
            // 获取目标文件夹路径的目录条目
            fs.root.getDirectory(
              targetDirectoryPath,
              { create: true, exclusive: false },
              function (targetDirEntry) {
                // 创建一个空的目录读取器
                let directoryReader = sourceDirEntry.createReader();
                // 读取源目录中的所有文件和子目录
                directoryReader.readEntries(
                  function (entries) {
                    // 目标文件夹没有内容,直接返回
                    if (!entries.length) {
                      return resolve();
                    }

                    let copyNum = 0;
                    // 遍历文件和子目录
                    for (let i = 0; i < entries.length; i++) {
                      let entry = entries[i];
                      if (entry.isFile) {
                        // 确保是文件
                        // 复制文件
                        entry.copyTo(
                          targetDirEntry,
                          entry.name,
                          function () {
                            ++copyNum;
                            if (copyNum == entries.length) {
                              resolve();
                            }
                          },
                          function (error) {
                            console.error("创建目标目录失败:", error.message);

                            reject({
                              ...FILE_ENUM.copyFileError,
                            });
                          }
                        );
                      } else if (entry.isDirectory) {
                        // 确保是目录
                        // 创建目标目录
                        targetDirEntry.getDirectory(
                          entry.name,
                          { create: true, exclusive: false },
                          function (targetDirEntry) {
                            // 递归复制目录
                            copyDirectory(
                              entry.fullPath,
                              targetDirEntry.fullPath
                            );
                          },
                          function (error) {
                            console.error("copyDirectory:", error);

                            reject({
                              ...FILE_ENUM.createFileError,
                            });
                          }
                        );
                      }
                    }
                  },
                  function (error) {
                    console.error("copyDirectory:", error);

                    reject({
                      ...FILE_ENUM.readDirectoryError,
                    });
                  }
                );
              },
              function (error) {
                console.error("copyDirectory:", error);

                reject({
                  ...FILE_ENUM.readDirectoryError,
                });
              }
            );
          },
          function (error) {
            console.error("copyDirectory:", error);

            reject({
              ...FILE_ENUM.getDirectoryError,
            });
          }
        );
      },
      function (error) {
        console.error("copyDirectory:", error);

        reject({
          ...FILE_ENUM.fileSystemError,
        });
      }
    );
  });
}

// 复制多张图片到指定目录的函数（带权限请求）
export function copyImagesToFolder(sourcePaths, targetDir) {
  return new Promise((resolve, reject) => {
    // 1. 环境检查
    // if (!window.plus || !plus.io) {
    //   const err = new Error("当前环境不支持plus API");
    //   console.error(err);
    //   reject(err);
    //   return;
    // }

    console.log("开始复制图片文件...");

    // 2. 权限请求
    requestFilePermission()
      .then(() => {
        console.log("权限已获取，准备目标目录...");
        return prepareTargetDirectory(targetDir);
      })
      .then((targetDirEntry) => {
        console.log("目录准备完成，开始复制图片...");
        const copies = sourcePaths.map((path) =>
          copySingleImage(path, targetDirEntry)
        );
        return Promise.all(copies);
      })
      .then((results) => {
        console.log("所有图片复制成功", results);
        resolve(results);
      })
      .catch((err) => {
        console.error("复制图片出错:", err);
        reject(err);
      });
  });
}

// 请求权限（返回Promise）
function requestFilePermission() {
  return new Promise((resolve, reject) => {
    // if (plus.os.name === 'iOS') {
    //   resolve(); // iOS可能不需要显式请求
    //   return;
    // }

    plus.android.requestPermissions(
      [
        "android.permission.READ_EXTERNAL_STORAGE",
        "android.permission.WRITE_EXTERNAL_STORAGE",
      ],
      function (result) {
        if (Object.values(result.granted).every(Boolean)) {
          resolve();
        } else {
          reject(new Error("用户拒绝了文件权限"));
        }
      },
      function (error) {
        reject(error);
      }
    );
  });
}

// 准备目录（返回Promise）
function prepareTargetDirectory(targetDir) {
  return new Promise((resolve, reject) => {
    plus.io.requestFileSystem(
      plus.io.PUBLIC_DOCUMENTS,
      function (fs) {
        fs.root.getDirectory(
          targetDir,
          { create: true, exclusive: false },
          function (dirEntry) {
            resolve(dirEntry);
          },
          function (error) {
            reject(error);
          }
        );
      },
      function (error) {
        reject(error);
      }
    );
  });
}

// 复制单个图片文件（返回Promise）
function copySingleImage(sourcePath, targetDirEntry) {
  return new Promise((resolve, reject) => {
    plus.io.resolveLocalFileSystemURL(
      sourcePath,
      function (fileEntry) {
        if (!fileEntry.isFile) {
          reject(new Error("源路径不是文件"));
          return;
        }

        // 获取文件名
        const fileName = sourcePath.split("/").pop();

        // 检查文件是否已存在
        targetDirEntry.getFile(
          fileName,
          { create: false },
          () => {
            // 文件已存在，可以在这里决定是覆盖还是跳过
            // 这里选择覆盖
            fileEntry.copyTo(
              targetDirEntry,
              fileName,
              function (newEntry) {
                resolve(newEntry.toURL());
              },
              function (error) {
                reject(error);
              }
            );
          },
          () => {
            // 文件不存在，直接复制
            fileEntry.copyTo(
              targetDirEntry,
              fileName,
              function (newEntry) {
                resolve(newEntry.toURL());
              },
              function (error) {
                reject(error);
              }
            );
          }
        );
      },
      function (error) {
        reject(error);
      }
    );
  });
}
// 删除文件夹中所有文件（即使部分失败也会继续执行）
export function deleteAllFilesInDirectory(directoryPath) {
  return new Promise((resolve) => {
    plus.io.requestFileSystem(
      plus.io.PUBLIC_DOCUMENTS,
      (fs) => {
        fs.root.getDirectory(
          directoryPath,
          { create: false },
          (dirEntry) => {
            const directoryReader = dirEntry.createReader();
            directoryReader.readEntries(
              (entries) => {
                if (!entries.length) {
                  return resolve({
                    success: true,
                    message: "目录为空",
                    results: [],
                  });
                }

                const results = [];
                let completedCount = 0;

                const checkCompletion = () => {
                  if (completedCount === entries.length) {
                    resolve({
                      success: results.every((r) => r.success),
                      message: "操作完成",
                      results: results,
                    });
                  }
                };

                entries.forEach((entry) => {
                  if (entry.isFile) {
                    entry.remove(
                      () => {
                        results.push({
                          name: entry.name,
                          success: true,
                        });
                        completedCount++;
                        checkCompletion();
                      },
                      (error) => {
                        console.warn(`删除失败: ${entry.name}`, error);
                        results.push({
                          name: entry.name,
                          success: false,
                          error: error.message || "未知错误",
                        });
                        completedCount++;
                        checkCompletion();
                      }
                    );
                  } else {
                    // 如果是子目录，跳过（或可以递归删除）
                    completedCount++;
                    checkCompletion();
                  }
                });
              },
              (error) => {
                console.error("读取目录失败:", error);
                resolve({
                  success: false,
                  message: "读取目录失败",
                  error: error,
                });
              }
            );
          },
          (error) => {
            console.error("获取目录失败:", error);
            resolve({
              success: false,
              message: "目录不存在",
              error: error,
            });
          }
        );
      },
      (error) => {
        console.error("文件系统错误:", error);
        resolve({
          success: false,
          message: "文件系统访问失败",
          error: error,
        });
      }
    );
  });
}

// 初始化 -- 读取数据文件
export const readDirectoryData = () => {
  return new Promise(async (resolve, reject) => {
    readLogData()
      .then((res) => {
        store.commit("SET_LOG_LIST", res);
        return readInspectionData();
      })
      .then((res) => {
        store.commit("SET_ALL_DATA", res);
        return readDarfData();
      })
      .then((res) => {
        store.commit("SET_DARF_DATA", res);
        resolve();
      })
      .catch((error) => {
        reject(error);
      });
  });
};
