

//if(is_auto_generate_sample_number == 1) {generate_uuid('S','#sample-number')}

/*$('#modal-patient').on('show.bs.modal', function (event) {
    if(is_auto_generate_patient_code == 1) {generate_uuid('P','#patient-code')}
})*/

$('#sample-condition').change(function () {
    var sample_condition_id = $(this).val()
    if(sample_condition_id == 0) $('#reject-comment-id').attr('disabled', false)
    else $('#reject-comment-id').attr('disabled', true)
})

$('#patient-id').change(function () {
    var patient_id = $(this).val()
    if(patient_id>0) $('.sample-creation-form').fadeIn()
    else $('.sample-creation-form').fadeOut()
})

function searchPatientToForm(patientElementId){
    Swal.fire({
        html:"<p style='text-align: left;'>Search the patient with their name, phone, Khmer ID, or patient ID</p>",
        input: "text",
        showCancelButton: !0,
        confirmButtonText: "<i class='fa fa-search mr-2'></i>Search",
        cancelButtonText: "Close",
        position: 'top',
        showLoaderOnConfirm: !1,
        confirmButtonColor: "#4fb51a",
        preConfirm: function (n) {
            return new Promise(function (t) {
                $.ajax({
                    url: patient_base_url + "/async",
                    method:'get',
                    dataType:'json',
                    data:{kword: n},
                    success:function(response)
                    {
                        if(response.data.length<1 || !response.success){
                            Swal.showValidationMessage('No patient found!')
                            Swal.enableButtons()
                        }
                        else {
                            t(response.data)
                        }
                    }
                })
            })
        },
        allowOutsideClick:!1,
    }).then(function (t) {
        if(!t.dismiss){
            $('#'+patientElementId).html('');
            t.value.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                patientOption.text = item.patient_uuid + ' - ' + item.name_en;
                $('#'+patientElementId).append(patientOption);
            })
        }
    })
}

$("#searchPatientAddForm").click(function () {
    searchPatientToForm('patient-id')
});

$('#province-id').change(function () {
    getDistrictsByProvinceId('district-id', $(this).val())
})

$('#district-id').change(function () {
    getCommunesByDistrictId('commune-id', $(this).val())
})

$('#commune-id').change(function () {
    getVillagesByCommuneId('village-id', $(this).val())
})


$("#savePatient").on('click',function(e){
    e.preventDefault();
    $.ajax({
        url: patient_base_url.toString()+'.save',
        type:"POST",
        dataType:"JSON",
        data :{
            "_token": csrf_token,
            name_en: $('#patient-name').val(),
            patient_uuid: $('#patient-code').val(),
            dob: $('#dob').val(),
            gender: $("input[name='gender']:checked").attr('data-id'),
            marital_status: $("input[name='marital_status']:checked").attr('data-id'),
            phone_number: $('#phone-number').val(),
            province_id: $('#province-id').val(),
            district_id : $('#district-id').val(),
            commune_id: $('#commune-id').val(),
            village_id: $('#village-id').val(),
            khid_number: $('#khid-number').val(),
            house_number: $('#house-number').val(),
            street_number: $('#street-number').val()
        },
        success:function(res){
            if(res.success){
                var patient = res.data
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',patient.id);
                patientOption.setAttribute('selected','selected');
                patientOption.text = patient.patient_uuid + ' - ' + patient.name_en;
                $('#patient-id').append(patientOption);

                $('#modal-patient .close').click();
                $('#patient-id').trigger('change')

            }else{
                alertify.error("Can't create patient.")
            }
        }
    });
});

$("#saveSample").on('click',function(e){
    e.preventDefault();
    $.ajax({
        url: sample_base_url.toString()+'/save',
        type:"POST",
        dataType:"JSON",
        data :{
            "_token": csrf_token,
            patient_id: $('#patient-id').val(),
            sample_number : $('#sample-number').val(),
            sample_source_id: $('#sample-source-id').val(),
            physician_id : $('#physician-id').val(),
            sample_condition: $('#sample-condition').val(),
            reject_comment_id: $('#reject-comment-id').val(),
            collected_date : $('#collected-date').val(),
            received_date: $('#received-date').val(),
            admission_date: $('#admission-date').val(),
            diagnosis: $('#diagnosis').val(),
            is_urgent: 1,
        },
        success:function(res){
            if(res.success){
                $('#show-modal-assign-test').click()
                $('.modal-header .sample-number').html(res.data.sample_number)
                $('.modal-header .patient-code').html(res.data.patient.uuid)
                $('.modal-header .patient-name').html(res.data.patient.name)
                $('.modal-header .sample-source').html(res.data.sample_source.name)
                $('#sample-id').val(res.data.id)
                $('#sample-id').attr('data-source','new_sample');
            }else{
                $('#sample-id').val('')
                customErrorAlert(res)
            }
        },
        error:function(error){
            customErrorAlert(error)
            $('#sample-id').val('')
        }
    });
});
