<h3>{{ customTitle ? customTitle : labels.Title }}</h3>
<el-form
  ref="form"
  :model="FormData"
  class="WorkflowDesignerWindowForm"
  label-position="top"
  label-width="150px">

  <div v-if="Field.State != undefined" class="SettingsWithPadding">
    <div class="el-form--inline el-form--label-top">
      <el-form-item
        :label="customLabels.Name"
        prop="Name"
        :rules="getFieldRules(Field.Name)"
        class="el-form-item"
        style="flex-grow: 1;">
        <el-input v-model="FormData.Name" :readonly="readonly"></el-input>
      </el-form-item>

      <el-form-item
        :label="customLabels.State"
        prop="State"
        :rules="getFieldRules(Field.State)"
        class="el-form-item"
        style="flex-grow: 1;">
        <el-input v-model="FormData.State" :readonly="readonly"></el-input>
      </el-form-item>
    </div>
  </div>

  <h4 v-if="Field.State != undefined" style="padding-bottom: 1px;border-bottom: 1px solid rgba(34,36,38,.15);">
    {{ customLabels.Heading }}</h4>
  <div :class="Field.State != undefined ?'SettingsWithPadding' : '' " style="margin-bottom: 10px;">
    <div class="el-form--inline el-form--label-top">
      <el-form-item
        :label="customLabels.Scheme"
        prop="Scheme"
        :rules="getFieldRules(Field.Scheme)"
        class="el-form-item"
        style="flex-grow: 1;">
        <el-input v-model="FormData.Scheme" :readonly="readonly"></el-input>
      </el-form-item>

      <el-form-item
        :label="customLabels.ProcessId"
        prop="ProcessId"
        :rules="getFieldRules(Field.ProcessId)"
        class="el-form-item"
        style="flex-grow: 1;">
        <el-input v-model="FormData.ProcessId" :readonly="readonly"></el-input>
      </el-form-item>
    </div>
  </div>

    <h4 class="WorkflowDesignerTitleWithCreate Underline">
      {{customLabels.ProcessCreationParameters}}
      <a v-if="!readonly" @click="add()">{{ButtonTextCreate}}</a>
  </h4>
  <div id="WorkflowDesignerParametersList">
    <table class="WorkflowDesignerTable">
      <tr v-if="items.length > 0">
        <th></th>
        <th>{{ customLabels.ParameterName }}</th>
        <th>{{ customLabels.ParameterPurpose }}</th>
        <th>{{ customLabels.ParameterValue }}</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 || item.Purpose == 'System'"
            :title="validateField('Name', item)"
          ></el-input>
        </td>
        <td>
          <el-select
            v-model="item.Purpose"
            :class="validateField('Purpose', item) ? 'WorkflowDesignerInputError' : ''"
            :disabled="readonly || item.Purpose == 'System'"
            clearable 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-model="item.Value"
            :class="validateField('Value', item) ? 'WorkflowDesignerInputError' : ''"
            :readonly="readonly"
            :title="validateField('Value', item)"
          ></el-input>
        </td>
        <td v-if="!readonly" class="WorkflowDesignerTableEditButtons Double">
          <el-button-group>
            <el-button :class="'WorkflowDesignerTableCodeActionsButton ' + (editItem == item ? 'is-active' : '')"
                       @click="showjson('Value', item)"></el-button>
            <el-button class="WorkflowDesignerTableDeleteButton " @click="remove(index)"></el-button>
          </el-button-group>
        </td>
      </tr>
    </table>
  </div>
</el-form>

<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 customforms_basicsplugin_createprocessform_Data(me) {
    return {
      customTitle: undefined,
      readonly: false,
      editItem: undefined,
      FormData: {},
      Field: {},
      items: []
    }
  }

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

    methods.UpdateLanguage = function () {
      Object.assign(data, {
        labels: WorkflowDesignerConstants.EditParametersFormlabel,
        customLabels: WorkflowDesignerConstants.EditParametersFormlabel.CustomForms.CreateProcess,
        ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
        ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
        ButtonTextCreate: WorkflowDesignerConstants.ButtonTextCreate,
      })
    }

    methods.UpdateLanguage();

    methods.onUpdate = function (value) {
      data.readonly = me.graph.Settings.readonly;

      if (me.options && me.options.customTitle) {
        data.customTitle = me.options.customTitle;
      }

      var fields = undefined;
      var parameterDefinition = me.options.parameterDefinition;

      if (parameterDefinition && parameterDefinition.name) {
        for (var i = 0; i < parameterDefinition.type.length; i++) {
          fields = me.graph.getActionParameterDefinition(parameterDefinition.name, parameterDefinition.type[i]);
          if (fields && fields.length > 0)
            break;
        }
      } else if (Array.isArray(me.options.parameterDefinition)) {
        fields = me.options.parameterDefinition;
      }

      if (fields && fields.length > 0) {
        fields.forEach(function (field) {
          field.Label = field.Title ? field.Title : field.Name;
          if (field.Comment && field.Comment !== '') {
            field.Label = field.Label + ' (' + field.Comment + ')';
          }

          data.Field[field.Name] = field;
        });

        if (!value && !data.readonly) {
          var tmp = {};

          fields.forEach(function (field) {
            if (field.Type === 'Checkbox') {
              field.DefaultValue = field.DefaultValue !== null && field.DefaultValue !== undefined && field.DefaultValue.toString() === 'true';
            }

            if (typeof field.DefaultValue != 'undefined') {
              tmp[field.Name] = field.DefaultValue;
            } else {
              tmp[field.Name] = null;
            }
          });

          value = WorkflowDesignerCommon.toString(tmp);
        }
      }

      data.FormData = WorkflowDesignerCommon.toJSON(value);

      if (!data.FormData)
        data.FormData = {};

      for (var key in data.FormData) {
        if (key !== '__customtype' && data.FormData.hasOwnProperty(key))
          if (!data.Field.hasOwnProperty(key))
            delete data.FormData[key];
      }

      data.FormData = me.graph.insertDefaultValuesInForm(data.Field, data.FormData);

      var params = JSON.parse(data.FormData.ProcessCreationParameters);
      if (params != null) {
        data.items = []
        params.forEach(function (item) {
          var purpose = item.persist ? 'Persistence' : 'Temporary';
          data.items.push({'Purpose': purpose, 'Value': item.value, 'Name': item.name});
        });
      }
    };

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

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

    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 != '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.remove = function (index) {
      data.items.splice(index, 1);
    };

    methods.getFieldRules = function (field) {
      return field?.IsRequired ? me.requiredRule() : [];
    };

    methods.onSave = function () {

      data.FormData.ProcessCreationParameters = [];

      data.items.forEach(function (item) {
        data.FormData.ProcessCreationParameters.push({
          'persist': item.Purpose == 'Persistence',
          'value': item.Value,
          'name': item.Name
        });
      });

      data.FormData.ProcessCreationParameters = JSON.stringify(data.FormData.ProcessCreationParameters).toString();

      var value = WorkflowDesignerCommon.toString(data.FormData);
      this.$refs.form.validate(function (valid) {
        if (valid) {
          me.onSuccess(WorkflowDesignerCommon.toCompactJSON(value));
          me.onClose(true);
        }
      });
    };

    methods.onClose = function () {
      me.onClose(true);
    };
  }
</script>
