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 NoticeInstruction_exports = {};
__export(NoticeInstruction_exports, {
  default: () => NoticeInstruction_default
});
module.exports = __toCommonJS(NoticeInstruction_exports);
var import_utils = require("@tachybase/utils");
var import_constants = require("../../constants");
var import_instructions = __toESM(require("../../instructions"));
var import_constants2 = require("../common/constants");
var import_constants3 = require("./constants");
var import_tools = require("./tools");
class NoticeInstruction extends import_instructions.default {
  async run(node, prevJob, processor) {
    const job = await processor.saveJob({
      status: import_constants.JOB_STATUS.RESOLVED,
      nodeId: node.id,
      nodeKey: node.key,
      upstreamId: (prevJob == null ? void 0 : prevJob.id) ?? null
    });
    const notifiedPerson = await (0, import_tools.parsePerson)(node, processor);
    if (notifiedPerson && notifiedPerson.length > 0) {
      const { db } = processor.options.plugin;
      const ApprovalRepo = db.getRepository("approvals");
      const approval = await ApprovalRepo.findOne({
        filter: {
          "executions.id": processor.execution.id
        },
        fields: ["id", "status", "data", "summary", "collectionName"],
        appends: ["approvalExecutions"],
        except: ["data"]
      });
      const NoticeModel = db.getModel(import_constants2.COLLECTION_NOTICE_NAME);
      const notifiedPersonMapData = notifiedPerson.map((userId, index) => ({
        userId,
        jobId: job.id,
        nodeId: node.id,
        executionId: job.executionId,
        workflowId: node.workflowId,
        index,
        status: node.config.order && index ? import_constants3.NOTICE_ACTION_STATUS.ASSIGNED : import_constants3.NOTICE_ACTION_STATUS.APPROVED,
        snapshot: approval.data,
        summary: approval.summary,
        collectionName: approval.collectionName,
        dataKey: approval.dataKey
      }));
      await NoticeModel.bulkCreate(notifiedPersonMapData, {
        transaction: processor.transaction
      });
    }
    this.workflow.noticeManager.notify("workflow:regular", { msg: "done" });
    return job;
  }
  // NOTE: 目前没有用处, 不过留着作为未来如果有动作的实现的参考
  async resume(node, job, processor) {
    if (job.nodeId !== node.id) {
      const nodeJob = processor.findBranchParentJob(job, node);
      if (job.status === import_constants.JOB_STATUS.RESOLVED) {
        const jobNode = processor.nodesMap.get(job.nodeId);
        const branchStart = processor.findBranchStartNode(jobNode);
        if (branchStart.branchIndex === import_constants3.NOTICE_ACTION_STATUS.RETURNED) {
          nodeJob.set("status", import_constants.JOB_STATUS.RETRY_NEEDED);
        } else if (branchStart.branchIndex === import_constants3.NOTICE_ACTION_STATUS.REJECTED && node.config.endOnReject) {
          nodeJob.set("status", import_constants.JOB_STATUS.REJECTED);
        }
        return nodeJob;
      }
      return processor.exit(job.status);
    }
    const { branchMode, negotiation, order } = node.config;
    const notifiedPerson = await (0, import_tools.parsePerson)(node, processor);
    const NoticeRepo = this.workflow.app.db.getRepository(import_constants2.COLLECTION_NOTICE_NAME);
    const records = await NoticeRepo.find({
      filter: {
        jobId: job.id
      },
      except: ["snapshot"],
      sort: ["index"],
      transaction: processor.transaction
    });
    const distribution = records.reduce((prev, record) => {
      const item = prev.find((item2) => item2.status === record.status);
      if (item) {
        item.count += 1;
      } else {
        prev.push({
          status: record.status,
          count: 1
        });
      }
      return prev;
    }, []);
    const processing = Boolean(distribution.find((item) => item.status !== import_constants3.NOTICE_ACTION_STATUS.PENDING));
    const status = job.status || ((0, import_tools.getNegotiationMode)(negotiation).getStatus(distribution, notifiedPerson, negotiation) ?? import_constants.JOB_STATUS.PENDING);
    const result = import_tools.NoticeJobStatusMap[status];
    processor.logger.debug(`notice resume job and next status: ${status}`);
    job.set({
      status: status && status !== import_constants.JOB_STATUS.CANCELED ? branchMode ? import_constants.JOB_STATUS.RESOLVED : status : status,
      result
    });
    if (status && status !== import_constants.JOB_STATUS.CANCELED || negotiation && processing) {
      await job.latestUserJob.approval.update(
        {
          status: import_constants3.NOTICE_STATUS.PROCESSING
        },
        { transaction: processor.transaction }
      );
    }
    const nextPerson = notifiedPerson[notifiedPerson.indexOf(job.latestUserJob.userId) + 1];
    if (!status && negotiation && order && nextPerson) {
      await NoticeRepo.update({
        values: {
          status: import_constants3.NOTICE_ACTION_STATUS.PENDING
        },
        filter: {
          jobId: job.id,
          userId: nextPerson
        },
        transaction: processor.transaction
      });
    }
    if (branchMode) {
      const branchNode = processor.nodes.find((item) => item.upstream === node && item.branchIndex === result);
      if (branchNode) {
        await processor.saveJob(job);
        await processor.run(branchNode, job);
        return null;
      }
    }
    return job;
  }
  async duplicateConfig(node, { transaction }) {
    const uiSchemaRepo = this.workflow.app.db.getRepository("uiSchemas");
    if (!node.config.showNoticeDetail) {
      return node.config;
    }
    const result = await uiSchemaRepo.duplicate(node.config.showNoticeDetail, {
      transaction
    });
    return {
      ...node.config,
      showNoticeDetail: (result == null ? void 0 : result["x-uid"]) ?? (0, import_utils.uid)()
    };
  }
}
var NoticeInstruction_default = NoticeInstruction;
