var modelProjTable;
var modelProjRowPos;
var modelProjRowID;

var modelQuotationTable;
var modelQuotationRowPos;
var modelQuotationRowID;

var mainItem_items = [];
var mainItem_map = {};

var subItem_items = [];
var subItem_map = {};

var deledMainItems = [];
var deledSubItems = [];

var preSubItem_name = '';
var hasBind = 'N';
$(document).ready(function () {
    deptList();
    loadModelQuotationDataTable();

    $('#dept_select').on('change', function () {
        $('#dt-responsive').DataTable().ajax.reload();
    });

    //報價單範本儲存鈕
    $('#modelQuotationDialogSaveBtn').on('click', function () {
        var method = $('#modelQuotation_method').val();
        var modelQuotation_uid = $('#modelQuotation_uid').val();
        var modelMainItem_uid = $('#modelMainItem_uid').val();
        var modelQuotation_name = $('#modelQuotation_name').val();
        var modelProj_uid = $('#parent_modelProj_uid').val();

        var msg = '';

        if (modelQuotation_name == '') {
            alert('請輸入報價單範本名稱!');
            return;
        }

        var ItemArray = [];
        $('#modelItem_div .card').each(function (index, obj) {
            var dataType = $(obj).attr('data-type');
            var mainItem_uid = $(obj).attr('data-main-uid');
            var modelMainItem_uid = $(obj).attr('data-uid');
            var modelMainItem_name = $(obj).find('[data-name="mainItem_name"').val();
            var modelMainItem_ac = $(obj).find('[data-name="modelMainItem_ac"').val();

            var subItemArray = [];

            $(obj).find('ol li').each(function (i, item) {
                var itemDataType = $(item).attr('data-method');
                var modelSubItem_uid = $(item).attr('data-model-subitem-uid');
                var modelSubItem_name = $(item).find('[data-name="model-subitem-name"]').val();
                var modelSubItem_descript = $(item).find('[data-name="model-subitem-descript"]').val();
                var modelSubItem_price = $(item).find('[data-name="model-subitem-price"]').val();
                var modelSubItem_unitType = $(item).find('[data-name="model-subitem-unitType"]').val();
                var modelSubItem_number = $(item).find('[data-name="model-subitem-number"]').val();
                var modelSubItem_subTotal = $(item).find('[data-name="model-subitem-subTotal"]').val();
                var modelSubItem_hasAC = $(item).find('[data-name="model-subitem-hasAC"]').val();

                var subItemObj = {
                    method: itemDataType,
                    modelSubItem_uid: modelSubItem_uid,
                    modelSubItem_name: modelSubItem_name,
                    modelSubItem_descript: modelSubItem_descript,
                    modelSubItem_price: modelSubItem_price,
                    modelSubItem_unitType: modelSubItem_unitType,
                    modelSubItem_number: modelSubItem_number,
                    modelSubItem_subTotal: modelSubItem_subTotal,
                    modelSubItem_hasAC: modelSubItem_hasAC
                }

                subItemArray.push(subItemObj);
            });

            var quotationModelJson = {
                method: dataType,
                mainItem_uid: mainItem_uid,
                modelMainItem_uid: modelMainItem_uid,
                modelMainItem_name: modelMainItem_name,
                modelMainItem_ac: modelMainItem_ac,
                subItems: subItemArray
            }

            ItemArray.push(quotationModelJson);
        });

        var quotationForm = {
            method: method,
            modelProj_uid: modelProj_uid,
            modelQuotation_uid: modelQuotation_uid,
            dept_uid: $('#dept_select').val(),
            modelQuotation_name: modelQuotation_name,
            mainItemsJson: JSON.stringify(ItemArray),
            deledMainItemsJson: JSON.stringify(deledMainItems),
            deledSubItemsJson: JSON.stringify(deledSubItems)
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetModelQuotation",
            type: "post",
            data: quotationForm,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.modelQuotationDetails[0];

                    if (method == "add") {
                        modelQuotationTable.fnAddData(obj);
                        alert('新增範本完成!');
                    }

                    if (method == 'edit') {
                        modelQuotationTable.fnUpdate(obj, modelQuotationRowPos);
                        alert('儲存範本完成');
                    }

                    $('#clientModelQuotationPreviewModal').modal('toggle');
                } else {
                    alert(data.message);

                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    });

    //新增次項目對話框儲存鈕
    $('#modelSubItemDialogSaveBtn').on('click', function () {
        var method = $('#modelSubItem_method').val();
        var subItem_uid = $('#modelSubItem_uid').val();
        var modelSubItem_uid = $('#parent_Item_uid').val();
        var modelSubItem_name = $('#modelSubItem_name').val();
        var modelSubItem_descript = $('#modelSubItem_descript').val();
        var modelSubItem_price = $('#modelSubItem_price').val().replace(/,/g, "");
        var modelSubItem_unitType = $('#modelSubItem_unitType').val();
        var modelSubItem_number = $('#modelSubItem_number').val().replace(/,/g, "");
        var modelSubItem_hasAC = 'N';
        var parent_data_uid = $('#model_parent_data_uid').val();

        if ($('#modelSubItem_hasAC').prop("checked")) {
            modelSubItem_hasAC = 'Y';
        } else {
            modelSubItem_hasAC = 'N';
        }

        var msg = '';

        if (modelSubItem_price == '') {
            msg += '請輸入單價!\n';
        } else {
            if (modelSubItem_price.isNumber() == false) {
                msg += '單價必須為數字!\n';
            }
        }

        if (modelSubItem_number == '') {
            msg += '請輸入數量!\n';
        } else {
            if (modelSubItem_number.isNumber() == false) {
                msg += '數量必須為數字!\n';
            }
        }

        if (msg != '') {
            alert(msg);
            return;
        }

        

        var modelSubItem_subTotal = modelSubItem_price * modelSubItem_number;

        if (method == 'edit') {
            var datauid = $('#modelSubItem_uid').val();

            var htmlObj = $('#modelItem_div').find('[data-uid="' + parent_data_uid + '"]').find('ol').find('[data-model-subitem-uid="' + datauid + '"]');

            $(htmlObj).find('[data-name="subItem_uid"]').val(subItem_uid);
            $(htmlObj).find('[data-name="model-subItem_uid"]').val(modelSubItem_uid);
            $(htmlObj).find('[data-name="model-subitem-name"]').val(modelSubItem_name);
            $(htmlObj).find('[data-name="model-subitem-price"]').val(modelSubItem_price);
            $(htmlObj).find('[data-name="model-subitem-unitType"]').val(modelSubItem_unitType);
            $(htmlObj).find('[data-name="model-subitem-number"]').val(modelSubItem_number);
            $(htmlObj).find('[data-name="model-subitem-hasAC"]').val(modelSubItem_hasAC);
            $(htmlObj).find('[data-name="model-subitem-subTotal"]').val(modelSubItem_subTotal);
            $(htmlObj).find('[data-name="model-subitem-descript"]').val(modelSubItem_descript);
            $(htmlObj).children().children().find('[data-name="subname"]').text(modelSubItem_name);
            $(htmlObj).children().children().find('[data-name="subdesc"]').text(modelSubItem_descript);

            var detailData = '';
            detailData += '單價 NT$' + AppendComma(modelSubItem_price) + ', 數量 ' + modelSubItem_number + ', 單位 ' + modelSubItem_unitType + '\r\n';
            detailData += '小計 NT$' + AppendComma(modelSubItem_subTotal) + '\r\n';
            detailData += 'AC(' + modelSubItem_hasAC + ')';

            $(htmlObj).children().children().find('[data-name="subsummy"]').text(detailData);

            $('#modelSubItemModal').modal('toggle');
        }

        if (method == 'add') {
            var datauid = Math.floor(Math.random() * 999999999);
            var htmlCode = '';

            htmlCode += '   <li class="dd-item dd-nodrag" data-model-subitem-uid="' + datauid + '" data-method="add">';
            htmlCode += '       <textarea style="display:none;" data-name="subItem_uid">' + subItem_uid + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="model-subItem_uid">' + modelSubItem_uid + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="model-subitem-name">' + modelSubItem_name + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="model-subitem-price">' + modelSubItem_price + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="model-subitem-unitType">' + modelSubItem_unitType + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="model-subitem-number">' + modelSubItem_number + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="model-subitem-hasAC">' + modelSubItem_hasAC + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="model-subitem-subTotal">' + modelSubItem_subTotal + '</textarea>';
            htmlCode += '       <textarea data-name="model-subitem-descript" style="display:none;">' + modelSubItem_descript + '</textarea>';
            htmlCode += '       <div class="dd-handle">';
            htmlCode += '           <div class="list-group-item">';
            htmlCode += '               <div class="list-group-item-figure">';
            htmlCode += '                   <span class="drag-indicator"></span>';
            htmlCode += '               </div>';
            htmlCode += '               <div class="list-group-item-body">';
            htmlCode += '                   <div class="team">';
            htmlCode += '                       <h4 data-name="subname" class="list-group-item-title">';
            htmlCode += '                           ' + modelSubItem_name;
            htmlCode += '                       </h4><br/>';
            htmlCode += '                    <p class="list-group-item-text" data-name="subdesc" style="white-space: pre-line;font-size: 13px;">';
            htmlCode += '                           ' + modelSubItem_descript;
            htmlCode += '                    </p><br/>';
            htmlCode += '                    <p class="list-group-item-text" data-name="subsummy" style="white-space: pre-line;font-size: 11px;">';
            htmlCode += '                           單價 NT$' + AppendComma(modelSubItem_price) + ', 數量 ' + modelSubItem_number + ', 單位 ' + modelSubItem_unitType + '\r\n';
            htmlCode += '                           小計 NT$' + AppendComma(modelSubItem_subTotal) + '\r\n';
            htmlCode += '                           AC(' + modelSubItem_hasAC + ')';
            htmlCode += '                    </p>';
            htmlCode += '                   </div>';
            htmlCode += '               </div>';
            htmlCode += '           </div>';
            htmlCode += '           <div class="dd-nodrag btn-group ml-auto">';
            htmlCode += '            <button type="button" onclick="editSubItemButton(this);" class="btn btn-sm btn-secondary">Edit</button> <button type="button" onclick="delSubItemButton(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
            htmlCode += '           </div>';
            htmlCode += '       </div>         ';
            htmlCode += '   </li>';

            var htmlObj = $('#modelItem_div').find('[data-uid="' + parent_data_uid + '"]').find('ol');

            //var htmlObj = $('#' + parent_data_uid).find('ol');
            htmlObj.append(htmlCode);

            $('#modelSubItemModal').modal('toggle');
        }

    });

    //新增主項目對話框儲存鈕
    $('#modelMainItemDialogSaveBtn').on('click', function () {
        var modelMainItem_uid = $('#modelMainItem_uid').val();
        var mainItem_uid = $('#parent_mainItem_uid').val();
        var method = $('#modelMainItem_method').val();
        var modelMainItem_name = $('#modelMainItem_name').val();
        var modelMainItem_ac = $('#modelMainItem_ac').val().replace(/,/g, "");;




        if (modelMainItem_ac.isNumber() == false) {
            alert('AC必須為數字!');
            return;
        }

        if (modelMainItem_ac == "") {
            modelMainItem_ac = "0";
        }

        if (modelMainItem_name == "") {
            alert('主項目名稱不得為空白!');
            return;
        }

        if (method == 'edit') {
            var obj = $('#modelItem_div').find("[data-uid='" + modelMainItem_uid + "']");
            $(obj).prop('data-main-uid', mainItem_uid);
            $(obj).find("[data-name='mainItem_name']").val(modelMainItem_name);
            $(obj).find("[data-span='mainItem_name']").text(modelMainItem_name);
            $(obj).find("[data-name='modelMainItem_ac']").val(modelMainItem_ac);
            $('#modelMainItemModal').modal('toggle');
        }

        if (method == 'add') {
            var datauid = Math.floor(Math.random() * 99999999);

            var htmlCode = '';
            htmlCode += '<!-- .card -->';
            htmlCode += '<div class="card card-fluid" data-uid="' + datauid + '"  data-main-uid="' + mainItem_uid + '" data-type="add">';
            htmlCode += '    <div class="card-header border-bottom-0 btn-group">';
            htmlCode += '    <input type="hidden" data-name="mainItem_name" value="' + modelMainItem_name + '" />';
            htmlCode += '    <input type="hidden" data-name="modelMainItem_ac" value="' + modelMainItem_ac + '" />';
            htmlCode += '        <span data-span="mainItem_name">' + modelMainItem_name + '</span>';
            htmlCode += '        <div class="dd-nodrag btn-group ml-auto">';
            htmlCode += '            <button type="button" class="btn btn-sm btn-secondary" onclick="editModelMainItem(this);">Edit</button> <button type="button" onclick="delModelMainItem(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
            htmlCode += '        </div>';
            htmlCode += '        ';
            htmlCode += '    </div>';
            htmlCode += '        <!-- .dd-list -->';
            htmlCode += '        <ol class="dd-list">';
            htmlCode += '       ';
            htmlCode += '        </ol><!-- /.dd-list -->';
            htmlCode += ' ';
            htmlCode += '    <!-- .card-footer -->';
            htmlCode += '    <div class="card-footer">';
            htmlCode += '        <a href="javascript: void(0);" onclick="addSubItem(this);" class="card-footer-item justify-content-start"><span><i class="fa fa-plus-circle mr-1"></i> 添加子項目</span></a>';
            htmlCode += '    </div><!-- /.card-footer -->';
            htmlCode += '</div><!-- /.card -->';

            $('#modelItem_div').append(htmlCode);

            $('#modelMainItemModal').modal('toggle');
        }

        
    });

    
    

    //新增主項目鈕
    $('#addModelMainItemBtn').on('click', function () {
        

        $('#modelMainItem_name').typeahead('destroy');

        loadMainItemTypeahead();
        $('#modelMainItem_method').val('add');
        $('#modelMainItemModal').modal('toggle');
    });

    //新增報價單範本視窗
    $('#modelQuotationListNewBtn').on('click', function () {
        deledMainItems = [];
        deledSubItems = [];
        $('#modelQuotation_method').val('add');
        $('#modelItem_div').html('');
        $('#clientModelQuotationPreviewModal').modal('toggle');
    });

    $('#modelProjNewBtn').on('click', function () {
        $("#modelProj_method").val('add');
        $("#dept_uid").val($("#dept_select").val()).trigger('change');


        $('#modelProjModal').modal('toggle');
    });

    $('#search_btn').on('click', function () {
        $('#dt-responsive').DataTable().ajax.reload();
    });

    //專案類型對話框儲存鈕
    $('#modelProjDialogSaveBtn').on('click', function () {
        var errmsg = '';
        var method = $('#modelProj_method').val();
        var modelProj_uid = $('#modelProj_uid').val();
        var dept_uid = $('#dept_uid').val();
        var modelProj_name = $('#modelProj_name').val();

        if (modelProj_name == '') {
            alert('請輸入專案類型名稱!\n');
            return;
        }

        var formData = {
            method: method,
            modelProj_uid: modelProj_uid,
            modelProj_name: modelProj_name,
            dept_uid: dept_uid
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetModelProj",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.modelProjs[0];

                    if (method == "add") {
                        modelProjTable.fnAddData(obj);
                    }

                    if (method == "edit") {
                        modelProjTable.fnUpdate(obj, modelProjRowPos);
                    }



                    $('#modelProjModal').modal('toggle');
                } else {
                    alert(data.message);

                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    });
});

//次項目刪除鈕
function delSubItemButton(obj) {
    if (confirm('確定刪除此次項目資料? ')) {
        var model_subitem_uid = $(obj).parent().parent().parent().attr('data-model-subitem-uid');

        var delItem = {
            modelSubItem_uid: model_subitem_uid
        }

        deledSubItems.push(delItem);

        $(obj).parent().parent().parent().remove();

        alert('預定刪除完成! 記得按下下方儲存鈕才是真的刪除喔~');
    }
}

//次項目編輯鈕
function editSubItemButton(obj) {
    var divObj = $(obj).parent().parent().parent();

    var model_subitem_uid = $(obj).parent().parent().parent().attr('data-model-subitem-uid');
    var subItem_name = $(divObj).find("[data-name='model-subitem-name']").val();
    var parent_item_uid = $(divObj).find("[data-name='model-subItem_uid']").val();
    var modelSubItem_price = $(divObj).find("[data-name='model-subitem-price']").val();
    var modelSubItem_unitType = $(divObj).find("[data-name='model-subitem-unitType']").val();
    var modelSubItem_number = $(divObj).find("[data-name='model-subitem-number']").val();
    var modelSubItem_hasAC = $(divObj).find("[data-name='model-subitem-hasAC']").val();
    var modelSubItem_descript = $(divObj).find("[data-name='model-subitem-descript']").val();
    var modelMainItem_uid = $(divObj).parent().parent().attr("data-uid");
    var parent_mainItem_uid = $(divObj).parent().parent().attr("data-main-uid");

    

    $('#modelSubItem_method').val('edit');
    $('#modelSubItem_uid').val(model_subitem_uid);
    $('#parent_Item_uid').val(parent_item_uid);
    $('#model_parent_data_uid').val(modelMainItem_uid).trigger('change');
    $('#modelSubItem_name').val(subItem_name).trigger('change');
    $('#modelSubItem_descript').val(modelSubItem_descript).trigger('change');
    $('#modelSubItem_price').val(modelSubItem_price).trigger('change');
    $('#modelSubItem_unitType').val(modelSubItem_unitType).trigger('change');
    $('#modelSubItem_number').val(modelSubItem_number).trigger('change');

    if (modelSubItem_hasAC == 'Y') {
        $('#modelSubItem_hasAC').prop('checked', true).trigger('change');
    } else {
        $('#modelSubItem_hasAC').prop('checked', false).trigger('change');
    }

    $('#modelSubItem_name').typeahead('destroy');

    loadSubItemTypeahead(parent_mainItem_uid);

    setTimeout(function () { preSubItem_name = subItem_name; }, 1000);

    $('#modelSubItemModal').modal('toggle');
}

function addSubItem(obj) {
    var modelMainItem_uid = $(obj).parent().parent().attr("data-uid");
    var modelMainItem_name = $(obj).parent().parent().find("[data-name='mainItem_name']").val();
    var parent_mainItem_uid = $(obj).parent().parent().attr("data-main-uid");
    var ac = $(obj).parent().parent().find('[data-name="modelMainItem_ac"]').val();

    $('#modelSubItem_name').typeahead('destroy');

    loadSubItemTypeahead(parent_mainItem_uid);

    
    $('#modelSubItem_method').val('add');
    $('#modelSubItem_uid').val('');
    $('#parent_Item_uid').val('');
    $('#model_parent_data_uid').val(modelMainItem_uid);

    if (ac != '0') {
        $('#modelSubItem_hasAC').prop("checked", true).trigger("change");
    } else {
        $('#modelSubItem_hasAC').prop("checked", false).trigger("change");
    }

    

    $('#modelSubItemModal').modal('toggle');
}

function delModelMainItem(obj) {
    if (confirm('確定刪除此主項目資料? 所有子項目也會一併刪除~')) {
        if (confirm('再次確認是否刪除所有此項目與子項目?')) {
            var modelMainItem_uid = $(obj).parent().parent().parent().attr("data-uid");

            var delItem = {
                modelMainItem_uid: modelMainItem_uid
            }

            deledMainItems.push(delItem);

            $(obj).parent().parent().parent().remove();

            alert('預定刪除完成! 記得按下下方儲存鈕才是真的刪除喔~');
        }
    }
}

function editModelMainItem(obj) {
    var modelMainItem_name = $(obj).parent().parent().find("[data-name='mainItem_name']").val();
    var parent_mainItem_uid = $(obj).parent().parent().parent().attr("data-main-uid");
    var modelMainItem_uid = $(obj).parent().parent().parent().attr("data-uid");
    var modelMainItem_ac = $(obj).parent().parent().find("[data-name='modelMainItem_ac']").val();
    $('#modelMainItem_name').typeahead('destroy');

    loadMainItemTypeahead();
    $('#modelMainItem_method').val('edit');
    $('#modelMainItem_uid').val(modelMainItem_uid); 
    $('#modelMainItem_name').val(modelMainItem_name);
    $('#modelMainItem_ac').val(modelMainItem_ac);
    $('#parent_mainItem_uid').val(parent_mainItem_uid);
    $('#modelMainItemModal').modal('toggle');
}

function loadSubItemTypeahead(mainItem_uid) {
    var formData = {
        dept_uid: $('#dept_select').val(),
        mainItem_uid: mainItem_uid
    }

    $.ajax({
        url: "/AuthApi/authSubItemList",
        type: "post",
        data: formData,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.subItems;

                subItem_items = [];
                subItem_map = {};

                $.each(obj, function (i, item) {
                    var id = item.subItem_uid;
                    var name = item.subItem_name;
                    var descript = item.subItem_descript;
                    var price = item.subItem_price;
                    var unitType = item.subItem_unitType;

                    subItem_map[name] = { id: id, name: name, descript: descript, price: price, unitType: unitType };
                    subItem_items.push(name);
                });

                var bh = new Bloodhound({
                    local: subItem_items,
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    datumTokenizer: Bloodhound.tokenizers.whitespace
                });

                var nflTeamsWithDefaults = function nflTeamsWithDefaults(q, sync) {
                    if (q === '') {
                        sync(bh.index.all());
                    } else {
                        bh.search(q, sync);
                    }
                };

                $('#modelSubItem_name').typeahead(
                    {
                        minLength: 0,
                        highlight: false
                    },
                    {
                        source: nflTeamsWithDefaults
                    }

                );

                preSubItem_name = '';

                if (hasBind == 'N') {
                    bindTypeHead();
                    hasBind = 'Y';
                }
                
                //$('#modelMainItem_name').bind('typeahead:autocomplete', function (ev, suggestion) {
                //    console.log('Selection: ' + suggestion);
                //    console.log('Selection key: ' + mainItem_map[suggestion].id);
                //    $('#parent_mainItem_uid').val(mainItem_map[suggestion].id);
                //});

            } else {
                alert(data.message);

                if (data.err_code == "99999") {
                    location.href = "/Root/Login";
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('網路或伺服器發生錯誤，請稍後重試!');
        }
    });
}

function bindTypeHead() {
    $('#modelSubItem_name').bind('typeahead:select', function (ev, suggestion) {
        var modelSubItem_descript = $('#modelSubItem_descript').val();

        if (preSubItem_name != '') {
            if (suggestion != preSubItem_name) {
                if (confirm('確定要用新項目覆蓋目前資料?')) {
                    $('#parent_Item_uid').val(subItem_map[suggestion].id);
                    preSubItem_name = suggestion;

                    $('#modelSubItem_price').val(subItem_map[suggestion].price).trigger('change');
                    $('#modelSubItem_unitType').val(subItem_map[suggestion].unitType).trigger('change');
                    $('#modelSubItem_descript').val(subItem_map[suggestion].descript).trigger('change');
                    $('#modelSubItem_number').val('').trigger('change');
                } else {
                    $('#modelSubItem_name').typeahead('val', preSubItem_name);
                    //suggestion = preSubItem_name;
                    //$('#modelSubItem_name').val(preSubItem_name).trigger('change');;
                }
            }
        } else {
            $('#parent_Item_uid').val(subItem_map[suggestion].id);
            preSubItem_name = suggestion;

            $('#modelSubItem_price').val(subItem_map[suggestion].price).trigger('change');
            $('#modelSubItem_unitType').val(subItem_map[suggestion].unitType).trigger('change');
            $('#modelSubItem_descript').val(subItem_map[suggestion].descript).trigger('change');
            
        }



        console.log('Selection: ' + suggestion);
        console.log('Selection key: ' + subItem_map[suggestion].id);

    });

}

function loadMainItemTypeahead() {
    var formData = {
        dept_uid: $('#dept_select').val()
    }

    $.ajax({
        url: "/AuthApi/authMainItemList",
        type: "post",
        data: formData,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.mainItems;

                mainItem_items = [];
                mainItem_map = {};

                $.each(obj, function (i, item) {
                    var id = item.mainItem_uid;
                    var name = item.mainItem_name;
                    mainItem_map[name] = { id: id, name: name };
                    mainItem_items.push(name);
                });

                var bh = new Bloodhound({
                    local: mainItem_items,
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    datumTokenizer: Bloodhound.tokenizers.whitespace
                });

                var nflTeamsWithDefaults = function nflTeamsWithDefaults(q, sync) {
                    if (q === '') {
                        sync(bh.index.all());
                    } else {
                        bh.search(q, sync);
                    }
                };

                $('#modelMainItem_name').typeahead(
                    {
                        minLength: 0,
                        highlight: false
                    },
                    {
                        source: nflTeamsWithDefaults
                    }

                );

                $('#modelMainItem_name').bind('typeahead:select', function (ev, suggestion) {
                    console.log('Selection: ' + suggestion);
                    console.log('Selection key: ' + mainItem_map[suggestion].id);
                    $('#parent_mainItem_uid').val(mainItem_map[suggestion].id);
                });

                $('#modelMainItem_name').bind('typeahead:autocomplete', function (ev, suggestion) {
                    console.log('Selection: ' + suggestion);
                    console.log('Selection key: ' + mainItem_map[suggestion].id);
                    $('#parent_mainItem_uid').val(mainItem_map[suggestion].id);
                });
              
            } else {
                alert(data.message);

                if (data.err_code == "99999") {
                    location.href = "/Root/Login";
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('網路或伺服器發生錯誤，請稍後重試!');
        }
    });

    
}
function loadModelQuotationDataTable() {
    var dataTables = {
        init: function init() {

            this.bindUIActions();
        },
        bindUIActions: function bindUIActions() {

            // event handlers
            this.table = this.handleDataTables();

            // add buttons
            //this.table.buttons().container().appendTo('#dt-buttons').unwrap();
        },
        handleDataTables: function handleDataTables() {
            //$('#myTable').append("<tfoot><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr></tfoot>");
            return $('#dt-responsive-modelQuotation').DataTable({
                dom: '<\'text-muted\'Bif>\n        <\'table-responsive\'trl>\n        <\'mt-4\'p>',
                lengthChange: true,
                lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
                pageLength: 25,
                buttons: [
                    //{
                    //    text: '休假設定',
                    //    action: function (e, dt, node, config) {
                    //        vacationBtnFun();

                    //    }
                    //},
                    //'excelHtml5'
                ],
                language: {
                    paginate: {
                        previous: '<i class="fa fa-lg fa-angle-left"></i>',
                        next: '<i class="fa fa-lg fa-angle-right"></i>'
                    },
                    buttons: {
                        copyTitle: 'Data copied',
                        copyKeys: 'Use your keyboard or menu to select the copy command'
                    }
                },
                autoWidth: false,
                rowId: 'modelQuotation_uid',
                deferRender: true,
                initComplete: function () {
                    modelQuotationTable = $('#dt-responsive-modelQuotation').dataTable();
                    $('#dt-responsive-modelQuotation').on('click', 'a', function () {
                        buttonModelQuotationClick(this);
                    });

                    $('#dt-responsive-modelQuotation').on('click', 'button', function () {
                        buttonModelQuotationClick(this);
                    });


                },
                order: [[1, 'desc']],
                info: true,
                search: "搜尋:",
                searching: true,
                columns: [
                    { data: 'modelQuotation_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'modelQuotation_createdate', className: 'align-top text-right', orderable: true, searchable: true },
                    { data: 'modelQuotation_uid', className: 'align-top text-center', orderable: false, searchable: false }
                ],
                columnDefs: [
                    {
                        targets: 0,
                        className: 'align-middle text-left',
                        orderable: false,
                        searchable: true,
                        render: function render(data, type, row, meta) {

                            return row.modelQuotation_name;

                        }
                    },
                    {
                        targets: 1,
                        className: 'align-middle text-right',
                        orderable: true,
                        searchable: true,
                        render: function render(data, type, row, meta) {

                            return (new Date(row.modelQuotation_createdate)).format("yyyy/MM/dd hh:mm:ss");
                        }
                    },
                    {
                        targets: 2,
                        className: 'align-middle text-center',
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = '';

                            ret += '<button type="button" data-uid="' + row.modelQuotation_uid + '" data-method="edit" class="btn btn-sm btn-icon btn-secondary" ><i class="fa fa-pencil-alt"></i> <span class="sr-only">Edit</span></button>';
                            ret += '<button type="button" data-uid="' + row.modelQuotation_uid + '" data-method="del" class="btn btn-sm btn-icon btn-secondary"><i class="far fa-trash-alt"></i> <span class="sr-only">Remove</span></button>';
                            return ret;
                        }
                    }

                ],
                responsive: {
                    details: {
                        display: $.fn.dataTable.Responsive.display.childRowImmediate,
                        type: ''
                    }
                }
            });
        },
        handleSearchRecords: function handleSearchRecords() {
            var self = this;

            $('#table-search, #filterBy').on('keyup change focus', function (e) {
                var filterBy = $('#filterBy').val();
                var hasFilter = filterBy !== '';
                var value = $('#table-search').val();

                self.table.search('').columns().search('').draw();

                if (hasFilter) {
                    self.table.columns(filterBy).search(value).draw();
                } else {
                    self.table.search(value).draw();
                }

            });
        }
    }

    dataTables.init();
}

function loadDataTable() {
    var dataTables = {
        init: function init() {

            this.bindUIActions();
        },
        bindUIActions: function bindUIActions() {

            // event handlers
            this.table = this.handleDataTables();

            // add buttons
            //this.table.buttons().container().appendTo('#dt-buttons').unwrap();
        },
        handleDataTables: function handleDataTables() {
            //$('#myTable').append("<tfoot><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr></tfoot>");
            return $('#dt-responsive').DataTable({
                dom: '<\'text-muted\'Bif>\n        <\'table-responsive\'trl>\n        <\'mt-4\'p>',
                lengthChange: true,
                lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
                pageLength: 50,
                buttons: [
                    //{
                    //    text: '休假設定',
                    //    action: function (e, dt, node, config) {
                    //        vacationBtnFun();

                    //    }
                    //},
                    //'excelHtml5'
                ],
                language: {
                    paginate: {
                        previous: '<i class="fa fa-lg fa-angle-left"></i>',
                        next: '<i class="fa fa-lg fa-angle-right"></i>'
                    },
                    buttons: {
                        copyTitle: 'Data copied',
                        copyKeys: 'Use your keyboard or menu to select the copy command'
                    }
                },
                autoWidth: false,
                ajax: {
                    url: '/authApi/authModalProjList',
                    type: 'POST',
                    data: function (d) {
                        Object.assign(d, {
                            dept_uid: $('#dept_select').val()
                        });

                        return d;
                    },
                    dataSrc: 'modelProjs'
                },
                rowId: 'modelProj_uid',
                deferRender: true,
                initComplete: function () {
                    modelProjTable = $('#dt-responsive').dataTable();
                    $('#dt-responsive').on('click', 'a', function () {
                        buttonClick(this);
                    });

                    $('#dt-responsive').on('click', 'button', function () {
                        buttonClick(this);
                    });


                },
                order: [[1, 'desc']],
                info: true,
                search: "搜尋:",
                searching: true,
                columns: [
                    { data: 'modelProj_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'modelProj_createdate', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'modelProj_uid', className: 'align-top text-center', orderable: false, searchable: false }
                ],
                columnDefs: [
                    {
                        targets: 0,
                        className: 'align-middle text-left',
                        orderable: false,
                        searchable: true,
                        render: function render(data, type, row, meta) {


                            return '<a href="javascript: void(0);" data-uid="' + row.modelProj_uid + '" data-method="preview" >' + row.modelProj_name + '</a>';

                        }
                    },
                    {
                        targets: 1,
                        className: 'align-middle text-left',
                        orderable: false,
                        searchable: true,
                        render: function render(data, type, row, meta) {


                            return (new Date(row.modelProj_createdate)).format("yyyy/MM/dd hh:mm:ss");
                        }
                    },
                    {
                        targets: 2,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = '';

                            ret += '<button type="button" data-uid="' + row.modelProj_uid + '" data-method="edit" class="btn btn-sm btn-icon btn-secondary" ><i class="fa fa-pencil-alt"></i> <span class="sr-only">Edit</span></button>';
                            ret += '<button type="button" data-uid="' + row.modelProj_uid + '" data-method="del" class="btn btn-sm btn-icon btn-secondary"><i class="far fa-trash-alt"></i> <span class="sr-only">Remove</span></button>';
                            return ret;
                        }
                    }

                ],
                responsive: {
                    details: {
                        display: $.fn.dataTable.Responsive.display.childRowImmediate,
                        type: ''
                    }
                }
            });
        },
        handleSearchRecords: function handleSearchRecords() {
            var self = this;

            $('#table-search, #filterBy').on('keyup change focus', function (e) {
                var filterBy = $('#filterBy').val();
                var hasFilter = filterBy !== '';
                var value = $('#table-search').val();

                self.table.search('').columns().search('').draw();

                if (hasFilter) {
                    self.table.columns(filterBy).search(value).draw();
                } else {
                    self.table.search(value).draw();
                }

            });
        }
    }

    dataTables.init();
}

function deptList() {
    $.ajax({
        url: "/AuthApi/authDeptList",
        type: "post",
        data: null,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.depts;
                var items = "";
                $.each(obj, function (i, item) {


                    $("#dept_select").append($("<option>", {
                        value: item.dept_uid,
                        text: item.dept_name
                    }));


                });

                loadDataTable();
            } else {
                alert(data.message);

                if (data.err_code == "99999") {
                    location.href = "/Root/Login";
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('網路或伺服器發生錯誤，請稍後重試!');
        }
    });
}

function mainItemHtml(obj) {
    var htmlCode = '';
    htmlCode += '<!-- .card -->';
    htmlCode += '<div class="card card-fluid" data-uid="' + obj.modelMainItem_uid + '"  data-main-uid="' + obj.mainItem_uid + '" data-type="edit">';
    htmlCode += '    <div class="card-header border-bottom-0 btn-group">';
    htmlCode += '    <input type="hidden" data-name="mainItem_name" value="' + obj.modelMainItem_name + '" />';
    htmlCode += '    <input type="hidden" data-name="modelMainItem_ac" value="' + obj.modelMainItem_ac + '" />';
    htmlCode += '        <span data-span="mainItem_name">' + obj.modelMainItem_name + '</span>';
    htmlCode += '        <div class="dd-nodrag btn-group ml-auto">';
    htmlCode += '            <button type="button" class="btn btn-sm btn-secondary" onclick="editModelMainItem(this);">Edit</button> <button type="button" onclick="delModelMainItem(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
    htmlCode += '        </div>';
    htmlCode += '        ';
    htmlCode += '    </div>';
    htmlCode += '        <!-- .dd-list -->';
    htmlCode += '        <ol class="dd-list">';

    $.each(obj.modelSubItems, function (i, subitem) {
        htmlCode += subItemHtml(subitem);
    });

    htmlCode += '       ';
    htmlCode += '        </ol><!-- /.dd-list -->';
    htmlCode += ' ';
    htmlCode += '    <!-- .card-footer -->';
    htmlCode += '    <div class="card-footer">';
    htmlCode += '        <a href="javascript: void(0);" onclick="addSubItem(this);" class="card-footer-item justify-content-start"><span><i class="fa fa-plus-circle mr-1"></i> 添加子項目</span></a>';
    htmlCode += '    </div><!-- /.card-footer -->';
    htmlCode += '</div><!-- /.card -->';

    return htmlCode;
}

function subItemHtml(obj) {
    var htmlCode = '';

    htmlCode += '   <li class="dd-item dd-nodrag" data-model-subitem-uid="' + obj.modelSubItem_uid + '" data-method="edit">';
    htmlCode += '       <textarea style="display:none;" data-name="subItem_uid">' + obj.subItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="model-subItem_uid">' + obj.modelSubItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="model-subitem-name">' + obj.modelSubItem_name + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="model-subitem-price">' + obj.modelSubItem_price + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="model-subitem-unitType">' + obj.modelSubItem_unitType + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="model-subitem-number">' + obj.modelSubItem_number + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="model-subitem-hasAC">' + obj.modelSubItem_hasAC + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="model-subitem-subTotal">' + obj.modelSubItem_subTotal + '</textarea>';
    htmlCode += '       <textarea data-name="model-subitem-descript" style="display:none;">' + obj.modelSubItem_descript + '</textarea>';
    htmlCode += '       <div class="dd-handle">';
    htmlCode += '           <div class="list-group-item">';
    htmlCode += '               <div class="list-group-item-figure">';
    htmlCode += '                   <span class="drag-indicator"></span>';
    htmlCode += '               </div>';
    htmlCode += '               <div class="list-group-item-body">';
    htmlCode += '                   <div class="team">';
    htmlCode += '                       <h4 data-name="subname" class="list-group-item-title">';
    htmlCode += '                           ' + obj.modelSubItem_name;
    htmlCode += '                       </h4><br/>';
    htmlCode += '                    <p class="list-group-item-text" data-name="subdesc" style="white-space: pre-line;font-size: 13px;">';
    htmlCode += '                           ' + obj.modelSubItem_descript;
    htmlCode += '                    </p><br/>';
    htmlCode += '                    <p class="list-group-item-text" data-name="subsummy" style="white-space: pre-line;font-size: 11px;">';
    htmlCode += '                           單價 NT$' + AppendComma(obj.modelSubItem_price) + ', 數量 ' + obj.modelSubItem_number + ', 單位 ' + obj.modelSubItem_unitType + '\r\n';
    htmlCode += '                           小計 NT$' + AppendComma(obj.modelSubItem_subTotal) + '\r\n';
    htmlCode += '                           AC(' + obj.modelSubItem_hasAC + ')';
    htmlCode += '                    </p>';
    htmlCode += '                   </div>';
    htmlCode += '               </div>';
    htmlCode += '           </div>';
    htmlCode += '           <div class="dd-nodrag btn-group ml-auto">';
    htmlCode += '            <button type="button" onclick="editSubItemButton(this);" class="btn btn-sm btn-secondary">Edit</button> <button type="button" onclick="delSubItemButton(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
    htmlCode += '           </div>';
    htmlCode += '       </div>         ';
    htmlCode += '   </li>';

    return htmlCode;
}

function buttonModelQuotationClick(obj) {
    var type = obj.getAttribute('data-method');
    var uid = obj.getAttribute('data-uid');
    var dept_uid = $('#dept_select').val();
    var modelProj_uid = $('#parent_modelProj_uid').val();

    modelQuotationRowID = $('#' + uid);

    modelQuotationRowPos = modelQuotationTable.fnGetPosition($('#' + uid)[0]);

    if (type == "del") {
        if (confirm('確定刪除此報價單範本? ')) {
            if (confirm('請再次確定刪除此報價單範本? ')) {
                var formData = {
                    dept_uid: dept_uid,
                    modelQuotation_uid: uid,
                    modelProj_uid: modelProj_uid,
                    method: 'del'
                }

                $.ajax({
                    url: "/AuthApi/addEditDelGetModelQuotation",
                    type: "post",
                    data: formData,
                    success: function (data, textStatus, jqXHR) {
                        if (data.ret == "yes") {
                            var row = modelQuotationTable.api().row(modelQuotationRowID).remove().draw(false);
                            alert('刪除成功');

                        } else {
                            alert(data.message);

                            if (data.err_code == "99999") {
                                location.href = "/Root/Login";
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('網路或伺服器發生錯誤，請稍後重試!');
                    }
                });
            }
        }

    }

    if (type == "edit") {
        var formData = {
            dept_uid: dept_uid,
            modelQuotation_uid: uid,
            modelProj_uid: modelProj_uid,
            method: 'get'
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetModelQuotation",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.modelQuotationDetails[0];

                    $("#modelQuotation_method").val('edit');
                    $("#modelQuotation_uid").val(obj.modelQuotation_uid);
                    $("#modelQuotation_name").val(obj.modelQuotation_name).trigger('change');

                    var htmlCode = '';
                    $.each(obj.modelMainItemDetails, function (i, item) {
                        htmlCode += mainItemHtml(item);
                    });

                    $('#modelItem_div').html(htmlCode);

                    $('#clientModelQuotationPreviewModal').modal('toggle');
                } else {
                    alert(data.message);

                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    }
}

function buttonClick(obj) {

    var type = obj.getAttribute('data-method');
    var uid = obj.getAttribute('data-uid');
    var dept_uid = $('#dept_select').val();

    modelProjRowID = $('#' + uid);

    modelProjRowPos = modelProjTable.fnGetPosition($('#' + uid)[0]);

    if (type == "preview") {
        var modelProj_name = obj.innerText.trim();
        var formData = {
            dept_uid: dept_uid,
            modelProj_uid: uid
        }

        $.ajax({
            url: "/AuthApi/authModalQuotationList",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.modelQuotations;

                    $('#dt-responsive-modelQuotation').dataTable().fnClearTable();
                    if (obj.length > 0) {

                        $('#dt-responsive-modelQuotation').dataTable().fnAddData(obj);
                    }
                    $('#modelQuotationTitle').val(modelProj_name + ' 的範本列表').trigger('change');

                    $('#parent_modelProj_uid').val(uid);
                    $('#clientModelQuotationListModal').modal('toggle');
                } else {
                    alert(data.message);

                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    }

    if (type == "edit") {
        var formData = {
            method: 'get',
            modelProj_uid: uid,
            dept_uid: dept_uid
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetModelProj",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.modelProjs[0];

                    $("#modelProj_method").val('edit');
                    $("#modelProj_uid").val(obj.modelProj_uid);
                    $("#dept_uid").val(obj.dept_uid).trigger('change');
                    $("#modelProj_name").val(obj.modelProj_name).trigger('change');


                    $('#modelProjModal').modal('toggle');
                } else {
                    alert(data.message);

                    if (data.err_code == "99999") {
                        location.href = "/Root/Login";
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });


    }

    if (type == "del") {
        if (confirm('確定刪除此筆資料? 所有子項目也會一併刪除~')) {
            if (confirm('再次確認是否刪除所有此項目與子項目?')) {
                var formData = {
                    method: 'del',
                    modelProj_uid: uid,
                    dept_uid: dept_uid
                }

                $.ajax({
                    url: "/AuthApi/addEditDelGetModelProj",
                    type: "post",
                    data: formData,
                    success: function (data, textStatus, jqXHR) {
                        if (data.ret == "yes") {
                            var row = modelProjTable.api().row(modelProjRowID).remove().draw(false);
                            alert('刪除成功');

                        } else {
                            alert(data.message);

                            if (data.err_code == "99999") {
                                location.href = "/Root/Login";
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('網路或伺服器發生錯誤，請稍後重試!');
                    }
                });
            }

        }
    }
}