
<div class="page-wrapper chiller-theme toggled">


    <main class="page-content">
        <div class="container  containerFileBatchUpload" >
            <form class="priceListProfitCenterForm needs-validation" >
                @csrf
                <div class="form-group row">
                    <label for="supplierSelect" class="col-sm-2 col-form-label">Csatolmány:</label>
                    <div class="col-sm-10">
                        <select class="supplierSelect" name="attachmentType" multiple="multiple" style="width: 100%">
                            <option value="picture" selected >Kép</option>
                            <option value="specification" >Specifikáció</option>
                        </select>
                    </div>
                </div>
                <div class="form-group row">
                    <label for="supplierSelect" class="col-sm-2 col-form-label">Beszállító:</label>
                    <input type="hidden" name="formUUID" value="{{$formUUID}}">
                    <div class="col-sm-10">
                        <select class="supplierSelect" name="supplier" multiple="multiple" style="width: 100%">
                            @foreach($suppliers as $supplier)
                                <option value="{{$supplier['id']}}" @if ($supplier['id']==26) selected @endif>{{$supplier['name']}}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </form>
            {{--<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
--}}

            <link rel="stylesheet" href="{{asset('vendor/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css')}}" type="text/css" />
            <script type="text/javascript" src="{{asset('vendor/plupload/plupload.full.min.js')}}"></script>
            <script type="text/javascript" src="{{asset('vendor/plupload/jquery.ui.plupload/jquery.ui.plupload.js')}}"></script>
            <script type="text/javascript" src="{{asset('vendor/plupload/i18n/hu.js')}}"></script>
            <div id="uploader" class="fileBatchUploader">
                <p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
            </div>
            <br />

            <div class="accordion">
                <div class="card accordionFileAdded">
                    <div class="card-header" id="headingOne">
                        <h2 class="mb-0">
                            <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                Hozzáadott <span class="badge badge-success d-none" data-num="0">Success</span>
                                <span class="badge badge-danger d-none" data-num="0">Danger</span>
                                <span class="badge badge-info d-none" data-num="0">Info</span>

                            </button>
                        </h2>
                    </div>

                    <div id="collapseOne" class="resultFileAdded collapse show" aria-labelledby="headingOne" data-parent=".accordion">
                        <div class="card-body">
                            <table class="table table-hover tableFileAdded">
                                <thead>
                                <tr>
{{--
                                    <th scope="col">#</th>
--}}
                                    <th scope="col">Név</th>
                                    <th scope="col">Státusz</th>
                                </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <template data-name="tableFileAddedRow">
                                    <tr class="[[class]]" data-fileId="[[id]]" data-status="[[status]]">
{{--
                                        <td>[[id]]</td>
--}}
                                        <td>[[name]]</td>
                                        <td>[[desc]]</td>
                                    </tr>
                                </template>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="card accordionFileUploaded">
                    <div class="card-header" id="headingTwo">
                        <h2 class="mb-0">
                            <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                                Feltöltött
                                <span class="badge badge-success d-none" data-num="0">Success</span>
                                <span class="badge badge-danger d-none" data-num="0">Danger</span>
                                <span class="badge badge-info d-none" data-num="0">Info</span>
                            </button>
                        </h2>
                    </div>
                    <div id="collapseTwo" class="resultFileUploaded collapse show" aria-labelledby="headingTwo" data-parent=".accordion">
                        <div class="card-body">
                            <table class="table table-hover tableFileUploaded">
                                <thead>
                                <tr>
                                    {{--
                                                                        <th scope="col">#</th>
                                    --}}
                                    <th scope="col">Név</th>
                                    <th scope="col">Feltöltve</th>
                                    <th scope="col">Hozzárendelve</th>
                                </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <template data-name="tableFileUploadedRow">
                                    <tr class="[[class]]" data-fileId="[[id]]" data-status="[[status]]">
                                        {{--
                                                                                <td>[[id]]</td>
                                        --}}
                                        <td>[[name]]</td>
                                        <td>[[uploaded]]</td>
                                        <td data-filed="desc">[[desc]]</td>
                                    </tr>
                                </template>
                                <template data-name="tableFileUploadedRowSpinner">
                                    Feldolgozás
                                    <div class="spinner-border spinner-border-sm" role="status">

                                        <span class="sr-only">Loading...</span>
                                    </div>
                                </template>

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

            </div>
        </div>

    </main>
</div>





<script>

    window.FileBatchUploader=function (options) {
        /*
         * Variables accessible
         * in the class
         */
        let Opts = {
            token: null,
            containerCssSelector: '.fileBatchUploader',
            testMode: false,
            maxFileCount:100,
            URL: {
                getDataTableContent: '',
                getProductGroupHTML: '',
                index: '',
                show: '',
                edit: '',
                create: '',
                store: '',
                update: '',
                destroy: '',
                upload: '',

            },
            ajaxPostParam:{},
            headers:false,
            onAfterInit: function () {
            },
            onComplete: function (up,files) {
                console.log('[UploadComplete1]');
                console.log(up);
                console.log(files);
            },
            onFilesAdded:function() {},
            onFilesRemoved:function() {},
            onFileUploaded:function() {},
            onUploadComplete:function() {},

        };
        let root = this;
        /*
         * Constructor
         */
        this.construct = function (options) {
            console.log('PriceListProfitCenterAdmin constructor called');
            $.extend(Opts, options);
        };
        this.getOpts = function () {
            return Opts;
        }

        this.onFilesAdded=function(up, files) {
            // Called when files are added to queue
            Opts.onFilesAdded(up,files);
        }
        this.onFilesRemoved=function(up, files) {
            // Called when files are added to queue
            Opts.onFilesRemoved(up,files);
        }

        this.onFileUploaded=function(up, file,info) {
            // Called when files are added to queue
            Opts.onFileUploaded(up,file,info);
        }

        this.onComplete=function(up, files) {
            // Called when files are added to queue
            Opts.onComplete(up,files);
        }
        this.onUploadComplete=function (up, files,res) {
            Opts.onUploadComplete(up, files,res);
        }

        this.init=function (options){
            $.extend(Opts, options);
            if(!Opts.header){
                Opts.headers={
                    'X-CSRF-TOKEN': Opts.token
                };
            }

            $(Opts.containerCssSelector).plupload({
                // General settings
                runtimes : 'html5,html4',
                url : Opts.URL.upload,
                headers: Opts.headers,
                multipart_params : Opts.ajaxPostParam,
                // User can upload no more then 20 files in one go (sets multiple_queues to false)
                max_file_count: Opts.maxFileCount,
                chunk_size: '10mb',
                // Resize images on clientside if we can
                resize : {
                    width : 200,
                    height : 200,
                    quality : 90,
                    //crop: true // crop to exact dimensions
                },

                filters : {
                    // Maximum file size
                    max_file_size : '100mb',
                    // Specify what files to browse for
                    mime_types: [
                        {title : "Image files", extensions : "jpg,gif,png"},
                        {title : "Document files", extensions : "pdf,doc,docx,xls,xlsx,txt"},
                       /* {title : "Zip files", extensions : "zip"}*/
                    ]
                },

                // Rename files by clicking on their titles
                rename: true,

                // Sort files
                sortable: true,

                // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
                dragdrop: true,

                // Views to activate
                views: {
                    list: true,
                    thumbs: true, // Show thumbs
                    active: 'thumbs'
                },
                init:{
                    Error: function(up, args) {
                        // Called when error occurs
                        console.log('[Error] ');
                        console.log('[Error] ', args);
                    },
                    Browse: function(up) {
                        // Called when file picker is clicked
                        console.log('[Browse]');
                    },
                    BeforeUpload:function(up, file) {
                        console.log(' BeforeUpload');
                        console.log(file);
                        //Opts.ajaxPostParam['fileId']=console.log(file);
                        let tmpParam={...Opts.ajaxPostParam};
                        tmpParam['fileId']=file.id;
                        up.setOption('multipart_params',tmpParam);

                        /*
                        plupload.each(files, function(file) {
                            console.log('  init BeforeUpload File:', file);
                            //root.resultTableRemove(file.id,'FileAdded');
                        });

                         */
                    },
                    FilesAdded:root.onFilesAdded,
                    FilesRemoved:root.onFilesRemoved,
                    FileUploaded:root.onFileUploaded,
                    UploadComplete:root.onUploadComplete,
                    /*UploadComplete: function(up, files,res) {
                        // Called when all files are either uploaded or failed
                        debug ('[init UploadComplete]');
                        console.log(res);
                        plupload.each(files, function(file) {
                            console.log('  init UploadComplete File:', file.id);
                            //root.resultTableRemove(file.id,'FileAdded');
                        });
                    },
*/
                }
            });
        }

    }

    window.ProductFileBatchUploaderAdmin=function (options) {
        /*
         * Variables accessible
         * in the class
         */
        let Opts = {
            token: null,
            containerCssSelector: '.containerFileBatchUpload',
            FileBatchUploaderContainerCssSelector:false,
            testMode: false,
            URL: {
                index: '',
                show: '',
                edit: '',
                create: '',
                store: '',
                update: '',
                destroy: '',
                upload: '',
            },
            maxQueueProcessItemOneTime:2,
            dataTable: {
                orderDirective: [1, 'asc']
            },
            onAfterInit: function () {
            }
        };
        let FileBatchUploader=false;
        let root = this;
        /*
         * Constructor
         */
        this.construct = function (options) {
            console.log('ProductFileBatchUploaderAdmin constructor called');
            $.extend(Opts, options);
        };
        this.getOpts = function () {
            return Opts;
        }

        this.FileBatchUploaderOnFilesRemoved=function(up, files) {
            debug('call FileBatchUploaderOnFilesRemoved');
            debug(up);
            debug(files);
            plupload.each(files, function(file) {
                console.log('  File:', file.id);
                root.resultTableRemove(file.id,'FileAdded');
            });
        }
        this.FileBatchUploaderOnFilesAdded= function(up, files) {
            // Called when files are added to queue
            console.log('[FilesAdded ProductFileBatchUploaderAdmin]');
/*
            let FileNames=new Array();
            plupload.each(files, function(file) {
                console.log('  File:', file);
                FileNames.push(file.name);
            });
*/
            let FileNames={};
            plupload.each(files, function(file) {
                console.log('  File:', file);
                FileNames[file.id]=file.name;
            });
            //console.log(FileNames);
            let ajaxData=new FormData($(Opts.containerCssSelector+' form')[0]);
            ajaxData.append('requestType','filesAdded');
            //ajaxData.append('files',Object.entries(files));
            ajaxData.append('fileNames',JSON.stringify(FileNames));
            console.log(ajaxData);
            let ajaxUrl=Opts.URL.store;
            let ajaxMethod="POST";
            $.ajax({
                url:ajaxUrl,
                data:ajaxData,
                type:ajaxMethod,
                contentType:false,
                processData: false,
                headers: {
                    'X-CSRF-TOKEN': Opts.token
                },
                success:function (data){
                    debug(data);
                    if(data.status==200){
                        root.processFileBatchUploaderOnFilesAddedResult(data.result);
                    }else{
                        console.log('File Check received');
                        let errorData='';
                        errorData+=ajaxUrl+'<br>\n';
                        let object = {};
                        ajaxData.forEach((value, key) => object[key] = value);
                        errorData+=JSON.stringify(object)+'<br>\n<br>\n';
                        errorData+='Response> '+JSON.stringify(data)+'<br>\n';
                        Toast.create('Feldolgozási hiba!', '<b>Kérjük jelezze a fejlesztőknek az alábbi adatokat:</b><br>\n'+errorData, TOAST_STATUS.DANGER);
                    }
                }
            });

        }
        this.FileBatchUploaderOnUploadComplete=function (up, files,res) {
                // Called when all files are either uploaded or failed
                debug ('[init UploadComplete yeeee]');
                console.log(res);
                plupload.each(files, function(file) {
                    console.log('  init UploadComplete File:', file.id);
                    //root.resultTableRemove(file.id,'FileAdded');
                });
                root.processUploadedFileAttach();
        }

        this.initFileBatchUploader=function (options) {
            let FileBatchUploaderOptions={...Opts};
            FileBatchUploaderOptions.ajaxPostParam={'formUUID':$('input[name="formUUID"]').val()};
            if(Opts.FileBatchUploaderContainerCssSelector){
                FileBatchUploaderOptions.containerCssSelector=Opts.FileBatchUploaderContainerCssSelector;
            }else{
                delete FileBatchUploaderOptions.containerCssSelector;

            }
            delete FileBatchUploaderOptions.FileBatchUploaderContainerCssSelector;
            FileBatchUploaderOptions.onFilesAdded=root.FileBatchUploaderOnFilesAdded;
            FileBatchUploaderOptions.onFilesRemoved=root.FileBatchUploaderOnFilesRemoved;
            FileBatchUploaderOptions.onComplete=root.FileBatchUploaderOnComplete;
            FileBatchUploaderOptions.onFileUploaded=root.FileBatchUploaderOnFileUploaded;
            FileBatchUploaderOptions.onUploadComplete=root.FileBatchUploaderOnUploadComplete;


            //console.log(FileBatchUploaderOptions);
            root.FileBatchUploader=new window.FileBatchUploader();
            root.FileBatchUploader.init(FileBatchUploaderOptions);
        }


        this.addBadgeNum=function (type,status, num=1){
            let badge=$('.accordion'+type+' .badge-'+status)
            let val=badge.data('num');
            val+=num;
            if(val<1){
                badge.addClass('d-none');
                badge.data("num",0);
                return;
            }
            badge.data("num",val);
            badge.text(val);
            badge.removeClass('d-none');
        }



        this.resultTableRemove=function (fileId,type) {
            console.log('  fileId:', fileId);
            console.log('  fileId:', type);
            debug('.table'+type+' tbody tr[data-fileId="'+fileId+'"]');
            let tr=$('.table'+type+' tbody tr[data-fileId="'+fileId+'"]');
            console.log(tr);
            debug(tr.data("status"));
            root.addBadgeNum(type,tr.data("status"),-1);
            tr.remove();
        }

        this.processFileBatchUploaderOnFilesAddedResult=function (data) {
            debug('call processFileBatchUploaderOnFilesAddedResult');

            $.each(data,function (i, v){
                v.id=i;
                root.resultTableAdd(v,'FileAdded');
            });
            //root.resultTableRemove('o_1hcef2opnu1m30muvc1m4f1krdh','FileAdded');
        }

        this.init=function (options){
            $.extend(Opts, options);
            console.log('ProductFileBatchUploaderAdmin init called');
            root.initFileBatchUploader(options);
            //root.fucker();
            return ;
                        root.processFileBatchUploaderOnFilesAddedResult({
                                "o_1hcef2opn1g7f1et41srn13i9394e": {
                                    "name": "200012003000.jpg",
                                    "status": "ok",
                                    "pid": 3858,
                                    "desc": "Sertés 2*200gr Apróh\u00fas"
                                },
                                "o_1hcef2opn1n541suvk3cl2u1hslf": {
                                    "name": "200012003003.png",
                                    "status": "ok",
                                    "pid": 3859,
                                    "desc": "Sertés apróhús darálva(70%-30%) fagy. Vcs."
                                },
                                "o_1hcef2opn1sp22uggcum3i1135g": {
                                    "name": "200012003006.jpg",
                                    "status": "ok",
                                    "pid": 3857,
                                    "desc": "Sertés apró darálva(70%-30%) vcs.2"
                                },
                                "o_1hcef2opnu1m30muvc1m4f1krdh": {
                                    "name": "illkerfood.jpg",
                                    "status": "error",
                                    "pid": null,
                                    "desc": "Nincs ilyen termék"
                                }
                        });
        }
        this.statusConverter=function (status) {
            switch (status){
                case "ok":
                    return 'success';
                    break;
                case "error":
                    return'danger';
                    break;
                case "uploaded":
                    return 'info';
                    break;
                default:
                    return 'info';
            }
        }
        this.resultTableAdd=function (data,type,updateBadge=true) {
            debug(type);
            debug(data);
            let templateData=data;
            let status=root.statusConverter(data.status);

            /*switch (data.status){
                case "ok":
                    status='success';
                    break;
                case "error":
                    status='danger';
                    break;
                case "uploaded":
                    status='info';
                    break;
            }*/
            templateData.status=status;
            templateData.class='table-'+status;
            root.addBadgeNum(type,status);
            let template=$('template[data-name="table'+type+'Row"]').html()
            let render=Mustache.render(template,templateData);
            $('.table'+type+' tbody').append(render);

            return;
            //let templateData=rowData.originalData;
            templateData.rowNum=rowData.rowNum;
            //let template=$('template[data-name="priceListTableRow"]').html()
            //let render=Mustache.render(template,templateData);
            $('.priceListTable tbody').append(render);

        }
        this.processFileBatchUploaderOnFilesAddedResult=function (data) {
            debug('call processFileBatchUploaderOnFilesAddedResult');

            $.each(data,function (i, v){
                v.id=i;
                root.resultTableAdd(v,'FileAdded');
            });
            //root.resultTableRemove('o_1hcef2opnu1m30muvc1m4f1krdh','FileAdded');
        }
        this.FileBatchUploaderOnComplete=function(up, files) {
            console.log('call FileBatchUploaderOnComplete');
            console.log(up);
            console.log(files.files);
            plupload.each(files.files, function(file) {
                console.log('  FileComplette:', file.id);
                //root.resultTableRemove(file.id,'FileAdded');
                //root.resultTableAdd(v,'FileAdded');
            });
        }

        this.FileBatchUploaderOnFileUploaded=function (up,file,info) {
            //Opts.onFileUploaded(up,file,info);
/*
            console.log('file>',file,' info>',info);
            console.log('hhh');
            console.log(typeof info);
            console.log(typeof info.response);
            console.log(info.response);
            console.log(JSON.parse(info.response));
*/
            $.each(JSON.parse(info.response).result,function (i, v){
                v.id=i;
                root.resultTableAdd(v,'FileUploaded');
                uploadedFileQueue[v.id]=v.name;
            });
            //root.resultTableAdd(info.result,'FileUploaded');
        }

        let uploadedFileQueue={};

this.fucker=function () {
    let info={};
    info.response='{"result":{"o_1hcm503sih8917kju7d1v61er0d":{"name":"200012003000.jpg","status":"uploaded","uploaded":"2023-10-14 05:52:08"},"o_1hcm503sic3d13bt1lp51sd01uuse":{"name":"200012003003.png","status":"uploaded","uploaded":"2023-10-14 05:52:09"},"o_1hcm503sikj01kns1ve21qn51nbof":{"name":"200012003006.jpg","status":"uploaded","uploaded":"2023-10-14 05:52:09"}}}';

    root.FileBatchUploaderOnFileUploaded({},{},info);
/*
    uploadedFileQueue={
        o_1hcm503sic3d13bt1lp51sd01uuse:"200012003003.png",
        o_1hcm503sih8917kju7d1v61er0d:"200012003000.jpg",
        o_1hcm503sikj01kns1ve21qn51nbof:"200012003006.jpg"
    }
*/
    console.log(uploadedFileQueue);
    root.processUploadedFileAttach();

}
        this.addSpinnerToRowDesc=function (fileId,type="FileUploaded") {
            debug('.table'+type+' tbody tr[data-fileId="'+fileId+'"]');
            let td=$('.table'+type+' tbody tr[data-fileId="'+fileId+'"] td[data-filed="desc"]');
            td.html(Mustache.render($('template[data-name="tableFileUploadedRowSpinner"]').html(),{}));
        }


        this.processUploadedFileAttach=function () {
            let count=1;
            let FileNames={};



            for (const [fileId, fileName] of Object.entries(uploadedFileQueue)) {
                count++;
                //console.log(`${key}: ${value}`);
                FileNames[fileId]=fileName;
                root.addSpinnerToRowDesc(fileId,'FileUploaded');
                if(count>Opts.maxQueueProcessItemOneTime){
                    break;
                }
            }
            let ajaxData=new FormData($(Opts.containerCssSelector+' form')[0]);
            ajaxData.append('requestType','filesAttach');
            //ajaxData.append('files',Object.entries(files));
            ajaxData.append('fileNames',JSON.stringify(FileNames));
            console.log(ajaxData);
            let ajaxUrl=Opts.URL.store;
            let ajaxMethod="POST";
            $.ajax({
                url:ajaxUrl,
                data:ajaxData,
                type:ajaxMethod,
                contentType:false,
                processData: false,
                headers: {
                    'X-CSRF-TOKEN': Opts.token
                },
                success:function (data){
                    if(data.status==200){
                        root.processUploadedFileAttachResult(data.result);
                    }else{
                        console.log('File Check received');
                        let errorData='';
                        errorData+=ajaxUrl+'<br>\n';
                        let object = {};
                        ajaxData.forEach((value, key) => object[key] = value);
                        errorData+=JSON.stringify(object)+'<br>\n<br>\n';
                        errorData+='Response> '+JSON.stringify(data)+'<br>\n';
                        Toast.create('Feldolgozási hiba!', '<b>Kérjük jelezze a fejlesztőknek az alábbi adatokat:</b><br>\n'+errorData, TOAST_STATUS.DANGER);
                    }
                }
            });
        }
        this.setRowStatus=function (type,fileId,status) {
            let tr=$('.table'+type+' tbody tr[data-fileId="'+fileId+'"]');
            tr.removeClass("table-"+tr.data("status"));
            tr.addClass("table-"+status);
        }
        this.processUploadedFileAttachResult=function (data) {
            debug('call processUploadedFileAttachResult');
            $.each(data,function (fileId, v){
                v.id=fileId;
                let td=$('.tableFileUploaded tbody tr[data-fileId="'+fileId+'"] td[data-filed="desc"]');
                td.html(v.desc);
                let tr=$('.tableFileUploaded tbody tr[data-fileId="'+fileId+'"]');
                root.addBadgeNum("FileUploaded",tr.data("status"),-1);
                root.addBadgeNum("FileUploaded",root.statusConverter(v.status));
                root.setRowStatus("FileUploaded",fileId,root.statusConverter(v.status))
                delete uploadedFileQueue[fileId];
                //root.resultTableAdd(v,'FileAdded');
            });
            if(Object.keys(uploadedFileQueue).length>0){
                root.processUploadedFileAttach();
            }
        }
    }

    $(document).ready(function() {
        console.log('helloka');
        APP.ProductFileBatchUploaderAdmin= new window.ProductFileBatchUploaderAdmin();
        APP.ProductFileBatchUploaderAdmin.init({
            token:'{{csrf_token()}}',
            URL:{
                root:'{{url('')}}',
                store:'{{route('admin.fileBatchUpload.store')}}',
                upload:'{{route('admin.fileBatchUpload.upload')}}',
            },
        });
        $(".supplierSelect").select2({
            maximumSelectionLength: 1,
        });


        window.xxx=function () {
 /*           // When all files are uploaded submit form
            $('#uploader').on('complete', function(up, files) {
                //$('#form')[0].submit();
                console.log('[UploadComplete]');
                console.log(up);
                console.log(files);
            });*/

            // Handle the case when form was submitted before uploading has finished
            $('#form').submit(function(e) {
                // Files in queue upload them first
                if ($('#uploader').plupload('getFiles').length > 0) {

                    // When all files are uploaded submit form
                    $('#uploader').on('complete', function() {
                        //$('#form')[0].submit();
                    });

                    $('#uploader').plupload('start');
                } else {
                    alert("Nincs kijelőlve file!");
                }
                return false; // Keep the form from submitting
            });

        }

    });
</script>
