@extends('admin.master')

@section('content')
    <div class="row">
        <div class="col-xl-12">
            <form id="EditForm" class="form-horizontal" method="post"
                  action="{{ url('/backend/dataManagement/track/store') }}" enctype="multipart/form-data">
                {{ csrf_field() }}
                <div class="panel _panel-primary">
                    <div class="panel-heading _panel-heading">
                        <h4 class="panel-title m-0">{{ ($operdata == "") ? "新增 " : "修改 " }}議程資料</h4>
                    </div>
                    <div class="panel-body row">
                        <div>
                            <table class="table" style="border-collapse:collapse;">
                                <tbody class="msgTbody">
                                <input type="hidden" id="operateMode" value="edit"/>
                                <input type="hidden" id="id" value="{{$id}}"/>
                                
                                <!-- 欄位：圖文頭貼設定 -->
                                <tr class="msgTemplate">
                                    <td class="header-require col-xl-2">議程資料設定</td>
                                    <td>
                                        <div id="imgmapcontent-tab1">
                                            <input type="hidden" id="tab1MenuFlag"/>
                                            <input type="hidden" id="tab1ImagemapModelType" value="m1">
                                            <input type="hidden" id="tab1ImagemapImgSize" value='{"width":800,"height":800}'>
                                            
                                            <!-- 表格本體 -->
                                            <table class="table" id="DetailsView1" style="border-collapse:collapse;">
                                                <tbody>
                                                <!-- 序號 -->
                                                @if ($operdata == "")
                                                    <!-- Insert Mode -->
                                                    <input type="hidden" name="mode" value="insert"/>
                                                @else
                                                    <!-- Edit Mode -->
                                                    <input type="hidden" name="mode" value="edit"/>
                                                    <tr>
                                                        <td class="col-xl-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-xl-2">trackNo</td>
                                                        <td>
                                                            <div class="col-xl-3 nopadding">
                                                                @if ($operdata == "")
                                                                    <input name="trackNo" type="text" value="" maxlength="100"
                                                                        id="trackNo" class="form-control">
                                                                @else
                                                                    <input name="trackNo" type="text"
                                                                        value="{{ $operdata['trackNo'] }}" maxlength="100"
                                                                        id="trackNo" class="form-control">
                                                                @endif
                                                                <label class="error" for="trackNo"></label>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <!-- 欄位：說明 -->
                                                    <!-- ALL Mode -->
                                                    <tr>
                                                        <td class="header-require col-xl-2">trackTitle</td>
                                                        <td>
                                                            <div class="col-xl-3 nopadding">
                                                                @if ($operdata == "")
                                                                    <input name="trackTitle" type="text" value="" maxlength="500"
                                                                        id="trackTitle"
                                                                        class="form-control">
                                                                @else
                                                                    <input name="trackTitle" type="text"
                                                                        value="{{ $operdata['trackTitle'] }}"
                                                                        maxlength="500" id="trackTitle" class="form-control">
                                                                @endif
                                                                <label class="error" for="trackTitle"></label>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <!-- 欄位：說明 -->
                                                    <!-- ALL Mode -->
                                                    <tr>
                                                        <td class="header-require col-xl-2">trackLimit</td>
                                                        <td>
                                                            <div class="col-xl-3 nopadding">
                                                                @if ($operdata == "")
                                                                    <input name="trackLimit" type="text" value="" maxlength="500"
                                                                        id="trackLimit"
                                                                        class="form-control">
                                                                @else
                                                                    <input name="trackLimit" type="text"
                                                                        value="{{ $operdata['trackLimit'] }}"
                                                                        maxlength="500" id="trackLimit" class="form-control">
                                                                @endif
                                                                <label class="error" for="trackLimit"></label>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        
                                            <hr>

                                        </div>
                                    </td>
                                </tr>

                                <!-- 下控制按鈕 -->
                                <tr>
                                    <td>&nbsp;</td>
                                    <td>
                                        <div style="text-align: right">
                                            <input type="button" id="btnSave" value="儲存" class="btn btn-primary" style="margin-right: 5px;">
                                            <input type="button" id="btnBackToList" value="返回" class="btn btn-secondary">
                                        </div>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div id="ajax-spinner" style="display:none;">
        <img src="{{ asset('assets/images/backend_spinner.svg') }}" />
    </div>

    <link rel="stylesheet" href="{{url('assets/resize-controller/project/resizeControl.css')}}">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        /* --------------- 全域 --------------- */

        .msgTemplate div.form-group _form-group {
            margin: 0;
        }

        .tab-content {
            -webkit-box-shadow: none;
            -moz-box-shadow: none;
            box-shadow: none;
        }

        /* --------------- Imagemap --------------- */

        .imagemap-model-small-container {
            display: flex;
            flex-wrap: wrap;
        }

        .imagemap-model-small-container .imagemap-model-small {
            width: 80px;
            height: 55px;
            margin: 10px;
        }

        .imagemap-model-small-container .table {
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .imagemap-model-small-container .table td {
            background-color: #cecece;
            color: #ffffff;
            border: 1px solid #858484;
        }

        .imagemap-model-small-container > .imagemap-model-small.active td {
            border-color: #6c62f3;
            border-width: 2px;
        }

        /* --------------- imagemap-model --------------- */

        .imagemap-model {
            width: 240px;
            height: 166px;
        }

        .imagemap-model > table {
            width: 100%;
            height: 100%;
            text-align: center;
        }

        .imagemap-model > table > tbody td {
            background-color: #bfbfbf;
            color: #ffffff;
            vertical-align: middle;
        }

        .imagemap-model > table > tbody td.active {
            background-color: #58ae58;
        }

        .imagemap-model > table > tbody td:not(.active):hover {
            background-color: #898989c9;
            cursor: default;
        }

        /* --------------- uri 綁定標籤 ----------------- */

        .select2-container--default .select2-selection--multiple .select2-selection__choice {
            background-color: #5897fb;
            border-radius: 10px;
            color: white;
            padding-top: 5px;
            padding-bottom: 5px;
        }

        .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
            border-right: unset;
            color: #fff;
            font-size: 1.2em;
            left: 1px;
            top: 3px;
        }

        .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover, .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:focus {
            background-color: #5897fb;
            color: #fff;
        }

        .select2-selection.select2-selection--multiple {
            min-height: 24px;
        }

        .select2-container--default .select2-search--inline .select2-search__field {
            min-height: 24px;
            font-size: 14px;
        }

        /* --------------- AJAX upload --------------- */

        .image-preview-wrapper{
            position: relative;
            cursor: pointer;
        }
        .spinner-wrapper {
            position: absolute;
            opacity: 0;
            margin: 0;
            padding: 0;
            /*left: 50%;*/
            /*top: 50%;*/
            transform: translate(-50%, -50%);

            width: 100px;
            height: 100px;
            background-image: url(/assets/images/backend_spinner.svg);
            background-size: 50px;
            background-repeat: no-repeat;
            background-position: center;
        }
        .opacity-1 {
            opacity: 1;
        }
    </style>
@endsection

@section('extjs')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="{{url('assets/js/jquery.mousewheel-3.0.6.min.js')}}"></script>
    <script src="{{url('assets/js/jquery.mCustomScrollbar.min.js')}}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.18.1/babel.min.js"></script>
    <script src="{{url('assets/resize-controller/project/index.js')}}"></script>
    <script>
        var imagemapBoxes = {};

        $(document).ready(function () {
            // 下控制按鈕 儲存
            $("#btnSave").click(function () {
                
                finishEdit();
            });

            // 下控制按鈕 返回
            $("#btnBackToList").click(function () {
                location.href = '/backend/dataManagement/track';
            });

            // 註冊事件
            eventImagemap();
            eventUriAction();

        });

        function restoreMsgInfo(msgInfo) {
            // 初始化
            var tabId = 'tab1';
            var menuInfoObj = JSON.parse(msgInfo).menuInfo;
            // console.log(menuInfoObj);

            // var menuFlag = menuInfoObj.menuFlag;
            // var modelType = menuInfoObj.modelType;
            // var chatBarText = menuInfoObj.chatBarText;
            // var displayByDefault = menuInfoObj.displayByDefault;
            var imgUrl = menuInfoObj.imgUrl;
            // var imgSize = menuInfoObj.imgSize;
            // var imagemapActions = menuInfoObj.actions;

            // 還原內容
            $('#'+tabId+'MenuFlag').val(menuFlag);
            $("#"+tabId+"ImagemapModelType").val(modelType);
            $("#chatBarText").val(chatBarText);
            if (!displayByDefault) {
                $("input[name='displayByDefault']").filter('[value="0"]').prop('checked', true);
            }
            $("img[data-target='"+tabId+"-image-preview-imagemapImg']").attr("src", imgUrl);

            // 點擊 選擇的版型
            // trigger: $('.imagemap-model-small').click()
            var $chosen_model = $("#imgmapcontent-"+tabId).find('.imagemap-model-small').filter("[data-model_type='"+modelType+"']");
            if (modelType === 'mcustom') {
                $chosen_model.trigger('click', [menuInfoObj]);
            } else {
                $chosen_model.click();
            }

            if (modelType == 'mjson') {
                // todo 重新組合 ImagemapJson
                var imagemapJson = '';
                $("#"+tabId+"ImagemapJson").val(imagemapJson);
            } else {
                // 還原 每個按鈕的值
                $.each(imagemapActions, function(i, actionObj) {
                    var btnNum = i + 1;
                    $("#"+tabId+"Imagemapbtn"+btnNum+"Act").val(actionObj.type);
                    $("#"+tabId+"Imagemapbtn"+btnNum+"Act").trigger('change'); // 觸發事件切換按鈕N動作
                    $("#"+tabId+"Imagemapbtn"+btnNum+"Content").val(actionObj.content);

                    // 前往選單
                    if (actionObj.type == 'richmenu') {
                        $("#"+tabId+"Imagemapbtn"+btnNum+"Submenu").val(actionObj.content);
                        $("#"+tabId+"Imagemapbtn"+btnNum+"Submenu").trigger('change');

                        if ('keywordValue' in actionObj) {
                            $("#"+tabId+"Imagemapbtn"+btnNum+"Content").attr('data-keyword_value', actionObj.keywordValue);
                        }
                    }

                    // 貼標 (開啟連結)
                    if ('tags' in actionObj) {
                        $("#"+tabId+"Imagemapbtn"+btnNum+"Tags").val(actionObj.tags);
                        $("#"+tabId+"Imagemapbtn"+btnNum+"Tags").trigger('change');
                    }
                });
            }
        }
        
        // 完成編輯
        function finishEdit() {
            var msgInfoObj = msgInfo();
            // console.log(msgInfoObj);
            // return;

            if ('err' in msgInfoObj) {
                alert("有錯誤：\n" + msgInfoObj.err.join("\n"));
                return;
            }

            $.blockUI({
                message: $('#ajax-spinner'),
                css: {
                    backgroundColor: 'transparent',
                    border: '0'
                },
            });

            $.ajax({
                type: "POST",
                url: '/backend/dataManagement/track/store',
                data: {
                    "operateMode": $("#operateMode").val(),
                    "trackNo": $("#trackNo").val(),
                    "trackTitle": $("#trackTitle").val(),
                    "trackLimit": $("#trackLimit").val(),
                    "_token":"{{ csrf_token() }}",

                    "id": $("#id").val(),
                },
                success: function(result) {
                    
                    if (result.code === 0) {
                        alert('儲存成功');
                        location.href = '/backend/dataManagement/track';
                    } else {
                        alert(result.message);
                        alert('123');
                    }
                },
                fail: function(jqXHR, textStatus) {
                    console.log(jqXHR);
                    console.log(textStatus);
                },
                complete: function() {
                    $.unblockUI();
                }
            });
        }

        function eventImagemap() {
            // 選擇版型
            $('.imagemap-model-small').unbind("click");
            $('.imagemap-model-small').click(function (event, imagemapContent) {
                var $model_small = $(this);
                var $model_small_container = $model_small.parent('.imagemap-model-small-container');
                var $imagemap_content = $model_small.closest('div[id^="imgmapcontent-tab"]');
                var $imagemap_btns = $imagemap_content.children('.imagemap-btn'); // 此頁籤下所有按鈕區域

                var tabNum = 1;
                var tabId = 'tab'+tabNum;
                var modelType = $model_small.attr('data-model_type');
                var imgSizeObj = JSON.parse($('#'+tabId+'ImagemapImgSize').val());

                // 三種版型類型的容器
                var $imagemap_model = $imagemap_content.find('.imagemap-model');
                var $custom_container = $('#'+tabId+'ImagemapBoxContainer');
                var $json_container = $('#'+tabId+'ImagemapJson').closest('div.row');

                if ($model_small.hasClass('active')) {
                    return;
                }

                // 設定選擇的 active
                $model_small_container.find('.imagemap-model-small').removeClass('active');
                $model_small.addClass('active');

                // 設定 model type
                $('#'+tabId+'ImagemapModelType').val(modelType);

                imagemapClearBtns($imagemap_btns, tabId);

                if (modelType == 'mjson') {
                    $imagemap_model.hide();
                    $custom_container.hide();
                    $json_container.show();
                    $imagemap_btns.hide();
                }
                else if (modelType == 'mcustom') {
                    $imagemap_model.hide();
                    $custom_container.show();
                    $json_container.hide();

                    var boxNum = 1; // ImagemapBox1
                    // 要等 ImagemapBox HTML 完全顯示才能繪製，所以等 300ms 才初始化
                    setTimeout(function() {
                        imagemapInitBox(tabNum, boxNum, imgSizeObj, imagemapContent);

                        // 設定背景圖案 (initImagemapBox 後才能設定)
                        var imagemapUrl = $('img[data-target="'+tabId+'-image-preview-imagemapImg"]').attr('src');
                        $('#ImagemapBox'+boxNum).css('background-image', 'url(' + imagemapUrl + ')');
                    }, 300);
                }
                else {
                    $imagemap_model.show();
                    $custom_container.hide();
                    $json_container.hide();

                    // 建立對應的 imagemap-model
                    $imagemap_model.children('.table').remove();
                    $model_small.children('.table').clone(false).appendTo($imagemap_model);
                    $imagemap_model.find('td').each(function (index) {
                        var btnNum = index + 1;
                        if (btnNum === 1) $(this).addClass('active');
                        $(this).html('按鈕'+btnNum);
                        $(this).attr('data-btn', btnNum);
                    });
                }
            });

            // 編輯按鈕區域
            $('.imagemap-model').unbind("click");
            $('.imagemap-model').on('click', 'td', function () {
                var $clicked_td = $(this);
                var $table = $clicked_td.closest('.table');
                var $imagemap_content = $clicked_td.closest('div[id^="imgmapcontent-tab"]');
                var tabNum = '1';
                var btnNum = $clicked_td.attr('data-btn');

                // 設定選擇的 active
                $table.find('td').removeClass('active');
                $clicked_td.addClass('active');

                // 顯示對應按鈕
                $imagemap_content.find('.imagemap-btn').hide();
                $('#tab'+'1'+'Imagemapbtn'+btnNum).show();
            });

            // 切換 按鈕N動作
            $('.imagemap-btn').find('select.imagemapBtnAct').unbind("change");
            $('.imagemap-btn').find('select.imagemapBtnAct').change(function () {
                var tabNum = 1;
                var btnNum = $(this).attr('id').split('Imagemapbtn')[1].replace(/\D/g, ''); // tab1Imagemapbtn1Act
                var type = $(this).val();

                var $btnContent = $('#tab1Imagemapbtn'+btnNum+'Content');
                var $btnSubmenu = $('#tab1Imagemapbtn'+btnNum+'Submenu');
                var $btnTags = $('#tab1Imagemapbtn'+btnNum+'Tags');

                // 清空
                $btnContent.val('');
                $btnSubmenu.val(0);
                $btnTags.val(null).trigger('change');

                // 顯示按鈕對應的元件
                imagemapShowBtnInputsByAction(type, $btnContent, $btnTags, $btnSubmenu);
            });
        }

        function eventUriAction() {
            $('.js-example-basic-multiple').select2({
                placeholder: '請選擇或輸入以搜尋標籤'
            });
        }

        function msgInfo() {
            var result = {
                menuInfo: {},
                err: []
            };

            var msgObj = {};
            var tabNum = '1';
            var tabId = 'tab' + tabNum;

            // 取資料
            var menuFlag = $('#'+tabId+'MenuFlag').val();
            var modelType = $("#"+tabId+"ImagemapModelType").val();
            var imgUrl = $("img[data-target$='"+tabId+"-image-preview-imagemapImg']").attr("src");
            var json = $("#"+tabId+"ImagemapJson").val();
            var menuTitle = $("#menuTitle").val();
            var chatBarText = $("#chatBarText").val();
            var displayByDefault = $("input[name='displayByDefault']:checked").val();

            // 檢查
            if (menuTitle === '') result.err.push('標題內容為空');
            if (imgUrl === '/assets/images/placeholder_upload_380_260.png') result.err.push('圖片沒上傳');
            if (modelType == 'mjson' && json === '') result.err.push('JSON內容為空');
            if (chatBarText === '') result.err.push('選單顯示名稱為空');

            var imagemapActions = '';
            if (modelType == 'mjson') {
                // todo msgInfoImagemapActionsFromJson(json)
                imagemapActions = '';
            } else if (modelType == 'mcustom') {
                imagemapActions = msgInfoImagemapActions(tabNum, modelType, result);
            } else { // 預設版型
                imagemapActions = msgInfoImagemapActions(tabNum, modelType, result);
            }

            msgObj = {
                // menuFlag: menuFlag,
                // modelType: modelType,
                // name: menuTitle,
                // chatBarText: chatBarText,
                // displayByDefault: !!parseInt(displayByDefault),
                imgUrl: imgUrl,
                // imgSize: {
                //     "width": 800,
                //     "height": 800
                // },
                // actions: imagemapActions,
            };

            result.menuInfo = msgObj;

            if (result.err.length === 0) {
                delete result.err;
            }

            return result;
        }

        function msgInfoImagemapActions(tabNum, modelType, result) {
            var tabId = 'tab'+tabNum;

            var areas = [];
            if (modelType == 'mcustom') {
                areas = imagemapBoxes[tabNum].getResultPos();
            } else if (modelType != 'mjson') {
                // 樣板按鈕區域定義 (依照頁面顯示的按鈕順序)
                var modelAreaMap = {
                    "m1": [
                        {"x": 0, "y": 0, "width": 833, "height": 843},
                        {"x": 833, "y": 0, "width": 833, "height": 843},
                        {"x": 1666, "y": 0, "width": 834, "height": 843},
                        {"x": 0, "y": 843, "width": 833, "height": 843},
                        {"x": 833, "y": 843, "width": 833, "height": 843},
                        {"x": 1666, "y": 843, "width": 834, "height": 843},
                    ],
                    "m2": [
                        {"x": 0, "y": 0, "width": 1250, "height": 843},
                        {"x": 1250, "y": 0, "width": 1250, "height": 843},
                        {"x": 0, "y": 843, "width": 1250, "height": 843},
                        {"x": 1250, "y": 843, "width": 1250, "height": 843},
                    ],
                    "m3": [
                        {"x": 0, "y": 0, "width": 2500, "height": 843},
                        {"x": 0, "y": 843, "width": 833, "height": 843},
                        {"x": 833, "y": 843, "width": 833, "height": 843},
                        {"x": 1666, "y": 843, "width": 834, "height": 843},
                    ],
                    "m4": [
                        {"x": 0, "y": 0, "width": 1250, "height": 1686},
                        {"x": 1250, "y": 0, "width": 1250, "height": 843},
                        {"x": 1250, "y": 843, "width": 1250, "height": 843},
                    ],
                    "m5": [
                        {"x": 0, "y": 0, "width": 2500, "height": 843},
                        {"x": 0, "y": 843, "width": 2500, "height": 843},
                    ],
                    "m6": [
                        {"x": 0, "y": 0, "width": 1250, "height": 1686},
                        {"x": 1250, "y": 0, "width": 1250, "height": 1686},
                    ],
                    "m7": [
                        {"x": 0, "y": 0, "width": 2500, "height": 1686},
                    ]
                };
                areas = modelAreaMap[modelType];
            }

            var actions = [];
            for (var btnNum = 1; btnNum <= areas.length; btnNum++) {
                var btnId = 'btn'+btnNum;
                var type = $("#"+tabId+"Imagemap"+btnId+"Act").val();
                var content = $("#"+tabId+"Imagemap"+btnId+"Content").val();
                var submenuId = $("#"+tabId+"Imagemap"+btnId+"Submenu").val();
                var tagsData = $("#"+tabId+"Imagemap"+btnId+"Tags").select2('data');
                var area = areas[btnNum-1];

                if (type != 'richmenu' && content === '') result.err.push('按鈕'+btnNum+'的內容為空');
                if (type == 'uri'
                    && !content.startsWith('https://')
                    && !content.startsWith('tel:')
                    && !content.startsWith('line://')
                ) {
                    result.err.push('按鈕'+btnNum+'的連結網址須為 https:// 或 tel:// 或 line://');
                }

                var action = {
                    "type": type,
                    "content": content,
                    "area": {
                        "x": area.x,
                        "y": area.y,
                        "width": area.width,
                        "height": area.height
                    }
                };

                if (type == 'uri' && tagsData.length !== 0) { // uri 貼標
                    var tags = [];
                    $.each(tagsData, function(i, item) {
                        tags.push(item.id);
                    });
                    action.tags = tags;
                } else if (type == 'richmenu') { // 前往子選單
                    action.content = submenuId;

                    var keywordValue = $("#"+tabId+"Imagemapbtn"+btnNum+"Content").attr('data-keyword_value');
                    if (typeof keywordValue === 'undefined') {
                        var menuFlag = $('#tab1MenuFlag').val();
                        keywordValue = 'richmenu-' + menuFlag.replace(/menu-/g, '') + '-' + Date.now();
                    }
                    action.keywordValue = keywordValue;
                }

                actions.push(action);
            }
            // console.log(actions);

            return actions
        }

        function generateFlag(length) {
            var result = '';
            var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var charactersLength = characters.length;
            for ( var i = 0; i < length; i++ ) {
                result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            return result;
        }

        function imagemapInitBox(tabNum, boxNum, imgSizeObj, imagemapContent) {
            let imagemapBox;
            var mapData = null;

            // console.log(imagemapContent);
            if (typeof imagemapContent !== 'undefined') {
                mapData = imagemapContent;
            }

            imagemapBox = new resizer({
                container: '#ImagemapBox'+boxNum,
                wrap: imgSizeObj,
                wrapperWidth: 380,
                itemDefaultSize: 380,
                add: '#AddImagemapBox'+boxNum,
                delete: {
                    selector: '#DeleteImagemapBox'+boxNum,
                    getDelete: function(res) {
                        // console.log(res);
                        var btnNum = res.index + 1;
                        var tabId = 'tab'+tabNum;

                        // 重設按鈕的值 (從刪除的下一個的開始往前遞補)
                        for (btnNum; btnNum < 12; btnNum++) {
                            var nextNum = btnNum + 1;

                            var $currentAct = $('#'+tabId+'Imagemapbtn'+btnNum+'Act');
                            var $currentContent = $('#'+tabId+'Imagemapbtn'+btnNum+'Content');
                            var $currentSubmenu = $('#'+tabId+'Imagemapbtn'+btnNum+'Submenu');
                            var $currentTags = $('#'+tabId+'Imagemapbtn'+btnNum+'Tags');

                            var $nextAct = $('#'+tabId+'Imagemapbtn'+nextNum+'Act');
                            var $nextContent = $('#'+tabId+'Imagemapbtn'+nextNum+'Content');
                            var $nextSubmenu = $('#'+tabId+'Imagemapbtn'+nextNum+'Submenu');
                            var $nextTags = $('#'+tabId+'Imagemapbtn'+nextNum+'Tags');

                            // 內容
                            $currentAct.val($nextAct.val());
                            $currentContent.val($nextContent.val());
                            $currentSubmenu.val($nextSubmenu.val());
                            // 標籤
                            var nextTagsData = $nextTags.select2('data');
                            if (nextTagsData.length !== 0) {
                                var nextTags = [];
                                $.each(nextTagsData, function(i, item) {
                                    nextTags.push(item.id);
                                });
                                $currentTags.val(nextTags);
                                $currentTags.trigger('change');
                            }

                            // 顯示按鈕對應的元件
                            imagemapShowBtnInputsByAction($currentAct.val(), $currentContent, $currentTags, $currentSubmenu);
                        }

                        // 清除最後一個按鈕
                        $('#'+tabId+'Imagemapbtn12Act').val('postback'); // richmenu 預設
                        $('#'+tabId+'Imagemapbtn12Content').val('');
                        $('#'+tabId+'Imagemapbtn12Submenu').val(0);
                        $('#'+tabId+'Imagemapbtn12Tags').val(null).trigger('change');

                        // 顯示最後一個按鈕對應的元件
                        imagemapShowBtnInputsByAction('postback', $('#'+tabId+'Imagemapbtn12Content'), $('#'+tabId+'Imagemapbtn12Tags'), $('#'+tabId+'Imagemapbtn12Submenu'));
                    }
                },
                get: '#GetImagemapBox'+boxNum,
                map: mapData,
                getActive: function(res) {
                    // console.log(res);
                    var $imagemapContent = $('#imgmapcontent-tab'+tabNum);
                    var btnNum = res.index + 1;

                    // 顯示對應按鈕
                    $imagemapContent.find('.imagemap-btn').hide();
                    $('#tab'+tabNum+'Imagemapbtn'+btnNum).show();
                }
            });

            imagemapBoxes[tabNum] = imagemapBox;
        }

        function imagemapShowBtnInputsByAction(action, $btnContent, $btnTags, $btnSubmenu) {
            if (action == 'uri') {
                $btnContent.closest('div[class="row"]').show();
                $btnTags.closest('div[class="row"]').show();
                $btnSubmenu.closest('div[class="row"]').hide();
            } else if (action == 'richmenu') {
                $btnContent.closest('div[class="row"]').hide();
                $btnTags.closest('div[class="row"]').hide();
                $btnSubmenu.closest('div[class="row"]').show();
            } else {
                $btnContent.closest('div[class="row"]').show();
                $btnTags.closest('div[class="row"]').hide();
                $btnSubmenu.closest('div[class="row"]').hide();
            }
        }

        function imagemapClearBtns($imagemap_btns, tabId) {
            var $btnContents = $imagemap_btns.find('.imagemapBtnContent');
            var $btnActs = $imagemap_btns.find('.imagemapBtnAct');
            var $btnSubmenus = $imagemap_btns.find('select.imagemapBtnSubmenu');
            var $btnTags = $imagemap_btns.find('.imagemapBtnTags');

            // 清除按鈕區域內容
            $btnContents.val('');
            $btnActs.val('postback'); // richmenu 預設
            $btnSubmenus.val(0)
            $btnTags.val(null).trigger('change');

            // 顯示按鈕對應的元件 (這邊是一次設定所有按鈕下所有元件)
            imagemapShowBtnInputsByAction('postback', $btnContents, $btnTags, $btnSubmenus);

            // 顯示按鈕1
            $imagemap_btns.hide();
            $('#'+tabId+'Imagemapbtn1').show();
        }

        // AJAX 上傳圖片/影片
        // http://arsee88.blogspot.com/2020_09_20_archive.html
        var imagePreview = [];
        var spinner = [];
        var fileUploader = [];
        // 註冊上傳圖片的功能(可以重複註冊)
        var imagemapImgId = 'imagemapImg' + '1';
        imagePreview[imagemapImgId] = document.querySelector('[data-target="tab'+'1'+'-image-preview-imagemapImg"]');
        spinner[imagemapImgId] = document.querySelector('[data-target="tab'+'1'+'-spinner-imagemapImg"]');
        fileUploader[imagemapImgId] = document.querySelector('[data-target="tab'+'1'+'-file-uploader-imagemapImg"]');
        fileUploader[imagemapImgId].addEventListener("change", handleFileUpload);
        // File input 上傳檔案時綁定的處理函式
        async function handleFileUpload(e) {
            e.preventDefault();

            var $file_uploader = $(this);
            var splitItems = $file_uploader.attr('id').split('-');
            // tab1-file-uploader-imagemapImg
            var msgType = splitItems[splitItems.length-1]; // lastItem
            console.log(msgType);

            var msgNum = '1';
            var itemId = msgType + msgNum;
            console.log(itemId);

            try {
                const file = e.target.files[0];
                if (!file) {
                    return;
                }

                setUploading(true, itemId);

                // 檢查
                const beforeUploadCheck = await checkBeforeUpload(file, msgType, msgNum);
                if (!beforeUploadCheck.isValid) throw beforeUploadCheck.errorMessages;

                // 上傳
                const arrayBuffer = await getArrayBuffer(file);
                var response = await uploadFileAJAX(arrayBuffer);
                alert("上傳成功");
                setUploading(false, itemId);
                showPreviewImage(response.url, itemId);

                // 更新 ImagemapBox
                var $imgPreview = $(imagePreview[itemId]);
                if ($imgPreview.attr('data-target').indexOf('imagemap') !== -1) {
                    $imgPreview.closest('#imgmapcontent-tab1').find('.imagemapBox').css('background-image', 'url(' + response.url + ')');
                }
            } catch (error) {
                setUploading(false, itemId);
                alert(error);
                console.log("上傳失敗: ", error);
            } finally {
                e.target.value = '';
            }
        }
        // If you prefer Base64 image, use "FileReader.readAsDataURL"
        function showPreviewImage(url, itemId) {
            imagePreview[itemId].src = url;
        }
        // Change file object into ArrayBuffer
        function getArrayBuffer(fileObj) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                // Get ArrayBuffer when FileReader on load
                reader.addEventListener("load", () => {
                    resolve(reader.result);
                });

                // Get Error when FileReader on error
                reader.addEventListener("error", () => {
                    reject("error occurred in getArrayBuffer");
                });

                // read the blob object as ArrayBuffer
                // if you nedd Base64, use reader.readAsDataURL
                reader.readAsArrayBuffer(fileObj);
            });
        }
        // Use "new Uint8Array()"" to change ArrayBuffer into TypedArray (TypedArray is not a truly Array)
        // Use "Array.from()" to change it into Array
        function uploadFileAJAX(arrayBuffer) {
            return fetch("{{ env('APP_URL') }}/backend/dataManagement/eLecturerTeachersList/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 checkBeforeUpload(fileObject, msgType, msgNum) {
            return new Promise(resolve => {
                let errorMessages = [];

                // isValidFileType
                const validFileTypes = ["image/jpeg", "image/png" ];
                const isValidFileType = validFileTypes.includes(fileObject.type);
                if (!isValidFileType) {
                    errorMessages.push("只支援 JPG / PNG 格式圖片");
                    resolve({
                        isValid: isValidFileType,
                        errorMessages: errorMessages.join("\n")
                    });
                    return;
                }

                // isValidFileSize
                const isValidFileSize = (fileObject.size / 1024 / 1024) < 1; // 1 MB
                if (!isValidFileSize) {
                    errorMessages.push("圖片最大 1MB");
                }
                
                // isValidDimension
                var isValidDimension = true;
                const dim = Promise.resolve(getImageSize(fileObject));
                dim.then(function(result) {
                    switch (msgType)
                    {
                        case "imagemapImg":
                            if (result.width != 800 || result.height != 800) {
                                errorMessages.push("圖片尺寸必須為 800x800");
                                isValidDimension = false;
                            }
                            break;
                    }

                    resolve({
                        isValid: isValidFileType && isValidFileSize && isValidDimension,
                        errorMessages: errorMessages.join("\n")
                    });
                });
            });
        }
        function setUploading(isUploading, itemId) {
            if (isUploading === true) {
                spinner[itemId].classList.add("opacity-1");
            } else {
                spinner[itemId].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);
            });
        }
    </script>
@endsection
