<h3 class="WorkflowDesignerTitleWithCreate">
  {{ labels.Title }}
  <a v-if="!readonly" @click="add()">{{ ButtonTextCreate }}</a>
</h3>
<div id="WorkflowDesignerCommandsList" class="WorkflowDesignerWindowForm">
  <table class="WorkflowDesignerTable">
    <tr>
      <th></th>
      <th>{{ labels.Name }}</th>
    </tr>
    <tr v-for="(item, index) in items" :key="index"
        :class="dragOverIndex == index && dragOverBlock  == item ? 'dragOver' : ''"
        @dragend="dragend($event)" @dragover="dragover(item, index, $event)"
        @dragstart="dragstart(index, $event)">
      <td :draggable="!readonly" class='WorkflowDesignerTableMoveCol'>
        <div v-if="!readonly" class='WorkflowDesignerTableMoveButton'></div>
      </td>
      <td>
        <el-input
          v-model="item.Name"
          :class="validateField('Name', item) ? 'WorkflowDesignerInputError' : ''"
          :readonly="readonly"
          :title="validateField('Name', item)"
        ></el-input>
      </td>
      <td v-if="!readonly" class="WorkflowDesignerTableEditButtons Triple">
        <el-button-group>
          <el-button :class="'WorkflowDesignerTableCodeParametersButton ' + (editParametersItem == item ? 'is-active' : '')"
                     v-on:click="showparameters(item)"></el-button>
          <el-button icon="IconComment" class="WorkflowDesignerTableCommentButton" v-on:click="showComment(item)"></el-button>
          <el-button class="WorkflowDesignerTableDeleteButton" @click="remove(index)"></el-button>
        </el-button-group>
      </td>
    </tr>
  </table>
</div>
<div class="WorkflowDesignerButtons">
  <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 commands_Data(me) {
    return {
      readonly: false,
      editItem: undefined,
      editParametersItem: undefined,
      items: []
    }
  }

  function commands_Init(me) {
    const {VueConfig} = me;
    const {state: data, methods} = VueConfig

    methods.UpdateLanguage = function () {
      Object.assign(data, {
        labels: WorkflowDesignerConstants.CommandFormLabel,
        ButtonTextCreate: WorkflowDesignerConstants.ButtonTextCreate,
        ButtonTextDelete: WorkflowDesignerConstants.ButtonTextDelete,
        ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
        ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
      });
    }

    methods.UpdateLanguage();

    methods.setCurrentItem = function (item) {
      this.currentItem = item;
    };

    methods.onUpdate = function () {
      var clonedItems = WorkflowDesignerCommon.clone(me.graph.data.Commands);
      clonedItems.forEach(function (item) {
        if (!Array.isArray(item.InputParameters)) {
          item.InputParameters = [];
        }
        item.InputParameters.forEach(function (parameterItem) {
          if (!parameterItem.Parameter) parameterItem.Parameter = {};
        })
      });
      data.items = clonedItems;
      data.readonly = me.graph.Settings.readonly;
    };

    methods.add = function () {
      data.items.push({Name: '', InputParameters: []});

      setTimeout(function () {
        var objDiv = document.getElementById('WorkflowDesignerCommandsList');
        objDiv.scrollTop = objDiv.scrollHeight;
      }, 10);
    };

    methods.remove = function (index) {
      data.items.splice(index, 1);
    };

    methods.showjson = function (name, item) {
      data.editItem = item;
      me.editItem = item;
      data.jsonform = me.showjson(item[name], {}, function (value) {
        if (me.editItem) {
          me.editItem[name] = value;
          data.editItem = undefined;
          delete me.editItem;
        }
      })
    };

    methods.validateField = function (name, item) {
      if (name !== 'Name')
        return;

      if (!item[name]) {
        return WorkflowDesignerConstants.FieldIsRequired;
      }

      if (name === 'Name') {
        var res = data.items.filter(function (i) {
          return i != item && i.Name == item.Name
        });
        if (res.length > 0) {
          return WorkflowDesignerConstants.FieldMustBeUnique;
        }
      }
    };

    methods.showparameters = function (item) {
      data.editParametersItem = me.editParametersItem = item;

      var windowId = me.id + '_commandParameters';

      var onSuccess = function (res) {
        if (me.editParametersItem) {
          me.editParametersItem.ParameterDefinitions = WorkflowDesignerCommon.clone(res);
          data.editParametersItem = undefined;
          delete me.editParametersItem;
        }
      };

      var onClose = function () {
        if (me.editParametersItem) {
          data.editParametersItem = undefined;
          delete me.editParametersItem;
        }
      }

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

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

    methods.showComment = function (item) {
      const name = 'Comment';
      const title = 'Edit comment';
      const type = WorkflowDesignerConstants.ParameterTypes.TextArea;

      me.editItem = item;

      me.showJsonForm(item[name], {
        customTitle: title,
        parameterDefinition: {type},
        onSuccess: function (value) {
          if (me.editItem) {
            me.editItem[name] = value;
          }
        },
        onClose: function () {
          delete me.editItem;
        }
      });
    };

    methods.validate = function () {
      var validateFunc = methods.validateField;

      var items = data.items;
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (validateFunc('Name', item))
          return false;
      }

      return true;
    };

    methods.onSave = function () {
      if (methods.validate && methods.validate()) {
        me.graph.UpdateData(me.graph.data.Commands, data.items);
        me.onClose(true);
      }
    };

    methods.onClose = function () {

      if (data.readonly) {
        me.onClose(true);
        return;
      }
      if (!data.readonly && !WorkflowDesignerCommon.compareArray(
        me.graph.data.Commands,
        data.items,
        ['Name', 'InputParameters', 'Comment'])) {

        me.showConfirm();
        return false;
      } else {
        me.onClose(true);
      }
    };

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

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