var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var importXlsx_exports = {};
__export(importXlsx_exports, {
  importXlsx: () => importXlsx
});
module.exports = __toCommonJS(importXlsx_exports);
var import_utils = require("@tachybase/utils");
var import_node_xlsx = __toESM(require("node-xlsx"));
var import_xlsx = __toESM(require("xlsx"));
var import__ = require("../../");
const IMPORT_LIMIT_COUNT = 1e4;
class Importer {
  constructor(ctx) {
    this.items = [];
    const { resourceName, resourceOf } = ctx.action;
    this.context = ctx;
    this.repository = ctx.db.getRepository(resourceName, resourceOf);
    this.collection = this.repository.collection;
    this.parseXlsx();
  }
  getRows() {
    const workbook = import_xlsx.default.read(this.context.file.buffer, {
      type: "buffer"
      // cellDates: true,
      // raw: false,
    });
    const r = workbook.Sheets[workbook.SheetNames[0]];
    const rows = import_xlsx.default.utils.sheet_to_json(r, { header: 1, defval: null, raw: false });
    return rows;
  }
  parseXlsx() {
    const rows = this.getRows();
    let columns = this.context.request.body.columns;
    if (typeof columns === "string") {
      columns = JSON.parse(columns);
    }
    this.columns = columns.map((column) => {
      return {
        ...column,
        field: this.collection.fields.get(column.dataIndex[0])
      };
    }).filter((col) => col.field);
    const str = this.columns.map((column) => column.defaultTitle).join("||");
    for (const row of rows) {
      if (this.hasHeaderRow()) {
        if (row && row.join("").trim()) {
          this.items.push(row);
        }
      }
      if (str === row.filter((r) => r).join("||")) {
        this.headerRow = row;
      }
    }
  }
  getFieldByIndex(index) {
    return this.columns[index].field;
  }
  async getItems() {
    const items = [];
    for (const row of this.items) {
      const values = {};
      const errors = [];
      for (let index = 0; index < row.length; index++) {
        if (!this.columns[index]) {
          continue;
        }
        const column = this.columns[index];
        const { field, defaultTitle } = column;
        let value = row[index];
        if (value === void 0 || value === null) {
          continue;
        }
        const parser = this.context.db.buildFieldValueParser(field, { ...this.context, column });
        await parser.setValue(typeof value === "string" ? value.trim() : value);
        value = parser.getValue();
        if (parser.errors.length > 0) {
          errors.push(`${defaultTitle}: ${parser.errors.join(";")}`);
        }
        if (value === void 0) {
          continue;
        }
        values[field.name] = value;
      }
      items.push({
        row,
        values,
        errors
      });
    }
    return items;
  }
  hasSortField() {
    return !!this.collection.options.sortable;
  }
  async run() {
    return await this.context.db.sequelize.transaction(async (transaction) => {
      let sort = 0;
      if (this.hasSortField()) {
        sort = await this.repository.model.max("sort", { transaction });
      }
      const result = [[], []];
      for (const { row, values, errors } of await this.getItems()) {
        if (errors.length > 0) {
          row.push(errors.join(";"));
          result[1].push(row);
          continue;
        }
        if (this.hasSortField()) {
          values["sort"] = ++sort;
        }
        try {
          const instance = await this.repository.create({
            values,
            transaction,
            logging: false,
            context: this.context
          });
          result[0].push(instance);
        } catch (error) {
          if (error.message !== "current transaction is aborted, commands ignored until end of transaction block") {
            this.context.log.error(error, row);
          }
          row.push(error.message);
          result[1].push(row);
        }
      }
      return result;
    });
  }
  hasHeaderRow() {
    return !!this.headerRow;
  }
}
async function importXlsx(ctx, next) {
  const importer = new Importer(ctx);
  if (!importer.hasHeaderRow()) {
    ctx.throw(400, ctx.t("Imported template does not match, please download again.", { ns: import__.namespace }));
  }
  const [success, failure] = await importer.run();
  ctx.body = {
    rows: import_node_xlsx.default.build([
      {
        name: `${(0, import_utils.uid)()}.xlsx`,
        data: [importer.headerRow].concat(failure),
        options: {}
      }
    ]),
    successCount: success.length,
    failureCount: failure.length
  };
  await next();
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  importXlsx
});
