<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_Init(me){
         me.VueConfig.data = Object.assign(me.VueConfig.data, {
            readonly: false,
            labels: WorkflowDesignerConstants.CodeActionsFormLabel,
            editItem: undefined,
            ButtonTextCreate: WorkflowDesignerConstants.ButtonTextCreate,
            ButtonTextDelete: WorkflowDesignerConstants.ButtonTextDelete,
            ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
            ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
            EditCodeLabel: WorkflowDesignerConstants.EditCodeLabel.EditCodeButton,
            Usings: null,
            UsingsValue: null,
            editCodeItem: undefined,
            editParametersItem: undefined
        });

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

        me.VueConfig.methods.onUpdate = function(){
            var data = me.VueConfig.data;
            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);
      me.VueConfig.methods.onUsingsChange(data.UsingsValue);
    };

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

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

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

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

      me.VueConfig.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;
          me.VueConfig.data.editCodeItem = undefined;
          delete me.editCodeItem;
        }
      };

      var onClose = function () {
        if (me.editCodeItem) {
          me.VueConfig.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: me.VueConfig.data.UsingsValue});
    };

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

      var windowId = me.id + '_parametersform';

      var onSuccess = function (res) {
        if (me.editParametersItem) {
          me.editParametersItem.ParameterDefinitions = WorkflowDesignerCommon.clone(res);
          me.VueConfig.data.editParametersItem = undefined;
          delete me.editParametersItem;
        }
      };

      var onClose = function () {
        if (me.editParametersItem) {
          me.VueConfig.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);
    };


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

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

      if (name == 'Name') {
        var res = me.VueConfig.data.items.filter(function (i) {
          return i != item && i.Name == item.Name && item.Type == i.Type
        });
        if (res.length > 0) {
          return WorkflowDesignerConstants.FieldMustBeUnique;
        }
      }
    };

    me.VueConfig.methods.validate = function () {
      var validateFunc = me.VueConfig.methods.validateField;
      var items = me.VueConfig.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;
    };

        me.VueConfig.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;
    }
        me.VueConfig.methods.onSave = function(){
            if(!(me.VueConfig.methods.validate && me.VueConfig.methods.validate())) {
                return;
            }

            for (var j = 0; j <me.VueConfig.data.items.length; j++) {
                var dataItem = me.VueConfig.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 = me.VueConfig.methods.getGlobalCodeActionsForDelete(me.graph.data.CodeActions, me.VueConfig.data.items);
      if (names.length > 0) {
        me.graph.designer.deleteGlobalCodeAction(names);
      }

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

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

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

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

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

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

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

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