@extends('admin.master')

@section('content')
    <div class="row">
        <div class="col-lg-12">
            <!-- 指定新增的端點 -->
            <form id="EditForm" class="form-horizontal" method="post"
                  action="{{ url('/backend/dataManagement/eventManagement/store') }}">
                {{ csrf_field() }}
                <div class="panel panel-primary">
                    <div class="panel-heading">
                        <!-- 更改文案 -->
                        <h4 class="panel-title">{{ ($operdata == "") ? "Create " : "Modify " }}活動</h4>
                    </div>
                    <div class="panel-body">
                        <div>
                            <!-- 表格本體 -->
                            <table class="table" cellspacing="0" id="DetailsView1" style="border-collapse:collapse;">
                                <tbody>
                                <!-- 欄位：自增量 -->
                                @if ($operdata == "")
                                    <input type="hidden" name="mode" value="insert"/>
                                    <!-- Insert Mode -->
                                @else
                                    <!-- Edit Mode -->
                                    <tr>
                                        <td class="col-lg-2">自增量</td>
                                        <td>
                                            <input name="id" type="hidden" value="{{ $operdata['id'] }}" id="id"/>
                                            {{ $operdata['id'] }}
                                        </td>
                                    </tr>
                                @endif
                                <!-- 欄位：活動名稱 -->
                                <!-- ALL Mode -->
                                <tr>
                                    <td class="header-require col-lg-2">活動名稱</td>
                                    <td>
                                        <div class="col-lg-3 nopadding">
                                            @if ($operdata == "")
                                                <input name="name" type="text" value="" maxlength="16" id="name"
                                                       class="form-control">
                                            @else
                                                <input name="name" type="text" value="{{ $operdata['name'] }}"
                                                       maxlength="16" id="name" class="form-control">
                                            @endif
                                            <label class="error" for="name"></label>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 欄位：主視覺 -->
                                <!-- ALL Mode -->
                                <tr>
                                    <td class="header-require col-lg-2">主視覺</td>
                                    <td>
                                        <div class="col-lg-3 nopadding">
                                            @if ($operdata == "")
                                                <div class="form-group has-warning" style="margin: 0">
                                                    <div>預覽圖片 (限制 JPG 格式 / 尺寸為 1024x1024 / 最大為 2MB)</div>
                                                    <label class="text-center mb-5 image-preview-wrapper"
                                                           for="file-uploader">
                                                        <img src="https://via.placeholder.com/300x300/efefef?text=Upload"
                                                             alt="placehoder" class="img-thumbnail"
                                                             data-target="image-preview" width="100" height="100">
                                                        <div class="spinner-wrapper position-absolute"
                                                             data-target="spinner">
                                                            <div class="spinner-border text-secondary" role="status">
                                                                <span class="sr-only">Loading...</span>
                                                            </div>
                                                        </div>
                                                    </label>
                                                    <div class="row">
                                                        <div class="col-12 col-md-6 mx-auto">
                                                            <div class="custom-file">
                                                                <input type="file" class="custom-file-input"
                                                                       data-target="file-uploader" id="file-uploader"
                                                                       style="display: none;">
                                                                <input type="hidden" data-target="file-kv" id="kv"
                                                                       name="kv" value="" class="form-control"/>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            @else
                                                <div class="form-group has-warning" style="margin: 0">
                                                    <div>預覽圖片 (限制 JPG 格式 / 尺寸為 1024x1024 / 最大為 2MB)</div>
                                                    <label class="text-center mb-5 image-preview-wrapper"
                                                           for="file-uploader">
                                                        <img src="{{ env('APP_URL') . $operdata['kv'] }}"
                                                             alt="placehoder" class="img-thumbnail"
                                                             data-target="image-preview" width="100" height="100">
                                                        <div class="spinner-wrapper position-absolute"
                                                             data-target="spinner">
                                                            <div class="spinner-border text-secondary" role="status">
                                                                <span class="sr-only">Loading...</span>
                                                            </div>
                                                        </div>
                                                    </label>
                                                    <div class="row">
                                                        <div class="col-12 col-md-6 mx-auto">
                                                            <div class="custom-file">
                                                                <input type="file" class="custom-file-input"
                                                                       data-target="file-uploader" id="file-uploader"
                                                                       style="display: none;">
                                                                <input type="hidden" data-target="file-kv" id="kv"
                                                                       name="kv" value="{{ $operdata['kv'] }}"
                                                                       class="form-control"/>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            @endif
                                            <label class="error" for="kv"></label>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 欄位：起始日 -->
                                <!-- ALL Mode -->
                                <tr>
                                    <td class="header-require col-lg-2">起始日</td>
                                    <td>
                                        <div class="col-lg-1 nopadding">
                                            @if ($operdata == "")
                                                <input class="form-control input-sm" name="date_begin" type="text"
                                                       value="" maxlength="10" id="date_begin">
                                            @else
                                                <input class="form-control input-sm" name="date_begin" type="text"
                                                       value="{{ $operdata['date_begin'] }}" id="date_begin">
                                            @endif
                                            <label class="error" for="date_begin"></label>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 欄位：結束日 -->
                                <!-- ALL Mode -->
                                <tr>
                                    <td class="header-require col-lg-2">結束日</td>
                                    <td>
                                        <div class="col-lg-1 nopadding">
                                            @if ($operdata == "")
                                                <input class="form-control input-sm" name="date_final" type="text"
                                                       value="" maxlength="10" id="date_final">
                                            @else
                                                <input class="form-control input-sm" name="date_final" type="text"
                                                       value="{{ $operdata['date_final'] }}" id="date_final">
                                            @endif
                                            <label class="error" for="date_final"></label>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 欄位：獎項訊息 -->
                                <!-- ALL Mode -->
                                <tr>
                                    <td class="header-require col-lg-2">獎項訊息</td>
                                    <td>
                                        <div class="col-lg-1 nopadding">
                                            <a id="addRow">添加獎項</a>
                                            <table id="item" class="table table-striped table-bordered"
                                                   cellspacing="0">
                                                <thead>
                                                <tr>
                                                    <th></th>
                                                    <th>獎項名稱</th>
                                                    <th>需上傳身分證</th>
                                                    <th>需上傳存摺</th>
                                                    <th>專屬連結</th>
                                                </tr>
                                                </thead>
                                            </table>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 欄位：聯絡人信箱 -->
                                <!-- ALL Mode -->
                                <tr>
                                    <td class="header-require col-lg-2">聯絡人信箱</td>
                                    <td>
                                        <div class="col-lg-3 nopadding">
                                            @if ($operdata == "")
                                                <input name="email" type="text" value="" maxlength="128" id="email"
                                                       class="form-control">
                                            @else
                                                <input name="email" type="text" value="{{ $operdata['email'] }}"
                                                       maxlength="128" id="email" class="form-control">
                                            @endif
                                            <label class="error" for="email"></label>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 欄位：聯絡人電話 -->
                                <!-- ALL Mode -->
                                <tr>
                                    <td class="header-require col-lg-2">聯絡人電話</td>
                                    <td>
                                        <div class="col-lg-3 nopadding">
                                            @if ($operdata == "")
                                                <input name="tel" type="text" value="" maxlength="128" id="tel"
                                                       class="form-control">
                                            @else
                                                <input name="tel" type="text" value="{{ $operdata['tel'] }}"
                                                       maxlength="128" id="tel" class="form-control">
                                            @endif
                                            <label class="error" for="tel"></label>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 欄位：建立日期 -->
                                <!-- ALL Mode -->
                                @if ($operdata == "")
                                @else
                                    <tr>
                                        <td class="header-require col-lg-2">建立日期</td>
                                        <td>
                                            <div class="col-lg-3 nopadding">
                                                {{ $operdata['cdate'] }}
                                            </div>
                                        </td>
                                    </tr>
                                @endif
                                <!-- 欄位：最後修改日期 -->
                                <!-- ALL Mode -->
                                @if ($operdata == "")
                                @else
                                    <tr>
                                        <td class="header-require col-lg-2">最後修改日期</td>
                                        <td>
                                            <div class="col-lg-3 nopadding">
                                                {{ $operdata['mdate'] }}
                                            </div>
                                        </td>
                                    </tr>
                                @endif
                                <!-- 欄位：最後修改人 -->
                                <!-- ALL Mode -->
                                @if ($operdata == "")
                                @else
                                    <tr>
                                        <td class="header-require col-lg-2">最後修改人</td>
                                        <td>
                                            <div class="col-lg-3 nopadding">
                                                {{ $operdata['oid'] }}
                                            </div>
                                        </td>
                                    </tr>
                                @endif
                                <!-- 下控制按鈕 -->
                                <tr>
                                    <td>&nbsp;</td>
                                    <td>
                                        <div style="text-align: right">
                                        @if ($operdata == "")
                                            <!-- Insert Mode -->
                                                <input type="submit" name="btnUpdate_foot" value="Create"
                                                       id="btnUpdate_foot" class="btn btn-primary btn-xs"
                                                       onclick="submitForm();">
                                        @else
                                            <!-- Edit Mode -->
                                                <input type="submit" name="btnUpdate_foot" value="Modify"
                                                       id="btnUpdate_foot" class="btn btn-primary btn-xs"
                                                       onclick="submitForm();">
                                            @endif
                                            <input type="button" name="btnBackTo2_foot" value="Back"
                                                   id="btnBackTo2_foot" class="btn btn-default btn-xs">
                                        </div>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <!-- panel-body -->
                </div>
            </form>
        </div>
    </div>
@endsection

@section('extjs')
    <script>
        $(document).ready(function () {
            $("#btnBackTo2").click(function () {
                // 上方的返回列表按鈕觸發
                location.href = '{{ url('backend/dataManagement/eventManagement') }}';
            });
            $("#btnBackTo2_foot").click(function () {
                // 下方的返回列表按鈕觸發
                location.href = '{{ url('backend/dataManagement/eventManagement') }}';
            });
            // 初始化需要偵錯的表格
            $('#EditForm').validate();
            // 正規表達驗證初始化
            $.validator.addMethod(
                "regex",
                function (value, element, regexp) {
                    var re = new RegExp(regexp);
                    return this.optional(element) || re.test(value);
                }
            );
            // 各欄位
            $('#name').rules("add", {
                required: true,
                minlength: 1,
                maxlength: 16,
                messages: {
                    required: "活動名字 length must between 1-16",
                    minlength: "活動名字 length must between 1-16",
                    maxlength: "活動名字 length must between 1-16"
                }
            });
            $('#kv').rules("add", {
                // 此單元沒有用
                required: true,
                minlength: 1,
                maxlength: 16,
                messages: {
                    required: "必須上傳圖片",
                    minlength: "必須上傳圖片",
                    maxlength: "必須上傳圖片"
                }
            });
            $('#date_begin').rules("add", {
                required: true,
                minlength: 10,
                maxlength: 10,
                messages: {
                    required: "必須要有起始日",
                    minlength: "必須要有起始日",
                    maxlength: "必須要有起始日"
                }
            });
            $('#date_final').rules("add", {
                required: true,
                minlength: 10,
                maxlength: 10,
                messages: {
                    required: "必須要有結束日",
                    minlength: "必須要有結束日",
                    maxlength: "必須要有結束日"
                }
            });
            $('#email').rules("add", {
                required: true,
                minlength: 1,
                maxlength: 128,
                messages: {
                    required: "聯絡人信箱 length must between 1-128",
                    minlength: "聯絡人信箱 length must between 1-128",
                    maxlength: "聯絡人信箱 length must between 1-128"
                }
            });
            $('#tel').rules("add", {
                required: true,
                minlength: 1,
                maxlength: 128,
                messages: {
                    required: "聯絡人電話 length must between 1-128",
                    minlength: "聯絡人電話 length must between 1-128",
                    maxlength: "聯絡人電話 length must between 1-128"
                }
            });

            // 表格
            var t = $('#item').DataTable({
                "paging": false,
                "bFilter": false
            });
            // 添加獎項
            var counter = 1;
            $('#addRow').on('click', function () {
                t.row.add([
                    "<a class='row-delete'>X</a>",
                    "<input type='text' maxlength='16' name='items[new][" + counter + "][name]' id='text_new_name_" + counter + "'><label class='error' for='text_new_name_" + counter + "'></label>",
                    "<input class='form-check-input' type='checkbox' name='items[new][" + counter + "][is_ide]' data-type='chk_new_is_ide_" + counter + "' value='N'>",
                    "<input class='form-check-input' type='checkbox' name='items[new][" + counter + "][id_acc]' data-type='chk_new_id_acc_" + counter + "' value='N'>",
                    ''
                ]).draw(false);
                // 新增元件的綁定事件
                $("#text_new_name_" + counter).rules("add", {
                    required: true,
                    minlength: 1,
                    maxlength: 16,
                    messages: {
                        required: "獎項名稱 length must between 1-16",
                        minlength: "獎項名稱 length must between 1-16",
                        maxlength: "獎項名稱 length must between 1-16"
                    }
                });
                $("input[data-type='chk_new_is_ide_" + counter + "']").click(function () {
                    if ($(this).is(":checked")) {
                        $(this).val('Y');
                    } else {
                        $(this).val('N');
                    }
                });
                $("input[data-type='chk_new_id_acc_" + counter + "']").click(function () {
                    if ($(this).is(":checked")) {
                        $(this).val('Y');
                    } else {
                        $(this).val('N');
                    }
                });
                counter++;
            });
            // 刪除獎項
            $('#item tbody').on('click', 'a.row-delete', function () {
                t
                    .row($(this).parents('tr'))
                    .remove()
                    .draw();
            });
            // 編輯模式載入既有獎項
            @if ($operdata != "")
            $.ajax({
                url: '{{ env('APP_URL') }}/backend/dataManagement/eventManagement/getItems/{{ $operdata['id'] }}',
                type: 'get',
                cache: false,
                processData: false,
                contentType: false,
                async: false,
                dataType: 'json',
                success: function (data) {
                    for (i = 0; i < data.length; i++) {
                        t.row.add([
                            "",
                            "<input type='text' maxlength='16' name='items[edit][" + data[i]['id'] + "][name]' id='text_edit_name_" + data[i]['id'] + "' value='" + data[i]['name'] + "'><label class='error' for='text_edit_name_" + data[i]['id'] + "'></label>",
                            "<input class='form-check-input' type='checkbox' name='items[edit][" + data[i]['id'] + "][is_ide]' data-type='chk_edit_is_ide_" + data[i]['id'] + "' value='N' readonly>",
                            "<input class='form-check-input' type='checkbox' name='items[edit][" + data[i]['id'] + "][id_acc]' data-type='chk_edit_id_acc_" + data[i]['id'] + "' value='N' readonly>",
                            "<input type='text' id='text_edit_link_" + data[i]['id'] + "' value='" + data[i]['link'] + "' readonly>"
                        ]).draw(false);
                        // 新增元件的綁定事件
                        $("#text_edit_name_" + data[i]['id']).rules("add", {
                            required: true,
                            minlength: 1,
                            maxlength: 16,
                            messages: {
                                required: "獎項名稱 length must between 1-16",
                                minlength: "獎項名稱 length must between 1-16",
                                maxlength: "獎項名稱 length must between 1-16"
                            }
                        });
                        $("input[data-type='chk_edit_is_ide_" + data[i]['id'] + "']").click(function () {
                            if ($(this).is(":checked")) {
                                $(this).val('Y');
                            } else {
                                $(this).val('N');
                            }
                        });
                        $("input[data-type='chk_edit_id_acc_" + data[i]['id'] + "']").click(function () {
                            if ($(this).is(":checked")) {
                                $(this).val('Y');
                            } else {
                                $(this).val('N');
                            }
                        });
                        if (data[i]['is_ide'] == 'Y') $("input[data-type='chk_edit_is_ide_" + data[i]['id'] + "']").click();
                        if (data[i]['id_acc'] == 'Y') $("input[data-type='chk_edit_id_acc_" + data[i]['id'] + "']").click();
                        $("input[data-type='chk_edit_is_ide_" + data[i]['id'] + "']").attr('disabled', 'disabled');
                        $("input[data-type='chk_edit_id_acc_" + data[i]['id'] + "']").attr('disabled', 'disabled');
                        $("#text_edit_link_" + data[i]['id']).click(function () {
                            $(this).select();
                            document.execCommand("copy");
                        });
                    }
                }
            });
            @if ($operdata['archive'] == \App\Http\Services\ConstDef\GeneralConst::ARCHIVE_YES)
            $("input").prop("disabled", true);
            @endif
            @endif

        });

        //提交與取消按鈕
        function submitForm() {
            if (!!($("#EditForm").valid()) === false) {
                return false;
            } else {
                $(document).ready(function () {
                    $.blockUI({
                        css: {
                            border: 'none',
                            padding: '15px',
                            backgroundColor: '#000',
                            '-webkit-border-radius': '10px',
                            '-moz-border-radius': '10px',
                            opacity: .5,
                            color: '#FFF'
                        }
                    });
                });
            }
        }

        function cancelValidate() {
            $("#EditForm").validate().cancelSubmit = true;
        }

        // 圖片上傳
        imagePreview = document.querySelector('[data-target="image-preview"]');
        spinner = document.querySelector('[data-target="spinner"]');
        fileUploader = document.querySelector('[data-target="file-uploader"]');
        fileKv = document.querySelector('[data-target="file-kv"]');
        fileUploader.addEventListener("change", handleFileUpload);

        async function handleFileUpload(e) {
            e.preventDefault();
            try {
                const file = e.target.files[0];
                setUploading(true);
                if (!file) return;
                else {
                    const beforeUploadCheck = await beforeUpload(file);
                    if (!beforeUploadCheck.isValid) throw beforeUploadCheck.errorMessages;
                    const arrayBuffer = await getArrayBuffer(file);
                    var response = await uploadFileAJAX(arrayBuffer);
                    alert("上傳成功");
                    showPreviewImage(response);
                }
            } catch (error) {
                alert(error);
                console.log("上傳失敗: ", error);
            } finally {
                e.target.value = '';
                setUploading(false);
            }
        }

        function showPreviewImage(response) {
            imagePreview.src = response.url;
            fileKv.value = response.kv;
        }

        function getArrayBuffer(fileObj) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.addEventListener("load", () => {
                    resolve(reader.result);
                });
                reader.addEventListener("error", () => {
                    reject("error occurred in getArrayBuffer");
                });
                reader.readAsArrayBuffer(fileObj);
            });
        }

        function uploadFileAJAX(arrayBuffer) {
            return fetch("{{ env('APP_URL') }}/backend/dataManagement/eventManagement/saveImg", {
                headers: {
                    version: 1,
                    "content-type": "application/json"
                },
                method: "POST",
                body: JSON.stringify({
                    image: Array.from(new Uint8Array(arrayBuffer))
                })
            })
                .then(res => {
                    if (!res.ok) {
                        throw res.statusText;
                    }
                    return res.json();
                })
                .then(data => data)
                .catch(err => console.log("err", err));
        }

        function beforeUpload(fileObject) {
            return new Promise(resolve => {
                const validFileTypes = ["image/jpeg"];
                const isValidFileType = validFileTypes.includes(fileObject.type);
                let errorMessages = [];
                if (!isValidFileType) {
                    errorMessages.push("只支援 JPG 格式圖片");
                }
                const dim = Promise.resolve(getImageSize(fileObject));
                var isValidDimension = true;
                dim.then(function (result) {
                    if (result.width != 1024 || result.height != 1024) {
                        errorMessages.push("圖片尺寸必須為 1024x1024");
                        isValidDimension = false;
                    }
                    const isValidFileSize = (fileObject.size / 1024 / 1024) < 2;
                    if (!isValidFileSize) {
                        errorMessages.push("圖片最大 2MB");
                    }
                    resolve({
                        isValid: isValidFileType && isValidFileSize && isValidDimension,
                        errorMessages: errorMessages.join("\n")
                    });
                });
            });
        }

        function setUploading(isUploading) {
            if (isUploading === true) {
                spinner.classList.add("opacity-1");
            } else {
                spinner.classList.remove("opacity-1");
            }
        }

        function getImageSize(file) {
            return new Promise((resolve, reject) => {
                var _URL = window.URL || window.webkitURL;
                var img = new Image();
                img.onload = () => resolve({height: img.height, width: img.width});
                img.onerror = reject;
                img.src = _URL.createObjectURL(file);
            });
        }

        // 日期選擇器
        $('#date_begin').datepicker({
            dateFormat: 'yy-mm-dd'
        });
        $('#date_final').datepicker({
            dateFormat: 'yy-mm-dd'
        });

    </script>
@endsection
