var company_profile_idx = 0;
var company_profile_code_list = [];

var C_LIST_COMPANY_PROFILE = "76301";
var C_NEW_COMPANY_PROFILE = "76302";

var company_profile_id = 0;

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

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

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

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

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

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

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

function onResponseCompanyProfile(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }
    if (resp.type == C_LIST_COMPANY_PROFILE) {
        company_profile_code_list = [];
        var myObj = JSON.parse(resp.data);
        showCompanyProfileList(myObj);
    } if (resp.type == C_GET) {
        showContentIndex(resp.data.htmlContent);
        $(".btnSaveCompanyProfile").attr("onclick", "updateCompanyProfile();");
        //change button to Update
        $('.btnSaveCompanyProfile').html('Update');

        $('#txtCompanyProfileID').val(resp.data.headerData.id);
        $('#txtCompanyProfileCode').val(resp.data.headerData.code);
        if (resp.data.headerData.status == '1') {
            $('#chkCustomerActive').prop('checked', true);
        } else {
            $('#chkCustomerActive').prop('checked', false);
        }

        $('#txtCompanyProfileName').val(resp.data.headerData.name);
        $('#txtCompanyProfileUrl').val(resp.data.headerData.url);
        $('#cobCompanyProfileOAuth').val(resp.data.headerData.oauth);
        $('#cobCompanyProfileOAuth').trigger('change');
        $('#txtCompanyProfileTenantID').val(resp.data.headerData.tenant_id);
        $('#txtCompanyProfileMailServer').val(resp.data.headerData.mail_server);
        $('#txtCompanyProfilePort').val(resp.data.headerData.port);
        $('#txtCompanyProfileMailSender').val(resp.data.headerData.mail_sender);
        $('#txtCompanyProfileMailPassword').val(resp.data.headerData.mail_password);
        if (resp.data.headerData.ea == '1') {
            $('#chkCompanyProfileEA').prop('checked', true);
        } else {
            $('#chkCompanyProfileEA').prop('checked', false);
        }
        if (resp.data.headerData.ssl == '1') {
            $('#chkCompanyProfileSSL').prop('checked', true);
        } else {
            $('#chkCompanyProfileSSL').prop('checked', false);
        }

        var src = resp.data.headerData.src;
		var path_picture = resp.data.headerData.path_picture;
        
        if (src != "") {
            $("#imgCompanyProfileLogo").attr('src', path_picture);
            $("#txtCompanyProfileLogoFilename").val(resp.data.headerData.filename);
            // $('#txtFixedAssetPicture').val(resp.data.headerData.path_picture);
        }
        
        var src_signature  = resp.data.headerData.signature;
		var path_signature = resp.data.headerData.path_signature;

        if (src_signature != "") {
            $("#imgCompanyProfileSignature").attr('src', path_signature);
            $("#txtCompanyProfileSignatureFilename").val(resp.data.headerData.signature);
            // $('#txtFixedAssetPicture').val(resp.data.headerData.path_picture);
        }

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

        $(".btnSaveCompanyProfile").attr("onclick", "addCompanyProfile();");
        $("#cmbCompanyProfileDeliveryContact").html(resp.data.contactOption);
    } else if (resp.type == "C_COMPANY_PROFILE_READ_EXCEL") {
        $('#importCompanyProfileModal').modal('hide');
        swal.fire('Success', resp.mesg, 'success');
        companyProfileFilter();
    }
}

function showCompanyProfileList(myObj) {
    company_profile_idx = 0;
    company_profile_id = 0;
    $('#companyprofile-table-body').html('');

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

        company_profile_code_list.push(code);

        $('#companyprofile-table-body').append(
            '<tr id="tr_company_profile' + company_profile_idx + '">' +
            '<td><input type="checkbox" id="company_profile_checkbox' + company_profile_idx + '" class="company_profile_checkbox" value="' + company_profile_idx + '" name="company_profile_chk[]" ></td>' +
            '<td><label id="company_profile_code' + company_profile_idx + '" class="company_profile_code" value="' + code + '" >' + code + '</label></td>' +
            '<td><label id="company_profile_name' + company_profile_idx + '" class="company_profile_name" value="' + company_profile_name + '" >' + company_profile_name + '</label></td>' +
            '<td style="display:none" class="company_profile_id" id="company_profile_id' + company_profile_idx + '">' + id + '</td>' +
            '<td style="display:none" class="company_profile_idx" id="company_profile_idx' + company_profile_idx + '">' + company_profile_idx + '</td>' +
            '</tr>'
        );

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

        company_profile_idx++;
    }
}

function onchangeCompanyOAuth(){
    var use_graph_api = $("#cobCompanyProfileOAuth").val();

	if(use_graph_api == "YES"){
		$(".showOAuth").css("display", "");
		$(".showNormal").css("display", "none");
		// $("#LedgerSettingSalesQuotationMailSender").attr('class', 'col-sm-3');
	}else{
        $(".showOAuth").css("display", "none");
		$(".showNormal").css("display", "");
		// $("#LedgerSettingSalesQuotationMailSender").attr('class', 'col-sm-4');
	}
}

function checkCompanyProfileCode(obj){
    if($('#txtCompanyProfileID').val() == ""){
        var code = $(obj).val();
        if(jQuery.inArray(code, company_profile_code_list) > -1){
            swal.fire('Warning', "Company Profile Code is exist.", 'warning');
            return;
        }
    }
}
