<h3>{{ labels.MessageCatchEvent }}</h3>
<el-form ref="form"
         :model="FormData"
         class="WorkflowDesignerWindowForm"
         label-position="top"
         label-width="150px">
  <div class="SettingsWithPadding">
    <div class="el-form--inline el-form--label-top">
      <el-form-item :label="labels.Name" :rules="activityNameRules()" class="el-form-item" prop="Name" style="flex-grow: 1;">
        <el-input v-model="FormData.Name" :placeholder="labels.Name" :readonly="readonly" @input="nameOnChange"></el-input>
      </el-form-item>
      <el-form-item :label="labels.State" class="el-form-item" prop="State" style="flex-grow: 1;">
        <el-input v-model="FormData.State" :placeholder="labels.State" :readonly="readonly"></el-input>
      </el-form-item>
    </div>
    <el-form-item size="small">
      <el-checkbox v-model="FormData.IsForSetState" :disabled="readonly" :label="labels.IsForSetState" name="type"></el-checkbox>
      <el-checkbox v-model="FormData.IsAutoSchemeUpdate" :disabled="readonly" :label="labels.IsAutoSchemeUpdate" name="type"></el-checkbox>
    </el-form-item>
    <el-form-item size="small">
      <el-checkbox v-if="expertMode" v-model="disableAllPersist" :disabled="readonly" :indeterminate="isIndeterminate"
                   :label="labels.DisablePersist" @change="handleCheckAllPersistsChange"></el-checkbox>
    </el-form-item>
    <el-checkbox-group v-if="expertMode && (disableAllPersist || isIndeterminate)" v-model="checkedPersists"
                       @change="handleCheckedPersistsChange">
      <el-checkbox v-for="persist in persists" :key="persist" :disabled="readonly" :label="persist">{{ persist }}</el-checkbox>
    </el-checkbox-group>
  </div>
  <el-form-item :label="labels.TriggerCommand" :rules="requiredRule()" prop="__commandName">
    <el-select
      v-model="FormData.__commandName"
      :disabled="readonly"
      allow-create
      clearable
      filterable
      placeholder=""
      style="width: 100%; margin-right: 10px;"
      @change="commandsListChange">
      <el-option v-for="item in commands" :key="item" :label="item" :value="item"></el-option>
    </el-select>
    <el-button :disabled="!FormData.__commandName" class="WorkflowDesignerTableCodeParametersButton" @click="commandParameters"></el-button>
  </el-form-item>
  <div style="margin-bottom: 10px;">
    <el-button v-if="!readonly && !itemHasComment" circle icon="el-icon-s-comment" @click="showUserComment()"></el-button>
    <h4 v-if="itemHasComment" style="padding-bottom: 1px;border-bottom: 1px solid rgba(34,36,38,.15);">{{ labels.UserComment }}</h4>
    <el-input
      v-if="itemHasComment"
      v-model="FormData.UserComment"
      :placeholder="labels.UserComment"
      rows="5"
      type="textarea"
    >
    </el-input>
  </div>
</el-form>
<div class="WorkflowDesignerButtons">
  <el-button type="text" @click="expertMode = !expertMode">{{ expertMode ? SwitchToDefaultMode : SwitchToExpertMode }}</el-button>
  <el-button v-if="!readonly" type="primary" @click="onSave">{{ ButtonTextSave }}</el-button>
  <el-button @click="onClose">{{ ButtonTextCancel }}</el-button>
</div>
<script type="application/javascript">
  function customforms_bpmnplugin_messagecatch_Init(me) {
    me.VueConfig.methods.UpdateLanguage = function () {
      me.VueConfig.data = Object.assign(me.VueConfig.data, {
        labels: Object.assign({},
          WorkflowDesignerConstants.ActivityFormLabel,
          WorkflowDesignerConstants.BpmnPlugin,
          {TriggerCommand: WorkflowDesignerConstants.TransitionFormLabel.TriggerCommand}),
        ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
        ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
        ButtonTextCreate: WorkflowDesignerConstants.ButtonTextCreate,
        ButtonTextDelete: WorkflowDesignerConstants.ButtonTextDelete,
        SwitchToDefaultMode: WorkflowDesignerConstants.SwitchToDefaultMode,
        SwitchToExpertMode: WorkflowDesignerConstants.SwitchToExpertMode
      });
    }
    me.VueConfig.methods.UpdateLanguage();
    me.VueConfig.data = Object.assign(me.VueConfig.data, {
      readonly: false,
      expertMode: false,
      activities: [],
      states: [],
      itemHasComment: false,
      FormData: {},
      disableAllPersist: false,
      isIndeterminate: false,
      persists: [],
      checkedPersists: [],
      commands: [],
      commandsStore: me.graph.data.Commands
    });

    me.VueConfig.watch = {
      commandsStore: function (val) {
        me.VueConfig.data.commands = me.graph.getCommandNames();
      },
    };

    me.VueConfig.methods.onUpdate = function (item) {
      const formData = me.VueConfig.data.FormData;
      formData.Name = item.Name;
      formData.State = item.State;
      formData.IsForSetState = item.IsForSetState;
      formData.IsAutoSchemeUpdate = item.IsAutoSchemeUpdate;
      formData.DisablePersistState = !!item.DisablePersistState;
      formData.DisablePersistTransitionHistory = !!item.DisablePersistTransitionHistory;
      formData.DisablePersistParameters = !!item.DisablePersistParameters;
      formData.UserComment = item.UserComment;

      me.linkItem = item;
      me.VueConfig.data.originalItem = WorkflowDesignerCommon.clone(formData);
      me.VueConfig.data.readonly = me.graph.Settings.readonly;
      me.VueConfig.data.itemHasComment = formData.UserComment != null && formData.UserComment.length > 0;

      const {activities, states} = me.VueConfig.data;
      me.graph.data.Activities.forEach(({Name, State}) => {
        if (item.Name === Name) return;

        if (!activities.includes(Name)) activities.push(Name);
        if (State && !states.includes(State)) states.push(State);
      });

      activities.sort();
      states.sort();

      me.VueConfig.data.disableAllPersist = formData.DisablePersistState && formData.DisablePersistTransitionHistory && formData.DisablePersistParameters;
      me.VueConfig.data.isIndeterminate = formData.DisablePersistState || formData.DisablePersistTransitionHistory || formData.DisablePersistParameters;
      me.VueConfig.data.persists = [
        me.VueConfig.data.labels.DisablePersists.DisablePersistState,
        me.VueConfig.data.labels.DisablePersists.DisablePersistParameters,
        me.VueConfig.data.labels.DisablePersists.DisablePersistTransitionHistory
      ];
      me.VueConfig.data.checkedPersists = [];
      if (formData.DisablePersistState !== undefined && formData.DisablePersistState) {
        me.VueConfig.data.checkedPersists.push(me.VueConfig.data.labels.DisablePersists.DisablePersistState);
      }
      if (formData.DisablePersistParameters !== undefined && formData.DisablePersistParameters) {
        me.VueConfig.data.checkedPersists.push(me.VueConfig.data.labels.DisablePersists.DisablePersistParameters);
      }
      if (formData.DisablePersistTransitionHistory !== undefined && formData.DisablePersistTransitionHistory) {
        me.VueConfig.data.checkedPersists.push(me.VueConfig.data.labels.DisablePersists.DisablePersistTransitionHistory);
      }

      if (me.VueConfig.data.disableAllPersist || me.VueConfig.data.isIndeterminate) {
        me.VueConfig.data.expertMode = true;
      }

      me.VueConfig.data.prevName = item.Name;

      me.VueConfig.data.commands = me.graph.getCommandNames();

      const commandName = item.Annotations.find(a => a.Name === '__commandName');
      formData.__commandName = commandName?.JsonValue ?? null;
      me.VueConfig.data.originalItem.__commandName = formData.__commandName;
    };

    me.VueConfig.methods.activityNameRules = function () {
      var res = me.requiredRule();

      var validator = function (rule, value, callback) {
        var hasEqualNames = me.graph.data.Activities.find(function (a) {
          return a !== me.linkItem && a.Name === value;
        });

        hasEqualNames ? callback(new Error(rule.message)) : callback();
      };
      res.push({validator: validator, message: WorkflowDesignerConstants.FieldMustBeUnique});
      return res;
    }

    me.VueConfig.methods.handleCheckAllPersistsChange = function (val) {
      me.VueConfig.data.checkedPersists = val ? me.VueConfig.data.persists : [];
      me.VueConfig.data.isIndeterminate = false;
    };

    me.VueConfig.methods.handleCheckedPersistsChange = function (value) {
      let checkedCount = value.length;
      me.VueConfig.data.disableAllPersist = checkedCount === me.VueConfig.data.persists.length;
      me.VueConfig.data.isIndeterminate = checkedCount > 0 && checkedCount < me.VueConfig.data.persists.length;
    }

    me.VueConfig.methods.showUserComment = function () {
      me.VueConfig.data.itemHasComment = true;
    }

    me.VueConfig.methods.onSave = function () {
      me.VueConfig.data.FormData.DisablePersistState = false;
      me.VueConfig.data.FormData.DisablePersistParameters = false;
      me.VueConfig.data.FormData.DisablePersistTransitionHistory = false;

      const persists = me.VueConfig.data.checkedPersists;
      for (var i = 0; i < persists.length; i++) {
        switch (persists[i]) {
          case  me.VueConfig.data.labels.DisablePersists.DisablePersistState:
            me.VueConfig.data.FormData.DisablePersistState = true;
            break;
          case me.VueConfig.data.labels.DisablePersists.DisablePersistParameters:
            me.VueConfig.data.FormData.DisablePersistParameters = true;
            break;
          case me.VueConfig.data.labels.DisablePersists.DisablePersistTransitionHistory:
            me.VueConfig.data.FormData.DisablePersistTransitionHistory = true;
            break;
        }
      }

      const commandItem = me.getCommandItem(me.VueConfig.data.FormData.__commandName);
      if (!!commandItem) me.updateAllOutgoingTransitions(commandItem);

      if (this.$refs && WorkflowDesignerCommon.validateForms(this.$refs)) {
        me.onSuccess(me.VueConfig.data.FormData);
        me.onClose(true);
      }
    };

    me.VueConfig.methods.nameOnChange = function (value) {
      const formData = me.VueConfig.data.FormData;
      if (formData.State === me.VueConfig.data.prevName) {
        formData.State = value;
      }
      me.VueConfig.data.prevName = value;
    };

    me.VueConfig.methods.commandParameters = function () {
      var windowId = me.id + '_commandParameters';

      var item = me.getCommandItem(me.VueConfig.data.FormData.__commandName);
      if (!item) return;

      if (!me.parametersform) {
        var options = {
          move: true,
          resize: true,
          savePosition: true,
          class: 'WorkflowDesignerParametersForm',
          parameterDefinition: {}
        };
        me.parametersform = me.graph.CreateWindow(windowId, options);
      }

      me.parametersform.show('commandParameters', item);
    };

    me.updateAllOutgoingTransitions = function (commandItem) {
      let outgoingTransitions = me.graph.data.Transitions.filter(function (transition) {
        return transition.From.Name === me.VueConfig.data.FormData.Name;
      });
      for (let i = 0; i < outgoingTransitions.length; i++) {
        let transition = outgoingTransitions[i];
        transition.Conditions = [{Type: 'Always', Action: {}}];
        transition.Trigger.Command = commandItem;
        transition.Trigger.Type = 'Command';
      }
    }

    me.getCommandItem = function (commandName) {
      return me.graph.data.Commands.find(function (command) {
        return command.Name === commandName;
      });
    }

    me.VueConfig.methods.commandsListChange = function (commandName) {
      if (!me.getCommandItem(commandName)) {
        me.graph.data.Commands.push({Name: commandName, InputParameters: []});
      }
    }

    me.VueConfig.methods.onClose = function () {
      if (me.VueConfig.data.readonly) {
        me.onClose(true);
        return;
      }

      var originalItem = me.VueConfig.data.originalItem;
      var item = me.VueConfig.data.FormData;

      if (WorkflowDesignerCommon.deepCompare(originalItem, item)) {
        me.onClose(true);
      } else {
        me.showConfirm();
        return false;
      }
    };

    me.VueConfig.methods.onCloseSave = function () {
      me.onClose(true);
    };

    me.showConfirm = function () {
      me.VueConfig.methods.showConfirm({
        title: WorkflowDesignerConstants.DialogConfirmText,
        message: WorkflowDesignerConstants.CloseWithoutSaving,
        onSuccess: function () {
          me.VueConfig.methods.onCloseSave();
        }
      });
    }
  }
</script>
