<h3 class="WorkflowDesignerTitleWithCreate">
  {{ name }}
  {{ labels.EditParameters }}
  <a v-if="!readonly" @click="add()">{{ ButtonTextCreate }}</a>
</h3>
<div id="WorkflowDesignerCodeActionsParametersList" class="WorkflowDesignerWindowForm">
  <table class="WorkflowDesignerTable">
    <tr>
      <th></th>
      <th>{{ labels.Name }}</th>
      <th>{{ labels.TitleField }}</th>
      <th>
        <div>
          {{ labels.Type }}
          <el-tooltip :content="labels.CustomTypeHint" placement="right" effect="light">
            <template #content>
              <div style="max-width: 300px">
                {{ labels.CustomTypeHint }}
                <a target="_blank" href="https://workflowengine.io/documentation/designer-customization/custom-activity#custom-form">
                  {{ labels.ReadMore }}
                </a>
              </div>
            </template>
            <template #default>
              <el-icon size="14px" class="header-info-icon">
                <icon-question-filled></icon-question-filled>
              </el-icon>
            </template>
          </el-tooltip>
        </div>
      </th>
      <th>{{ labels.IsRequired }}</th>
      <th>{{ labels.DefaultValue }}</th>
      <th>{{ showValuesLabel() ? labels.Values : '' }}</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) && items.length > 1? 'WorkflowDesignerInputError' : ''"
                  :readonly="readonly" :title="items.length > 1? validateField('Name', item):''"></el-input>
      </td>
      <td>
        <el-input v-model="item.Title" :readonly="readonly"></el-input>
      </td>
      <td>
        <el-select
          v-model="item.Type" :class="validateField('Type', item) ? 'WorkflowDesignerInputError' : ''"
          :title="validateField('Type', item)" :disabled="readonly" filterable
          @change="typeOnChange(item)" allow-create
          placeholder="" style="width: 100%;">
          <el-option v-for="type in types" :key="type" :label="labels[type]" :value="type"></el-option>
        </el-select>
      </td>
      <td>
        <el-checkbox
          v-model="item.IsRequired"
          :readonly="readonly"
        ></el-checkbox>
      </td>
      <td>
        <el-input v-if="item.Type == 'Text' || item.Type == 'Json' || !types.includes(item.Type)" v-model="item.DefaultValue"
                  :readonly="readonly"></el-input>
        <el-input-number v-if="item.Type == 'Number'" v-model="item.DefaultValue" :readonly="readonly"
                         controls-position="right"></el-input-number>
        <el-checkbox v-if="item.Type == 'Checkbox'" v-model="item.DefaultValue" :readonly="readonly"></el-checkbox>
        <el-input v-if="item.Type == 'TextArea'" v-model="item.DefaultValue" :readonly="readonly" :rows="4" type="textarea">
        </el-input>

        <el-date-picker
          v-if="item.Type == 'DateTime'"
          v-model="item.DefaultValue"
          :readonly="readonly"
          type="datetime">
        </el-date-picker>
        <el-date-picker
          v-if="item.Type == 'Date'"
          v-model="item.DefaultValue"
          :readonly="readonly"
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD">
        </el-date-picker>
        <el-time-picker
          v-if="item.Type == 'Time'"
          v-model="item.DefaultValue"
          :picker-options="{
                            selectableRange: '00:00:00 - 23:59:59'
                        }"
          :readonly="readonly"
          value-format="HH:mm:ss">
        </el-time-picker>

        <el-select v-if="item.Type == 'Dropdown'" v-model="item.DefaultValue" :disabled="readonly" filterable placeholder="" clearable
                   style="width: 100%;">
          <el-option
            v-for="item in item.DropdownValues"
            :key="item.Value"
            :label="item.Name"
            :value="item.Value">
          </el-option>
        </el-select>
        <el-select v-if="item.Type == 'MultiSelect'" v-model="item.DefaultValue" :disabled="readonly" filterable multiple placeholder=""
                   style="width: 100%;">
          <el-option
            v-for="v in item.DropdownValues"
            :key="v.Value"
            :label="v.Name"
            :value="v.Value">
          </el-option>
        </el-select>
      </td>
      <td v-if="!readonly" class="WorkflowDesignerTableEditButtons Double">
        <el-button-group>
          <el-button v-if="item.Type == 'Dropdown' || item.Type == 'MultiSelect' "
                     :class="'WorkflowDesignerTableCodeParametersButton ' + (editParametersItem == item ? 'is-active' : '')"
                     @click="showDropdownValuesWindow(item)"></el-button>
          <el-button v-if="item.Type == 'Json'" :class="'WorkflowDesignerTableCodeActionsButton ' + (editItem == item ? 'is-active' : '')"
                     @click="showjson('DefaultValue', 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 parametersform_Data(me) {
    const types = WorkflowDesignerConstants.ParameterTypes;

    return {
      readonly: false,
      name: '',
      editParametersItem: undefined,
      editItem: undefined,
      types: Object.keys(types).filter(type => type !== types.Custom),
      items: []
    }
  }

  function parametersform_Init(me) {
    const {VueConfig, graph} = me;
    const {state: data, methods} = VueConfig;
    const types = WorkflowDesignerConstants.ParameterTypes;

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

    methods.UpdateLanguage();

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

    methods.typeOnChange = function (item) {
      item.DefaultValue = undefined;
    }

    methods.onUpdate = function (parentItem) {
      me.parentItem = parentItem;
      data.items = WorkflowDesignerCommon.clone(parentItem.ParameterDefinitions);
      data.items.forEach(function (item) {
        const {DefaultValue, Type} = item;
        if (Type === types.MultiSelect && typeof DefaultValue === 'string') {
          item.DefaultValue = WorkflowDesignerCommon.toJSON(DefaultValue);
        } else if (Type === types.Dropdown && DefaultValue !== null && typeof DefaultValue !== 'string') {
          item.DefaultValue = WorkflowDesignerCommon.toString(DefaultValue);
        } else if (Type === types.DateTime && DefaultValue !== null) {
          item.DefaultValue = new Date(item.DefaultValue)
        }

        if (Type === types.Custom) {
          item.Type = item.CustomName;
        }
      });

      data.name = parentItem.Name;
      data.readonly = me.graph.Settings.readonly;
    };

    methods.add = function () {
      data.items.push({Name: '', Title: '', Type: types.Text, DropdownValues: [], IsRequired: false, DefaultValue: null});

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

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

    methods.showValuesLabel = function () {
      for (var i = 0; i < data.items.length; i++) {
        if (data.items[i].Type === types.Dropdown
          || data.items[i].Type === types.MultiSelect
          || data.items[i].Type === types.Json) {
          return true;
        }
      }
      return false;
    };

    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 = {
        name: item['Rule'],
        type: ['RuleCheck', 'RuleGet']
      };
      data.jsonform = me.showjson(item[name], params, onSuccess, onClose);
    };

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

      if ((name !== 'DefaultValue') && (!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)) {
          if (items.length > 1) {
            return false;
          }
        }

        if (validateFunc('Type', item))
          return false;

        if (validateFunc('DefaultValue', item))
          return false;
      }

      return true;
    };

    methods.onSave = function () {
      data.items.forEach(function (item) {
        const {DefaultValue, Type} = item;
        if (DefaultValue) {
          if (Type === types.Date || Type === types.Time) {
            item.DefaultValue = DefaultValue.toString();
          } else if (Type === types.DateTime) {
            item.DefaultValue = DefaultValue.toISOString();
          }
        }

        if (!Object.keys(types).includes(Type)) {
          item.CustomName = Type;
          item.Type = types.Custom;
        }
      });

      if (methods.validate && methods.validate()) {
        me.onSuccess(data.items);
        me.onClose(true);
      }
    };

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

      if (WorkflowDesignerCommon.compareArray(
        me.parentItem.ParameterDefinitions,
        data.items,
        ['Name', 'Title', 'Type', 'DefaultValue', 'DropdownValues', 'IsRequired'])) {

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

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

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

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

      var windowId = me.id + '_dropdownValues';

      var onSuccess = function (res) {
        if (me.editParametersItem) {
          me.editParametersItem = 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: 'WorkflowDesignerDropdownValues',
          onSuccess: onSuccess,
          onClose: onClose,
          parameterDefinition: {}
        };
        me.parametersform = me.graph.CreateWindow(windowId, options);
      }

      me.parametersform.show('dropdownValues', item);
    };
  }
</script>
