var projectTable;
var projectRowID;
var projectPos;

var quotationTable;
var quotationRowID;
var quotationPos;

var historyTable;
var historyDataTable;
var historyRowID;
var historyPos;

var quotation_total;

var deledMainItems = [];
var deledSubItems = [];
var deledPayments = [];
var deledInvoices = [];

var preSubItem_name = '';
var hasBind = 'N';
$(document).ready(function () {
    deptList();
    companyList();
    loadyearmonth();
    loadQuotationTable();
    initInvoiceSelectItem();
    loadHistoryTable();

    var actualDate = new Date(); // convert to actual date
    var prevDate = new Date(actualDate.getFullYear(), actualDate.getMonth() - 13, actualDate.getDate());

    var startTxt = prevDate.getFullYear().toString() + "/" + padding(prevDate.getMonth() + 1, 2);
    var endTxt = actualDate.getFullYear().toString() + "/" + padding(actualDate.getMonth() + 1, 2);

    const fpStart = flatpickr("#dateStart", {
        "locale": "zh_tw",
        "plugins": [
            new monthSelectPlugin({
                shorthand: true, //defaults to false
                dateFormat: "Y/m", //defaults to "F Y"
                altFormat: "Y M", //defaults to "F Y"
                theme: "light" // defaults to "light"
            })
        ]
    });

    const fpEnd = flatpickr("#dateEnd", {
        "locale": "zh_tw",
        "plugins": [
            new monthSelectPlugin({
                shorthand: true, //defaults to false
                dateFormat: "Y/m", //defaults to "F Y"
                altFormat: "Y M", //defaults to "F Y"
                theme: "light" // defaults to "light"
            })
        ]
    });

    const fpInvoiceDate = flatpickr("#invoice_date", {
        "locale": "zh_tw",
        "plugins": [
            new monthSelectPlugin({
                shorthand: true, //defaults to false
                dateFormat: "Y/m", //defaults to "F Y"
                altFormat: "Y M", //defaults to "F Y"
                theme: "light" // defaults to "light"
            })
        ]
    });

    fpStart.setDate(new Date(startTxt + '/1'));
    fpEnd.setDate(new Date(endTxt + '/1'));
    fpInvoiceDate.setDate(new Date(endTxt + '/1'));

    $("#quotation_range").flatpickr({
        mode: 'range',
        onChange: function (selectedDates, dateStr, instance) {
            if (selectedDates.length == 2) {
                var dateStart = instance.formatDate(selectedDates[0], "Y/m/d");
                var dateEnd = instance.formatDate(selectedDates[1], "Y/m/d");

                $('#quotation_expStart').val(dateStart);
                $('#quotation_expEnd').val(dateEnd);

                // interact with selected dates here
            }
        }
    })

    $('#projectSaveBtn').on('click', function () {
        var company_uid = $('#company_select').val();
        var project_name = $('#project_name').val();
        var project_ps = $('#project_ps').val();
        var project_uid = $('#project_uid').val();
        var method = $('#project_method').val();
        var dept_uid = $('#dept_select').val();

        var msg = '';

        if (company_uid == "") {
            msg += '請選擇客戶公司!\n';
        }

        if (project_name == '') {
            msg += '請輸入專案名稱!\n';
        }

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

        var formData = {
            method: method,
            project_uid: project_uid,
            project_name: project_name,
            company_uid: company_uid,
            project_ps: project_ps,
            dept_uid: dept_uid
        }

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

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

                    if (method == "edit") {
                        projectTable.fnUpdate(obj, projectRowPos);
                    }



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

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


    //新增報價單
    $('#QuotationListNewBtn').on('click', function () {

        deledMainItems = [];
        deledSubItems = [];
        deledPayments = [];
        deledInvoices = [];

        $('#modelItem_div').html('');
        $('#payment_group').find('ol').html('');
        $('#invoice_group').find('ol').html('');

        quotation_total = 0;

        $('#quotation_editType_div').show();
        $('#quotation_sa').val(service_text());
        $('#quotation_method').val('add');
        $('#modelQuotationDialogSaveBtn').show();
        $('#clientModelQuotationModal').modal("toggle");
    });

    $('#invoice_type').on('change', function () {
        if ($('#invoice_type').val() == "date") {
            $('#invoice_type_date').show();
            $('#invoice_type_text').hide();
        } else {
            $('#invoice_type_date').hide();
            $('#invoice_type_text').show();
        }
    });

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

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

    $('#projectNewBtn').on('click', function () {
        $('#project_method').val('add');
        $('#clientProjectModal').modal("toggle");
    });

    $("#modelProject_select").on('change', function () {
        var modelProj_uid = $("#modelProject_select").val();

        $("#modelQuotation_select").empty().append('<option value="">請先選擇專案類型</option>');

        if (modelProj_uid != '') {
            var formData = {
                dept_uid: $('#dept_select').val(),
                modelProj_uid: modelProj_uid
            }

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

                        

                        $.each(obj, function (i, item) {
                            $("#modelQuotation_select").append($("<option>", {
                                value: item.modelQuotation_uid,
                                text: item.modelQuotation_name
                            }));
                        });



                    } else {
                        alert(data.message);

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

    //套用範本鈕
    $('#applyTemp_btn').on('click', function () {
        var modelProj_uid = $('#modelProject_select').val();
        var modelQuotation_uid = $('#modelQuotation_select').val();
        var dept_uid = $('#dept_select').val();

        if (modelProj_uid == '' || modelQuotation_uid == '') {
            alert('請選擇要套用的範本!');
            return;
        }

        var nowModelItem_count = 0;

        $('#modelItem_div .card').each(function (index, obj) {
            nowModelItem_count++;
        });

        if (nowModelItem_count > 0) {
            if (confirm("確定要使用範本覆蓋目前報價項目資料?") == false) {
                return;
            }
        }

        var formData = {
            dept_uid: dept_uid,
            modelQuotation_uid: modelQuotation_uid,
            modelProj_uid: modelProj_uid,
            method: 'get'
        }

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

                    quotation_total = 0;

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

                    

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

                    $.each(obj.modelMainItemDetails, function (i, item) {
                        $('#nest_' + item.modelMainItem_uid).nestable();
                    });

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

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

    });
    function loadyearmonth() {
        var actualDate = new Date(); // convert to actual date

        var nowYear = actualDate.getFullYear();

        for (tmpY = nowYear; tmpY >= 2019; tmpY--) {
            $("#project_year").append($("<option></option>").attr("value", tmpY).text(tmpY + " 年度"));
        }

        for (tmpM = 1; tmpM <= 12; tmpM++) {
            $("#project_month").append($("<option></option>").attr("value", tmpM).text(tmpM + " 月"));

        }

    }

    //優惠價格變更
    $('#quotation_specTotal').on('change', function () {
        var specTotal = $('#quotation_specTotal').val();

        if (specTotal.isNumber() == false) {
            alert('請輸入正確的數字!(不能有符號)');
            $('#quotation_specTotal').val('');
        } else {
            updateGrandTotal();
        }
        
    });

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


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

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

    //新增次項目對話框儲存鈕
    $('#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();
        var modelSubItem_unitType = $('#modelSubItem_unitType').val();
        var modelSubItem_number = $('#modelSubItem_number').val();
        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="quotationSubItem_uid"]').val(modelSubItem_uid);
            $(htmlObj).find('[data-name="quotationSubItem_name"]').val(modelSubItem_name);
            $(htmlObj).find('[data-name="quotationSubItem_price"]').val(modelSubItem_price);
            $(htmlObj).find('[data-name="quotationSubItem_unitType"]').val(modelSubItem_unitType);
            $(htmlObj).find('[data-name="quotationSubItem_number"]').val(modelSubItem_number);
            $(htmlObj).find('[data-name="quotationSubItem_hasAC"]').val(modelSubItem_hasAC);
            $(htmlObj).find('[data-name="quotationSubItem_subTotal"]').val(modelSubItem_subTotal);
            $(htmlObj).find('[data-name="quotationSubItem_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" 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="quotationSubItem_uid">' + modelSubItem_uid + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_name">' + modelSubItem_name + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_price">' + modelSubItem_price + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_unitType">' + modelSubItem_unitType + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_number">' + modelSubItem_number + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_hasAC">' + modelSubItem_hasAC + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_subTotal">' + modelSubItem_subTotal + '</textarea>';
            htmlCode += '       <textarea data-name="quotationSubItem_descript" style="display:none;">' + modelSubItem_descript + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="subItem_uid_old">' + subItem_uid + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_uid_old">' + modelSubItem_uid + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_name_old">' + modelSubItem_name + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_price_old">' + modelSubItem_price + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_unitType_old">' + modelSubItem_unitType + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_number_old">' + modelSubItem_number + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_hasAC_old">' + modelSubItem_hasAC + '</textarea>';
            htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_subTotal_old">' + modelSubItem_subTotal + '</textarea>';
            htmlCode += '       <textarea data-name="quotationSubItem_descript_old" 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="editQuotationSubItemButton(this);" class="btn btn-sm btn-secondary">Edit</button> <button type="button" onclick="delQuotationSubItemButton(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);

            var li_count = 0;

            htmlObj.find('li').each(function (i, item) {
                li_count++;
            });

            if (li_count == 1) {
                $('#nest_' + parent_data_uid).nestable();
            }

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

        updateGrandTotal();
    });

    //新增主項目對話框儲存鈕
    $('#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();
       


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

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

        var ac_string = "";

        if (modelMainItem_ac == 0) {
            ac_string = "無";
        } else {
            ac_string = modelMainItem_ac + '%';
        }

        if (method == 'edit') {
            var obj = $('#modelItem_div').find("[data-uid='" + modelMainItem_uid + "']");
            $(obj).prop('data-main-uid', mainItem_uid);
            $(obj).find("[data-name='quotationMainItem_name']").val(modelMainItem_name);
            $(obj).find("[data-span='quotationMainItem_name']").text(modelMainItem_name);
            $(obj).find("[data-name='quotationMainItem_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="quotationMainItem_name" value="' + modelMainItem_name + '" />';
            htmlCode += '    <input type="hidden" data-name="quotationMainItem_ac" value="' + modelMainItem_ac + '" />';
            htmlCode += '    <input type="hidden" data-name="quotationMainItem_subTotal" value="0" />';
            htmlCode += '    <input type="hidden" data-name="quotationMainItem_name_old" value="" />';
            htmlCode += '    <input type="hidden" data-name="quotationMainItem_ac_old" value="" />';
            htmlCode += '    <input type="hidden" data-name="quotationMainItem_subTotal_old" value="" />';
            htmlCode += '    <input type="hidden" data-name="mainItem_uid_old" value="" />';
            htmlCode += '        <span data-span="quotationMainItem_name" style="width: 60%;">' + modelMainItem_name + '</span>';
            htmlCode += '        <span data-span="quotationMainItem_ac" style="width: 10%;">AC:&nbsp;' + ac_string + '&nbsp;</span>';
            htmlCode += '        <span data-span="quotationMainItem_subTotal" style="text-align: right;">項目合計:&nbsp;0</span>';
            htmlCode += '        <div class="dd-nodrag btn-group ml-auto">';
            htmlCode += '            <button type="button" class="btn btn-sm btn-secondary" onclick="editQuotationMainItem(this);">Edit</button> <button type="button" onclick="delQuotationMainItem(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
            htmlCode += '        </div>';
            htmlCode += '        ';
            htmlCode += '    </div>';
            htmlCode += '        <div class="dd" id="nest_' + datauid + '" data-toggle="sortable" data-max-depth="1" >';
            htmlCode += '        <!-- .dd-list -->';
            htmlCode += '        <ol class="dd-list">';
            htmlCode += '       ';
            htmlCode += '        </ol><!-- /.dd-list -->';
            htmlCode += '        </div>';
            htmlCode += '    <!-- .card-footer -->';
            htmlCode += '    <div class="card-footer">';
            htmlCode += '        <a href="javascript: void(0);" onclick="addQuotationSubItem(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');
        }

        updateGrandTotal();
    });

    //新增付款方式按鈕
    $('#addPaymentBtn').on('click', function () {

        $('#payment_method').val('add');
        $('#paymentModal').modal('toggle');
    });

    //付款方式下拉
    $('#paymentMethod_select').on('change', function () {
        var payment_method = $('#paymentMethod_select').val();

        switch (payment_method) {
            case 'cheque':
                $('#payment_descript').val('票期    天').trigger('change');
                break;
            case 'telegraphic':
                $('#payment_descript').val('入帳日     年    月    日').trigger('change');
                break;
            case 'paycash':
                $('#payment_descript').val('').trigger('change');
                break;
            case 'downpayment':
                $('#payment_descript').val('').trigger('change');
                break;
            case 'custom':
                $('#payment_descript').val('').trigger('change');
                break;
            default:
                console.log(`Sorry, we are out of ${expr}.`);
        }

    });

    //付款方式儲存鈕
    $('#paymentModalDialogSaveBtn').on('click', function () {
        var payment_method = $('#paymentMethod_select').val();
        var payment_methodname = $("#paymentMethod_select option:selected").text();
        var payment_descript = $('#payment_descript').val();



        if (payment_method != 'paycash' && payment_method != 'downpayment') {
            if (payment_descript == '') {
                alert('請輸入付款資訊!');
                return;
            }
        }

        var payment_display = payment_methodname;

        if (payment_descript != '') {
            payment_display = payment_display + ': ' + payment_descript;
        }

        var htmlCode = '';

        htmlCode += '                        <li class="list-group-item align-items-center drag-handle">\n';
        htmlCode += '                          <textarea style="display:none;" data-name="data_method">add</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="payment_method">' + payment_method + '</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="payment_methodname">' + payment_methodname + '</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="payment_descript">' + payment_descript + '</textarea>';
        htmlCode += '                          <span class="drag-indicator"></span>\n';
        htmlCode += '                          <div> ' + payment_display + ' </div>\n';
        htmlCode += '                          <div class="btn-group ml-auto">\n';
        htmlCode += '                            <button class="btn btn-sm btn-secondary" data-method="add" onclick="delPaymentItem(this);"><i class="far fa-trash-alt"></i></button>\n';
        htmlCode += '                          </div>\n';
        htmlCode += '                        </li>\n';

        $('#payment_group').find('ol').append(htmlCode);

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

    //新增發票項目
    $('#addInvoiceBtn').on('click', function () {
        $('#invoice_name').typeahead('destroy');

        initInvoiceSelectItem();

        fpInvoiceDate.setDate(new Date(endTxt + '/1'));
        $('#invoice_type').val('date');
        $('#invoice_type_text').hide();
        $('#invoice_method').val('add');
        $('#invoiceModal').modal('toggle');
    });

    //儲存發票項目
    $('#invoiceModalDialogSaveBtn').on('click', function () {
        var invoice_method = $('#invoice_method').val();
        var invoice_name = $("#invoice_name").val();
        var invoice_date = $('#invoice_date').val();
        var invoice_type = $('#invoice_type').val();
        var invoice_text = $('#invoice_text').val();
        var invoice_noTaxMoney = $('#invoice_noTaxMoney').val().replace(/,/g, "");

        

        if (invoice_noTaxMoney.isNumber() == false || invoice_noTaxMoney == '') {
            alert('發票金額得為純數字!');
            return;
        }

        if (invoice_name == '') {
            alert('請輸入品項名稱!');
            return;
        }

        if (invoice_type == 'date') {
            if (invoice_date == '') {
                alert('請輸入發票月份!');
                return;
            }
        }

        if (invoice_type == 'text') {
            if (invoice_text == '') {
                alert('請輸入發票開立時間說明!');
                return;
            }
        }

        var invoice_display = "開立品項: " + invoice_name + ",      開立月份: " + invoice_date + ",     金額(未稅): " + AppendComma(invoice_noTaxMoney);

        if (invoice_type == 'text') {
            invoice_display = "開立品項: " + invoice_name + ",      開立月份: " + invoice_text + ",     金額(未稅): " + AppendComma(invoice_noTaxMoney);
        }

        var htmlCode = '';

        htmlCode += '                        <li class="list-group-item align-items-center drag-handle">\n';
        htmlCode += '                          <textarea style="display:none;" data-name="data_method">add</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="invoice_name">' + invoice_name + '</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="invoice_type">' + invoice_type + '</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="invoice_date">' + invoice_date + '</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="invoice_text">' + invoice_text + '</textarea>';
        htmlCode += '                          <textarea style="display:none;" data-name="invoice_noTaxMoney">' + invoice_noTaxMoney + '</textarea>';
        htmlCode += '                          <span class="drag-indicator"></span>\n';
        htmlCode += '                          <span style="width: 15%;"> ' + "開立品項: " + invoice_name + ' </span>\n';

        if (invoice_type == 'date') {
            htmlCode += '                          <span style="width: 15%;"> ' + "開立月份: " + invoice_date + ' </span\n';
        } else {
            htmlCode += '                          <span style="width: 15%;"> ' + "開立月份: " + invoice_text + ' </span\n';
        }

        
        htmlCode += '                          <span style="width: 20%;">' + "金額(未稅): " + AppendComma(invoice_noTaxMoney) + ' </span>\n';
        htmlCode += '                          <span style="width: 50%;"></span>';
        htmlCode += '                          <div class="btn-group ml-auto">\n';
        htmlCode += '                            <button class="btn btn-sm btn-secondary" data-method="add" onclick="delInvoiceItem(this);"><i class="far fa-trash-alt"></i></button>\n';
        htmlCode += '                          </div>\n';
        htmlCode += '                        </li>\n';

        $('#invoice_group').find('ol').append(htmlCode);

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

    //報價單儲存
    $('#modelQuotationDialogSaveBtn').on('click', function () {
        updateGrandTotal();

        var quotation_method = $('#quotation_method').val();
        var quotation_uid = $('#quotation_uid').val();
        var quotation_version = $('#quotation_version').val();
        var quotation_prodMethod = '';
        var quotation_date = $('#quotation_date').val();
        var quotation_date_old = $('#quotation_date_old').val();
        var quotation_expStart = $('#quotation_expStart').val();
        var quotation_expEnd = $('#quotation_expEnd').val();
        var quotation_expStart_old = $('#quotation_expStart_old').val();
        var quotation_expEnd_old = $('#quotation_expEnd_old').val();
        var quotation_name = $('#quotation_name').val();
        var quotation_name_old = $('#quotation_name_old').val();
        var contactPerson_uid = $('#contactPerson_uid').val();
        var contactPerson_uid_old = $('#contactPerson_uid_old').val();
        var company_uid = $('#quotation_company_uid').val();
        var quotation_noTaxTotal = $('#quotation_noTaxTotal').val();
        var quotation_noTaxTotal_old = $('#quotation_noTaxTotal_old').val();
        var quotation_specTotal = $('#quotation_specTotal').val();
        var quotation_specTotal_old = $('#quotation_specTotal_old').val();
        var quotation_tax = $('#quotation_tax').val();
        var quotation_tax_old = $('#quotation_tax_old').val();
        var quotation_grandTotal = $('#quotation_grandTotal').val();
        var quotation_grandTotal_old = $('#quotation_grandTotal_old').val();
        var quotation_sa = $('#quotation_sa').val();
        var quotation_sa_old = $('#quotation_sa_old').val();

        var err_msg = '';

        if (quotation_date == '') {
            err_msg += '請輸入報價日期!\n';
        }

        if (quotation_name == '') {
            err_msg += '請輸入報價單名稱!\n';
        }

        if (quotation_expStart == '' || quotation_expEnd == '') {
            err_msg += '請輸入報價有效起訖日期!\n';
        }

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

        var quotation_log = '';



        if ($('#quotation_custom').prop('checked') == true) {
            quotation_prodMethod = 'custom';
        }

        if ($('#quotation_temp').prop('checked') == true) {
            quotation_prodMethod = 'template';
        }

        if (quotation_method == 'edit') {
            if (quotation_date != quotation_date_old) {
                quotation_log += '報價日期由 ' + quotation_date_old + ' 變更為 ' + quotation_date + '\n';
            }

            if (quotation_expStart != quotation_expStart_old || quotation_expEnd != quotation_expEnd_old) {
                quotation_log += '報價有效期由 ' + quotation_expStart_old + '至' + quotation_expEnd_old + ' 變更為 ' + quotation_expStart + '至' + quotation_expEnd + '\n';
            }

            if (quotation_name != quotation_name_old) {
                quotation_log += '報價單名稱由 ' + quotation_name_old + ' 變更為 ' + quotation_name + '\n';
            }

            if (contactPerson_uid != contactPerson_uid_old) {
                quotation_log += '客戶窗口人選變更\n';
            }

            if (quotation_noTaxTotal != quotation_noTaxTotal_old) {
                quotation_log += '專案總價由 ' + AppendComma(quotation_noTaxTotal_old) + ' 變更為 ' + AppendComma(quotation_noTaxTotal) + '\n';
            }

            if (quotation_specTotal != quotation_specTotal_old) {
                quotation_log += '專案優惠總價由 ' + AppendComma(quotation_specTotal_old) + ' 變更為 ' + AppendComma(quotation_specTotal) + '\n';
            }

            if (quotation_tax != quotation_tax_old) {
                quotation_log += '加值營業稅由 ' + AppendComma(quotation_tax_old) + ' 變更為 ' + AppendComma(quotation_tax) + '\n';
            }

            if (quotation_grandTotal != quotation_grandTotal_old) {
                quotation_log += '實際總價由 ' + AppendComma(quotation_grandTotal_old) + ' 變更為 ' + AppendComma(quotation_grandTotal) + '\n';
            }

            if (quotation_sa != quotation_sa_old) {
                quotation_log += '製作及維護服務協議條款內容有所變更\n';
            }

            $.each(deledMainItems, function (index, value) {
                quotation_log += value.mainItem_msg + '\n';
            });

            $.each(deledSubItems, function (index, value) {
                quotation_log += value.subItem_msg + '\n';
            });

            $.each(deledPayments, function (index, value) {
                quotation_log += value.message + '\n';
            });

            $.each(deledInvoices, function (index, value) {
                quotation_log += value.message + '\n';
            });
        }

        var mainItems = [];
        //報價單項目
        $('#modelItem_div .card').each(function (index, obj) {
            

            var data_type = $(obj).attr('data-type');
            var mainItem_uid = $(obj).attr('data-main-uid');
            var mainItem_uid_old = $(obj).find('[data-name="mainItem_uid_old"]').val();
            var quotationMainItem_uid = $(obj).attr('data-uid');
            var quotationMainItem_name = $(obj).find('[data-name="quotationMainItem_name"]').val();
            var quotationMainItem_name_old = $(obj).find('[data-name="quotationMainItem_name_old"]').val();
            var quotationMainItem_ac = $(obj).find('[data-name="quotationMainItem_ac"]').val();
            var quotationMainItem_ac_old = $(obj).find('[data-name="quotationMainItem_ac_old"]').val();
            var quotationMainItem_subTotal = $(obj).find('[data-name="quotationMainItem_subTotal"]').val();
            var quotationMainItem_subTotal_old = $(obj).find('[data-name="quotationMainItem_subTotal_old"]').val();

            if (quotation_method == 'edit') {
                if (data_type == 'add') {
                    quotation_log += '新增報價主項目 - ' + quotationMainItem_name + '\n';
                }

                if (data_type == 'edit') {
                    if (quotationMainItem_name != quotationMainItem_name_old) {
                        quotation_log += '報價主項目名稱由 [' + quotationMainItem_name_old + '] 更改為 [' + quotationMainItem_name + '] \n';
                    }

                    if (quotationMainItem_ac != quotationMainItem_ac_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的服務費比例由 [' + quotationMainItem_ac_old + '%] 更改為 [' + quotationMainItem_ac + '%] \n';
                    }
                }
            }

            var subitems = [];

            $(obj).find('ol li').each(function (i, item) {
                var data_method = $(item).attr('data-method');
                var quotationSubItem_uid = $(item).attr('data-model-subitem-uid');
                var subItem_uid = $(item).find('[data-name="subItem_uid"]').val();
                var quotationSubItem_name = $(item).find('[data-name="quotationSubItem_name"]').val();
                var quotationSubItem_price = $(item).find('[data-name="quotationSubItem_price"]').val();
                var quotationSubItem_hasAC = $(item).find('[data-name="quotationSubItem_hasAC"]').val();
                var quotationSubItem_unitType = $(item).find('[data-name="quotationSubItem_unitType"]').val();
                var quotationSubItem_number = $(item).find('[data-name="quotationSubItem_number"]').val();
                var quotationSubItem_subTotal = $(item).find('[data-name="quotationSubItem_subTotal"]').val();
                var quotationSubItem_descript = $(item).find('[data-name="quotationSubItem_descript"]').val();
                var subItem_uid_old = $(item).find('[data-name="subItem_uid_old"]').val();
                var quotationSubItem_name_old = $(item).find('[data-name="quotationSubItem_name_old"]').val();
                var quotationSubItem_price_old = $(item).find('[data-name="quotationSubItem_price_old"]').val();
                var quotationSubItem_hasAC_old = $(item).find('[data-name="quotationSubItem_hasAC_old"]').val();
                var quotationSubItem_unitType_old = $(item).find('[data-name="quotationSubItem_unitType_old"]').val();
                var quotationSubItem_number_old = $(item).find('[data-name="quotationSubItem_number_old"]').val();
                var quotationSubItem_subTotal_old = $(item).find('[data-name="quotationSubItem_subTotal_old"]').val();
                var quotationSubItem_descript_old = $(item).find('[data-name="quotationSubItem_descript_old"]').val();

                var subItemFormData = {
                    quotationSubItem_uid: quotationSubItem_uid,
                    subItem_uid: subItem_uid,
                    quotationSubItem_name: quotationSubItem_name,
                    quotationSubItem_price: quotationSubItem_price,
                    quotationSubItem_unitType: quotationSubItem_unitType,
                    quotationSubItem_number: quotationSubItem_number,
                    quotationSubItem_hasAC: quotationSubItem_hasAC,
                    quotationSubItem_subTotal: quotationSubItem_subTotal,
                    quotationSubItem_descript: quotationSubItem_descript
                }

                subitems.push(subItemFormData);

                if (data_method == 'add' && quotation_method == 'edit') {
                    if (quotationSubItem_name != quotationSubItem_name_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 中新增子項目 [' + quotationSubItem_name + ']  \n';
                    }
                }

                if (data_method == 'edit') {
                    if (quotationSubItem_name != quotationSubItem_name_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的子項目名稱由 [' + quotationSubItem_name_old + '] 更改為 [' + quotationSubItem_name + '] \n';
                    }

                    if (quotationSubItem_price != quotationSubItem_price_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的子項目 [' + quotationSubItem_name + '] 的單價由 [' + AppendComma(quotationSubItem_price_old) + '] 更改為 [' + AppendComma(quotationSubItem_price) + '] \n';
                    }

                    if (quotationSubItem_unitType != quotationSubItem_unitType_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的子項目 [' + quotationSubItem_name + '] 的計價單位由 [' + quotationSubItem_unitType_old + '] 更改為 [' + quotationSubItem_unitType + '] \n';
                    }

                    if (quotationSubItem_number != quotationSubItem_number_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的子項目 [' + quotationSubItem_name + '] 的數量由 [' + AppendComma(quotationSubItem_number_old) + '] 更改為 [' + AppendComma(quotationSubItem_number) + '] \n';
                    }

                    if (quotationSubItem_subTotal != quotationSubItem_subTotal_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的子項目 [' + quotationSubItem_name + '] 的價格由 [' + AppendComma(quotationSubItem_subTotal_old) + '] 更改為 [' + AppendComma(quotationSubItem_subTotal) + '] \n';
                    }

                    if (quotationSubItem_descript != quotationSubItem_descript_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的子項目 [' + quotationSubItem_name + '] 的細項敘述有異動 \n';
                    }

                    if (quotationSubItem_hasAC != quotationSubItem_hasAC_old) {
                        quotation_log += '報價主項目 [' + quotationMainItem_name + '] 的子項目 [' + quotationSubItem_name + '] 的收取AC由 [' + quotationSubItem_hasAC_old + '] 改為 [' + quotationSubItem_hasAC + '] \n';
                    }
                }

            });

            var mainItemFormData = {
                mainItem_uid: mainItem_uid,
                quotationMainItem_uid: quotationMainItem_uid,
                quotationMainItem_name: quotationMainItem_name,
                quotationMainItem_ac: quotationMainItem_ac,
                quotationMainItem_subTotal: quotationMainItem_subTotal,
                subitems: subitems
            }

            mainItems.push(mainItemFormData);
        });

        var payments = [];
        $('#payment_div').find('ol li').each(function (i, item) {
            
            var payment_method = $(item).find('[data-name="payment_method"]').val();
            var payment_methodname = $(item).find('[data-name="payment_methodname"]').val();
            var payment_descript = $(item).find('[data-name="payment_descript"]').val();

            var data_method = $(item).find('[data-name="data_method"]').val();
            if (quotation_method == 'edit' && data_method == 'add') {
                quotation_log += '付款方式增加了 [' + payment_methodname + ' - ' + payment_descript + ']\n';
            }
            
            var paymentFormData = {
                payment_method: payment_method,
                payment_methodname: payment_methodname,
                payment_descript: payment_descript
            }

            payments.push(paymentFormData);
        });

        var invoices = [];
        $('#invoice_div').find('ol li').each(function (i, item) {

            var invoice_name = $(item).find('[data-name="invoice_name"]').val();
            var invoice_type = $(item).find('[data-name="invoice_type"]').val();
            var invoice_date = $(item).find('[data-name="invoice_date"]').val();
            var invoice_text = $(item).find('[data-name="invoice_text"]').val();
            var invoice_noTaxMoney = $(item).find('[data-name="invoice_noTaxMoney"]').val();
            var data_method = $(item).find('[data-name="data_method"]').val();

            if (quotation_method == 'edit' && data_method == 'add') {
                quotation_log += '發票品項增加了 [' + invoice_name + ' (' + invoice_date + invoice_text + ') ' + AppendComma(invoice_noTaxMoney) + ']\n';
            }

            var invoiceFormData = {
                invoice_name: invoice_name,
                invoice_type: invoice_type,
                invoice_date: invoice_date,
                invoice_text: invoice_text,
                invoice_noTaxMoney: invoice_noTaxMoney
            }

            invoices.push(invoiceFormData);
        });

        var formData = {
            method: quotation_method,
            project_uid: $('#quotation_project_uid').val(),
            dept_uid: $('#dept_select').val(),
            quotation_uid: quotation_uid,
            quotation_version: quotation_version,
            quotation_prodMethod: quotation_prodMethod,
            quotation_date: quotation_date,
            quotation_expStart: quotation_expStart,
            quotation_expEnd: quotation_expEnd,
            quotation_name: quotation_name,
            contactPerson_uid: contactPerson_uid,
            company_uid: company_uid,
            quotation_log: quotation_log,
            quotation_noTaxTotal: quotation_noTaxTotal,
            quotation_specTotal: quotation_specTotal,
            quotation_tax: quotation_tax,
            quotation_grandTotal: quotation_grandTotal,
            quotation_sa: quotation_sa,
            mainItems: JSON.stringify(mainItems),
            payments: JSON.stringify(payments),
            invoices: JSON.stringify(invoices)
        }

        if (quotation_log == '' && quotation_method == 'edit') {
            alert('資料沒有異動，取消儲存!');
            return;
        }

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

                    if (quotation_method == "add") {
                        quotationTable.fnAddData(obj);
                    }

                    if (quotation_method == "edit") {
                        quotationTable.fnUpdate(obj, quotationRowPos);
                    }



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

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

    //另存報價單儲存鈕
    $('#save_to_same_SaveBtn').on('click', function () {
        var quotation_uid = $('#save_to_same_quotation_uid').val();
        var quotation_version = $('#save_to_same_quotation_version').val();
        var quotation_name = $('#save_to_same_quotation_name').val();


        if (quotation_name == '') {
            alert('請輸入新的報價單名稱!');
            return;
        }

        var formData = {
            quotation_uid: quotation_uid,
            quotation_version: quotation_version,
            quotation_name: quotation_name,
            method: 'save_to_same'
        }

        $.ajax({
            url: "/Api/saveas",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    obj = data.quotationView;

                    quotationTable.fnAddData(obj);

                    alert('另存至本專案為新報價單完成!');

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

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

    //另存至其他專案
    $('#save_to_other_SaveBtn').on('click', function () {
        var quotation_uid = $('#save_to_other_quotation_uid').val();
        var quotation_version = $('#save_to_other_quotation_version').val();
        var quotation_name = $('#save_to_other_quotation_name').val();
        var project_value = $('#project_select').val();

        if (project_value == '') {
            alert('請選擇要加入的專案');
            return;
        }

        var arr = project_value.split('/');
        var project_uid = arr[0];
        var company_uid = arr[1];
        var contactPerson_uid = $('#contactPerson_select').val();

        if (quotation_name == '') {
            alert('請輸入新的報價單名稱!');
            return;
        }

        if (contactPerson_uid == '') {
            alert('請選擇窗口!');
            return;
        }

        var formData = {
            quotation_uid: quotation_uid,
            quotation_version: quotation_version,
            quotation_name: quotation_name,
            project_uid: project_uid,
            company_uid: company_uid,
            contactPerson_uid: contactPerson_uid,
            method: 'save_to_other'
        }

        $.ajax({
            url: "/Api/saveas",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    obj = data.quotationView;

                    if (obj.project_uid == $('#quotation_project_uid').val()) {
                        quotationTable.fnAddData(obj);
                    }

                    

                    alert('另存至其他專案完成!');

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

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

    //另存至新專案
    $('#save_to_new_SaveBtn').on('click', function () {
        var quotation_uid = $('#save_to_new_quotation_uid').val();
        var quotation_version = $('#save_to_new_quotation_version').val();
        var quotation_name = $('#save_to_new_quotation_name').val();
        var project_name = $('#save_to_new_project_name').val();
        var company_uid = $('#company_new_select').val();
        var contactPerson_uid = $('#contactPerson_new_select').val();

        if (project_name == '') {
            alert('請輸入新專案名稱!');
            return;
        }

        if (quotation_name == '') {
            alert('請輸入新報價單名稱!');
            return;
        }

        if (company_uid == '') {
            aler('請選擇客戶公司!');
            return;
        }

        if (contactPerson_uid == '') {
            alert('請選擇窗口!');
            return;
        }

        var formData = {
            quotation_uid: quotation_uid,
            quotation_version: quotation_version,
            quotation_name: quotation_name,
            project_name: project_name,
            company_uid: company_uid,
            contactPerson_uid: contactPerson_uid,
            method: 'save_to_new'
        }

        $.ajax({
            url: "/Api/saveas",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    obj = data.projectView;
                    
                    projectTable.fnAddData(obj);
                    
                    alert('另存至新專案完成!');

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

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

    });

    //下拉專案列表選擇
    $('#project_select').on('change', function () {
        var project_value = $('#project_select').val();

        if (project_value == '') {
            $('#contactPerson_select').empty();
            return;
        }

        var arr = project_value.split('/');
        var project_uid = arr[0];
        var company_uid = arr[1];

        var formData = {
            company_uid: company_uid
        }

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

                    $("#contactPerson_select").empty();

                    $.each(obj, function (i, item) {
                        $("#contactPerson_select").append($("<option>", {
                            value: item.contactPerson_uid,
                            text: item.contactPerson_name + '   (Tel:' + item.contactPerson_tel + ',  Email:' + item.contactPerson_email + ')'
                        }));
                    });
                } else {
                    alert(data.message);

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

    });

    //下拉客戶公司列表
    $("#company_new_select").on('change', function () {
        var company_uid = $("#company_new_select").val();

        var formData = {
            company_uid: company_uid
        }

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

                    $("#contactPerson_new_select").empty();

                    $.each(obj, function (i, item) {
                        $("#contactPerson_new_select").append($("<option>", {
                            value: item.contactPerson_uid,
                            text: item.contactPerson_name + '   (Tel:' + item.contactPerson_tel + ',  Email:' + item.contactPerson_email + ')'
                        }));
                    });
                } else {
                    alert(data.message);

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

    });
});

function companyNewList() {
    $.ajax({
        url: "/Api/companyList",
        type: "post",
        data: null,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.companys;
                var items = "";

                $("#company_new_select").empty();

                $("#company_new_select").append($("<option>", {
                    value: '',
                    text: '請選擇客戶公司'
                }));
                $.each(obj, function (i, item) {


                    $("#company_new_select").append($("<option>", {
                        value: item.company_uid,
                        text: item.company_name
                    }));


                });


            } else {
                alert(data.message);

                if (data.err_code == "99999") {
                    location.href = "/Root/Login";
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('網路或伺服器發生錯誤，請稍後重試!');
        }
    });
}
function loadContactPersion() {
    var data = $('#dt-responsive').DataTable().row(projectRowPos).data();
    var uid = $('#quotation_company_uid').val();
    var formData = {
        company_uid: uid
    }

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

                $("#contactPerson_uid").empty();

                $.each(obj, function (i, item) {
                    $("#contactPerson_uid").append($("<option>", {
                        value: item.contactPerson_uid,
                        text: item.contactPerson_name + '   (Tel:' + item.contactPerson_tel + ',  Email:' + item.contactPerson_email + ')'
                    }));
                });
            } else {
                alert(data.message);

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

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

                $("#modelProject_select").empty().append('<option value="">請選擇專案類型</option>');
                $("#modelQuotation_select").empty().append('<option value="">請先選擇專案類型</option>');

                $.each(obj, function (i, item) {
                    $("#modelProject_select").append($("<option>", {
                        value: item.modelProj_uid,
                        text: item.modelProj_name
                    }));
                });

                

            } else {
                alert(data.message);

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

function buttonHistoryClick(obj) {
    var type = obj.getAttribute('data-method');
    var quotation_uid = obj.getAttribute('data-uid');
    var quotation_version = obj.getAttribute('data-version');

    historyRowID = $('#history_' + quotation_version + '_' + quotation_uid);

    historyRowPos = historyTable.fnGetPosition($('#history_' + quotation_version + '_' + quotation_uid)[0]);

    var quotation_row = historyDataTable.row(historyRowPos).data();

    if (type == "excel") {
        var formData = {
            quotation_uid: quotation_uid,
            quotation_version: quotation_version
        }

        $.redirect('/Api/exportXlsx', formData);
    }

    if (type == 'save_in_same') {
        $('#save_to_same_quotation_uid').val(quotation_uid);
        $('#save_to_same_quotation_version').val(quotation_version);
        $('#save_to_same_quotation_name').val(quotation_row.quotation_name + ' - Copy').trigger('change');
        $('#clientSaveToSameModal').modal('toggle');
    }

    if (type == 'saveas_to_other') {
        projectList();
        $('#save_to_other_quotation_uid').val(quotation_uid);
        $('#save_to_other_quotation_version').val(quotation_version);
        $('#save_to_other_quotation_name').val(quotation_row.quotation_name + ' - Copy').trigger('change');
        $('#clientSaveToOtherModal').modal('toggle');
    }

    if (type == 'saveas_to_new') {
        companyNewList();
        $('#save_to_new_quotation_uid').val(quotation_uid);
        $('#save_to_new_quotation_version').val(quotation_version);
        $('#save_to_new_quotation_name').val(quotation_row.quotation_name + ' - Copy').trigger('change');
        $('#clientSaveToNewModal').modal('toggle');
    }

    if (type == 'view') {
        var formData = {
            method: 'history',
            quotation_uid: quotation_uid,
            quotation_version: quotation_version
        }

        $.ajax({
            url: "/Api/addEditDelQuotation",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.quotationDetail;
                    var objView = data.quotationView;

                    $('#modelItem_div').html('');
                    $('#payment_group').find('ol').html('');
                    $('#invoice_group').find('ol').html('');

                    $("#quotation_method").val('edit');

                    quotationEditModelFillData(obj, objView);

                    $('#quotationTitle_name').val('報價單內容 (檢視唯讀狀態)');
                    $('#modelQuotationDialogSaveBtn').hide();

                    $('#clientModelQuotationModal').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();

    projectRowID = $('#' + uid);

    projectRowPos = projectTable.fnGetPosition($('#' + uid)[0]);

    if (type == "preview") {
        var data = $('#dt-responsive').DataTable().row(projectRowPos).data();
        
        var project_name = data.project_name;
        var company_name = data.company_name;
        var company_uid = data.company_uid;

        var project_info_div = '專案名稱: ' + project_name + ", 客戶公司:" + company_name;

        var formData = {
            project_uid: uid,
            dept_uid: dept_uid
        }

        $.ajax({
            url: "/Api/quotationList",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {

                    var obj = data.quotationViews;

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

                        $('#dt-responsive-quotation').dataTable().fnAddData(obj);
                    }

                    

                    $('#quotation_project_uid').val(uid);
                    $('#quotation_company_uid').val(company_uid);
                    $('#project_info_div').text(project_info_div);

                    loadContactPersion();
                    $('#clientQuotationListModal').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',
            project_uid: uid,
            dept_uid: dept_uid
        }

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

                    $("#project_method").val('edit');
                    $("#project_uid").val(obj.project_uid);
                    $("#project_name").val(obj.project_name).trigger('change');
                    $("#company_select").val(obj.company_uid);
                    $("#project_ps").val(obj.project_ps).trigger('change');

                    $('#clientProjectModal').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',
                    project_uid: uid,
                    dept_uid: dept_uid
                }

                $.ajax({
                    url: "/Api/addEditDelGetProject",
                    type: "del",
                    data: formData,
                    success: function (data, textStatus, jqXHR) {
                        if (data.ret == "yes") {
                            var row = projectTable.api().row(projectRowID).remove().draw(false);
                            alert('刪除成功');

                        } else {
                            alert(data.message);

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

        }
    }
}

function quotationEditModelFillData(obj, objView) {
    $('#quotation_editType_div').hide();
    $('#quotation_uid').val(obj.quotation_uid);
    $('#quotation_version').val(obj.quotation_version);
    $('#quotation_date').val(obj.quotation_date).trigger('change');
    $('#quotation_date_old').val(obj.quotation_date);
    $('#quotation_expStart').val(obj.quotation_expStart);
    $('#quotation_expEnd').val(obj.quotation_expEnd);
    $('#quotation_expStart_old').val(obj.quotation_expStart);
    $('#quotation_expEnd_old').val(obj.quotation_expEnd);
    $('#quotation_name').val(obj.quotation_name).trigger('change');
    $('#quotation_name_old').val(obj.quotation_name);
    $('#quotation_name').val(obj.quotation_name).trigger('change');
    $('#quotation_name_old').val(obj.quotation_name);

    //$('#quotation_noTaxTotal').val('').trigger('change');
    //$('#quotation_specTotal').val('').trigger('change');

    //$('#quotation_noTaxTotal').val(obj.quotation_noTaxTotal);
    //$('#quotation_noTaxTotal_old').val(obj.quotation_noTaxTotal);

    if (obj.quotation_specTotal != 0) {
        $('#quotation_specTotal').val(obj.quotation_specTotal).trigger('change');
        $('#quotation_specTotal_old').val(obj.quotation_specTotal);
    } else {
        $('#quotation_specTotal').val('').trigger('change');
        $('#quotation_specTotal_old').val('');
    }
    $('#quotation_noTaxTotal').val(obj.quotation_noTaxTotal);
    $('#quotation_noTaxTotal_old').val(obj.quotation_noTaxTotal);
    $('#quotation_tax').val(obj.quotation_tax).trigger('change');
    $('#quotation_tax_old').val(obj.quotation_tax);
    $('#quotation_grandTotal').val(obj.quotation_grandTotal).trigger('change');
    $('#quotation_grandTotal_old').val(obj.quotation_grandTotal);
    $('#quotation_sa').val(obj.quotation_sa).trigger('change');
    $('#quotation_sa_old').val(obj.quotation_sa);


    var no_found = 1;
    $("#contactPerson_uid option").each(function () {
        if ($(this).val() == obj.contactPerson_uid) {
            no_found = 0;
        }
    });

    if (no_found == 1) {
        $("#contactPerson_uid").append($("<option>", {
            value: obj.contactPerson_uid,
            text: objView.contactPerson_name
        }));
    }

    $('#contactPerson_uid').val(obj.contactPerson_uid);
    $('#contactPerson_uid_old').val(obj.contactPerson_uid);


    $("#quotation_range").flatpickr({
        mode: 'range',
        onChange: function (selectedDates, dateStr, instance) {
            if (selectedDates.length == 2) {
                var dateStart = instance.formatDate(selectedDates[0], "Y/m/d");
                var dateEnd = instance.formatDate(selectedDates[1], "Y/m/d");

                $('#quotation_expStart').val(dateStart);
                $('#quotation_expEnd').val(dateEnd);

                // interact with selected dates here
            }
        },
        defaultDate: [obj.quotation_expStart, obj.quotation_expEnd]
    });

    $("#quotation_range").trigger('change');

    quotation_total = 0;

    var mainItemHtmlCode = '';

    $.each(obj.quotationMainItemDetails, function (i, mainItem) {
        //產生報價項目
        mainItemHtmlCode += makeMainItemHtml(mainItem);
    });

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

    //產生付款方式
    var paymentHtmlCode = '';
    $.each(obj.payments, function (i, payment) {
        paymentHtmlCode += makePaymentHtml(payment);
    });

    $('#payment_group').find('ol').append(paymentHtmlCode);

    //產生發票品項
    var invoiceHtmlCode = '';
    
    $.each(obj.invoices, function (i, invoice) {
        invoiceHtmlCode += makeInvoiceHtml(invoice);
    });

    $('#invoice_group').find('ol').append(invoiceHtmlCode);
}

function makeMainItemHtml(obj) {
    var ac_string = '';

    if (obj.quotationMainItem_ac == 0) {
        ac_string = '無';
    } else {
        ac_string = obj.quotationMainItem_ac + '%'
    }

    var mainItem_total = 0;
    var mainItem_ac = 0.0;

    $.each(obj.quotationSubItems, function (i, subitem) {
        var subitem_val = subitem.quotationSubItem_subTotal;
        mainItem_total += subitem_val;
        if (subitem.quotationSubItem_hasAC == 'Y') {

            mainItem_ac += (subitem_val * (obj.quotationMainItem_ac / 100));
        }
    });

    var mainItem_totalac = Math.round(mainItem_total + mainItem_ac);

    quotation_total += mainItem_totalac;

    var htmlCode = '';
    htmlCode += '<!-- .card -->';
    htmlCode += '<div class="card card-fluid" data-uid="' + obj.quotationMainItem_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="quotationMainItem_name" value="' + obj.quotationMainItem_name + '" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_ac" value="' + obj.quotationMainItem_ac + '" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_subTotal" value="' + mainItem_totalac + '" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_name_old" value="' + obj.quotationMainItem_name +'" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_ac_old" value="' + obj.quotationMainItem_ac + '" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_subTotal_old" value="' + mainItem_totalac + '" />';
    htmlCode += '    <input type="hidden" data-name="mainItem_uid_old" value="" />';
    htmlCode += '        <span data-span="quotationMainItem_name" style="width: 60%;">' + obj.quotationMainItem_name + '&nbsp;</span>';
    htmlCode += '        <span data-span="quotationMainItem_ac" style="width: 10%;">AC:&nbsp;' + ac_string + '&nbsp;</span>';
    htmlCode += '        <span data-span="quotationMainItem_subTotal" style="text-align: right;">項目合計:&nbsp;' + AppendComma(mainItem_totalac) + '</span>';
    htmlCode += '        <div class="dd-nodrag btn-group ml-auto">';
    htmlCode += '            <button type="button" class="btn btn-sm btn-secondary" onclick="editQuotationMainItem(this);">Edit</button> <button type="button" onclick="delQuotationMainItem(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
    htmlCode += '        </div>';
    htmlCode += '        ';
    htmlCode += '    </div>';
    htmlCode += '        <div class="dd" id="nest_' + obj.quotationMainItem_uid + '" data-toggle="sortable" data-max-depth="1" >';
    htmlCode += '        <!-- .dd-list -->';
    htmlCode += '        <ol class="dd-list">';

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

    htmlCode += '       ';
    htmlCode += '        </ol><!-- /.dd-list -->';
    htmlCode += '        </div>';
    htmlCode += '    <!-- .card-footer -->';
    htmlCode += '    <div class="card-footer">';
    htmlCode += '        <a href="javascript: void(0);" onclick="addQuotationSubItem(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 makeSubItemHtml(obj) {
    var htmlCode = '';

    htmlCode += '   <li class="dd-item" data-model-subitem-uid="' + obj.quotationSubItem_uid + '" data-method="edit">';
    htmlCode += '       <textarea style="display:none;" data-name="subItem_uid">' + obj.subItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_uid">' + obj.subItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_name">' + obj.quotationSubItem_name + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_price">' + obj.quotationSubItem_price + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_unitType">' + obj.quotationSubItem_unitType + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_number">' + obj.quotationSubItem_number + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_hasAC">' + obj.quotationSubItem_hasAC + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_subTotal">' + obj.quotationSubItem_subTotal + '</textarea>';
    htmlCode += '       <textarea data-name="quotationSubItem_descript" style="display:none;">' + obj.quotationSubItem_descript + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="subItem_uid_old">' + obj.subItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_uid_old">' + obj.quotationSubItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_name_old">' + obj.quotationSubItem_name + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_price_old">' + obj.quotationSubItem_price + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_unitType_old">' + obj.quotationSubItem_unitType + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_number_old">' + obj.quotationSubItem_number + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_hasAC_old">' + obj.quotationSubItem_hasAC + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_subTotal_old">' + obj.quotationSubItem_subTotal + '</textarea>';
    htmlCode += '       <textarea data-name="quotationSubItem_descript_old" style="display:none;">' + obj.quotationSubItem_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.quotationSubItem_name;
    htmlCode += '                       </h4><br/>';
    htmlCode += '                    <p class="list-group-item-text" data-name="subdesc" style="white-space: pre-line;font-size: 13px;">';
    htmlCode += '                           ' + obj.quotationSubItem_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.quotationSubItem_price) + ', 數量 ' + obj.quotationSubItem_number + ', 單位 ' + obj.quotationSubItem_unitType + '\r\n';
    htmlCode += '                           小計 NT$' + AppendComma(obj.quotationSubItem_subTotal) + '\r\n';
    htmlCode += '                           AC(' + obj.quotationSubItem_hasAC + ')';
    htmlCode += '                    </p>';
    htmlCode += '                   </div>';
    htmlCode += '               </div>';
    htmlCode += '           </div>';
    htmlCode += '           <div class="dd-nodrag btn-group ml-auto">';
    htmlCode += '            <button type="button" onclick="editQuotationSubItemButton(this);" class="btn btn-sm btn-secondary">Edit</button> <button type="button" onclick="delQuotationSubItemButton(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
    htmlCode += '           </div>';
    htmlCode += '       </div>         ';
    htmlCode += '   </li>';

    return htmlCode;
}

function makePaymentHtml(obj) {
    var payment_display = obj.payment_methodname;

    if (obj.payment_descript != '') {
        obj.payment_display = obj.payment_display + ': ' + obj.payment_descript;
    }

    var htmlCode = '';

    htmlCode += '                        <li class="list-group-item align-items-center drag-handle">\n';
    htmlCode += '                          <textarea style="display:none;" data-name="data_method">edit</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="payment_method">' + obj.payment_method + '</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="payment_methodname">' + obj.payment_methodname + '</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="payment_descript">' + obj.payment_descript + '</textarea>';
    htmlCode += '                          <span class="drag-indicator"></span>\n';
    htmlCode += '                          <div> ' + payment_display + ' </div>\n';
    htmlCode += '                          <div class="btn-group ml-auto">\n';
    htmlCode += '                            <button class="btn btn-sm btn-secondary" data-method="edit" onclick="delPaymentItem(this);"><i class="far fa-trash-alt"></i></button>\n';
    htmlCode += '                          </div>\n';
    htmlCode += '                        </li>\n';

    return htmlCode;
}

function makeInvoiceHtml(obj) {
    var invoice_display = "開立品項: " + obj.invoice_name + ",      開立月份: " + obj.invoice_date + ",     金額(未稅): " + AppendComma(obj.invoice_noTaxMoney);
    var invoice_date = obj.invoice_year + "/" + String(obj.invoice_month).padStart(2, "0");
    var invoice_text = obj.invoice_text;
    var invoice_type = obj.invoice_type;
    var htmlCode = '';

    htmlCode += '                        <li class="list-group-item align-items-center drag-handle">\n';
    htmlCode += '                          <textarea style="display:none;" data-name="data_method">edit</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="invoice_name">' + obj.invoice_name + '</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="invoice_type">' + obj.invoice_type + '</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="invoice_date">' + invoice_date + '</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="invoice_text">' + invoice_text + '</textarea>';
    htmlCode += '                          <textarea style="display:none;" data-name="invoice_noTaxMoney">' + obj.invoice_noTaxMoney + '</textarea>';
    htmlCode += '                          <span class="drag-indicator"></span>\n';
    htmlCode += '                          <span style="width: 15%;"> ' + "開立品項: " + obj.invoice_name + ' </span>\n';

    if (invoice_type == 'date') {
        htmlCode += '                          <span style="width: 15%;"> ' + "開立月份: " + invoice_date + ' </span\n';
    } else {
        htmlCode += '                          <span style="width: 15%;"> ' + "開立月份: " + invoice_text + ' </span\n';
    }

    
    htmlCode += '                          <span style="width: 20%;">' + "金額(未稅): " + AppendComma(obj.invoice_noTaxMoney) + ' </span>\n';
    htmlCode += '                          <span style="width: 50%;"></span>';
    htmlCode += '                          <div class="btn-group ml-auto">\n';
    htmlCode += '                            <button class="btn btn-sm btn-secondary" data-method="edit" onclick="delInvoiceItem(this);"><i class="far fa-trash-alt"></i></button>\n';
    htmlCode += '                          </div>\n';
    htmlCode += '                        </li>\n';

    return htmlCode;
}
function buttonQuotationClick(obj, view) {
    var type = obj.getAttribute('data-method');
    var version = obj.getAttribute('data-version');
    var uid = obj.getAttribute('data-uid');
    var dept_uid = $('#dept_select').val();

    quotationRowID = $('#' + uid);

    quotationRowPos = quotationTable.fnGetPosition($('#' + uid)[0]);

    if (type == "excel") {
        var formData = {
            quotation_uid: uid,
            quotation_version: version
        }

        $.redirect('/Api/exportXlsx', formData);
    }

    if (type == "history") {
        var formData = {
            method: 'get',
            quotation_uid: uid,
            version: version
        }

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

                    $('#now_version').val(version);

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

                        $('#dt-responsive-history').dataTable().fnAddData(obj);
                    }

                    $('#clientHistoryListModal').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('確定要刪除此張報價單?')) {
            var formData = {
                method: 'del',
                quotation_uid: uid,
                dept_uid: dept_uid
            }

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

                        } else {
                            alert(data.message);

                            if (data.err_code == "99999") {
                                location.href = "/Root/Login";
                            }
                        }
                    } 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',
            quotation_uid: uid,
            dept_uid: dept_uid
        }

        $.ajax({
            url: "/Api/addEditDelQuotation",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.quotationDetail;
                    var objView = data.quotationView;

                    $('#modelItem_div').html('');
                    $('#payment_group').find('ol').html('');
                    $('#invoice_group').find('ol').html('');

                    $("#quotation_method").val('edit');

                    quotationEditModelFillData(obj, objView);
                    //$("#project_uid").val(obj.project_uid);
                    //$("#project_name").val(obj.project_name).trigger('change');
                    //$("#company_select").val(obj.company_uid);
                    //$("#project_ps").val(obj.project_ps).trigger('change');
                    $('#modelQuotationDialogSaveBtn').show();

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

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

//歷史清單
function loadHistoryTable() {
    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-history').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: function (row) {
                    return 'history_' + row.quotation_version + '_' + row.quotation_uid;
                },
                deferRender: true,
                initComplete: function () {
                    historyTable = $('#dt-responsive-history').dataTable();
                    historyDataTable = $('#dt-responsive-history').DataTable();
                    $('#dt-responsive-history').on('click', 'a', function () {
                        buttonHistoryClick(this);
                    });

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


                },
                order: [[3, 'desc']],
                info: true,
                search: "搜尋:",
                searching: true,
                columns: [
                    { data: 'quotation_uid', className: 'align-top text-center', orderable: false, searchable: false },
                    { data: 'quotation_modifydate', className: 'align-top text-left', orderable: true, searchable: false },
                    { data: 'quotation_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'quotation_version', className: 'align-top text-left', orderable: true, searchable: true }
                   
                ],
                columnDefs: [
                    
                    {
                        targets: 0,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = '';
                            var drowdownHtml = '';
                            drowdownHtml += '<div class="dropdown d-inline-block">\n';
                            drowdownHtml += '   <button data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="saveas" class="btn btn-icon btn-secondary" data-toggle="dropdown"><i class="fa fa-fw fa-ellipsis-h"></i></button>';
                            drowdownHtml += '   <div class="dropdown-menu dropdown-menu-left" style="">';
                            drowdownHtml += '       <div class="dropdown-arrow"></div>'; 
                            drowdownHtml += '       <button data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="save_in_same" type="button" class="dropdown-item">另存到此專案</button>';
                            drowdownHtml += '       <button data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="saveas_to_other" type="button" class="dropdown-item">另存到其他專案</button>';
                            drowdownHtml += '       <button data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="saveas_to_new" type="button" class="dropdown-item">另存為新專案</button>';
                            drowdownHtml += '   </div>';
                            drowdownHtml += '</div>&nbsp;';
                            ret += drowdownHtml;
                            ret += '<button type="button" data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="view" class="btn btn-icon btn-secondary" ><i class="fa fa-eye fa-fw"></i> <span class="sr-only">View</span></button>&nbsp;';
                            ret += '<button type="button" data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="excel" class="btn btn-icon btn-secondary" ><i class="far fa-file-excel"></i> <span class="sr-only">Excel</span></button>';
                            return ret;
                        }
                    }, {
                        targets: 1,
                        orderable: true,
                        searchable: true,
                        render: function render(data, type, row, meta) {
                            return (new Date(row.quotation_modifydate)).format("yyyy/MM/dd hh:mm:ss");
                        }
                    } ,
                    {
                        targets: 3,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = row.quotation_version;

                            if (ret == $('#now_version').val()) {
                                ret = ret + '  (目前版本)';
                            }

                            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 loadQuotationTable() {
    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-quotation').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,  
                rowId: 'quotation_uid',
                deferRender: true,
                initComplete: function () {
                    quotationTable = $('#dt-responsive-quotation').dataTable();
                    $('#dt-responsive-quotation').on('click', 'a', function () {
                        buttonQuotationClick(this);
                    });

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


                },
                order: [[1, 'desc']],
                info: true,
                search: "搜尋:",
                searching: true,
                columns: [
                    { data: 'quotation_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'quotation_createdate', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'contactPerson_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'quotation_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.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="preview" >' + row.quotation_name + '</a>';
                            return row.quotation_name;
                        }
                    },
                    {
                        targets: 1,
                        className: 'align-middle text-left',
                        orderable: false,
                        searchable: true,
                        render: function render(data, type, row, meta) {

                            return (new Date(row.quotation_createdate)).format("yyyy/MM/dd hh:mm:ss");
                            //return '<a href="javascript: void(0);" data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="preview" >' + row.quotation_name + '</a>';
                            //return row.quotation_name;
                        }
                    },
                    {
                        targets: 3,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = '';
                            
                            ret += '<button type="button" data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" 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>&nbsp;';
                            ret += '<button type="button" data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" 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>&nbsp;';
                            ret += '<button type="button" data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="history" class="btn btn-sm btn-icon btn-secondary" ><i class="oi oi-list"></i> <span class="sr-only">History</span></button>&nbsp;';
                            ret += '<button type="button" data-uid="' + row.quotation_uid + '" data-version="' + row.quotation_version + '" data-method="excel" class="btn btn-sm btn-icon btn-secondary" ><i class="far fa-file-excel"></i> <span class="sr-only">Excel</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: '/Api/projectViewList',
                    type: 'POST',
                    data: function (d) {
                        Object.assign(d, {
                            dept_uid: $('#dept_select').val(),
                            start_txt: $('#dateStart').val(),
                            end_txt: $('#dateEnd').val()
                        });

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

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


                },
                order: [[0, 'desc']],
                info: true,
                search: "搜尋:",
                searching: true,
                columns: [
                    { data: 'project_datetime', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'project_name', className: 'align-top text-left', orderable: false, searchable: true },
                    { data: 'company_name', className: 'align-top text-left', orderable: false, searchable: true },
                    { data: 'project_ps', className: 'align-top text-left', orderable: false, searchable: false },
                    { data: 'project_uid', className: 'align-top text-center', orderable: false, searchable: false }
                ],
                columnDefs: [
                    {
                        targets: 1,
                        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.project_uid + '" data-method="preview" >' + row.project_name + '</a>';

                        }
                    },
                    {
                        targets: 4,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = '';

                            ret += '<button type="button" data-uid="' + row.project_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.project_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 companyList() {
    $.ajax({
        url: "/Api/companyList",
        type: "post",
        data: null,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.companys;
                var items = "";

                $("#company_select").append($("<option>", {
                    value: '',
                    text: '請選擇客戶公司'
                }));
                $.each(obj, function (i, item) {


                    $("#company_select").append($("<option>", {
                        value: item.company_uid,
                        text: item.company_name
                    }));


                });
             

            } else {
                alert(data.message);

                if (data.err_code == "99999") {
                    location.href = "/Root/Login";
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('網路或伺服器發生錯誤，請稍後重試!');
        }
    });
}
function deptList() {
    $.ajax({
        url: "/Api/deptList",
        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();
                loadQuotation_custom();
            } else {
                alert(data.message);

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

function projectList() {
    var formData = {
        dept_uid: $('#dept_select').val(),
        start_txt: '2023/09',
        end_txt: $('#dateEnd').val()
    }

    $.ajax({
        url: "/Api/projectViewList",
        type: "post",
        data: formData,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.projectViews;
                var items = "";

                $('#project_select')
                    .empty()
                    .append('<option selected="selected" value="">請選擇要加入的專案</option>');

                $.each(obj, function (i, item) {

                    $("#project_select").append($("<option>", {
                        value: item.project_uid + '/' + item.company_uid,
                        text: item.project_name + ' (' + item.company_name + ')'
                    }));
                });
               
            } else {
                alert(data.message);

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

function mainItemHtml(obj) {
    var ac_string = '';

    if (obj.modelMainItem_ac == 0) {
        ac_string = '無';
    } else {
        ac_string = obj.modelMainItem_ac + '%'
    }

    var mainItem_total = 0;
    var mainItem_ac = 0.0;

    $.each(obj.modelSubItems, function (i, subitem) {
        var subitem_val = subitem.modelSubItem_subTotal;
        mainItem_total += subitem_val;
        if (subitem.modelSubItem_hasAC == 'Y') {
            
            mainItem_ac += (subitem_val * (obj.modelMainItem_ac / 100));
        }
    });

    var mainItem_totalac = Math.round(mainItem_total + mainItem_ac);

    quotation_total += mainItem_totalac;

    var htmlCode = '';
    htmlCode += '<!-- .card -->';
    htmlCode += '<div class="card card-fluid" data-uid="' + obj.modelMainItem_uid + '"  data-main-uid="' + obj.mainItem_uid + '" data-type="add">';
    htmlCode += '    <div class="card-header border-bottom-0 btn-group">';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_name" value="' + obj.modelMainItem_name + '" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_ac" value="' + obj.modelMainItem_ac + '" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_subTotal" value="' + mainItem_totalac + '" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_name_old" value="" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_ac_old" value="" />';
    htmlCode += '    <input type="hidden" data-name="quotationMainItem_subTotal_old" value="" />';
    htmlCode += '    <input type="hidden" data-name="mainItem_uid_old" value="" />';
    htmlCode += '        <span data-span="quotationMainItem_name" style="width: 60%;">' + obj.modelMainItem_name + '&nbsp;</span>';
    htmlCode += '        <span data-span="quotationMainItem_ac" style="width: 10%;">AC:&nbsp;' + ac_string + '&nbsp;</span>';
    htmlCode += '        <span data-span="quotationMainItem_subTotal" style="text-align: right;">項目合計:&nbsp;' + AppendComma(mainItem_totalac) + '</span>';
    htmlCode += '        <div class="dd-nodrag btn-group ml-auto">';
    htmlCode += '            <button type="button" class="btn btn-sm btn-secondary" onclick="editQuotationMainItem(this);">Edit</button> <button type="button" onclick="delQuotationMainItem(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
    htmlCode += '        </div>';
    htmlCode += '        ';
    htmlCode += '    </div>';
    htmlCode += '        <div class="dd" id="nest_' + obj.modelMainItem_uid + '" data-toggle="sortable" data-max-depth="1" >';
    htmlCode += '        <!-- .dd-list -->';
    htmlCode += '        <ol class="dd-list">';

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

    htmlCode += '       ';
    htmlCode += '        </ol><!-- /.dd-list -->';
    htmlCode += '        </div>';
    htmlCode += '    <!-- .card-footer -->';
    htmlCode += '    <div class="card-footer">';
    htmlCode += '        <a href="javascript: void(0);" onclick="addQuotationSubItem(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" 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="quotationSubItem_uid">' + obj.modelSubItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_name">' + obj.modelSubItem_name + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_price">' + obj.modelSubItem_price + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_unitType">' + obj.modelSubItem_unitType + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_number">' + obj.modelSubItem_number + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_hasAC">' + obj.modelSubItem_hasAC + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_subTotal">' + obj.modelSubItem_subTotal + '</textarea>';
    htmlCode += '       <textarea data-name="quotationSubItem_descript" style="display:none;">' + obj.modelSubItem_descript + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="subItem_uid_old">' + obj.subItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_uid_old">' + obj.modelSubItem_uid + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_name_old">' + obj.modelSubItem_name + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_price_old">' + obj.modelSubItem_price + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_unitType_old">' + obj.modelSubItem_unitType + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_number_old">' + obj.modelSubItem_number + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_hasAC_old">' + obj.modelSubItem_hasAC + '</textarea>';
    htmlCode += '       <textarea style="display:none;" data-name="quotationSubItem_subTotal_old">' + obj.modelSubItem_subTotal + '</textarea>';
    htmlCode += '       <textarea data-name="quotationSubItem_descript_old" 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="editQuotationSubItemButton(this);" class="btn btn-sm btn-secondary">Edit</button> <button type="button" onclick="delQuotationSubItemButton(this);" class="btn btn-sm btn-secondary"><i class="far fa-trash-alt"></i></button>';
    htmlCode += '           </div>';
    htmlCode += '       </div>         ';
    htmlCode += '   </li>';

    return htmlCode;
}

//計算專案總價
function noTaxCalcItemPrice() {
    var tmpTotalPrice = 0;

    $('#modelItem_div .card').each(function (index, obj) {
        
        var quotationMainItem_ac = $(obj).find('[data-name="quotationMainItem_ac"').val();
        var tmpTotal = 0;
        $(obj).find('ol li').each(function (i, item) {
            var quotationSubItem_subTotal = $(item).find('[data-name="quotationSubItem_subTotal"]').val();
            var quotationSubItem_hasAC = $(item).find('[data-name="quotationSubItem_hasAC"]').val();

            var tmpPrice = parseInt(quotationSubItem_subTotal);

            if (quotationSubItem_hasAC == 'Y') {
                quotationSubItem_subTotal = parseInt(quotationSubItem_subTotal) + (Math.round(quotationSubItem_subTotal * (quotationMainItem_ac / 100)));
                tmpPrice = quotationSubItem_subTotal;
            }

            tmpTotalPrice += parseInt(quotationSubItem_subTotal);
            tmpTotal += tmpPrice;
        });

        var ac_string = '';

        if (quotationMainItem_ac == 0) {
            ac_string = '無';
        } else {
            ac_string = quotationMainItem_ac + '%'
        }

        $(obj).find('[data-name="quotationMainItem_subTotal"]').val(tmpTotal);
        $(obj).find('[data-span="quotationMainItem_subTotal"]').html('項目合計:&nbsp;' + AppendComma(tmpTotal));
        $(obj).find('[data-span="quotationMainItem_ac"]').html('AC:&nbsp;' + ac_string + '&nbsp;');
    });

    return tmpTotalPrice;
}

//更新總價與含稅價
function updateGrandTotal() {
    var grandTotal = noTaxCalcItemPrice();

    $('#quotation_noTaxTotal').val(grandTotal).trigger('change');

    $('#quotation_tax').val(Math.round(grandTotal * 0.05)).trigger('change');

    var specTotal = $('#quotation_specTotal').val();

    if (specTotal != "") {
        var specTotalNum = parseInt($('#quotation_specTotal').val());
        $('#quotation_tax').val(Math.round(specTotalNum * 0.05)).trigger('change');
        $('#quotation_grandTotal').val(specTotalNum + Math.round(specTotalNum * 0.05)).trigger('change');
    } else {
        $('#quotation_grandTotal').val(grandTotal + Math.round(grandTotal * 0.05)).trigger('change');
    }

   

    
}

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 addQuotationSubItem(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="quotationMainItem_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 editQuotationMainItem(obj) {
    var modelMainItem_name = $(obj).parent().parent().find("[data-name='quotationMainItem_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='quotationMainItem_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 delQuotationMainItem(obj) {
    if (confirm('確定刪除此主項目資料? 所有子項目也會一併刪除~')) {
        if (confirm('再次確認是否刪除所有此項目與子項目?')) {
            var modelMainItem_uid = $(obj).parent().parent().parent().attr("data-uid");
            var modelMainItem_name = $(obj).parent().parent().find("[data-name='quotationMainItem_name']").val();
            var delItem = {
                mainItem_uid: modelMainItem_uid,
                mainItem_msg: '刪除主項目 - ' + modelMainItem_name
            }

            deledMainItems.push(delItem);

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

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

//次項目編輯鈕
function editQuotationSubItemButton(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='quotationSubItem_name']").val();
    var parent_item_uid = $(divObj).find("[data-name='quotationSubItem_uid']").val();
    var modelSubItem_price = $(divObj).find("[data-name='quotationSubItem_price']").val();
    var modelSubItem_unitType = $(divObj).find("[data-name='quotationSubItem_unitType']").val();
    var modelSubItem_number = $(divObj).find("[data-name='quotationSubItem_number']").val();
    var modelSubItem_hasAC = $(divObj).find("[data-name='quotationSubItem_hasAC']").val();
    var modelSubItem_descript = $(divObj).find("[data-name='quotationSubItem_descript']").val();

    var divTmp = $(divObj).parent().parent().parent();

    var modelMainItem_uid = $(divTmp).attr("data-uid");
    var parent_mainItem_uid = $(divTmp).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 delQuotationSubItemButton(obj) {
    if (confirm('確定刪除此次項目資料? ')) {
        var model_subitem_uid = $(obj).parent().parent().parent().attr('data-model-subitem-uid');
        var divObj = $(obj).parent().parent().parent();

        var subItem_name = $(divObj).find("[data-name='quotationSubItem_name']").val();

        var delItem = {
            subItem_uid: model_subitem_uid,
            subItem_msg: '刪除次項目 - ' + subItem_name
        }

        deledSubItems.push(delItem);

        $(obj).parent().parent().parent().remove();
        updateGrandTotal();
        alert('預定刪除完成! 記得按下下方儲存鈕才是真的刪除喔~');


    }
}

function service_text() {
    var serviceTxt = '';

    serviceTxt += '1.以下簡稱##客戶公司##為甲方，##我們公司##為乙方。本契約係為甲方委託乙方進行本專案製作，且乙方同意承攬本專案工作之證明，經雙方於本契約簽章後，具有拘束雙方之法律效力。\n';
    serviceTxt += '\n';
    serviceTxt += '2.本專案之報價金額應自報價日起15日內有效，如經雙方確認無誤後，甲方應於本報價單上簽署同意，乙方始得執行本專案。\n';
    serviceTxt += '\n';
    serviceTxt += '3.乙方保證履行本契約內所載明之各工作項目，實際製作內容以本專案製作說明之內容為準；如因甲方要求變更設計致工作項目之製作內容有變更或工作項目之數量有增減之情形時，該變更或增減之工作項目應另行議價後，併入本契約執行。\n';
    serviceTxt += '\n';
    serviceTxt += '4.專案經公開發表後視同甲方同意結案，除另有約定外，乙方得於結案後開立本專案報酬之發票向甲方請款。\n';
    serviceTxt += '\n';
    serviceTxt += '5.執行：\n';
    serviceTxt += '(a)乙方開始設計製作前，應先就甲方提出之需求與甲方充分溝通。甲方得要求乙方提供功能說明及/或製作進度供甲方確認。\n';
    serviceTxt += '(b)甲方應於受領乙方已完成之功能說明及製作進度後儘速審核完畢，並若甲方認為前項功能說明及/或製作進度有需修正者，應於受領功能說明及/或製作進度後，將應修改處通知乙方修改。如甲方未於受領功能說明及/或製作進度後3個工作天內通知乙方修改時，即視為該功能說明及/或製作進度已經甲方之確認，乙方得依此進行本專案之設計製作。\n';
    serviceTxt += '(c)甲方必須提供本專案工作所需之相關文案及圖片資料（以下稱「甲方製作素材」）供乙方執行本專案使用。除因天災等自然不可抗力因素，或經甲方同意延後進度外，如因甲方製作素材提供延遲所致之專案遲延者，乙方扣除延遲之時日後，仍應按本工作進度完成之。如因乙方延遲交付本專案之完成物致甲方受有損害時，乙方應負賠償之責任。\n';
    serviceTxt += '(d)乙方對各工作項目之提案應各別經甲方同意後始得開始製作。乙方對一工作項目之提案經甲方同意並開始製作後，如因甲方或甲方其他配合廠商之原因無法履行本約，導致本專案停止製作或必須重新發展製作方向時，因此對於各工作項目中乙方已支出之成本及造成乙方之損害部分，甲方同意依乙方實際之支出或損失負賠償之責任。\n';
    serviceTxt += '\n';
    serviceTxt += '6.驗收：\n';
    serviceTxt += '(a)乙方須依照雙方對各工作項目所協議之各完成期限內完成該工作項目，並將該工作項目之完成物（以下稱「製作物」）提供予甲方驗收。每一製作物，乙方應將其上傳至乙方之測試網站，並通知甲方進行測試。\n';
    serviceTxt += '(b)如甲方認為乙方所完成之任一製作物與需求不符者，應於乙方交付製作物後十日內以書面通知乙方進行修改，乙方應於甲方限期之時間內將該製作物修正至符合甲方需求，並再次通知甲方依本條第(a)項方式進行驗收。\n';
    serviceTxt += '(c)如乙方交付製作物後，甲方未於十日內通知乙方進行修改者，則視為甲方同意該製作物而驗收完成。\n';
    serviceTxt += '(d)乙方應配合甲方之意見為各製作物必要之修改，並於每製作物交付後，經甲方認為有修改之必要時，乙方得提出修改建議書，並取得甲方對修改建議書之同意後，依修改建議書進行修改；若甲方提出非屬本契約所列之工作項目內之修改時，則視為本契約第3條變更設計致工作項目之製作內容有變更或工作項目之數量有增減之情形，雙方需另行議價。\n';
    serviceTxt += '(e)自本專案下所有工作項目皆完成後ㄧ個月內，乙方須對本專案提供免費諮詢及維修/維護管理服務（但若因甲方不當使用、自行更動本專案設計或由甲方所使用之硬體異常所造成之本專案損壞者，則不在此限）。\n';
    serviceTxt += '\n';
    serviceTxt += '7.擔保事項：\n';
    serviceTxt += '(a)甲方使乙方使用於本專案之任何素材，包括但不限於畫作、照片、肖像、商標圖樣、動態或平面廣告等畫面及文字(以下稱「甲方素材」)，甲方應擔保其有權使用或事先均已依法取得權利人之同意進行本專案之使用。\n';
    serviceTxt += '(b)若乙方因製作本專案而使用甲方素材，遭第三人對其主張侵害著作權或其他智慧財產權之情事時，甲方應協助處理，如因該第三人之主張致乙方受有任何損害時，甲方同意賠償乙方因此所生實際費用。\n';
    serviceTxt += '(c)乙方向甲方保證其對本專案所提供的設計及本專案各工作項目之開發、組裝或為此所建造的設備、機器、工序、軟體或其他與本專案相關之任何事項皆沒有違反或侵害任何專利權、著作權、營業秘密或其他智慧財產權，乙方亦應保證其接受本專案之工作絕無違反其與其他任意第三人之契約義務或約定。\n';
    serviceTxt += '(d)乙方擔保交付甲方之製作物及本專案所使用之程式並無侵害第三人之專利權、著作權、智慧財產權或其他任何權利，若甲方因乙方違反前述擔保而遭第三人對其主張侵害任何權利時，甲方應立即以書面通知乙方，並得提供有關資料予乙方，乙方應盡力協助甲方處理，並應償付甲方及第三人一切損失及相關費用（包括但不限於律師費用等）。\n';
    serviceTxt += '\n';
    serviceTxt += '8.智慧財產權：\n';
    serviceTxt += '(a)除雙方另有協議外，乙方擁有本契約製作物之著作權、專利權等智慧財產權與其他權益。於乙方交付製作物資料後，甲方擁有上述權利之使用權以及合理範圍內修改之權利。\n';
    serviceTxt += '(b)本專案之網頁原始檔（包括但不限於可用於重製修改之製作素材、程式設計碼及既有之製作物內容）之著作權、所有權、使用權及任何衍生之其他權利均歸乙方所有，甲方如需取得相關權利，雙方需另案議價訂約。\n';
    serviceTxt += '(c)本契約製作物僅限台灣地區網路相關媒體使用，若需其它語文版本或將製作內容放置到其他媒體或國家地區使用，需另計價並取得乙方授權使用同意。\n';
    serviceTxt += '(d)未經乙方同意，甲方不得逕自修改本約著作物或自行提供予第三人利用之，如甲方違背上述規定而使乙方利益受損時，甲方應損害賠償責任。\n';
    serviceTxt += '(e)乙方應於結案後將本專案及各製作物之電子檔案提供予甲方，但不包含製作物相關原始檔。\n';
    serviceTxt += '\n';
    serviceTxt += '9.資料保密：\n';
    serviceTxt += '(a)本契約所稱之營業秘密資料係指甲方因本契約提供乙方或由乙方交付予甲方之ㄧ切相關資訊、文件和資料（包括並不限於本契約內容、網頁設計、服務項目、行銷、銷售資訊、統計數字等）。\n';
    serviceTxt += '(b)就營業秘密資料，非經甲方之事前書面同意，乙方不得交付、告知或以任何形式洩露予任意第三人，亦不得在非雙方合作目的之必要範圍外使用營業秘密資料。\n';
    serviceTxt += '(c)乙方應確實保護營業秘密資料，並於乙方公司內部採取適當合理之保密措施以維護營業秘密資料，使其僅得洩露於與本契約相關且有必要知悉該營業秘密資料之乙方人員，且該等乙方人員應遵守本契約之保密義務，乙方人員違反本保密約定者視同乙方違約，乙方需負完全之賠償責任。\n';
    serviceTxt += '(d)乙方明瞭所收受之營業秘密資料係屬甲方所有，除了本契約作為設計、評估、分析或討論用途外，該營業秘密資料不得用來做為生產、重製、轉讓、轉售、販賣或其他為圖利而使用之用途。\n';
    serviceTxt += '(e)乙方在下列情形不負保密責任：\n';
    serviceTxt += '(1)甲方自行主動公開、或於本契約簽定前乙眾所周知之文件、資訊或資料。\n';
    serviceTxt += '(2)乙方合法所知悉之文件、資訊或資料。\n';
    serviceTxt += '(3)乙方可提出證明係其自行獨立研究開發者。\n';
    serviceTxt += '(4)經甲方書面同意者。\n';
    serviceTxt += '(5)依法律、法院或其他政府機關之命令應揭示之資訊者。\n';
    serviceTxt += '\n';
    serviceTxt += '10.網站維護管理：\n';
    serviceTxt += '(a)乙方可提供本專案網站空間及頻寬代管服務，代管服務包含網路環境一般性安全維護及網站檔案定期備份，詳細所需規格及費用需經專案評估後提供。\n';
    serviceTxt += '(b)乙方進行網站維護管理時，網站連線異常故障處理方式如下：\n';
    serviceTxt += '(1)乙方標準工作服務時間為週一~週五10：00~19：00，如有發生網站連線異常，上班時段接獲通知將於2小時內進行處理；若網站異常發生於非乙方標準工作服務時間時，乙方仍應進行網站維護管理之服務，並應於接獲通知後6小時內進行處理；例假日或是國定假日如有發生網站異常狀況時，乙方應於接獲通報後12小時內進行處理。\n';
    serviceTxt += '(2)如網站異常係因機房設備發生斷線時，則乙方將進行遠端連線檢查，如仍無法排除該異常情形時，始派員至機房做狀況排除。若因網路供應商（例：中華電信）之線路突發問題導致網站連線異常等乙方無法主動排除之異常，則乙方無須為該等異常負責，但乙方仍應主動連絡該網路供應商了解原因，並視情形提供甲方協助。\n';
    serviceTxt += '(3)如非可歸責於乙方之原因而網路或主機發生異常等問題，導致斷線而需至機房處理，收費以工時計算，星期例假日及夜間21:00~08:00每工時NTD4,000，其餘每工時NTD1,500。\n';
    serviceTxt += '\n';
    serviceTxt += '11.網站移轉交接：\n';
    serviceTxt += '(a)如甲方委託乙方進行非乙方製作之網站之維護管理時，為使該網站移轉順利，甲方需提供相關檔案資訊（包含但不限於網路位址之設定），以符合乙方做網站環境設定，惟乙方僅處理該網站網址之移轉與架設設定，不包含該網站相關之安全掃描作業，如甲方有此需要必須行計價。\n';
    serviceTxt += '(b)如乙方所提供之網站維護管理服務終止時，乙方應將該網站檔案以光碟形式交予甲方；若甲方委託第三人進行本專案之網站維護管理服務時，乙方應提供相關之協助，促使網站移轉順利。\n';
    serviceTxt += '\n';
    serviceTxt += '12.契約終止：\n';
    serviceTxt += '(a)本契約生效後，非有下列情事之一者，任一方不得任意終止本契約。\n';
    serviceTxt += '(1)經雙方書面同意。\n';
    serviceTxt += '(2)因有法律、政策變更或其他不可歸責於甲、乙雙方之事由，致乙方無法完成本契約執行工作，且前述不可歸責之事由持續三十日以上仍無法排除時，甲、乙任一方均得以書面通知對方終止本契約，甲方並應支付乙方已履行之義務或已到期之應付製作費及乙方依約辦理而於甲方有益事項所墊付之費用。\n';
    serviceTxt += '(b)因可歸責於甲方之事由致遲延給付到期之製作費用及其他必要費用，或怠於提供關於製作本契約標的物內容所需之文件及其他資料，並經乙方以書面通知催告後仍不支付或提供者，乙方得終止本契約，並沒收已付款項，毋庸交付未完成之標的物，甲方並應賠償乙方因之所受之損失。\n';
    serviceTxt += '(c)乙方無法履行或不完全履行或違反契約義務者，視為乙方違約，乙方同意負責因此所生之一切損害之賠償責任。\n';
    serviceTxt += '\n';
    serviceTxt += '13.其他約定事項：\n';
    serviceTxt += '(a)乙方應依雙方所約定之進度交付本專案及/或製作物予甲方。惟若製作物或本專案之交付遲延係可歸責於甲方之事由造成時，不在此限。\n';
    serviceTxt += '(b)本契約未約定事項，雙方得以書面方式另行約定，修正時亦同。\n';

    return serviceTxt;

}

//刪除付款方式
function delPaymentItem(obj) {
    if (confirm('確定刪除此付款方式? ')) {
        var data_type = $(obj).attr("data-method");
        var payment = $(obj).parent().parent();

        var payment_method = payment.find("[data-name='payment_method']").val();
        var payment_methodname = payment.find("[data-name='payment_methodname']").val();
        var payment_descript = payment.find("[data-name='payment_descript']").val();

        if (data_type == 'edit') {
            var payment_display = payment_methodname;

            if (payment_descript != '') {
                payment_display = payment_display + ': ' + payment_descript;
            }

            var formData = {
                payment_method: payment_method,
                payment_methodname: payment_methodname,
                payment_descript: payment_descript,
                message: '刪除了付款方式 - ' + payment_display
            }

            

            deledPayments.push(formData);
        }

        payment.remove();
    }
}

function initInvoiceSelectItem() {
    var items = [];

    items.push('網頁製作');
    items.push('廣告服務');
    items.push('網路服務');

    var bh = new Bloodhound({
        local: 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);
        }
    };

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

//刪除發票品項
function delInvoiceItem(obj) {
    if (confirm('確定刪除此發票開立品項? ')) {
        var data_type = $(obj).attr("data-method");
        var invoice = $(obj).parent().parent();

        var invoice_name = invoice.find("[data-name='invoice_name']").val();
        var invoice_date = invoice.find("[data-name='invoice_date']").val();
        var invoice_noTaxMoney = invoice.find("[data-name='invoice_noTaxMoney']").val();

        if (data_type == 'edit') {
            

            var formData = {
                invoice_name: invoice_name,
                invoice_date: invoice_date,
                invoice_noTaxMoney: invoice_noTaxMoney,
                message: '刪除了發票開立品項 - ' + invoice_name + '(' + invoice_date + ')  金額 ' + AppendComma(invoice_noTaxMoney)
            }



            deledInvoices.push(formData);
        }

        invoice.remove();
    }
}