<h3 class="WorkflowDesignerTitleWithCreate">
  {{ labels.Title }}
  <a v-if="!readonly" @click="add()">{{ ButtonTextCreate }}</a>
</h3>
<div id="WorkflowDesignerCodeActionsList" class="WorkflowDesignerWindowForm">
  <b class="CustomLabel">{{ labels.CommonUsings }}</b>
  <el-select
    v-model="UsingsValue"
    :title="labels.CommonUsings"
    allow-create
    collapse-tags
    filterable
    multiple
    placeholder="Select"
    style="width: 100%; margin-bottom: 15px;"
    @change="onUsingsChange">
    <el-option
      v-for="item in Usings"
      :key="item"
      :label="item"
      :value="item">
    </el-option>
  </el-select>
  <table class="WorkflowDesignerTable">
    <tr>
      <th></th>
      <th>{{ labels.Name }}</th>
      <th>{{ labels.Type }}</th>
      <th>{{ labels.IsGlobal }}</th>
      <th>{{ labels.IsAsync }}</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"
          :title="validateField('Name', item)"
        ></el-input>
      </td>
      <td>
        <el-select
          v-model="item.Type"
          :class="validateField('Type', item) ? 'WorkflowDesignerInputError' : ''"
          :disabled="readonly"
          :title="validateField('Type', item)"
          filterable
          placeholder=""
          style="width: 100%;">
          <el-option key="Action" label="Action" value="Action"></el-option>
          <el-option key="Condition" label="Condition" value="Condition"></el-option>
          <el-option key="RuleGet" label="RuleGet" value="RuleGet"></el-option>
          <el-option key="RuleCheck" label="RuleCheck" value="RuleCheck"></el-option>
        </el-select>
      </td>
      <td>
        <el-checkbox v-model="item.IsGlobal" :readonly="readonly" @change="isGlobalOnChange(item)"></el-checkbox>
      </td>
      <td>
        <el-checkbox v-model="item.IsAsync" :readonly="readonly"></el-checkbox>
      </td>
      <td v-if="!readonly" class="WorkflowDesignerTableEditButtons Triple">
        <el-button-group>
          <el-button :class="'WorkflowDesignerTableCodeActionsButton ' + (editCodeItem == item ? 'is-active' : '')"
                     v-on:click="showcode(item)"></el-button>
          <el-button :class="'WorkflowDesignerTableCodeParametersButton ' + (editParametersItem == item ? 'is-active' : '')"
                     v-on:click="showparameters(item)"></el-button>
          <el-button class="WorkflowDesignerTableDeleteButton" v-on:click="remove(index, item)"></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 codeactions_Data(me) {
    return {
      readonly: false,
      editItem: undefined,
      Usings: null,
      UsingsValue: null,
      editCodeItem: undefined,
      editParametersItem: undefined,
      items: []
    }
  }

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

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

    methods.UpdateLanguage();

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

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

      data.Usings = WorkflowDesignerCommon.clone(me.graph.data.AdditionalParams.Usings);
      var commonUsings = me.graph.data.CodeActionsCommonUsings ?
        me.graph.data.CodeActionsCommonUsings.split(';').filter(function (using) {
          return using !== ''
        }) :
        me.graph.data.AdditionalParams.Usings;
      data.UsingsValue = WorkflowDesignerCommon.clone(commonUsings);
      methods.onUsingsChange(data.UsingsValue);
    };

    methods.onUsingsChange = function (values) {
      values.forEach(function (value) {
        if (!data.Usings.includes(value)) {
          data.Usings.push(value);
        }
      });
      data.Usings.sort();
    };

    methods.add = function () {
      data.items.push({Name: '', Type: 'Action', ParameterDefinitions: [], IsAsync: false, IsGlobal: false});

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

    methods.remove = function (index, item) {
      if (item.IsGlobal) {
        me.graph.showConfirm({
          message: WorkflowDesignerConstants.CodeActionsFormLabel.GlobalDeleteMessage, onSuccess: function () {
            data.items.splice(index, 1);
            return true;
          }
        });
      } else {
        data.items.splice(index, 1);
      }
    };
    methods.isGlobalOnChange = function (item) {
      if (!item.IsGlobal) {
        me.graph.showConfirm({
            message: WorkflowDesignerConstants.CodeActionsFormLabel.UnGlobalMessage,
            isAlert: true,
            onSuccess: function () {
              return true;
            }
          }
        );
      }
    };
    methods.showcode = function (item) {

      data.editCodeItem = me.editCodeItem = item;

      var windowId = me.id + '_codeform';

      var onSuccess = function (res) {
        if (me.editCodeItem) {
          me.editCodeItem['ActionCode'] = res.ActionCode;
          me.editCodeItem['Usings'] = res.Usings;
          me.editCodeItem['ExcludedUsings'] = res.ExcludedUsings;
          data.editCodeItem = undefined;
          delete me.editCodeItem;
        }
      };

      var onClose = function () {
        if (me.editCodeItem) {
          data.editCodeItem = undefined;
          delete me.editCodeItem;
        }
      }

      if (!me.codeform) {
        var options = {
          move: true,
          resize: true,
          savePosition: true,
          class: 'WorkflowDesignerCodeForm',
          onSuccess: onSuccess,
          onClose: onClose,
          parameterDefinition: {}
        };
        me.codeform = me.graph.CreateWindow(windowId, options);
      }

      me.codeform.show('codeform', {item: item, commonUsings: data.UsingsValue});
    };

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

      var windowId = me.id + '_parametersform';

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


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

      if (!item[name]) {
        return WorkflowDesignerConstants.FieldIsRequired;
      }

      if (name == 'Name') {
        var res = data.items.filter(function (i) {
          return i != item && i.Name == item.Name && item.Type == i.Type
        });
        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('Type', item))
          return false;
      }

      return true;
    };

    methods.getGlobalCodeActionsForDelete = function (original, target) {
      var names = [];
      original.forEach(function (ca) {
        if (ca.IsGlobal) {
          var isSameName = false;
          for (var i = 0; i < original.length; i++) {
            if (ca.Name == original[i].Name && ca.IsGlobal != original[i].IsGlobal) {
              isSameName = true;
              break;
            }
          }

          var isFind = false;
          for (var i = 0; i < target.length; i++) {
            if (isSameName) {
              if (ca.Name == target[i].Name && target[i].IsGlobal) {
                isFind = true;
                break;
              }
            } else {
              if (ca.Name == target[i].Name) {
                isFind = true;
                break;
              }
            }
          }

          if (!isFind)
            names.push(ca.Name);
        }
      });
      return names;
    }
    methods.onSave = function () {
      if (!(methods.validate && methods.validate())) {
        return;
      }

      for (var j = 0; j < data.items.length; j++) {
        var dataItem = data.items[j];
        if (typeof dataItem.ActionCode === 'undefined') {
          if (dataItem.Type === 'Action') {
            dataItem.ActionCode = 'return;'
          } else if (dataItem.Type === 'Condition') {
            dataItem.ActionCode = 'return false;'
          } else if (dataItem.Type === 'RuleGet') {
            dataItem.ActionCode = 'return new List<string>();'
          } else if (dataItem.Type === 'RuleCheck') {
            dataItem.ActionCode = 'return false;'
          }
        }

        if (typeof dataItem.Usings === 'undefined') {
          dataItem.Usings = '';
        }
      }

      var names = methods.getGlobalCodeActionsForDelete(me.graph.data.CodeActions, data.items);
      if (names.length > 0) {
        me.graph.designer.deleteGlobalCodeAction(names);
      }

      me.graph.UpdateData(me.graph.data.CodeActions, data.items);

      var usingsString = data.UsingsValue.join(';');
      if (usingsString !== '') {
        usingsString += ';'; //for unification with legacy usings
      }
      me.graph.data.CodeActionsCommonUsings = usingsString;
      me.graph.StoreGraphData();
      me.onClose(true);
    };

    methods.onClose = function () {

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

      if (!data.readonly && !WorkflowDesignerCommon.compareArray(
        me.graph.data.CodeActions,
        data.items,
        ['Name', 'Type', 'IsAsync', 'IsGlobal', 'Usings', 'ActionCode', 'ParameterDefinitions'])) {

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

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

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