<h3>{{ customTitle ? customTitle : labels.Title }}</h3>
<el-form
        class="WorkflowDesignerWindowForm"
        :model="FormData"
        ref="form"
        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="Field.Name.Label"
                    :rules="getFieldRules(Field.Name)"
                    :prop="customLabels.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"
                    :rules="getFieldRules(Field.State)"
                    :prop="Field.State.Name"
                    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;">
        <el-form-item
                :label="customLabels.Name"
                :rules="getFieldRules(Field.AssignmentName)"
                :prop="Field.AssignmentName.Name">
            <el-input  v-model="FormData.AssignmentName" :readonly="readonly"></el-input>
        </el-form-item>

        <div class="el-form--inline el-form--label-top" style="display: flex">
            <el-form-item
                    :label="customLabels.Code"
                    :rules="getFieldRules(Field.AssignmentCode)"
                    :prop="Field.AssignmentCode.Name"
                    class="el-form-item"
                    style="flex-grow: 4;">
                <el-input  v-model="FormData.AssignmentCode" :readonly="readonly"></el-input>
            </el-form-item>
            <el-form-item
                    :label="customLabels.Executors"
                    :prop="Field.Executors.Name"
                    :rules="getExecutorsRules(executors)"
                    class="el-form-item"
                    style="flex-grow: 4;">
                <el-select
                        @focus="onFocusSelectUser"
                        style="width:100%"
                        :readonly="readonly"
                        v-model="executors"
                        :disabled="readonly"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="getUsers"
                        :loading="loading">
                    <el-option-group>
                        <el-option v-for="item in actors" :key="item" :label="item" :value="{value:item,isActor:true, name: item}"></el-option>
                    </el-option-group>
                    <el-option-group>
                        <el-option
                                v-for="user in userIdentities"
                                :key="user.value"
                                :label="user.label"
                                :value="{value:user.value, isActor:false, name: user.label}">
                        </el-option>
                    </el-option-group>
                </el-select>
            </el-form-item>
            <el-form-item
                    :rules="getFieldRules(Field.IsActive,FormData.IsActive)"
                    :prop="Field.IsActive.Name"
                    class="el-form-item"
                    style="flex-grow: 1;">
                <span slot="label">{{customLabels.IsActive}}
                    <span @click="function(){FormData.IsActive = parameterFromProcess.IsActive ? false : null; parameterFromProcess.IsActive = !parameterFromProcess.IsActive}"
                          :style="parameterFromProcess.IsActive ? {color:parameterFromProcessColor}: {}"
                          class="WorkflowDesignerParameterFromProcess">@
                    </span>
                </span>
                <el-checkbox
                        v-if="!parameterFromProcess.IsActive"
                        v-model="FormData.IsActive"
                        :disabled="readonly"
                        style="width:150px">
                </el-checkbox>
                <el-input v-if="parameterFromProcess.IsActive" v-model="FormData.IsActive" :disabled="readonly" style="width:150px"></el-input>
            </el-form-item>
        </div>

        <el-form-item
                :label="customLabels.Description"
                :rules="getFieldRules(Field.Description)"
                :prop="Field.Description.Name">
            <el-input
                    type="textarea"
                    :rows="3"
                    v-model="FormData.Description"
                    :readonly="readonly"></el-input>
        </el-form-item>

        <div class="el-form--inline el-form--label-top" style="display: flex">
            <el-form-item
                    :label="customLabels.DeadlineToStart"
                    :rules="getDateStepRules(deadlineToStart)"
                    :prop="Field.DeadlineToStart.Name"
                    class="el-form-item"
                    style="flex-grow: 1;">
                <el-input :readonly="readonly" v-model="deadlineToStart">
                </el-input>
            </el-form-item>

            <el-form-item
                    :label="customLabels.DeadlineToComplete"
                    :rules="getDateStepRules(deadlineToComplete)"
                    :prop="Field.DeadlineToComplete.Name"
                    class="el-form-item"
                    style="flex-grow: 1;">
                <el-input :readonly="readonly" v-model="deadlineToComplete">
                </el-input>
            </el-form-item>
        </div>

        <div class="el-form--inline el-form--label-top" style="display: flex">
            <el-form-item
                    style="width:100%"
                    :label="customLabels.Observers"
                    :rules="getFieldRules(Field.Observers)"
                    :prop="Field.Observers.Name">
                <el-select
                        @focus="onFocusSelectUser"
                        style="width:100%"
                        :readonly="readonly"
                        v-model="observers"
                        :disabled="readonly"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="getUsers"
                        :loading="loading">
                    <el-option
                            v-for="user in userIdentities"
                            :key="user.value"
                            :label="user.label"
                            :value="{value:user.value, identity:user.value, userName: user.label}">
                    </el-option>
                </el-select>
            </el-form-item>
        </div>
        <div class="el-form--inline el-form--label-top" style="display: flex">
            <el-form-item
                    style="width:100%"
                    :label="customLabels.Tags"
                    :rules="getFieldRules(Field.Tags)"
                    :prop="Field.Tags.Name">
                <el-tag
                        class="el-form-item"
                        style="margin-right: 5px;flex-grow: 1;"
                        :key="tag"
                        v-for="tag in tags"
                        :closable="!readonly"
                        :disable-transitions="false"
                        @close="handleClose(tags, tag)">
                    {{tag}}
                </el-tag>
                <el-input
                        :readonly="readonly"
                        class="el-form-item"
                        style="line-height:normal;width: 150px;flex-grow: 1;"
                        v-if="inputTagVisible"
                        v-model="inputTagValue"
                        ref="saveTagInput"
                        size="small"
                        @blur="handleTagInputConfirm"
                        @keyup.enter.native="handleTagInputConfirm">
                </el-input>
                <el-button v-if="!inputTagVisible && !readonly" class="el-form-item" size="small" @click="showTagInput">+ {{customLabels.NewTag}}</el-button>
            </el-form-item>
        </div>
    </div>
</el-form>


<div class="WorkflowDesignerButtons">
    <el-button v-if="!readonly" @click="onSave" type="primary">{{ ButtonTextSave }}</el-button>
    <el-button @click="onClose">{{ ButtonTextCancel }}</el-button>
</div>

<script type="application/javascript">
    function customforms_assignmentplugin_assignmentcreateform_Init(me){
        me.VueConfig.data = Object.assign(me.VueConfig.data, {
            customTitle: undefined,
            readonly: false,
            FieldIsRequired: WorkflowDesignerConstants.FieldIsRequired,
            labels: WorkflowDesignerConstants.EditParametersFormlabel,
            customLabels: WorkflowDesignerConstants.EditParametersFormlabel.CustomForms.AssignmentCreate,
            ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
            ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
            parameterFromProcessColor: WorkflowDesignerConstants.ParameterFromProcessColor,
            FormData: {},
            Field: {},
            parameterFromProcess:{
                IsActive: false,
            },
            deadlineToStart:'',
            deadlineToComplete: '',
            tags: [],
            observers: [],
            executors:[],
            actors:[],
            inputTagVisible: false,
            inputTagValue: '',
            userIdentities: [],
            loading: 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.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.graph.insertDefaultValuesInForm(me.VueConfig.data.Field, me.VueConfig.data.FormData);

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


        me.VueConfig.methods.initializeData = function() {
            me.VueConfig.data.actors = me.graph.getActorNames();

            me.VueConfig.data.deadlineToStart = me.VueConfig.data.FormData.DeadlineToStart;
            me.VueConfig.data.deadlineToComplete = me.VueConfig.data.FormData.DeadlineToComplete;

            if( me.VueConfig.data.FormData.Observers != null && me.VueConfig.data.FormData.Observers != undefined){
                me.VueConfig.data.observers = JSON.parse(me.VueConfig.data.FormData.Observers);
                me.VueConfig.data.observers.forEach(function (observers) {
                        me.VueConfig.data.userIdentities.push({ value: observers.identity, label: observers.userName});
                });
            }

            if( me.VueConfig.data.FormData.Executors != null && me.VueConfig.data.FormData.Executors != undefined){
                me.VueConfig.data.executors = JSON.parse(me.VueConfig.data.FormData.Executors);
                me.VueConfig.data.executors.forEach(function (executor){
                    if(!executor.isActor){
                        me.VueConfig.data.userIdentities.push({ value: executor.value, label: executor.name});
                    }
                });
            }

            if( me.VueConfig.data.FormData.Tags != null && me.VueConfig.data.FormData.Tags != undefined){
                me.VueConfig.data.tags = JSON.parse(me.VueConfig.data.FormData.Tags);
            }
        };

        me.VueConfig.methods.onFocusSelectUser = function(event) {
            if(event.sourceCapabilities != null){
                me.VueConfig.methods.getUsers("");
            }
        };

        me.VueConfig.methods.getUsers = function(query) {
            me.VueConfig.data.loading = true;
            setTimeout(function () {
                var users = me.graph.designer.getuseridentities(query, 1, 20);
                me.VueConfig.data.userIdentities = users.map(function (user) {
                    return { value: user.Identity, label: user.UserName };
                });
                me.VueConfig.data.loading = false;
            }, 200);
        };

        me.VueConfig.methods.handleClose = function (items, item) {
            items.splice(items.indexOf(item), 1);
        };

        me.VueConfig.methods.showTagInput = function () {
            me.VueConfig.data.inputTagVisible = true;
            this.$nextTick(function (_) {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        };

        me.VueConfig.methods.handleTagInputConfirm = function () {
            let inputValue = me.VueConfig.data.inputTagValue;
            if (inputValue) {
                me.VueConfig.data.tags.push(inputValue);
            }
            me.VueConfig.data.inputTagVisible = false;
            me.VueConfig.data.inputTagValue = '';
        };

        me.VueConfig.methods.getDateStepRules = function(interval){
            var res =[];
            var validator = function(rule, value, callback){
                if(interval == null || interval == '' || WorkflowDesignerCommon.containsAt(interval)){
                    callback();
                    return;
                }

                var isValid = true;
                interval = interval.trim();
                var stepArray = interval.split(/\s+/);
                interval = 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(!(interval && isCorrect)){
                    isValid = false;
                }

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

        me.VueConfig.methods.getExecutorsRules = function (executors){
            var res =[];
            var validator = function(rule, value, callback){
                if(executors == null || executors.length <= 0){
                    callback(new Error(rule.message));
                }
                else{
                    callback();
                }
            };
            res.push({ validator: validator, required: true, message: WorkflowDesignerConstants.FieldIsNotCorrected, trigger: 'blur'});
            return res;
        }

        me.VueConfig.methods.getFieldRules  = function(field, parameterValue){
            var rules = [];
            if(field.IsRequired){
                rules.push({ required: true, message: WorkflowDesignerConstants.FieldIsRequired, trigger: 'blur'});
            }

            if(me.VueConfig.data.parameterFromProcess[field.Name]){
                var validator = function(rule, value, callback){
                    if(WorkflowDesignerCommon.containsAt(parameterValue)){
                        callback();
                    }
                    else{
                        callback(new Error(rule.message));
                    }
                };
                rules.push({ validator: validator, required: true, message: WorkflowDesignerConstants.FieldMustContainAt, trigger: 'blur'});
            }

            return rules;
        };

        me.VueConfig.methods.onSave = function(){
            me.VueConfig.data.FormData.Observers = JSON.stringify(me.VueConfig.data.observers);
            me.VueConfig.data.FormData.Executors = JSON.stringify(me.VueConfig.data.executors);
            me.VueConfig.data.FormData.Tags = JSON.stringify(me.VueConfig.data.tags);

            me.VueConfig.data.FormData.DeadlineToStart = me.VueConfig.data.deadlineToStart;
            me.VueConfig.data.FormData.DeadlineToComplete = me.VueConfig.data.deadlineToComplete;

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

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

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


