<div id="ClassificationDataForm" style="display:none">
<form action="index.php?module=errorpatterns&event=createClassification" method="POST" class="form">
    <input type="hidden" name="save" value="1" />
    <input type="hidden" name="ErrorPatternID" id="ErrorPatternID" value="[% $PatternData.patternid|default:"0" %]" />
    <div class="row" id="ClassiData">
        <div class="col-sm-12">
            <div class="form-group row mb-3">
                <label class="col-lg-2 control-label">[% $user->gettext('Können Sie den Fehler eindeutig einem Bauteil zuordnen?') %]</label>
                <div class="col-lg-10">
                    <label><input type='radio' name="isSymptome" value='0' id='isNotSymptome' [% if !$PatternData.issymptome || $PatternData.issymptome == 0 %]checked[% /if %]/> [% $user->gettext('Ja') %]</label>
                    <label><input type='radio' name="isSymptome" value='1' id='isSymptome' [% if $PatternData.issymptome == 1 %]checked[% /if %]/> [% $user->gettext('Nein') %] </label>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
            <div class="form-group row mb-3">
                <label class="col-lg-2 control-label">[% $user->gettext('Klassifikation wählen') %]</label>
                <div class="col-lg-10">
                    <div class="input-group">
                        <select name="ClassificationID" id="ClassificationID" class="form-control" >
                            <option value="0">-- [% $user->gettext('Klassifikation wählen') %] --</option>
                        </select>
                        <div class="input-group-text">
                            <span class="btn btn-outline-secondary btn-sm" onclick="refreshClassificationSelection();" title="[% $user->gettext('Klassifikationen neu laden') %]"><span class="fa fa-refresh"></span></span>                            
                        </div>                               
                    </div>
                    <p id="ClassificationDescr_ol"></p>

                </div>
            </div>       
        </div>

        <div class="col-sm-12">
            <div class="form-group row mb-3">
                <label class="col-lg-2 control-label">[% $user->gettext('Fehlerbild wählen') %]</label>
                <div class="col-lg-10">
                    <div class="input-group">
                        <select name="ErrorPatterns" id="ErrorPatterns" class="form-control" >
                            <option value="0" disabled>-- [% $user->gettext('Erst Klassifikation wählen') %] --</option>
                        </select>
                        <div class="input-group-text">
                            <span class="btn btn-outline-secondary btn-sm" onclick="loadErrorPatterns();" title="[% $user->gettext('Fehlerbilder neu laden') %]"><span class="fa fa-refresh"></span></span>
                                [% if $user->hasRight(1100) %]
                                <a href="index.php?module=errorpatterns&event=AddErrorPattern[% if $PatternData.classicode != '' %]&ClassificationCode=[% $PatternData.classicode %][% /if %]"  id="AddPatternLink" class="btn btn-outline-secondary btn-sm openInLargeModal" ><span class="fa fa-plus"></span> </a>
                            [% /if %]
                        </div>                      
                    </div>
                    <p id="ErrorPatternDescr_ol"></p>
                </div>
            </div>
        </div>
    </div>

    [% if !$PatternData.ticketid && $user->isInternUser() %]
        <div id="SimilarTicketsItem" class="card panel-info shadow-sm rounded" style="display:none;" >
            <div class="card-header" role="tab" id="headingSimilarTickets">
                <div class="row">
                    <div class="col-md-12">
                        <h4 class="card-title">
                            [% $user->gettext('Ähnliche Tickets') %]
                            <small>[% $user->gettext('Tickets mit der gleichen Klassifikation, dem gleichen Fehlerbild und dem selben Gerätetypen') %]</small>
                        </h4>
                    </div>
                </div>

            </div>
            <div id="SimilarTicketsPanel" class="" role="tabpanel" aria-labelledby="headingProject">

            </div>
        </div>
    [% /if %]

    [% if $PatternData.ticketid && $FinancialCommitment.showfinancialcommitment %]
        <div class="row">
            <div class="col-sm-12">
                <div class="form-group row mb-3">
                    <div class="col-lg-8 col-sm-12">
                        <input type='checkbox' name="IsFinancialCommitment" id='IsFinancialCommitment' [% if $FinancialCommitment.hasfinancialcommitment %]checked disabled[% /if %]/> 
                        <label for="IsFinancialCommitment">[% $user->gettext('Finanzielle Zusage') %]</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="FinancialCommitment" id="FinancialCommitment"  value="[% $FinancialCommitment.financialcommitmentvalue %]" [% if $FinancialCommitment.hasfinancialcommitment %]readonly[% /if %] [% if !$FinancialCommitment.hasfinancialcommitment %]style="display:none"[% /if %]/>   
                            <div class="input-group-text">
                                <button type="button"  name="btnSaveFinancialCommitment" id="btnSaveFinancialCommitment" class="btn btn-outline-secondary" onclick="SaveFinancialCommitment();" style="display:none">[% $user->gettext('Speichern')%]</button>
                            </div>
                        </div>
                    </div>
                </div>       
            </div>
        </div>
    [% /if %]

    [% if !$PatternData.ticketid %]
        <div class="row" id="ActionRequiredItem" style="display:none">
            <div class="col-sm-12">
                <div class="form-group row mb-3">
                    <label class="col-lg-4 col-sm-12 control-label">[% $user->gettext('Aktion durch Sennebogen erforderlich?') %]</label>
                    <div class="col-lg-8 col-sm-12">
                        <label><input type='radio' name="isSennebogenActionRequired" value='0' id='SennebogenActionRequired' checked/> [% $user->gettext('Ja') %]</label>
                        <label><input type='radio' name="isSennebogenActionRequired" value='1' id='SennebogenActionNotRequired'/> [% $user->gettext('Nein') %] </label>
                    </div>
                </div>
            </div>
        </div>
    [% /if %]
    <div id="ServiceSchecksItem" class="card panel-default" style="display:none;">
        <div class="card-header" role="tab" id="HeadingServiceSchecks">
            <div class="row">
                <div class="col-6">
                    <h4 class="card-title">
                        [% $user->gettext('Service-Schecks') %]
                    </h4>

                </div>
                [% if $PatternData.ticketid %]
                    <div class="col-6 text-end">
                        <div class="btn-group">
                            <button class="btn btn-outline-primary" onclick="SaveServiceScheck();">[% $user->gettext('Speichern')%]</button>
                        </div>
                    </div>
                [% /if %]
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <div class="card-body">
                    <div class="form-group row mb-3">
                        <label class="col-lg-4 col-sm-12 control-label">[% $user->gettext('Service-Scheck wählen') %]</label>
                        <div class="col-lg-8 col-sm-12">
                            <div class="input-group">
                                <select name="ServiceSchecks" id="ServiceSchecks" class="form-control" >
                                </select>
                                <div class="input-group-text">
                                    <span class="btn btn-outline-secondary btn-sm" onclick="RefreshServiceScheckSelection();" title="[% $user->gettext('Service-Schecks neu laden') %]"><span class="fa fa-refresh"></span></span>                            
                                </div>                               
                            </div>
                        </div>
                    </div>       
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <div class="card-body">
                    <div class="form-group row mb-3">
                        <label class="col-lg-4 col-sm-12 control-label">[% $user->gettext('Durchführungsart wählen') %]</label>
                        <div class="col-lg-8 col-sm-12">
                            <div class="input-group">
                                <select name="ServiceScheckExecutionTypes" id="ServiceScheckExecutionTypes" class="form-control" >
                                </select>
                            </div>
                        </div>
                    </div>       
                </div>
            </div>
        </div>

    </div>
    <div id="ConnectedServiceSchecksItem" class="card panel-default" style="display:none;" >
        <div class="card-header" role="tab" id="HeadingConnectedServiceSchecks">
            <div class="row">
                <div class="col-md-12">
                    <h4 class="card-title">
                        [% $user->gettext('Bereits zugewiesene Service-Schecks') %]
                    </h4>
                </div>
            </div>
        </div>
        <div id="ConnectedServiceSchecksPanel" class="" role="tabpanel" aria-labelledby="headingProject">
        </div>
    </div>
</form>
</div>

<script>
    [% if $PatternDataJson !== 'null' %]
    var PatternDataJson = [% $PatternDataJson|default:"[]" %];
    var Klassi = [];
    var EP = [];
    [% else %]
    var PatternDataJson = "[]";

    [% /if %]
    $('input[name="isSymptome"]').on('click', function () {
        refreshClassificationSelection();
    })

    [% if $PatternData.ticketid %]
    $(document).ready(function () {
        refreshClassificationSelection();
        RefreshServiceScheckSelection();
        LoadServiceScheckExecutionTypes();
        SetServiceScheck();

        if (typeof (TicketID) !== 'undefined')
        {
            ChangeServiceScheckVisibility();
        }

    })
    [% /if %]


    /**
     * Läd den Inhalt der Fehlerbildauswahl neu. Wird nach einer Geräteauswahl aufgerufen
     */
    function refreshClassificationSelection() {
        $("#ClassificationDescr_ol").html("");

        if (typeof (TicketID) !== 'undefined')
        {
            useTicketID = TicketID;
        } else
        {
            useTicketID = 0;
        }

        var url = 'index.php?module=errorpatterns&event=loadClassificationsForTicket';

        $.post(url, {ticketid: useTicketID, isSymptome: $('input[name="isSymptome"]:checked').val(), selectedValue: PatternDataJson.classicode}, function (Response)
        {
            if (Response.error) {
                return false;
            } else {
                Klassi = Response;
                $('#ClassificationID').empty();
                var PlaceholderOption = new Option('-- [% $user->gettext('Klassifikation wählen') %] --', "0", true, true);
                $('#ClassificationID').append(PlaceholderOption);

                $.each(Response, function (i, item)
                {
                    if (item.selected === true) {
                        $("#ClassificationDescr_ol").html(" &nbsp;" + item.string_ol + "");
                    }
                    var newOption = new Option(item.string, item.code, true, item.selected);
                    $('#ClassificationID').append(newOption);
                });
            }

            $('#ClassificationID').select2({theme: 'bootstrap-5'}).on('change', function (e) {
                ClassiCode = $('#ClassificationID').val();
                if (ClassiCode != '') {
                    $('#AddPatternLink').attr('href', 'index.php?module=errorpatterns&event=AddErrorPattern&ClassificationCode=' + ClassiCode);
                } else {
                    $('#AddPatternLink').attr('href', 'index.php?module=errorpatterns&event=AddErrorPattern');
                }
                loadErrorPatterns();
            });
            loadErrorPatterns();
        });
    }

    function loadErrorPatterns(SelectedPattern) {
        $("#ErrorPatternDescr_ol").html("");
 
        if ($('#ClassificationID').val() === "0") {
            $('#ClassificationDataForm').show();
            return false;
        }
        var url = 'index.php?module=errorpatterns&event=loadErrorpatterns';

        $.post(url, {ticketid: useTicketID, ClassificationID: $('#ClassificationID').val(), selectedValue: PatternDataJson.patternid}, function (Response)
        {
            if (Response.error) {
                return false;
            } else {
                EP = Response;
                EPCode = $('#ErrorPatterns').val();
                if (typeof (EP[EPCode]) === 'undefined') {
                    $("#ErrorPatternDescr_ol").html("");
                }
                $('#ErrorPatterns').empty();
                var PlaceholderOption = new Option('-- [% $user->gettext('Fehlerbild wählen') %] --', "0", true, true);
                $('#ErrorPatterns').append(PlaceholderOption);
                $.each(Response, function (i, item)
                {
                    if (item.selected === true) {
                        $("#ErrorPatternDescr_ol").html(" &nbsp;" + item.string_ol + "");
                    }
                    var newOption = new Option(item.string, item.code, true, item.selected);
                    $('#ErrorPatterns').append(newOption);
                });
            }
//            if (SelectedPattern !== undefined && SelectedPattern !== '' && changePatternID !== undefined && changePatternID) {
//                $('#ErrorPatterns').val(SelectedPattern).trigger('change');
//            }

            $('#ErrorPatterns').select2({theme: 'bootstrap-5'});

            
        $('#ClassificationDataForm').show();
        
            showSimilarTickets();


        });
    }


    $('#ErrorPatterns, #ClassificationID').select2({theme: 'bootstrap-5'}).on('select2:select', function (e) {
        $("#ClassificationDescr_ol").html("");
        $("#ErrorPatternDescr_ol").html("");
        ClassiCode = $('#ClassificationID').val();
        if (typeof (Klassi[ClassiCode]) !== 'undefined') {
            $("#ClassificationDescr_ol").html(" &nbsp;" + Klassi[ClassiCode].string_ol + "");
        } else {
            $("#ClassificationDescr_ol").html("");

        }
        EPCode = $('#ErrorPatterns').val();
        console.log(EP);
        if (typeof (EP[EPCode]) !== 'undefined') {
            $("#ErrorPatternDescr_ol").html(" &nbsp;" + EP[EPCode].string_ol + "");

        } else {
            $("#ErrorPatternDescr_ol").html("");
        }
        connectToTicket();
    });

    $('#saveTicketClassification').on('click', function (e) {
        connectToTicket();
    });


    function connectToTicket() {
        if (typeof (TicketID) === 'undefined') {
            return false;
        }

        $.ajax({
            type: "POST",
            url: "index.php?module=ticket&event=connEP2Ticket",
            data: {tid: TicketID, PatternID: $('#ErrorPatterns').val(), ClassificationCode: $("#ClassificationID").val(), isSymptome: $('input[name="isSymptome"]:checked').val()}
        }).done(function (Response) {
            if (Response.error) {
                noty({
                    text: Response.message,
                    type: 'error',
                    timeout: notifyTimeout
                });
            } else {
                noty({
                    text: Response.message,
                    type: 'success',
                    timeout: notifyTimeout
                });

                $("#SimilarTicketsPanel").load("index.php?module=ticket&event=showSimilarTickets&tid=" + TicketID);
            }

        });
    }

    $('#ClassificationID, #ErrorPatterns').on('change', function (e) {
        showSimilarTickets();
    })

    function showSimilarTickets() {
        if (!typeof (TicketID) === 'undefined') {
            return false;
        }

        if ($('#ErrorPatterns').val() > 0 && $("#ClassificationID").val() !== "") {
            $.ajax({
                type: "POST",
                url: "index.php?module=ticket&event=showSimilarTicketsBySelection",
                data: {PatternID: $('#ErrorPatterns').val(), ClassificationCode: $("#ClassificationID").val(), TicketID: TicketID}
            }).done(function (Response) {
                if (Response.error) {
                    noty({
                        text: Response.message,
                        type: 'error',
                        timeout: notifyTimeout
                    });
                } else {
                    $("#SimilarTicketsPanel").html(Response);
                    $('#SimilarTicketsItem').show();
                }
            });
        }
    }

    function RefreshServiceScheckSelection()
    {
        if (typeof (TicketID) !== 'undefined')
        {
            useTicketID = TicketID;
        } else
        {
            useTicketID = 0;
        }

        var url = 'index.php?module=errorpatterns&event=GetServiceSchecks';

        $.post(url, {ticketid: useTicketID}, function (Response)
        {
            if (Response.error) {
                return false;
            } else {
                $('#ServiceSchecks').empty();
                $.each(Response, function (i, item)
                {
                    var newOption = new Option(item.servicescheckname, item.servicescheckid);
                    $('#ServiceSchecks').append(newOption);
                });
            }

            $('#ServiceSchecks').select2({theme: 'bootstrap-5'});
        });
    }

    function LoadServiceScheckExecutionTypes()
    {
        var url = 'index.php?module=errorpatterns&event=GetServiceScheckExecutionTypes';

        $.post(url, {}, function (Response)
        {
            if (Response.error) {
                return false;
            } else {
                $('#ServiceScheckExecutionTypes').empty();
                $.each(Response, function (i, item)
                {
                    var newOption = new Option(item.servicescheckexecutiontypename, item.servicescheckexecutiontypeid);
                    $('#ServiceScheckExecutionTypes').append(newOption);
                });
            }

            $('#ServiceScheckExecutionTypes').select2({theme: 'bootstrap-5'});
            $('#ExecutionTypeID').val($("#ServiceScheckExecutionTypes").val());
        });
    }


    $('#ServiceSchecks').select2({theme: 'bootstrap-5'}).on('select2:select', function (e) {
        $('#ServiceScheckID').val($("#ServiceSchecks").val());

    });

    $('#ServiceScheckExecutionTypes').select2({theme: 'bootstrap-5'}).on('select2:select', function (e) {
        $('#ExecutionTypeID').val($("#ServiceScheckExecutionTypes").val());
    });

    function ChangeServiceScheckVisibility()
    {
        if (typeof (TicketID) !== 'undefined')
        {
            useTicketID = TicketID;
        } else
        {
            useTicketID = 0;
        }

        var url = 'index.php?module=errorpatterns&event=ChangeServiceScheckVisibility';

        $.post(url, {ticketid: useTicketID}, function (Response)
        {
            if (Response.error)
                return false;
            else
            {
                if (Response)
                {
                    $('#ServiceSchecksItem').show();
                    $('#ActionRequiredItem').show();
                    ShowConnectedServiceSchecks();
                } else
                {
                    $('#ServiceSchecksItem').hide();
                    $('#ActionRequiredItem').hide();
                }
            }
        });
    }

    function ShowConnectedServiceSchecks()
    {
        if (!typeof (TicketID) === 'undefined')
            return false;

        var url = 'index.php?module=errorpatterns&event=ShowConnectedServiceSchecks';

        $.post(url, {ticketid: TicketID}, function (Response)
        {
            if (Response.error)
                return false;
            else
            {
                $("#ConnectedServiceSchecksPanel").html(Response);
                $('#ConnectedServiceSchecksItem').show();
            }
        });
    }

    function SetServiceScheck()
    {
        if (!typeof (TicketID) === 'undefined')
            return false;

        var url = 'index.php?module=errorpatterns&event=SetServiceScheck';

        $.post(url, {ticketid: TicketID}, function (Response)
        {
            if (Response.error)
                return false;
            else
            {
                $.each(Response, function (i, item)
                {
                    $("#ServiceSchecks").val(item.servicescheckid).trigger("change");
                });

            }
        });
    }

    function SaveServiceScheck()
    {
        if (!typeof (TicketID) === 'undefined')
            return false;

        var url = 'index.php?module=errorpatterns&event=SaveServiceScheck';

        $.post(url, {ticketid: TicketID, ServiceScheckID: $('#ServiceSchecks').val(), ExecutionTypeID: $('#ServiceScheckExecutionTypes').val()}, function (Response)
        {
            if (Response.error)
                return false;
            else
            {
                ShowConnectedServiceSchecks();
                SetServiceScheck();
            }
        });
    }

    $('#IsFinancialCommitment').on("change", function ()
    {
        if (this.checked)
        {
            $("input#FinancialCommitment").show();
            $("#btnSaveFinancialCommitment").show();
        } else
        {
            $("input#FinancialCommitment").hide();
            $("#btnSaveFinancialCommitment").hide();
        }
    });

    function SaveFinancialCommitment()
    {
        if (!typeof (TicketID) === 'undefined')
            return false;

        var url = 'index.php?module=errorpatterns&event=SaveFinancialCommitment';

        $.post(url, {ticketid: TicketID, FinancialCommitment: $("#FinancialCommitment").val()}, function (Response)
        {
            if (Response.error)
                return false;
            else
            {
                location.reload();
            }
        });
    }
</script>
