<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"
        :rules="getFieldRules('Name')"
        class="el-form-item"
        prop="Name"
        style="flex-grow: 1;">
        <el-input v-model="FormData.Name" :readonly="readonly"></el-input>
      </el-form-item>

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

    <div class="el-form--inline el-form--label-top" style="display: flex">
      <el-form-item
        :label="customLabels.LoopCounterValueParameterName"
        :rules="getFieldRules('LoopCounterValueParameterName')"
        class="el-form-item"
        prop="LoopCounterValueParameterName"
        style="flex-grow: 1;">
        <el-input v-model="FormData.LoopCounterValueParameterName" :readonly="readonly"></el-input>
      </el-form-item>
      <el-form-item
        :label="customLabels.CounterType"
        :rules="getFieldRules('CounterType')"
        class="el-form-item"
        prop="CounterType"
        style="flex-grow: 1;">
        <el-select v-model="FormData.CounterType" :disabled="readonly" placeholder="" @change="updateDropdowns()">
          <el-option
            v-for="item in Field.CounterType.DropdownValues"
            :key="item.Value"
            :label="item.Name"
            :value="item.Value">
          </el-option>
        </el-select>
      </el-form-item>
    </div>

    <div v-if="FormData.CounterType == 'Int'" class="el-form--inline el-form--label-top" style="display: flex; flex-wrap: wrap">
      <el-form-item :rules="getFieldRules('StartValue')" prop="StartValue">
                <span slot="label">{{ customLabels.StartValue }}
                    <span :style="parameterFromProcess.StartValue ? {color:parameterFromProcessColor}: {}"
                          class="WorkflowDesignerParameterFromProcess"
                          @click="function(){FormData.StartValue = null; changeParameterInput('StartValue')}">@
                    </span>
                </span>
        <el-input v-if="!parameterFromProcess.StartValue" v-model="FormData.StartValue" :disabled="readonly" style="width:180px"
                  type="number"></el-input>
        <el-input v-if="parameterFromProcess.StartValue" v-model="FormData.StartValue" :disabled="readonly" style="width:180px"></el-input>
      </el-form-item>
      <el-form-item :rules="getFieldRules('EndValue')" prop="EndValue">
                <span slot="label">{{ customLabels.EndValue }}
                    <span :style="parameterFromProcess.EndValue ? {color:parameterFromProcessColor}: {}"
                          class="WorkflowDesignerParameterFromProcess"
                          @click="function(){FormData.EndValue = null; changeParameterInput('EndValue')}">@
                    </span>
                </span>
        <el-input v-if="!parameterFromProcess.EndValue" v-model="FormData.EndValue" :disabled="readonly" style="width:180px"
                  type="number"></el-input>
        <el-input v-if="parameterFromProcess.EndValue" v-model="FormData.EndValue" :disabled="readonly" style="width:180px"></el-input>
      </el-form-item>
      <el-form-item :rules="getFieldRules('Step')" prop="Step">
                <span slot="label">{{ customLabels.Step }}
                    <span :style="parameterFromProcess.Step ? {color:parameterFromProcessColor}: {}"
                          class="WorkflowDesignerParameterFromProcess"
                          @click="function(){FormData.Step = null; changeParameterInput('Step')}">@
                    </span>
                </span>
        <el-input v-if="!parameterFromProcess.Step" v-model="FormData.Step" :disabled="readonly" style="width:180px"
                  type="number"></el-input>
        <el-input v-if="parameterFromProcess.Step" v-model="FormData.Step" :disabled="readonly" style="width:180px"></el-input>
      </el-form-item>
    </div>

    <div v-if="FormData.CounterType == 'DateTime'" class="el-form--inline el-form--label-top">
      <el-form-item
        v-if="!(parameterFromProcess.EndValue || parameterFromProcess.StartValue)"
        :rules="getDateRangeRules()"
        prop="DateRange">
                <span slot="label">{{ customLabels.DateRange }}
                    <span
                      class="WorkflowDesignerParameterFromProcess"
                      @click="function(){FormData.DateRange =['',''];parameterFromProcess.EndValue = true; parameterFromProcess.StartValue = true}">@
                    </span>
                </span>
        <el-date-picker
          v-model="FormData.DateRange"
          :end-placeholder="customLabels.EndDate"
          :range-separator="customLabels.RangeSeparator"
          :readonly="readonly"
          :start-placeholder="customLabels.StartDate"
          type="datetimerange">
        </el-date-picker>
      </el-form-item>

      <el-form-item
        v-if="parameterFromProcess.StartValue || parameterFromProcess.EndValue "
        :rules="getFieldRules('StartValue')"
        prop="StartValue">
                <span slot="label">{{ customLabels.StartValue }}
                    <span
                      :style="parameterFromProcess.StartValue ? {color:parameterFromProcessColor}: {}"
                      class="WorkflowDesignerParameterFromProcess"
                      @click="function(){FormData.DateRange[0] = ''; parameterFromProcess.StartValue = !parameterFromProcess.StartValue}">@
                    </span>
                </span>
        <el-date-picker
          v-if="!parameterFromProcess.StartValue"
          v-model="FormData.DateRange[0]"
          :readonly="readonly"
          :required="true"
          style="width:200px"
          type="datetime">
        </el-date-picker>
        <el-input v-if="parameterFromProcess.StartValue" v-model="FormData.DateRange[0]" :disabled="readonly"
                  style="width:200px"></el-input>
      </el-form-item>

      <el-form-item
        v-if="parameterFromProcess.StartValue || parameterFromProcess.EndValue"
        :rules="getFieldRules('EndValue')"
        prop="EndValue">
                <span slot="label">{{ customLabels.EndValue }}
                    <span :style="parameterFromProcess.EndValue ? {color:parameterFromProcessColor}: {}"
                          class="WorkflowDesignerParameterFromProcess"
                          @click="function(){FormData.DateRange[1] = '';parameterFromProcess.EndValue = !parameterFromProcess.EndValue}">@
                    </span>
                </span>
        <el-date-picker
          v-if="!parameterFromProcess.EndValue"
          v-model="FormData.DateRange[1]"
          :readonly="readonly"
          :required="true"
          style="width:200px"
          type="datetime">
        </el-date-picker>
        <el-input v-if="parameterFromProcess.EndValue" v-model="FormData.DateRange[1]" :disabled="readonly" style="width:200px"></el-input>
      </el-form-item>
      <el-form-item
        :label="customLabels.Step"
        :rules="getDateStepRules()"
        prop="Step">
        <el-input v-model="FormData.Step" :readonly="readonly">
        </el-input>
      </el-form-item>
    </div>

    <div class="el-form--inline el-form--label-top">
      <el-form-item :rules="getFieldRules('StepType')" prop="StepType">
                <span slot="label">{{ customLabels.StepType }}
                    <span
                      :style="parameterFromProcess.StepType ? {color:parameterFromProcessColor}: {}"
                      class="WorkflowDesignerParameterFromProcess"
                      @click="function(){FormData.StepType =parameterFromProcess.StepType ? Field.StepType.DropdownValues[0].Value : null; changeParameterInput(Field.StepType.Name)}">@
                    </span>
                </span>
        <el-select v-if="!parameterFromProcess.StepType" v-model="FormData.StepType" :disabled="readonly" style="width:180px">
          <el-option
            v-for="item in Field.StepType.DropdownValues"
            :key="item.Value"
            :label="item.Name"
            :value="item.Value">
          </el-option>
        </el-select>
        <el-input v-if="parameterFromProcess.StepType" v-model="FormData.StepType" :disabled="readonly" style="width:180px"></el-input>
      </el-form-item>
      <el-form-item :rules="getFieldRules('IncludeLastValue')" prop="IncludeLastValue">
                <span slot="label">{{ customLabels.IncludeLastValue }}
                    <span
                      :style="parameterFromProcess.IncludeLastValue ? {color:parameterFromProcessColor}: {}"
                      class="WorkflowDesignerParameterFromProcess"
                      @click="function(){FormData.IncludeLastValue = parameterFromProcess.IncludeLastValue ? false : null; parameterFromProcess.IncludeLastValue = !parameterFromProcess.IncludeLastValue}">@
                    </span>
                </span>
        <el-checkbox
          v-if="!parameterFromProcess.IncludeLastValue"
          v-model="FormData.IncludeLastValue"
          :disabled="readonly"
          style="width:180px">
        </el-checkbox>
        <el-input v-if="parameterFromProcess.IncludeLastValue" v-model="FormData.IncludeLastValue" :disabled="readonly"
                  style="width:180px"></el-input>
      </el-form-item>
    </div>
  </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_startloopforform_Init(me) {
    me.VueConfig.methods.UpdateLanguage = function () {
      me.VueConfig.data = Object.assign(me.VueConfig.data, {
        labels: WorkflowDesignerConstants.EditParametersFormlabel,
        customLabels: WorkflowDesignerConstants.EditParametersFormlabel.CustomForms.StartLoopFor,
        ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
        ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
        parameterFromProcessColor: WorkflowDesignerConstants.ParameterFromProcessColor,
      })
    }

    me.VueConfig.methods.UpdateLanguage();
    me.VueConfig.data = Object.assign(me.VueConfig.data, {
      customTitle: undefined,
      readonly: false,
      FormData: {},
      Field: {},
      parameterFromProcess: {
        StartValue: false,
        EndValue: false,
        Step: false,
        StepType: false,
        IncludeLastValue: false
      },
    });

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

      if (me.options && me.options.customTitle) {
        me.VueConfig.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.FromProcess = false;
          field.Label = field.Title ? field.Title : field.Name;
          if (field.Comment && field.Comment !== '') {
            field.Label = field.Label + ' (' + field.Comment + ')';
          }

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

        if (!value && !me.VueConfig.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);
        }
      }

      me.VueConfig.data.FormData = WorkflowDesignerCommon.toJSON(value);

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

      for (key in me.VueConfig.data.FormData) {
        if (me.VueConfig.data.parameterFromProcess[key] != undefined && WorkflowDesignerCommon.containsAt(me.VueConfig.data.FormData[key]))
          me.VueConfig.data.parameterFromProcess[key] = true;
        if (key !== '__customtype' && me.VueConfig.data.FormData.hasOwnProperty(key))
          if (!me.VueConfig.data.Field.hasOwnProperty(key))
            delete me.VueConfig.data.FormData[key];
      }

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

      me.VueConfig.methods.initializeData();
    };

    me.VueConfig.methods.updateDropdowns = function () {
      for (key in me.VueConfig.data.parameterFromProcess) {
        me.VueConfig.data.parameterFromProcess[key] = false;
      }

      me.VueConfig.data.FormData.DateRange = '';
      me.VueConfig.data.FormData.StartValue = '';
      me.VueConfig.data.FormData.EndValue = '';
      me.VueConfig.data.FormData.Step = '';
    }

    me.VueConfig.methods.initializeData = function () {
      var counterType = me.VueConfig.data.FormData.CounterType;
      var step = me.VueConfig.data.FormData.Step;
      var stepType = me.VueConfig.data.FormData.StepType;
      var endValue = me.VueConfig.data.FormData.EndValue;
      var startValue = me.VueConfig.data.FormData.StartValue;
      if (counterType == 'DateTime') {
        var endValueDate = me.VueConfig.data.parameterFromProcess.EndValue ? endValue : new Date(endValue);
        var startValueDate = me.VueConfig.data.parameterFromProcess.StartValue ? startValue : new Date(startValue);

        me.VueConfig.data.FormData.Step = step;
        if (stepType == 'Decrement') {
          me.VueConfig.data.FormData.DateRange = [endValueDate, startValueDate];
        } else {
          me.VueConfig.data.FormData.DateRange = [startValueDate, endValueDate];
        }
      }

      if (counterType == 'Int') {
        me.VueConfig.data.FormData.StartValue = startValue != null ? startValue : '';
        me.VueConfig.data.FormData.EndValue = endValue != null ? endValue : '';
        me.VueConfig.data.FormData.Step = step != null ? step : '';
        me.VueConfig.data.FormData.DateRange = '';
      }
    }

    me.VueConfig.methods.parameterFromProcess = function (fieldName) {
      if (me.VueConfig.data.Field[fieldName].FromProcess != undefined && me.VueConfig.data.Field[fieldName].FromProcess == true) {
        return true;
      }
      return false;
    }

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

    me.VueConfig.methods.getDateRangeRules = function () {
      var res = [
        {required: true, message: WorkflowDesignerConstants.FieldIsRequired, trigger: ['change', 'blur']}
      ];
      var validator = function (rule, value, callback) {
        var isValid = true;
        var dateRange = me.VueConfig.data.FormData.DateRange;
        if (!dateRange
          || dateRange.length !== 2
          || dateRange.includes(null)
          || dateRange.includes('')
        ) {
          isValid = false;
        }

        if (isValid) {
          callback();
        } else {
          callback(new Error(rule.message));
        }
      };
      res.push({validator: validator, message: WorkflowDesignerConstants.FieldIsRequired, trigger: ['change', 'blur']});
      return res;
    };

    me.VueConfig.methods.getDateStepRules = function () {
      var res = [
        {required: true, message: WorkflowDesignerConstants.FieldIsRequired, trigger: 'blur'}
      ];
      var validator = function (rule, value, callback) {
        var step = me.VueConfig.data.FormData.Step
        if (WorkflowDesignerCommon.containsAt(step)) {
          callback();
          return
        }
        var isValid = true;
        step = step.trim();
        var stepArray = step.split(/\s+/);
        step = stepArray.join(' ');

        var yearsRegex = new RegExp('\d*\s*((years)|(year)|(y))(\W|\d|$)');
        var monthsRegex = new RegExp('\d*\s*((months)|(month)|(mm))(\W|\d|$)');
        var daysRegex = new RegExp('\d*\s*((days)|(day)|(d))(\W|\d|$)');
        var hoursRegex = new RegExp('\d*\s*((hours)|(hour)|(h))(\W|\d|$)');
        var minutesRegex = new RegExp('\d*\s*((minutes)|(minute)|(m))(\W|\d|$)');
        var secondsRegex = new RegExp('\d*\s*((seconds)|(second)|(s))(\W|\d|$)');
        var millisecondsRegex = new RegExp('\d*\s*((milliseconds)|(millisecond)|(ms))(\W|\d|$)');

        var isCorrect = true;
        stepArray.forEach(function (step) {
          isCorrect &= yearsRegex.test(step)
            || monthsRegex.test(step)
            || daysRegex.test(step)
            || hoursRegex.test(step)
            || minutesRegex.test(step)
            || secondsRegex.test(step)
            || millisecondsRegex.test(step);
        });

        if (!(step && isCorrect)) {
          isValid = false;
        }

        if (isValid) {
          callback();
        } else {
          callback(new Error(rule.message));
        }
      };
      res.push({validator: validator, message: WorkflowDesignerConstants.FieldIsNotCorrected, trigger: 'blur'});

      return res;
    };


    me.VueConfig.methods.getFieldRules = function (fieldName) {
      var isRequired = me.VueConfig.data.Field[fieldName].IsRequired;

      var rules = isRequired ? me.requiredRule() : [{required: false}];

      if (me.VueConfig.data.parameterFromProcess[fieldName]) {
        rules.push(WorkflowDesignerCommon.containsAtRule);
      }

      if (isRequired && me.VueConfig.data.FormData.CounterType === 'DateTime' && (fieldName === 'EndValue' || fieldName === 'StartValue')) {
        var validator = function (rule, value, callback) {
          if (value != null && value != '') {
            callback();
          } else {
            callback(new Error(rule.message));
          }
        };
        rules.push({validator: validator, message: WorkflowDesignerConstants.FieldIsRequired});
      }

      return rules;
    };

    me.VueConfig.methods.onSave = function () {

      this.$refs.form.validate(function (valid) {
        if (valid) {
          if (me.VueConfig.data.FormData.CounterType == 'DateTime') {
            var dateFormat = WorkflowDesignerConstants.DateTimeFormat;
            var dateRange = me.VueConfig.data.FormData.DateRange;
            var endValueDate = me.VueConfig.data.parameterFromProcess.EndValue ? dateRange[1] : moment(dateRange[1]).format(dateFormat);
            var startValueDate = me.VueConfig.data.parameterFromProcess.StartValue ? dateRange[0] : moment(dateRange[0]).format(dateFormat);

            if (me.VueConfig.data.FormData.StepType == 'Decrement') {
              me.VueConfig.data.FormData.EndValue = startValueDate;
              me.VueConfig.data.FormData.StartValue = endValueDate
            } else {
              me.VueConfig.data.FormData.EndValue = endValueDate;
              me.VueConfig.data.FormData.StartValue = startValueDate;
            }
          }

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

          me.onSuccess(WorkflowDesignerCommon.toCompactJSON(value));
          me.onClose(true);
        }
      });
    };

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