<h3>{{ labels.Title }}</h3>
<el-form class="WorkflowDesignerWindowForm"
    :model="FormData"
    ref="form"
    label-position="top"
    label-width="150px">
    <div class="SettingsWithPadding">
        <div class="el-form--inline el-form--label-top">
            <el-form-item class="el-form-item" :label="labels.Name" :rules="requiredRule(ActivityRules)" prop="Name" style="flex-grow: 1;">
                <el-input v-model="FormData.Name" :placeholder="labels.Name" :readonly="readonly"></el-input>
            </el-form-item>
            <el-form-item  v-if="expertMode" class="el-form-item" :label="labels.State" prop="State" style="flex-grow: 1;">
                <el-input v-model="FormData.State" :placeholder="labels.State" :readonly="readonly"></el-input>
            </el-form-item>
        </div>
        <el-form-item v-if="expertMode" size="small">
            <el-checkbox v-model="FormData.IsInitial" @change="onInitialChange" :label="labels.IsInitial" name="type" :disabled="readonly"></el-checkbox>
            <el-checkbox v-model="FormData.IsForSetState" :label="labels.IsForSetState" name="type" :disabled="readonly"></el-checkbox>
            <el-checkbox v-model="FormData.IsAutoSchemeUpdate" :label="labels.IsAutoSchemeUpdate" name="type" :disabled="readonly"></el-checkbox>
        </el-form-item>
    </div>

    <div style="margin-bottom: 10px">
        <h4 class="SettingsHeader"  style="margin-bottom: 17px;">
            <span >{{ labels.Transition  + (!readonly ? "  |  " : "")}}</span>
            <a style="cursor:pointer" @click="addRow(Transitions.all, {condition: {Type: 'Expression',Expression:null, Action: {ActionParameter:null}}})">{{ ButtonTextCreate }}</a>
        </h4>
        <div style="margin-left: 20px;">
            <table class="WorkflowDesignerTable">
                <tr>
                    <th></th>
                    <th style="width: 160px;">{{labels.ConditionType}}</th>
                    <th style="flex-grow: 1;">{{labels.Condition}}</th>
                    <th style="flex-grow: 1;"></th>
                    <template v-if="expertMode">
                        <th style="width: 100px;" v-if="expertMode">{{labels.ResultOnPreExecution}}</th>
                        <th style="width: 150px;" v-if="expertMode">{{labels.Classifier}}</th>
                    </template>
                    <th style="width: 180px;">{{labels.To}}</th>
                </tr>
                <tr v-for="(transition, index) in Transitions.all">
                    <td></td>
                    <td>
                        <el-select
                                v-model="transition.condition.Type"
                                :title="validateField('Type', transition.condition)"
                                :class="validateField('Type', transition.condition) ? 'WorkflowDesignerInputError' : ''"
                                :disabled="readonly"
                                filterable
                                placeholder="">
                            <el-option key="Action" :label="labels.ActionLabel" value="Action"></el-option>
                            <el-option key="Expression" :label="labels.ExpressionLabel" value="Expression"></el-option>
                        </el-select>
                    </td>
                    <td v-if="transition.condition.Type == 'Action'">
                        <el-select
                                v-model="transition.condition.Action.ActionName"
                                :title="validateField('Action.ActionName', transition.condition)"
                                :class="validateField('Action.ActionName', transition.condition) ? 'WorkflowDesignerInputError' : ''"
                                style="width: 100%;"
                                :disabled="readonly"
                                filterable
                                clearable
                                placeholder="">
                            <el-option v-for="item in conditions" :key="item" :label="item" :value="item"></el-option>
                        </el-select>
                    </td>
                    <td v-if="transition.condition.Type == 'Action'">
                        <el-autocomplete style="width: 100%;" v-model="transition.condition.Action.ActionParameter" :disabled="readonly" :fetch-suggestions="querySearch"
                                             @focus="setCurrentItem(transition)"
                                             :placeholder="labels.Parameters"></el-autocomplete>
                    </td>
                    <td v-if="transition.condition.Type == 'Expression'" colspan="2">
                        <el-input
                            v-model="transition.condition.Expression"
                            :title="validateField('Expression', transition.condition)"
                            :class="validateField('Expression', transition.condition) ? 'WorkflowDesignerInputError' : ''"
                            :readonly="readonly"
                            style="width: 100%;">
                        </el-input>
                    </td>
                    <template v-if="expertMode">
                        <td>
                            <el-select
                                    v-model="transition.condition.ResultOnPreExecution"
                                    style="width: 100%;"
                                    :disabled="readonly"
                                    filterable
                                    placeholder="">
                                <el-option key="True" label="True" :value="true"></el-option>
                                <el-option key="False" label="False" :value="false"></el-option>
                            </el-select>
                        </td>
                        <td>
                            <el-select
                                    v-model="transition.Classifier"
                                    style="width: 100%;"
                                    :disabled="readonly">
                                <el-option v-for="val in labels.ClassifierValues"
                                           :key="val" :label="val" :value="val"></el-option>
                            </el-select>
                        </td>
                    </template>
                    <td>
                        <el-select
                                v-model="transition.activity"
                                :title="validateField('activity', transition)"
                                :class="validateField('activity', transition) ? 'WorkflowDesignerInputError' : ''"
                                style="width: 100%;"
                                :disabled="readonly"
                                filterable
                                placeholder="">
                            <el-option v-for="item in activities" :key="item.Name" :label="item.Name" :value="item.Name"></el-option>
                        </el-select>
                    </td>
                    <td :style="!readonly ? 'width: 94px;' : 'width: 42px;'">
                        <el-button-group>
                            <el-button @click="transition.condition.Type == 'Action' ? showjson('Action.ActionParameter', transition.condition, {name: transition.condition.Action.ActionName ,type: ['Condition']}) : showjson('Expression', transition.condition, {expression: true})" :class="'WorkflowDesignerTableCodeActionsButton ' + (editItem == transition ? 'is-active' : '')"></el-button>
                            <el-button v-if="!readonly" @click="removeRow(Transitions.all, index)" class="WorkflowDesignerTableDeleteButton"></el-button>
                        </el-button-group>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <el-button
                            @click="EnableOtherwise"
                            style="text-align: left; padding-left: 15px; padding-right: 35px;"
                            type="primary" :plain="FormData.EnableOtherwise"
                            :style="FormData.EnableOtherwise ? 'opacity: 1;' : 'opacity: 0.5;'">
                            Otherwise <el-checkbox :value="FormData.EnableOtherwise"></el-checkbox>
                        </el-button>
                    </td>
                    <td></td>
                    <td></td>
                    <td v-if="expertMode"></td>
                    <td v-if="expertMode">
                        <el-select
                                v-model="Transitions.otherwise.Classifier"
                                style="width: 100%;"
                                :disabled="readonly">
                            <el-option v-for="val in labels.ClassifierValues"
                                       :key="val" :label="val" :value="val"></el-option>
                        </el-select>
                    </td>
                    <td>
                        <el-select
                                v-model="Transitions.otherwise.activity"
                                :title="validateField('activity', Transitions.otherwise)"
                                :class="validateField('activity', Transitions.otherwise) ? 'WorkflowDesignerInputError' : ''"
                                style="width: 100%;"
                                :disabled="!FormData.EnableOtherwise || readonly"
                                filterable
                                :placeholder="labels.Parameters">
                            <el-option v-for="item in activities" :key="item.Name" :label="item.Name" :value="item.Name"></el-option>
                        </el-select>
                    </td>
                    <td :style="!readonly ? 'width: 94px;' : 'width: 42px;'"></td>
                </tr>
            </table>
        </div>
    </div>
    <div style="margin-bottom: 10px;">
        <el-button v-if="!readonly && !itemHasComment" @click="showUserComment()" icon="el-icon-s-comment" circle></el-button>
        <h4 v-if="itemHasComment" style="padding-bottom: 1px;border-bottom: 1px solid rgba(34,36,38,.15);">{{ labels.UserComment }}</h4>
        <el-input
                v-if="itemHasComment"
                type="textarea"
                :placeholder="labels.UserComment"
                v-model="FormData.UserComment"
                rows="5"
        >
        </el-input>
    </div>
</el-form>
<div class="WorkflowDesignerButtons">
    <el-button @click="expertMode = !expertMode" type="text">{{ expertMode ? SwitchToDefaultMode : SwitchToExpertMode }}</el-button>
    <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 decisiontable_Init(me){
         me.VueConfig.data = Object.assign(me.VueConfig.data, {
            readonly: false,
            labels: Object.assign(
                WorkflowDesignerConstants.ActivityFormLabel,
                WorkflowDesignerConstants.TransitionFormLabel,
                WorkflowDesignerConstants.DecisionTable),
            ButtonTextSave: WorkflowDesignerConstants.ButtonTextSave,
            ButtonTextCancel: WorkflowDesignerConstants.ButtonTextCancel,
            ButtonTextCreate: WorkflowDesignerConstants.ButtonTextCreate,
            ButtonTextDelete: WorkflowDesignerConstants.ButtonTextDelete,
            SwitchToDefaultMode: WorkflowDesignerConstants.SwitchToDefaultMode,
            SwitchToExpertMode: WorkflowDesignerConstants.SwitchToExpertMode,
            expertMode: false,
            actions: [],
            activities: [],
            activitiesStore: me.graph.data.Activities,
            conditions: me.graph.getConditionNames() || [],
            conditionsStore: me.graph.data.CodeActions,
            states: [],
            editItem: null,
            itemHasComment: false,
            FormData: {},
        });
        me.transitionManager = me.graph.GetComponentByType('WorkflowDesignerTransitionManager');
        me.activityManager = me.graph.GetComponentByType('WorkflowDesignerActivityManager');

        me.VueConfig.methods.GetTransitionsFrom = function (activityName) {
            var transitions = {
                all: [],
                otherwise: undefined
            };
            var foundTransitions = me.transitionManager.GetTransitionsFrom(activityName);
            foundTransitions.forEach(function (transition) {
                var item = transition.item;
                var ToName = transition.to.GetName();
                var condition = item.Conditions ? item.Conditions[0] : null;
                if (condition) {
                    if (condition.Type.toLowerCase() === 'otherwise') {
                        transitions.otherwise = {
                            condition: WorkflowDesignerCommon.clone(condition),
                            Classifier: item.Classifier,
                            activity: ToName};
                    } else {
                        transitions.all.push({
                            condition: WorkflowDesignerCommon.clone(condition),
                            Classifier: item.Classifier,
                            activity: ToName});
                    }
                }
            });

            var labels = me.VueConfig.data.labels;

            if (!transitions.all.length) {
                transitions.all.push({condition: {Action: {ActionParameter:null},Expression:null, Type: 'Expression'}, Classifier: labels.ClassifierValues[0]});
            }

            if (!transitions.otherwise) {
                transitions.otherwise = {
                    condition: {Action: {}, Type: 'otherwise'},
                    Classifier: labels.ClassifierValues[0]
                };
            }

            return transitions;
        };

        me.VueConfig.methods.updateActivitiesList = function(value){
            me.VueConfig.data.activities = [];
            me.graph.data.Activities.forEach(function(element) {
                if(element == me.linkItem) //not add current activity
                    return;
                me.VueConfig.data.activities.push(element);
            });
        }

        me.VueConfig.watch = {
            conditionsStore:function(val) {
                    me.VueConfig.data.conditions = me.graph.getConditionNames();
            },
            activitiesStore:function(val) {
                    me.VueConfig.methods.updateActivitiesList();
            },
        }

        me.VueConfig.methods.onUpdate = function(item){
            var transitions = me.VueConfig.methods.GetTransitionsFrom(item.Name);
            me.VueConfig.data.transitions = transitions;
            var formdata = me.VueConfig.data.FormData;
            formdata.Name = item.Name;
            formdata.State = item.State;
            formdata.IsInitial = item.IsInitial;
            formdata.IsForSetState = item.IsForSetState;
            formdata.IsAutoSchemeUpdate = item.IsAutoSchemeUpdate;
            formdata.UserComment = item.UserComment;
            formdata.EnableOtherwise = !!transitions.otherwise.activity;
            me.VueConfig.data.Transitions = transitions;
            me.VueConfig.data.originalTransitions =  WorkflowDesignerCommon.clone(transitions);
            me.VueConfig.data.originalName = item.Name;

            transitions.all.forEach(function (transition) {
                if (!transition.condition.Action)
                    transition.condition.Action = {};
            });

            if (!transitions.otherwise.condition.Action)
                transitions.otherwise.condition.Action = {};

            me.linkItem = item;
            me.activityControl = me.activityManager.find(item.Name);
            me.VueConfig.data.originalItem = WorkflowDesignerCommon.clone(formdata);
            me.VueConfig.data.prevName = item.Name;
            me.VueConfig.data.readonly = me.graph.Settings.readonly;
            me.VueConfig.data.actions = me.graph.getActionNames();
            me.VueConfig.methods.updateActivitiesList();
            me.VueConfig.data.itemHasComment = formdata.UserComment != null && formdata.UserComment.length > 0;


            var objectCorrect = me.VueConfig.methods.objectCorrect;
        };

        me.VueConfig.methods.showUserComment = function (){
            me.VueConfig.data.itemHasComment = true;
        }

        me.VueConfig.methods.EnableOtherwise = function(e){
            var formdata = me.VueConfig.data.FormData;
            e.preventDefault();
            formdata.EnableOtherwise = !formdata.EnableOtherwise;
        };

        me.VueConfig.methods.onInitialChange = function(){
            var formdata = me.VueConfig.data.FormData;
            formdata.IsFinal = formdata.IsInitial ? false : formdata.IsFinal;
        };

        me.VueConfig.methods.onFinalChange = function(){
            var formdata = me.VueConfig.data.FormData;
            formdata.IsInitial = formdata.IsFinal ? false : formdata.IsInitial;
        };

        me.VueConfig.methods.setCurrentItem = function(item) {
            this.currentItem = item;
        };
        me.VueConfig.methods.querySearch = function(queryString, cb) {
            if(me.VueConfig.data.readonly)
                return cb([]);

            var res = me.graph.getAutoCompleteSuggestions2("actionparameter", this.currentItem.ActionName, queryString);
            cb(res);
        };

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

        if (field == "Name") {
            var validator = function (rule, value, callback) {
                var isValid = true;
                me.graph.data.Transitions.forEach(function (a) {
                    if (a != me.linkItem && a.Name == value) {
                        isValid = false;
                    }
                });

                if (isValid) {
                    callback();
                } else {
                    callback(new Error(rule.message));
                }
            };
            res.push({validator: validator, message: WorkflowDesignerConstants.FieldMustBeUnique});
        }
        return res;
    };

        me.VueConfig.methods.validateField = function (name, item) {
            if (name != 'Name' && name != "Actor.Name" && name != "Type" && name != "Action.ActionName" && name != "Expression" && name != "activity")
                return;

            if (name == "activity" && item.Type == "Otherwise" && !me.VueConfig.data.FormData.EnableOtherwise) {
                return;
            }

            if (!WorkflowDesignerCommon.getValueByPropertyName(item, name)) {
                return WorkflowDesignerConstants.FieldIsRequired;
            }

            if (name == "Type") {
                var conditions = me.VueConfig.data.FormData.Conditions;
                var labels = me.VueConfig.data.labels;
                if (item.Type == "Always" && conditions.filter(function (c) {
                    return c.Type == item.Type
                }).length > 1) {
                    return labels.AlwaysConditionShouldBeSingle;
                }

                if (item.Type == "Otherwise" && conditions.filter(function (c) {
                    return c.Type == item.Type
                }).length > 1) {
                    return labels.OtherwiseConditionShouldBeSingle;
                }
            }
        };

        me.VueConfig.methods.ActivityRules = function(res)
        {
            //validate on unique Activity name
            var validator = function(rule, value, callback){
                var isValid = true;
                me.graph.data.Activities.forEach(function (a) {
                    if (a != me.linkItem && a.Name == value) {
                        isValid = false;
                    }
                });

                if(isValid){
                    callback();
                }
                else{
                    callback(new Error(rule.message));
                }
            };

            res.push({ validator: validator, message: WorkflowDesignerConstants.FieldMustBeUnique});

            return res;
        };
        me.VueConfig.methods.addRow = function(items, item){
            items.push(item || {});
        };

        me.VueConfig.methods.removeRow = function(items, index){
            items.splice(index, 1);
        };

        me.VueConfig.methods.showjson = function(name, item, params) {
            me.VueConfig.data.editItem = item;
            me.editItem = item;

            var onSuccess = function (value) {
                if (me.editItem) {
                    WorkflowDesignerCommon.setValueByPropertyName(me.editItem, name, value);
                    me.VueConfig.data.editItem = undefined;
                    delete me.editItem;
                }
            };

            var onClose = function (value) {
                me.VueConfig.data.editItem = undefined;
            };

            var value = WorkflowDesignerCommon.getValueByPropertyName(item, name);
            me.VueConfig.data.jsonform = me.showjson(value, params, onSuccess, onClose);
        };

        me.VueConfig.methods.validate = function () {
            var validateFunc = me.VueConfig.methods.validateField;
            var transitions = me.VueConfig.data.Transitions;

            if (Array.isArray(transitions.all) && transitions.all.length == 0) {
                me.VueConfig.data.showconditionerror = WorkflowDesignerConstants.TransitionFormLabel.ConditionsListShouldNotBeEmpty;
                return false;
            }

            for (var i = 0; i < transitions.all.length; i++) {
                var condition = transitions.all[i].condition;
                if (validateFunc('Type', condition) ||
                        (condition.Type == 'Action' && validateFunc('Action.ActionName', condition)) ||
                        (condition.Type == 'Expression' && validateFunc('Expression', condition)))
                    return false;
                if (validateFunc('activity', transitions.all[i]))
                    return false;
            }
            if (me.VueConfig.data.FormData.EnableOtherwise && validateFunc('activity', transitions.otherwise))
                return false;

            return true;
        };

        me.VueConfig.methods.saveTransition =  function() {
                var FormData = me.VueConfig.data.FormData;
                var transitions = me.VueConfig.data.Transitions;
                var originalTransitions = me.VueConfig.data.originalTransitions;
                var originalName = me.VueConfig.data.originalName;

                if (FormData.Name !== originalName)
                {
                    originalTransitions.all.forEach(function (originalTransition) {
                        var controls = me.transitionManager.GetTransitionsFromTo(originalName, originalTransition.activity);
                        if (controls && controls.length) {
                            controls.forEach(function(control) {
                                control.Delete();
                            })
                        }
                    });
                }
                else
                {
                    originalTransitions.all.forEach(function (originalTransition) {
                        if (!transitions.all.some(function(current) {return originalTransition.activity === current.activity})) {
                            var controls = me.transitionManager.GetTransitionsFromTo(FormData.Name, originalTransition.activity);
                            if (controls && controls.length) {
                                controls.forEach(function(control) {
                                    control.Delete();
                                })
                            }
                        }
                    });
                }


                transitions.all.forEach(function(item) {
                    var controls = me.transitionManager.GetTransitionsFromTo(FormData.Name, item.activity);
                    if (!controls || !controls.length) {
                        var newTransition = me.transitionManager.CreateNewTransition(me.activityControl, me.activityManager.find(item.activity));
                        newTransition.item.Conditions = [item.condition];
                        newTransition.item.Classifier = item.Classifier;
                    } else {
                        controls[0].item.Conditions = [item.condition];
                        controls[0].item.Classifier = item.Classifier;
                    }
                });

                if (FormData.Name !== originalName && originalTransitions.otherwise) {
                    var controls = me.transitionManager.GetTransitionsFromTo(originalName, originalTransitions.otherwise.activity);
                    if (controls && controls.length) {
                        controls.forEach(function (control) {
                            control.Delete();
                        })
                    }
                }

                if (originalTransitions.otherwise.activity !== transitions.otherwise.activity || !me.VueConfig.data.FormData.EnableOtherwise) {
                    var controls = me.transitionManager.GetTransitionsFromTo(FormData.Name, originalTransitions.otherwise.activity);
                        if (controls && controls.length) {
                            controls.forEach(function(control) {
                                control.Delete();
                            })
                        }
                }

                if (!!me.VueConfig.data.FormData.EnableOtherwise) {
                    var controls = me.transitionManager.GetTransitionsFromTo(FormData.Name, transitions.otherwise.activity);
                    if (!controls || !controls.length) {
                        var newTransition = me.transitionManager.CreateNewTransition(me.activityControl, me.activityManager.find(transitions.otherwise.activity));
                            newTransition.item.Conditions = [{Type: 'Otherwise'}];
                        newTransition.item.Classifier = transitions.otherwise.Classifier;
                    } else {
                        controls[0].item.Conditions = [transitions.otherwise.condition];
                        controls[0].item.Classifier = transitions.otherwise.Classifier;
                    }
                }
        }


        me.VueConfig.methods.onSave = function()
        {
            if(this.$refs && WorkflowDesignerCommon.validateForms(this.$refs) && me.VueConfig.methods.validate())
             {
                me.VueConfig.methods.saveTransition();
                me.onSuccess(me.VueConfig.data.FormData);
                me.onClose(true);
            }
        };

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

            var originalItem = me.VueConfig.data.originalItem;
            var item = me.VueConfig.data.FormData;

            if (WorkflowDesignerCommon.deepCompare(originalItem, item)) {
                me.onClose(true);
            }
            else{
                me.showConfirm();
                return false;
            }
        };

        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>