var customer_idx = 0;
var customer_code_list = [];

var C_LIST_CUSTOMER = "77001";
var C_NEW_CUSTOMER = "77002";
var C_LIST_CUSTOMER_CONTACT = "77004";

var customer_id = 0;

function addNewCustomer() {
    LoadingScreen("show");
    screen_index++;
    cust_policy_idx = 0;
    var data = { "type": C_NEW_CUSTOMER, "index": screen_index };
    var url = "index.pzx?c=" + customer_entry_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCustomer, null);
}

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

function deleteCustomer() {
    //get who checked into the list
    var lines = [];
    $("input[name='customer_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 = $('#customer_id' + lines[i]).html();

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

                    callServer(url, "json", data, onResponseCustomer, null);
                }
            }
        });
    } else {
        return;
    }
}

function customerFilter() {
    LoadingScreen("show");
    var data = {
        "type": C_LIST_CUSTOMER,
        "index": screen_index,
        "sorts": sorts,
    };

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

function filterCustomerContact() {
    LoadingScreen("show");

    var data = {
        "type": C_LIST_CUSTOMER_CONTACT,
        "index": screen_index,
        "sorts": sorts,
        "cust_id": customer_id,
    };

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

function onResponseCustomer(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }
    if (resp.type == C_LIST_CUSTOMER) {
        customer_code_list = [];
        var myObj = JSON.parse(resp.data);
        showCustomerList(myObj);
    }
    if (resp.type == C_LIST_CUSTOMER_CONTACT) {
        var myObj = JSON.parse(resp.data);
        showContactList(myObj); 
    } 
    if (resp.type == C_GET) {
        showContentIndex(resp.data.htmlContent);
        cust_contact_idx    = 0;
        cust_software_idx   = 0;
        cust_branch_idx     = 0;
        cust_policy_idx     = 0;
        $(".btnSaveCustomer").attr("onclick", "updateCustomer();");
        //change button to Update
        $('.btnSaveCustomer').html('Update');

        
        $('#txtCustomerID').val(resp.data.headerData.id);
        $('#txtCustomerCode').val(resp.data.headerData.code);
        $('#txtCustomerCompanyTelephone').val(resp.data.headerData.telephone);
        if (resp.data.headerData.status == '1') {
            $('#chkCustomerActive').prop('checked', true);
        } else {
            $('#chkCustomerActive').prop('checked', false);
        }
        $('#txtCustomerName').val(resp.data.headerData.name);
        $('#txtCustomerCompanyRegNo').val(resp.data.headerData.company_reg_no);
        $('#txtCustomerBillingCycle').val(resp.data.headerData.billing_cycle);
        $('#txtCustomerAccount').val(resp.data.headerData.account);
        $('#txtCustomerAddress').val(resp.data.headerData.address);
        $('#txtCustomerRemarks').val(resp.data.headerData.remarks);
        $('#txtCustomerIndustry').val(resp.data.headerData.industry);
        $('#txtCustomerBusinessSector').val(resp.data.headerData.business_sector);
        $('#txtCustomerNoPeople').val(resp.data.headerData.no_people);
        $('#txtCustomerSalesTurnOver').val(resp.data.headerData.sales_turn_over);

        $('#txtCustomerSunsystemVersion').val(resp.data.headerData.sunsystem_ver);
        $('#txtCustomerMSSQLVersion').val(resp.data.headerData.mssql_ver);
        $('#txtCustomerQAVersion').val(resp.data.headerData.qa_ver);
        $('#txtCustomerWindowsServerVersion').val(resp.data.headerData.windows_server_ver);
        $('#txtCustomerSoftwareInfo').val(resp.data.headerData.software_info);
        $('#txtCustomerSupportingPartner').val(resp.data.headerData.supporting_partner);
        $('#txtCustomerProductConversation').val(resp.data.headerData.product_conver);
        $('#txtCustomerCompanyPolicy').val(resp.data.headerData.company_policy);
        
        $('#cobCustomerPrimaryRemoteAccess').val(resp.data.headerData.pri_remote_access);
        $('#cobCustomerPrimaryVideoMessage').val(resp.data.headerData.pri_video_mesg);
        $('#cobCustomerSecondaryRemoteAccess').val(resp.data.headerData.sec_remote_access);
        $('#cobCustomerSecondaryVideoMessage').val(resp.data.headerData.sec_video_mesg);

        showContactList(resp.data.contactData);
        showSoftwareList(resp.data.softwareData);
        showBranchList(resp.data.branchData);
        showPolicyList(resp.data.policyData);
        updateBranchContactOption();

    } else if (resp.type == C_DELETE) {
        swal.fire('Success', resp.mesg, 'success');
        customerFilter();
    } 
    else if (resp.type == C_NEW_CUSTOMER) {
        showContentIndex(resp.data.htmlContent);
        $("#contentTitle").html(resp.data.headTitle);

        $(".btnSaveCustomer").attr("onclick", "addCustomer();");
        $("#cmbCustomerDeliveryContact").html(resp.data.contactOption);
    } else if (resp.type == "C_CUSTOMER_READ_EXCEL") {
        $('#importCustomerModal').modal('hide');
        swal.fire('Success', resp.mesg, 'success');
        customerFilter();
    }
}

function showContactList(myObj) {
    $('#customer-contact-table-body').html('');
    for (i in myObj) {
        id                  = myObj[i].id;
        full_name           = myObj[i].full_name;
        prefer_name         = myObj[i].prefer_name;
        designation         = myObj[i].designation;
        salutation          = myObj[i].salutation;
        job_desc            = myObj[i].job_desc;
        dept                = myObj[i].dept;
        dept_group_id       = myObj[i].dept_group_id;
        contact_status      = myObj[i].contact_status;
        status              = myObj[i].status;
        report_to           = myObj[i].report_to;
        position            = myObj[i].position;
        email               = myObj[i].email;
        telephone           = myObj[i].telephone;
        mobile              = myObj[i].mobile;
        commun_prefer       = myObj[i].commun_prefer;
        hobbies             = myObj[i].hobbies;
        character           = myObj[i].character;
        priority            = myObj[i].priority;
        esupport_finance    = myObj[i].esupport_finance;
        esupport_it         = myObj[i].esupport_it;
        esupport_project    = myObj[i].esupport_project;
        esupport_management = myObj[i].esupport_management;

        $('#customer-contact-table-body').append(
            "<tr id='lineContact"+i+"' class='existing_contact'>"+
                "<td id='line_num"+i+"' class='counter' style='display:none;'>"+i+"</td>"+
                "<td id='cust_id"+i+"'style='display:none;'>"+id+"</td>"+
                "<td id='cust_prefer_name"+i+"' style='padding: 5px !important;'>"+prefer_name+"</td>"+
                "<td id='cust_dept"+i+"' style='padding: 5px !important;'>"+dept+"</td>"+
                "<td id='cust_email"+i+"' style='padding: 5px !important;'>"+email+"</td>"+
                "<td id='cust_telephone"+i+"' style='padding: 5px !important;'>"+telephone+"</td>"+
                "<td id='cust_mobile"+i+"' style='padding: 5px !important;'>"+mobile+"</td>"+
                "<td id='cust_priority"+i+"' style='padding: 5px !important;'>"+priority+"</td>"+
                "<td id='cust_contact_status_desc"+i+"' style='padding: 5px !important; text-align: center !important;'>"+contact_status+"</td>"+
                
                "<td style='text-align: center !important;'>"+
                "<button onclick='deleteCustomerContactByID("+id+")' class='btn btn-danger btn-sm btn-icon btn-icon-md'><i class='fa fa-trash-o'></i></button>"+
                "</td>"+
                "<td id='cust_contact_status"+i+"' style='display: none;'>"+status+"</td>"+
                "<td id='cust_dept_group_id"+i+"' style='display: none;'>"+dept_group_id+"</td>"+
                "<td id='cust_full_name"+i+"' style='display: none;'>"+full_name+"</td>"+
                "<td id='cust_designation"+i+"' style='display: none;'>"+designation+"</td>"+
                "<td id='cust_salutation"+i+"' style='display: none;'>"+salutation+"</td>"+
                "<td id='cust_job_desc"+i+"' style='display: none;'>"+job_desc+"</td>"+
                "<td id='cust_report_to"+i+"' style='display: none;'>"+report_to+"</td>"+
                "<td id='cust_position"+i+"' style='display: none;'>"+position+"</td>"+
                "<td id='cust_commun_prefer"+i+"' style='display: none;'>"+commun_prefer+"</td>"+
                "<td id='cust_hobbies"+i+"' style='display: none;'>"+hobbies+"</td>"+
                "<td id='cust_character"+i+"' style='display: none;'>"+character+"</td>"+
                "<td id='cust_esupport_finance"+i+"' style='display: none;'>"+esupport_finance+"</td>"+
                "<td id='cust_esupport_it"+i+"' style='display: none;'>"+esupport_it+"</td>"+
                "<td id='cust_esupport_project"+i+"' style='display: none;'>"+esupport_project+"</td>"+
                "<td id='cust_esupport_management"+i+"' style='display: none;'>"+esupport_management+"</td>"+
            "</tr>"
        );

        //set highlight function and get the journal type ID
        $("#customer-contact-table-body tr").click(function () {
            showCustomerContact($(this).find('td').eq(0).html());
            $(this).addClass('highlight').siblings().removeClass('highlight');
        });
        cust_contact_idx++;
    }
    clearCustomerContact();
}

function showBranchList(myObj) {
    for (i in myObj) {
        id                  = myObj[i].id;
        code                = myObj[i].code;
        name                = myObj[i].name;
        branch_type_name    = myObj[i].branch_type_name;
        branch_type         = myObj[i].branch_type;
        telephone           = myObj[i].telephone;
        add                 = myObj[i].add;
        web                 = myObj[i].web;
        contact             = myObj[i].contact;
        fax                 = myObj[i].fax;

        $('#customer-branch-table-body').append(
            "<tr id='lineBranch"+i+"' class='existing_branch'>"+
                "<td id='line_num"+i+"' class='counter' style='display:none;'>"+i+"</td>"+
                "<td style='padding: 5px !important; display:none;' id='cust_branch_id"+i+"'>"+id+"</td>"+
                "<td style='padding: 5px !important;' id='cust_branch_code"+i+"'>"+code+"</td>"+
                "<td style='padding: 5px !important;' id='cust_branch_name"+i+"'>"+name+"</td>"+
                "<td style='padding: 5px !important;' id='cust_branch_type_desc"+i+"'>"+branch_type_name+"</td>"+
                "<td style='padding: 5px !important; display:none;' id='cust_branch_type"+i+"'>"+branch_type+"</td>"+
                "<td style='padding: 5px !important;' id='cust_branch_telephone"+i+"'>"+telephone+"</td>"+
                "<td style='padding: 5px !important;' id='cust_branch_email"+i+"'>"+email+"</td>"+
                "<td style='text-align: center !important;'>"+
                    "<button onclick='deleteCustomerBranchByID("+id+")' class='btn btn-danger btn-sm btn-icon btn-icon-md'><i class='fa fa-trash-o'></i></button>"+
                "</td>"+
                "<td id='cust_branch_add"+i+"' style='display: none;'>"+add+"</td>"+
                "<td id='cust_branch_web"+i+"' style='display: none;'>"+web+"</td>"+
                "<td id='cust_branch_contact"+i+"' style='display: none;'>"+contact+"</td>"+
                "<td id='cust_branch_fax"+i+"' style='display: none;'>"+fax+"</td>"+
            "</tr>"
        );

        //set highlight function and get the journal type ID
        $("#customer-branch-table-body tr").click(function () {
            showCustomerBranch($(this).find('td').eq(0).html());
            $(this).addClass('highlight').siblings().removeClass('highlight');
        });
        cust_branch_idx++;
    }
}

function showPolicyList(myObj){
    if(myObj != ""){
        $('#customer-policy-table-body tr.new_policy').remove('');
        for (i in myObj) {
            id       = myObj[i].id;
            desc     = myObj[i].desc;
            filename = myObj[i].filename;
            $('#customer-policy-table-body').append(
                '<tr id="policyLine'+i+'" class="existing_policy">' +
                    '<td id="line_num'+i+'" class="counter" style="display:none;">'+i+'</td>'+
                    '<td style="display:none;"><input type="text" style="width: 100%;" id="txtCustomerPolicyId'+i+'" value='+id+'></td>'+
                    '<td><input type="text" style="width: 100%" id="txtCustomerPolicyDesc'+i+'" value='+desc+'></td>'+
                    '<td style="display: none;"><input type="hidden" id="txtCustomerPolicyFilename'+i+'" value='+filename+' ></td>'+
                    '<td><a title="View Attachment" style="color:green; margin-top: 5px;" href="javascript:" onclick="downloadCustomerPolicy('+i+')">'+filename+'</a></td>'+
                    '<td><button class="btn btn-danger btn-sm btn-icon btn-icon-md" type="button" id="btnDeletePolicy" onclick="deleteCustomerPolicy('+i+');"><i class="fa fa-trash-o"></i></button></td>'+
                '</tr>'
            );
            cust_policy_idx++;
        }
    }
}

function showSoftwareList(myObj){
    if(myObj != ""){
        $('#customer-software-table-body tr.new_software').remove('');
        for (i in myObj) {
            id          = myObj[i].id;
            code        = myObj[i].code;
            version     = myObj[i].version;
            type        = myObj[i].type;
            user        = myObj[i].user;
            live_date   = myObj[i].live_date;
            renew_date  = myObj[i].renew_date;
            $('#customer-software-table-body').append(
                '<tr id="softwareLine'+i+'" class="existing_software">' +
                    '<td id="line_num'+i+'" class="counter" style="display:none;">'+i+'</td>'+
                    '<td id="line_num'+i+'" class="counter" style="display:none;"><input type="hidden" id="txtCustomerSoftwareId'+i+'" value="'+id+'"></td>'+
                    '<td style="border-right: 1px solid #e0e0e0"><select id="cobCustomerSoftwareCode'+i+'" class="form-control" style="width: 100%">' + $('#cobCustomerSoftwareOption').html() +'</select></td>'+
                    '<td style="border-right: 1px solid #e0e0e0"><input type="text" style="width: 100%" class="form-control" value="'+version+'" id="txtCustomerSoftwareVersion'+i+'"></td>'+
                    '<td style="border-right: 1px solid #e0e0e0"><input type="number" style="width: 100%" class="form-control" value="'+user+'" id="txtCustomerSoftwareUser'+i+'"></td>'+
                    '<td style="border-right: 1px solid #e0e0e0">' +
                        '<select id="cobCustomerNewSoftwareType'+i+'" class="form-control" style="width: 100%">' +
                            '<option value="0">--- Select Type ---</option>' +
                            '<option value="1">Subscription</option>' +
                            '<option value="2">License</option>' +
                        '</select>' +
                    '</td>'+
                    '<td style="border-right: 1px solid #e0e0e0"><input type="date" style="width: 100%" class="form-control" value="'+live_date+'" id="txtCustomerSoftwareLiveDate'+i+'"></td>'+
                    '<td style="border-right: 1px solid #e0e0e0"><input type="date" style="width: 100%" class="form-control" value="'+renew_date+'" id="txtCustomerSoftwareRenewDate'+i+'"></td>'+
                    '<td><button class="btn btn-danger btn-sm btn-icon btn-icon-md" type="button" id="btnDeleteSoftware" onclick="deleteCustomerSoftware('+i+');"><i class="fa fa-trash-o"></i></button></td>'+
                '</tr>'
            );
            $('#cobCustomerSoftwareCode' + i).val(code);
            $('#cobCustomerSoftwareCode' + i).trigger("change");
            $('#cobCustomerNewSoftwareType' + i).val(type);
            $('#cobCustomerNewSoftwareType' + i).trigger("change");
            cust_software_idx++;
        }
    }
}

function showCustomerList(myObj) {
    customer_idx = 0;
    customer_id = 0;
    $('#customer-table-body').html('');

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

        customer_code_list.push(code);

        $('#customer-table-body').append(
            '<tr id="tr_customer' + customer_idx + '">' +
            '<td><input type="checkbox" id="customer_checkbox' + customer_idx + '" class="customer_checkbox" value="' + customer_idx + '" name="customer_chk[]" ></td>' +
            '<td><label id="customer_code' + customer_idx + '" class="customer_code" value="' + code + '" >' + code + '</label></td>' +
            '<td><label id="customer_name' + customer_idx + '" class="customer_name" value="' + customer_name + '" >' + customer_name + '</label></td>' +
            '<td style="display:none" class="customer_id" id="customer_id' + customer_idx + '">' + id + '</td>' +
            '<td style="display:none" class="customer_idx" id="customer_idx' + customer_idx + '">' + customer_idx + '</td>' +
            '</tr>'
        );

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

        customer_idx++;
    }
}

function checkCustomerCode(obj){
    if($('#txtCustomerID').val() == ""){
        var code = $(obj).val();
        if(jQuery.inArray(code, customer_code_list) > -1){
            swal.fire('Warning', "Customer Code is exist.", 'warning');
            return;
        }
    }
}

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

//IMPORT
function showImportCustomer() {
    $('#importCustomerModal').modal('show');
}

function downloadCustomerExcelTemplate() {
    var url = "index.pzx?c=" + customer_url + "&t=" + "C_DOWNLOAD_CUSTOMER_EXCEL_TEMPLATE" + "&r=1";
    showReport(url);
}

function triggerCustomerUploadExcel() {
    $("#uploadFileCustomer").trigger("click");
}

function processCustomerUploadExcel(obj) {
    upload_form_customer = obj.form;
    uploadExcelCustomer(upload_form_customer);
}

function uploadExcelCustomer(form) {
    LoadingScreen("show");
    var url = "index.pzx?c=" + customer_url + "&t=" + "C_CUSTOMER_UPLOAD_EXCEL" + "&d=" + new Date().getTime();
    ajaxUpload(form, url, customerMasterUploadEnd);
}

function customerMasterUploadEnd(resp) {
    LoadingScreen("hide");
    var msgArr = resp.split("*");
    var status = msgArr[0];
    if (status == C_OK) {
        readCustomerExcel(msgArr[1]);
    } else {
        swal.fire('Warning', msgArr[2], 'warning')        
        return false;
    }
}

function readCustomerExcel(new_name) {
    LoadingScreen("show");
    var data = {
        "type": "C_CUSTOMER_READ_EXCEL",
        "new_name": new_name
    };

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