<h3 class="WorkflowDesignerTitleWithCreate">
  {{ labels.Title }}
  <a v-if="!readonly" @click="add()">{{ ButtonTextCreate }}</a>
</h3>

<div id="WorkflowDesignerParametersList" class="WorkflowDesignerWindowForm">

  <div style="display: flex; justify-content: flex-end; margin-bottom: 5px;">
    <el-switch v-model="showSystem" :active-text="labels.ShowSystemParameters"></el-switch>
  </div>
  <table class="WorkflowDesignerTable">
    <tr>
      <th></th>
      <th>{{ labels.Name }}</th>
      <th>{{ labels.Type }}</th>
      <th>{{ labels.Purpose }}</th>
      <th>{{ labels.InitialValue }}</th>
    </tr>
    <template v-for="(item, index) in items">
      <tr :key="index" v-if="showSystem || item?.Purpose !== 'System'"
          :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 || item?.Purpose === 'System'"
            :title="validateField('Name', item)"
          ></el-input>
        </td>
        <td>
          <el-autocomplete v-model="item.Type"
                           :class="validateField('Type', item) ? 'WorkflowDesignerInputError' : ''"
                           :fetch-suggestions="querySearch"
                           :readonly="readonly || item?.Purpose === 'System'"
                           :title="validateField('Type', item)"
                           resize="horizontal"
                           style="width: 100%;">
          </el-autocomplete>
        </td>
        <td>
          <el-select
            :disabled="readonly || item?.Purpose === 'System'"
            :title="validateField('Purpose', item)" clearable
            :class="validateField('Purpose', item) ? 'WorkflowDesignerInputError' : ''"
            :model-value="item?.Purpose"
            @change="(value) => selectPurpose(item, value)"
            filterable
            placeholder=""
            style="width: 100%;">
            <el-option key="Temporary" label="Temporary" value="Temporary"></el-option>
            <el-option key="Persistence" label="Persistence" value="Persistence"></el-option>
            <el-option v-if="item?.Purpose === 'System'" key="System" label="System" value="System"></el-option>
          </el-select>
        </td>
        <td>
          <el-input
            v-if="item?.Purpose === 'Persistence'"
            v-model="item.InitialValue"
            :class="validateField('InitialValue', item) ? 'WorkflowDesignerInputError' : ''"
            :readonly="readonly"
            :title="validateField('InitialValue', item)"
          ></el-input>
        </td>

        <td v-if="!readonly" class="WorkflowDesignerTableEditButtons Double">
          <el-button-group>
            <el-button v-if="item?.Purpose === 'Persistence'"
                       :class="'WorkflowDesignerTableCodeActionsButton ' + (editItem == item ? 'is-active' : '')"
                       @click="showjson('InitialValue', item)"></el-button>
            <el-button v-if="item?.Purpose !== 'System'" class="WorkflowDesignerTableDeleteButton" @click="remove(index)"></el-button>
          </el-button-group>
        </td>
      </tr>
    </template>
  </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 parameters_Data(me) {
    return {
      readonly: false,
      editItem: undefined,
      showSystem: false,
      items: []
    }
  }

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

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

    methods.UpdateLanguage();

    methods.setCurrentItem = function (item) {
      this.currentItem = item;
    };
    methods.querySearch = function (queryString, cb) {
      if (data.readonly)
        return cb([]);

      var types = graph.getTypeNames();
      var res = [];

      var query = queryString ? queryString.toLowerCase() : queryString;
      types.forEach(function (item) {
        if (!query || !item || item.toLowerCase().indexOf(query) >= 0) {
          res.push({'value': item});
        }
      });

      cb(res);
    };

    methods.onUpdate = function () {
      data.items = WorkflowDesignerCommon.clone(graph.data.Parameters);
      data.readonly = graph.Settings.readonly;
    };

    methods.add = function () {
      data.items.push({Name: '', Type: '', Purpose: '', InitialValue: ''});

      setTimeout(function () {
        var objDiv = document.getElementById('WorkflowDesignerParametersList');
        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;

      var onSuccess = function (value) {
        if (me.editItem) {
          me.editItem[name] = value;
          data.editItem = undefined;
          delete me.editItem;
        }
      };

      var onClose = function (value) {
        data.editItem = undefined;
      };

      var params = {};
      data.jsonform = me.showjson(item[name], params, onSuccess, onClose);
    };

    methods.validateField = function (name, item) {
      if (name !== 'Name' && name !== 'Type' && name !== 'Purpose')
        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.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) || validateFunc('Rule', item))
          return false;
      }

      return true;
    };

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

    methods.onClose = function () {

      if (data.readonly) {
        me.onClose(true);
        return;
      }

      if (!data.readonly && !WorkflowDesignerCommon.compareArray(
        graph.data.Parameters,
        data.items,
        ['Name', 'Type', 'Purpose', 'InitialValue'])) {

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

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

    methods.selectPurpose = function (item, value) {
      item.Purpose = value;
    }

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