@extends('layouts.app')
@section('title')编辑-教程@endsection
@section('head')
    <link rel="stylesheet" type="text/css" href="{{mix('css/trix.css')}}">
    <script type="text/javascript" src="{{mix('js/trix.js')}}"></script>
    <script>

        addEventListener("trix-file-accept", function(event) {
            var config = laravelTrixConfig(event);

            if(
                config.hideToolbar ||
                (config.hideTools && config.hideTools.indexOf("file-tools") != -1) ||
                (config.hideButtonIcons && config.hideButtonIcons.indexOf("attach") != -1)
            ) {
                return event.preventDefault();
            }
        });

        addEventListener("trix-attachment-remove", function(event) {
            var config = laravelTrixConfig(event);

            var xhr = new XMLHttpRequest();

            var attachment = event.attachment.attachment.attributes.values.url.split("/").pop();

            xhr.open("DELETE", "{{url('laravel-trix/attachment/:attachment')}}".replace(':attachment',attachment), true);

            setAttachementUrlCollectorValue('attachment-' + config['id'], function(collector){
                for( var i = 0; i < collector.length; i++){
                    if ( collector[i] === attachment) {
                        collector.splice(i, 1);
                    }
                }

                return collector;
            });

            xhr.send();
        });

        addEventListener("trix-attachment-add", function(event) {
            var config = laravelTrixConfig(event);

            if (event.attachment.file) {
                var attachment = event.attachment;

                config['attachment'] = attachment;

                uploadFile(config, setProgress, setAttributes, errorCallback);

                function setProgress(progress) {
                    attachment.setUploadProgress(progress);
                }

                function setAttributes(attributes) {
                    attachment.setAttributes(attributes);
                }

                function errorCallback(xhr,attachment){
                    attachment.remove();
                    alert(xhr.statusText);
                }
            }
        });


        function uploadFile(data, progressCallback, successCallback, errorCallback) {
            var formData = createFormData(data);
            var xhr = new XMLHttpRequest();

            xhr.open("POST", "{{url('laravel-trix/attachment')}}", true);

            xhr.upload.addEventListener("progress", function(event) {
                var progress = (event.loaded / event.total) * 100;
                progressCallback(progress);
            });

            xhr.addEventListener("load", function(event) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    var response = JSON.parse(xhr.response);

                    setAttachementUrlCollectorValue('attachment-' + data['id'], function(collector){
                        collector.push(response.url.split("/").pop())

                        return collector;
                    });

                    successCallback({
                        url : response.url,
                        href: response.url
                    })
                } else {
                    errorCallback(xhr,data.attachment)
                }
            });

            xhr.send(formData);
        }

        function setAttachementUrlCollectorValue(inputId, callback){
            var attachmentCollector = document.getElementById(inputId);

            attachmentCollector.value = JSON.stringify(callback(JSON.parse(attachmentCollector.value)));
        }

        function createFormData(data) {
            var formData = new FormData();
            formData.append("Content-Type", data.attachment.file.type);
            formData.append("file", data.attachment.file);
            formData.append("field", data.field);
            formData.append("modelClass", data.modelClass);

            if(data.disk != undefined) {
                formData.append("disk", data.disk);
            }

            return formData;
        }
        function laravelTrixConfig (event) {
            return JSON.parse(event.target.getAttribute("data-config"));
        }
        window.onload = function() {
                var laravelTrixInstanceStyles =  document.getElementsByTagName('laravel-trix-instance-style');

                var style = document.createElement('style');
                style.type = 'text/css';

                for (var tag of laravelTrixInstanceStyles) {
                    style.innerHTML += tag.textContent + ' ';
                }

                document.getElementsByTagName('head')[0].appendChild(style);
            }
        </script>
@endsection
@section('content')
    <div id="nav2">
        @component('maintenance.menu')@endcomponent
        @component('maintenance.tutorial.menu')@endcomponent
    </div>
    <div class="card col-md-8 offset-md-2" id="tutorial">
        <div class="card-body">
            <form method="POST" action="{{ url('maintenance/tutorial/'.$tutorial->id) }}">
                @csrf
                @method('PUT')
                <div class="form-group row">
                    <label for="owner_id" class="col-2 col-form-label text-right">所属货主</label>
                    <div class="col-8">
                        <select name="owner_id" class="form-control @error('owner_id') is-invalid @enderror" style="width: 50%">
                            <option v-for="owner in owners" selected v-if="tutorial.owner_id==owner.id" :value="owner.id">@{{ owner.name }}</option>
                            <option v-for="owner in owners" v-if="tutorial.owner_id!=owner.id" :value="owner.id">@{{ owner.name }}</option>
                        </select>
                    </div>
                </div>
                <div class="form-group row">
                    <label for="name" class="col-2 col-form-label text-right">标题</label>
                    <div class="col-8">
                        <input type="text" class="form-control @error('name') is-invalid @enderror"
                               name="name" autocomplete="off" :value="tutorial.name" required>
                        @error('name')
                        <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                        @enderror
                    </div>
                </div>
                <div id="for-trix"></div>
                <div class="form-group row">
                    <label for="initial_weight" class="col-2 col-form-label text-right">内容</label>
                    <div class="col-8" id="content"></div>
                </div>
                <div class="form-group row">
                    <label for="type" class="col-2 col-form-label text-right">类型</label>
                    <div class="col-8">
                        <select name="type" class="form-control" style="width: 50%;">
                            <option value="二次加工">二次加工</option>
                        </select>
                    </div>
                </div>
                <div class="form-group row">
                    <div class="col-8 offset-2">
                        <input type="submit" class="btn btn-success form-control">
                    </div>
                </div>
            </form>
        </div>
    </div>
    </div>
    <div id="trix">
        @trix($tutorial, 'content')
    </div>
@endsection

@section('lastScript')
    <script>
        new Vue({
            el:"#tutorial",
            data:{
                tutorial:{owner_id:'{{old('owner_id')?old('owner_id'):$tutorial->owner_id}}',
                    name:'{{old('name')?old('name'):$tutorial->name}}',type:'{{old('type')?old('type'):$tutorial->type}}'},
                owners:[
                    @foreach($owners as $owner)
                    {!! $owner !!},
                    @endforeach
                ],
            },
            mounted() {
                let trix=$("#trix");
                $("#content").append(trix);
            },
        });
    </script>
@endsection
