<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="Field.Name.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="Field?.State?.Name"
        :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" style="display: flex">
      <el-form-item
        :label="customLabels.LoopName"
        :prop="Field?.LoopName?.Name"
        :rules="getFieldRules(Field.LoopName)"
        class="el-form-item"
        style="flex-grow: 1;">
        <el-input v-model="FormData.LoopName" :readonly="readonly"></el-input>
      </el-form-item>
      <el-form-item
        :label="customLabels.LoopStateParameterName"
        :prop="Field?.LoopStateParameterName?.Name"
        :rules="getFieldRules(Field?.LoopStateParameterName)"
        class="el-form-item"
        style="flex-grow: 1;">
        <el-input v-model="FormData.LoopStateParameterName" :readonly="readonly"></el-input>
      </el-form-item>
    </div>


    <el-form-item
      :label="customLabels.LoopCounterValueParameterName"
      :prop="Field?.LoopCounterValueParameterName?.Name"
      :rules="getFieldRules(Field.LoopCounterValueParameterName)">
      <el-input v-model="FormData.LoopCounterValueParameterName" :readonly="readonly"></el-input>
    </el-form-item>

  </div>

  <table class="WorkflowDesignerTable" style="margin-bottom: 10px">
    <tr>
      <th></th>
      <th class="WorkflowDesignerTitleWithCreate">
        {{ customLabels.Values }}
        <span :style="{color: isRequiredColor ,marginRight:'4px'}">*</span>
        <a v-if="!readonly" @click="addValue(values)">{{ ButtonTextCreate }}</a>
      </th>
    </tr>
    <template v-for="(value, index) in values" :key="index">
      <tr :class="dragOverIndex == index && dragOverBlock  == value ? 'dragOver' : ''"
          @dragend="dragend($event)"
          @dragover="dragover(value, index, $event)"
          @dragstart="dragstart(index, $event, values)">

        <td :draggable="!readonly" class='WorkflowDesignerTableMoveCol'>
          <div v-if="!readonly" class='WorkflowDesignerTableMoveButton'></div>
        </td>
        <td style="position: relative">
          <el-input v-model="value.value" :readonly="readonly" :rules="{ required: true, message: FieldIsRequired, trigger: 'change'}"
                    clearable
                    style="width: 100%;"></el-input>
          <div v-if="index == values.length -1 && !isCorrectValues" class="el-form-item__error">{{ customLabels.ValuesError }}</div>
        </td>
        <td v-if="!readonly && values.length > 1">
          <el-button class="WorkflowDesignerTableDeleteButton" @click="removeRow(values, index)"></el-button>
        </td>
      </tr>
    </template>
  </table>

  <div :class="Field.State != undefined ?'SettingsWithPadding' : '' " style="margin-bottom: 10px;">
    <el-form-item
      :prop="Field?.Reverse?.Name"
      :rules="getFieldRules(Field.Reverse)">
        <template #label>{{ customLabels.Reverse }}
            <span
              :style="parameterFromProcess.Reverse ? {color:parameterFromProcessColor}: {}"
              class="WorkflowDesignerParameterFromProcess"
              @click="Reverse">@
            </span>
        </template>
      <el-checkbox
        v-if="!parameterFromProcess.Reverse"
        v-model="FormData.Reverse"
        :disabled="readonly"
        style="width:200px">
      </el-checkbox>
      <el-input v-if="parameterFromProcess.Reverse" v-model="FormData.Reverse" :disabled="readonly" style="width:200px"></el-input>
    </el-form-item>
  </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_loopsplugin_startloopforeachform_Data(me) {
    return {
      customTitle: undefined,
      readonly: false,
      FormData: {},
      Field: {},
      parameterFromProcess: {
        Reverse: false
      },
      values: [{value: ''}],
      separator: null,
      isCorrectValues: true
    }
  }

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

    methods.UpdateLanguage = function () {
      Object.assign(data, {
        FieldIsRequired: WorkflowDesignerConstants.FieldIsRequired,
        ButtonTextCreate: WorkflowDesignerConstants.ButtonTextCreate,
        labels: WorkflowDesignerConstants.EditParametersFormlabel,
        customLabels: WorkflowDesignerConstants.EditParametersFormlabel.CustomForms.StartLoopForeach,
        ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
        ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
        isRequiredColor: WorkflowDesignerConstants.IsRequiredColor,
        parameterFromProcessColor: WorkflowDesignerConstants.ParameterFromProcessColor,
      })
    }

    methods.UpdateLanguage();

    methods.Reverse = function () {
      data.FormData.Reverse = data.parameterFromProcess.Reverse ? false : null;
      methods.changeParameterInput('Reverse')
    }

    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 (const key in data.FormData) {
        if (typeof data.parameterFromProcess[key] !== 'undefined' && WorkflowDesignerCommon.containsAt(data.FormData[key]))
          data.parameterFromProcess[key] = true;
        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);

      methods.initializeData();
    };

    methods.initializeData = function () {
      var separator = data.FormData.Separator;
      var values = data.FormData.Values;

      data.separator = separator != null ? separator : ',';
      if (data.FormData.Values != null) {
        data.values = [];

        var list = values.split(data.separator);
        for (var i = 0; i < list.length; i++) {
          data.values.push({value: list[i]});
        }
      }
    }

    methods.changeParameterInput = function (fieldName) {
      data.parameterFromProcess[fieldName] = !data.parameterFromProcess[fieldName];
    }

    methods.getFieldRules = function (field) {
      var rules = field?.IsRequired ? me.requiredRule() : [{required: false}];

      if (data.parameterFromProcess[field?.Name]) {
        rules.push(WorkflowDesignerCommon.containsAtRule);
      }

      return rules;
    };

    methods.addValue = function (items) {
      items.push({value: ''});
    };

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

    methods.onSave = function () {
      var isValid = true;
      var stringValues = [];
      data.values.forEach(function (valueObj) {
        if (valueObj.value != '') {
          stringValues.push(valueObj.value);
        } else {
          isValid = false;
        }
      });
      data.isCorrectValues = isValid;

      data.FormData.Separator = data.separator;
      data.FormData.Values = stringValues.join(data.separator);

      var value = WorkflowDesignerCommon.toString(data.FormData);

      this.$refs.form.validate(function (valid) {
        if (valid && data.isCorrectValues) {
          me.onSuccess(WorkflowDesignerCommon.toCompactJSON(value));
          me.onClose(true);
        }
      });
    };

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