@extends('admin.master')

@section('content')
    <div class="row">
        <div class="col-lg-12">
            <div class="contentpanel">
                <form id="listForm" method="post">
                    <!-- 功能按鈕(新增/批量處理等等) -->
                    <div class="row" style="margin-bottom: 5px;">
                        <div class="col-lg-12">
                            <ol class="headermenu">
                                <li>
                                    <button class="btn btn-darkblue btn-xs"
                                            id="step_0" {{ ($can_step_0) ? '' : 'disabled' }}><strong>前置作業:
                                            人工添加批次(全部)</strong>
                                    </button>
                                </li>
                                <li>
                                    <button class="btn btn-darkblue btn-xs" id="step_21"><strong>第二步:
                                            取得測試用XML連結(BY品牌)</strong></button>
                                    <input type="text" id="test_link" style="display: inline-block;">
                                </li>
                                <li>
                                    <button class="btn btn-darkblue btn-xs"
                                            id="step_22" {{ ($can_step_2) ? '' : 'disabled' }}><strong>第二步:
                                            匯入測試報告(BY品牌)</strong>
                                    </button>
                                    <input type="file" style="display: none;" id="step_23" name="step_23">
                                </li>
                                <li>
                                    <button class="btn btn-darkblue btn-xs" id="step_4"><strong>第四步:
                                            更新動態饋給來源(BY品牌)</strong>
                                    </button>
                                </li>
                                <li>
                                    <button class="btn btn-darkblue btn-xs" id="step_5"><strong>第五步:
                                            匯出修改用excel(BY品牌)</strong>
                                    </button>
                                </li>
                            </ol>
                        </div>
                    </div>
                    <!-- 搜尋段 -->
                    <div class="panel panel-default">
                        <div class="panel-heading" data-toggle="collapse" data-target="#search_content">
                            <h3 class="panel-title">商品維護</h3>
                        </div>
                        <div id="search_content" class="collapse in">
                            <div class="panel-body">
                                <!-- 第一步: 選品牌 -->
                                <div class="form-group col-xs-12 col-sm-6 col-lg-6">
                                    <label for="category">第一步: 選品牌</label>
                                    <select class="form-control input-sm" id="brand_no">
                                        @foreach($brands as $data)
                                            <option value="{{ $data['id'] }}"
                                                    data-label="{{ $data['brandLabel'] }}">{{ $data['brandName'] }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <!-- 第一步: 選批次號 -->
                                <div class="form-group col-xs-12 col-sm-6 col-lg-6">
                                    <label for="category">第一步: 選批次號</label>
                                    <select class="form-control input-sm" id="batch_no">
                                        @foreach($batchs as $data)
                                            <option value="{{ $data['batch_no'] }}">{{ $data['batch_no'] }}{{ ($data['m_status'] > 1) ? ' - 曾處理過' : '' }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <!-- 第三步: 品名檢視 -->
                                <div class="form-group col-xs-12 col-sm-6 col-lg-6">
                                    <label for="tagName">第三步: 品名檢視</label>
                                    <input type="text" class="form-control input-sm" id="g_title"
                                           maxlength="512">
                                </div>
                                <!-- 第三步: 描述檢視 -->
                                <div class="form-group col-xs-12 col-sm-6 col-lg-6">
                                    <label for="tagName">第三步: 描述檢視</label>
                                    <input type="text" class="form-control input-sm" id="g_description"
                                           maxlength="4096">
                                </div>
                                <!-- 第三步: 掃描問題檢視 -->
                                <div class="form-group col-xs-12 col-sm-6 col-lg-6">
                                    <label for="tagName">第三步: 掃描問題檢視</label>
                                    <input type="text" class="form-control input-sm" id="m_comment"
                                           maxlength="4096">
                                </div>
                                <!-- 第三步: 狀態檢視(匯入報告後為掃描結果) -->
                                <div class="form-group col-xs-12 col-sm-6 col-lg-6">
                                    <label for="category">第三步: 狀態檢視(匯入報告後為掃描結果)</label>
                                    <select class="form-control input-sm" id="m_status">
                                        @foreach($mstatuss as $data)
                                            <option value="{{ $data['id'] }}">{{ $data['mstatusName'] }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <!-- Search -->
                                <div class="form-group col-xs-12 col-sm-12 col-lg-12">
                                    <a class="btn btn-success btn-xs" onclick="javascript: custom_search();">
                                        <div class="glyphicon glyphicon-search"></div>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <hr class="search-hr"/>
                    <!-- 列表段 -->
                    <div class="row">
                        <div class="col-lg-12">
                            <table id="GridView1" class="table table-striped table-bordered" cellspacing="0">
                                <thead>
                                <tr>
                                    <th>系統號</th>
                                    <th>商品號</th>
                                    <th>品名</th>
                                    <th>描述</th>
                                    <th>圖片</th>
                                    <th>定價</th>
                                    <th>售價</th>
                                    <th>掃描結果</th>
                                    <th>掃描問題</th>
                                </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </form>
                <!-- row -->
            </div>
        </div>
    </div>
@endsection

@section('extjs')
    <script>
        $(document).ready(function () {
            var table = $('#GridView1').dataTable({
                "scrollX": true,
                "processing": true,
                "serverSide": true,
                "ajax": "productManagement/grid",
                "paging": true,
                "ordering": true,
                "info": true,
                "order": [[0, "desc"]],
                "stateSave": true,
                "pagingType": "full",
                "bFilter": true,
                "aoColumnDefs": [{
                    'bSortable': false,
                    'aTargets': [1, 4, 5, 6] //不想參加排序的欄位，可指定多個，逗號分隔
                }]
            });
            // 從網址參觸發搜尋
            custom_search();
            $('#GridView1_filter').hide();
        });

        //客製化搜尋欄位
        function custom_search() {
            $('#GridView1').DataTable()
                .column(1).search($('#brand_no').val())
                .column(2).search($('#batch_no').val())
                .column(3).search($('#g_title').val())
                .column(4).search($('#g_description').val())
                .column(5).search($('#m_comment').val())
                .column(6).search($('#m_status').val())
            ;
            $('#GridView1').dataTable().fnDraw(true);
        }

        // 人工添加批次
        $("#step_0").click(function () {
            $.ajax({
                url: 'productManagement/manualXml',
                type: 'GET',
                async: false,
                success: function (data) {
                    // 人工添加批次狀態鎖定
                    alert('請等待處裡完成');
                    $(this).prop("disabled", true);
                },
                error: function (xhr) {
                }
            });
            $(this).prop("disabled", true);
            return false;
        });

        // 取得測試連結
        $("#step_21").click(function () {
            var test_link = document.getElementById("test_link");
            test_link.value = 'https://' + '{{ $step_2_s3 }}' + '.s3.amazonaws.com/' + '{{ $step_2_env }}' + '/' + $('#brand_no :selected').attr('data-label') + '/' + $('#batch_no :selected').val().replace(/[^0-9]/g, '') + '.xml'
            test_link.select();
            document.execCommand("copy");
            return false;
        });

        // 匯入測試報告
        $("#step_22").click(function () {
            $("#step_23").click();
            $(this).prop("disabled", true);
            return false;
        });

        // 更新動態饋給
        $("#step_4").click(function () {
            $.ajax({
                url: 'productManagement/manualEndpoint',
                type: 'GET',
                async: false,
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                data: {
                    "brand_no": $("#brand_no").val(),
                    "batch_no": $("#batch_no").val()
                },
                success: function (data) {
                    // 更新動態饋給狀態鎖定
                    alert('請等待更新完成');
                    $(this).prop("disabled", true);
                },
                error: function (xhr) {
                }
            });
            $(this).prop("disabled", true);
            return false;
        });

        // 匯出報告
        $("#step_5").click(function () {
            //加個讀取中畫面
            $.blockUI({
                css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: .5,
                    color: '#FFF'
                }
            });
            var http = new XMLHttpRequest();
            http.responseType = 'blob';
            var header;
            var blob;
            var url = 'productManagement/exportCsv';
            var params = 'brand_no=' + $('#brand_no').val() + '&batch_no=' + $('#batch_no').val();
            http.open("POST", url, true);
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            http.onreadystatechange = function () {//Call a function when the state changes.
                if (http.readyState == 4 && http.status == 200) {
                    var filename = "";
                    var disposition = http.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }
                    var type = http.getResponseHeader('Content-Type');
                    blob = new Blob([http.response], {type: type, endings: 'native'});
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);
                    var a = document.createElement("a");
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                }
                //解除鎖定
                $.unblockUI();
            }
            http.send(params);
            return false;
        });

        setInterval(function () {
            // 人工添加批次狀態鎖定
            $.ajax({
                url: 'productManagement/manualXmlStatus',
                type: 'GET',
                async: false,
                success: function (data) {
                    if (data.can_step_0 == true) {
                        if ($("#step_0").prop("disabled") == true) {
                            alert('添加批次完成');
                        }
                        $("#step_0").prop("disabled", false);
                    } else {
                        $("#step_0").prop("disabled", true);
                    }
                },
                error: function (xhr) {
                }
            });
            // 匯入資料狀態鎖定
            $.ajax({
                url: 'productManagement/importCsvStatus',
                type: 'GET',
                async: false,
                success: function (data) {
                    if (data.can_step_2 == true) {
                        // if ($("#step_22").prop("disabled") == true) {
                        //     alert('匯入報告完成');
                        // }
                        $("#step_22").prop("disabled", false);
                    } else {
                        $("#step_22").prop("disabled", true);
                    }
                },
                error: function (xhr) {
                }
            });
            // 更新動態饋給狀態鎖定
            $.ajax({
                url: 'productManagement/manualEndpointStatus',
                type: 'GET',
                async: false,
                success: function (data) {
                    if (data.can_step_4 == true) {
                        if ($("#step_4").prop("disabled") == true) {
                            alert('更新動態饋給完成');
                        }
                        $("#step_4").prop("disabled", false);
                    } else {
                        $("#step_4").prop("disabled", true);
                    }
                },
                error: function (xhr) {
                }
            });
            $('[data-toggle="popover"]').popover();
        }, 5000);

        $(document).ready(function () {
            $("#step_23").on("change", function () {
                $.blockUI({
                    css: {
                        border: 'none',
                        padding: '15px',
                        backgroundColor: '#000',
                        '-webkit-border-radius': '10px',
                        '-moz-border-radius': '10px',
                        opacity: .5,
                        color: '#FFF'
                    }
                });
                var input = $(this);
                var formData = new FormData();
                formData.append('csv', input[0].files[0]);
                formData.append('brand_no', $("#brand_no").val());
                formData.append('batch_no', $("#batch_no").val());
                $.ajax({
                    url: "productManagement/importCsv",
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        alert('上傳完成，請等待匯入報告。');
                        $.unblockUI();
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        alert('上傳失敗。');
                        $.unblockUI();
                    }
                });
            });
        });

    </script>
@endsection
