var prospect_idx = 0;
var prospect_code_list = [];

var C_LIST_PROSPECT = "77101";
var C_NEW_PROSPECT = "77102";

var prospect_id = 0;

function addNewProspect() {
    LoadingScreen("show");
    screen_index++;
    var data = { "type": C_NEW_PROSPECT, "index": screen_index };
    var url = "index.pzx?c=" + prospect_entry_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseProspect, null);
}

function reviewProspect() {
    LoadingScreen("show");
    if (prospect_id != 0) {
        screen_index++;
        var data = {
            "type": C_GET,
            "index": screen_index,
            "id": prospect_id,
        };
        var url = "index.pzx?c=" + prospect_entry_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseProspect, null);
    }else{
        LoadingScreen("hide");
        swal.fire("Warning", "Please select a prospect", "warning")
    }
}

function deleteProspect() {
    //get who checked into the list
    var lines = [];
    $("input[name='prospect_chk[]']:checked").each(function (i) {
        lines[i] = $(this).val();
    });

    //confirmation and delete column
    if (lines.length > 0) {
        Swal.fire({
            title: "System Confirmation",
            text: "Are you sure you want to delete the selected record line?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "OK",
            cancelButtonText: "Cancel",
            customClass: {
                confirmButton: 'swal-btn-confirm',
                cancelButton: 'swal-btn-cancel'
            }
        }).then(function (result) {

            if (result.isConfirmed) {
                LoadingScreen("show");

                for (var i = 0; i < lines.length; i++) {
                    var id = $('#prospect_id' + lines[i]).html();

                    var data = { "type": C_DELETE, "id": id, "index": screen_index };
                    var url = "index.pzx?c=" + prospect_url + "&d=" + new Date().getTime();

                    callServer(url, "json", data, onResponseProspect, null);
                }
            }

        });
    } else {
        return;
    }
}

function prospectFilter() {
    LoadingScreen("show");
    var data = {
        "type": C_LIST_PROSPECT,
        "status": $('#cobProspectStatus').val(),
        "index": screen_index,
        "sorts": sorts,
    };

    var url = "request.pzx?c=" + prospect_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseProspect, null);
}

function onResponseProspect(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');

        if (resp.type == "C_PROSPECT_READ_EXCEL") {
            $("#uploadFileProspect").val('');
        }
        
        return;
    }
    if (resp.type == C_LIST_PROSPECT) {
        prospect_code_list = [];
        var myObj = JSON.parse(resp.data);
        showProspectList(myObj);
    } if (resp.type == C_GET) {
        //set Page html
        showContentIndex(resp.data.htmlContent);
        $("#contentTitle").html(resp.data.headTitle);

        //review prospect
        if (resp.data.headerData.status == '1') {
            $('#chkProspectActive').prop('checked', true);
        } else {
            $('#chkProspectActive').prop('checked', false);
        }

        $("#btnSaveProspect").attr("onclick", "updateProspect();");
        $('#txtProspectID').val(resp.data.headerData.id);
        $('#txtProspectCode').val(resp.data.headerData.code);
        $('#txtProspectName').val(resp.data.headerData.name);
        $('#txtCustCode').val(resp.data.headerData.code);
        $('#txtCustName').val(resp.data.headerData.name);
        $('#txtProspectTelephone').val(resp.data.headerData.telephone);

        $('#txtProspectSoftwareInfo').val(resp.data.headerData.software);
        $('#txtProspectBillingCycle').val(resp.data.headerData.billing_cycle);
        $('#txtProspectRemarks').val(resp.data.headerData.remarks);
        $('#txtProspectUEN').val(resp.data.headerData.uen);
        $('#txtProspectAddress1').val(resp.data.headerData.address1);
        //=======

        $("#cmbProspectDeliveryContact").html(resp.data.contactOption);

        prospect_delivery_idx = resp.data.deliveryIdx;
        $('#prospect-delivery-list-table').html(resp.data.htmlDelivery);

        contact_prospect_idx = resp.data.contactIdx;
        $('#prospect-contact-list-table').html(resp.data.htmlContact);

        if(resp.data.document.name != undefined){
            $('#viewDocPortal').html(resp.data.document.name);
            $('#divDocProspect').show();
        }else{
            $('#divDocProspect').hide();
        }

        if(resp.data.status == 2){
            $("#btnSaveProspect").prop("disabled", true);
            $('#txtProspectID').prop("disabled", true);
            $('#txtProspectCode').prop("disabled", true);
            $('#txtProspectName').prop("disabled", true);
            $('#txtCustCode').prop("disabled", true);
            $('#txtCustName').prop("disabled", true);
            $('#txtProspectTelephone').prop("disabled", true);
            $('#chkProspectActive').prop("disabled", true);
    
            $('#txtProspectSoftwareInfo').prop("disabled", true);
            $('#txtProspectBillingCycle').prop("disabled", true);
            $('#txtProspectRemarks').prop("disabled", true);
            $('#txtProspectUEN').prop("disabled", true);
            $('#txtProspectAddress1').prop("disabled", true);
            $('#btnSaveProspect').prop("disabled", true);
            $('#btnConvertToCustomer').prop("disabled", true);
            $('#btnNewDelivery').prop("disabled", true);
            $('#btnNewContact').prop("disabled", true);
        }else{
            $('#txtProspectCode').prop("disabled", true);
        }
       
    } else if (resp.type == C_DELETE) {
        swal.fire('Success', resp.mesg, 'success');
        prospectFilter();
    } else if (resp.type == C_NEW_PROSPECT) {
        showContentIndex(resp.data.htmlContent);
        $("#contentTitle").html(resp.data.headTitle);

        $("#btnSaveProspect").attr("onclick", "addProspect();");
        $("#cmbProspectDeliveryContact").html(resp.data.contactOption);
    } else if (resp.type == "C_PROSPECT_READ_EXCEL") {
        $('#importProspectModal').modal('hide');
        swal.fire('Success', resp.mesg, 'success');
        $("#uploadFileProspect").val('');
        prospectFilter();
    }
}

function showProspectList(myObj) {
    prospect_idx = 0;
    prospect_id = 0;
    $('#prospect-table-body').html('');

    for (i in myObj) {
        id = myObj[i].id;
        code = myObj[i].code;
        prospect_name = myObj[i].name;
        prospect_status = myObj[i].status;

        prospect_code_list.push(code);

        $('#prospect-table-body').append(
            '<tr id="tr_prospect' + prospect_idx + '">' +
            '<td><input type="checkbox" id="prospect_checkbox' + prospect_idx + '" class="prospect_checkbox" value="' + prospect_idx + '" name="prospect_chk[]" ></td>' +
            '<td><label id="prospect_code' + prospect_idx + '" class="prospect_code" value="' + code + '" >' + code + '</label></td>' +
            '<td><label id="prospect_name' + prospect_idx + '" class="prospect_name" value="' + prospect_name + '" >' + prospect_name + '</label></td>' +
            '<td><label id="prospect_status' + prospect_idx + '" class="prospect_status" value="' + prospect_status + '" >' + prospect_status + '</label></td>' +
            '<td style="display:none" class="prospect_id" id="prospect_id' + prospect_idx + '">' + id + '</td>' +
            '<td style="display:none" class="prospect_idx" id="prospect_idx' + prospect_idx + '">' + prospect_idx + '</td>' +
            '</tr>'
        );

        //set highlight function and get the journal type ID
        $("#prospect-table-body tr").click(function () {
            prospect_id = $(this).find('td').eq(4).html();
            $(this).addClass('highlight').siblings().removeClass('highlight');
        });

        prospect_idx++;
    }
}

function checkProspectCode(obj){
    if($('#txtProspectID').val() == ""){
        var code = $(obj).val();
        if(jQuery.inArray(code, prospect_code_list) > -1){
            swal.fire('Warning', "Prospect Code is exist.", 'warning');
            return;
        }
    }
}

//==================================================
function getProspectAutoSearch(type, idx){
    var data = { "type": type, "idx": idx } ;
    var url = "request.pzx?c=" + prospect_url + "&d=" + new Date().getTime() ;
    callServer(url, "json", data, onProspectAutoSearch,null) ;
}

function getSalesQuotationProspectCode(obj) {
    var prospect = $(obj).val();
    var code = prospect.substring(0, prospect.indexOf('-'));

    var data = {
        "type": "C_GET_SALES_QUOTATION_PROSPECT_CODE",
        "index": screen_index,
        "code": code,
    };
    var url = "index.pzx?c=" + prospect_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onProspectAutoSearch, null);
}
function getSalesQuotationProspectCodeFilter(obj) {
    var prospect = $(obj).val();
    var code = prospect.substring(0, prospect.indexOf('-'));

    var data = {
        "type": "C_GET_SALES_QUOTATION_FILTER_PROSPECT_CODE",
        "index": screen_index,
        "code": code,
    };
    var url = "index.pzx?c=" + prospect_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onProspectAutoSearch, null);
}

function onProspectAutoSearch(obj, resp) {
    if (resp.status == C_OK) {
        if (resp.data != null || resp.data.length != 0) {
            var filteredAutoSearch = resp.data.list;
            if (resp.type == "PROSPECT_CODE_SEARCH_SALES_QUOTATION") {
                $('#txtSalesQuotationProspectCode').autocomplete({
                    source: filteredAutoSearch,
                    minLength: 1,
                    autoFocus: true
                });
                $('#txtSalesQuotationAccountCodeFilter').autocomplete({
                    source: filteredAutoSearch,
                    minLength: 1,
                    autoFocus: true,
                    appendTo: "#showSalesQuotationView"
                });
            } else if (resp.type == "C_GET_SALES_QUOTATION_PROSPECT_CODE") {
                $('#txtSalesQuotationProspectId').val(resp.data.cust_id);
                $('#cobSalesQuotationAccountId').val(resp.data.cust_account);
                ledger_account_detail = resp.data;

                populateSalesQuotationProspectContact();
            } else if (resp.type == "C_GET_SALES_QUOTATION_FILTER_PROSPECT_CODE") {

                $('#txtSalesQuotationProspectIdFilter').val(resp.data.cust_id);
                ledger_account_detail = resp.data;
            }
        }
    }
}

//IMPORT
function showImportProspect() {
    $('#importProspectModal').modal('show');
}

function downloadProspectExcelTemplate() {
    var url = "index.pzx?c=" + prospect_url + "&t=" + "C_DOWNLOAD_PROSPECT_EXCEL_TEMPLATE" + "&r=1";
    showReport(url);
}

function triggerProspectUploadExcel() {
    $("#uploadFileProspect").trigger("click");
}

function processProspectUploadExcel(obj) {
    upload_form_prospect = obj.form;
    uploadExcelProspect(upload_form_prospect);
}

function uploadExcelProspect(form) {
    var url = "index.pzx?c=" + prospect_url + "&t=" + "C_PROSPECT_UPLOAD_EXCEL" + "&d=" + new Date().getTime();
    ajaxUpload(form, url, prospectMasterUploadEnd);
}

function prospectMasterUploadEnd(resp) {
    LoadingScreen("hide");
    var msgArr = resp.split("*");
    var status = msgArr[0];
    if (status == C_OK) {
        LoadingScreen("show");
        readProspectExcel(msgArr[1]);
    } else {
        LoadingScreen("hide");
        swal.fire("Warning", msgArr[1] + msgArr[2], "warning");
        $("#uploadFileProspect").val('');
        return false;
    }
}

function readProspectExcel(new_name) {
    LoadingScreen('show');
    var data = {
        "type": "C_PROSPECT_READ_EXCEL",
        "new_name": new_name
    };

    var url = "index.pzx?c=" + prospect_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseProspect, null);
}