var materialModal = $('#modal-material > .modal-dialog > .modal-content');

function resetFormAssignMaterial() {
    $('#select-material').val(null).trigger("change");
    $('#select-material').find('option').remove();
    $('#select-material').val("");
    $('#form-assign-material').trigger("reset");
    $('#btn-assign-material').html('Assign');
    $('#btn-assign-material').prop("disabled", false);
};


var rupiah = document.getElementById('price-req-material');
        rupiah.addEventListener('keyup', function (e) {
        rupiah.value = formatRibuanInput(this.value);
    });

var qty = document.getElementById('qty-req-material');
        qty.addEventListener('keyup', function (e) {
        qty.value = formatRibuanInput(this.value);
    });

$(document).ready(function () {
    var tableMaterial = $("#table-material").DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": `${base_url}assign-material/datatables`,
            "data": function (d) {
                d.idact = activityId;
            }
        },
        "columns": [

            { data: 'material_name', name: 'material_name' },
            {
                data: 'qty_planning', render: function (data, type) {
                    return data ? formatRupiah(data) : '-'
                }
            },
            { data: 'uom', name: 'uom' },
            {
                data: 'budget', render: function (data, type) {
                    return data ? "Rp. " + formatRupiah(data) : '-'
                }
            },
            {
                data: 'plan_date', render: function (data, type) {
                    return data ? formatDate(data) : '-'
                }
            },
            {
                data: 'action',
                name: 'action',
                orderable: true,
                searchable: true
            },
        ]
    });

    function deleteMaterialAssign(id) {
        $.ajax({
            url: `${base_url}assign-material/delete/${id}`,
            type: "DELETE",
            success: function (data) {
                actionHappen = true;
                gantt.alert("Delete Material Assign Success!");
                tableMaterial.draw();
            },
            error: function (data) {
                gantt.alert("Delete Material Assign Failed, try again later!");
            }
        });
    }

    $("#modal-material").on("click", "#show-form-material", function () {
        $(this).hide();
        $("#hide-form-material").show();
        $("#form-assign-material").show();
    });

    $("#modal-material").on("click", "#hide-form-material", function () {
        $(this).hide();
        resetFormAssignMaterial()
        $("#show-form-material").show();
    });

    $('#modal-material').on('show.bs.modal', function (event) {
        $('#modal-material-title').html("Material Resource " + activityName);
        tableMaterial.draw();
    });

    $('#modal-material').on('hide.bs.modal', function (event) {
        // $("#hide-form-material").hide();
        $("#show-form-material").show();
        console.log("there's before action change ", actionHappen);
        if (actionHappen) {
            console.log("there's action change ", actionHappen);
            updateActivity(activityId);
        }
        resetFormAssignMaterial();
    });

    $('#select-material').select2({
        dropdownParent: materialModal,
        placeholder: 'Pilih material resource',
        allowClear: true,
        ajax: {
            url: `${base_url}material-resource/select`,
            dataType: 'json',
            data: function (params) {
                var query = {
                    search: params.term,
                    type: 'public',
                    idProyek: proyekId,
                    idact: activityId
                }
                return query;
            },
            processResults: function (result) {
                return {
                    results: $.map(result, function (item) {
                        // console.log("cek item", item)
                        return {
                            text: item.description,
                            id: item.id
                        }
                    })
                };
            },
            cache: false
        }
    });

    $('#select-material-integration').select2({
        dropdownParent: materialModal,
        placeholder: 'Pilih material',
        allowClear: true,
        minimumInputLength: 3,
		ajax: {
			url: `${adwIntegrationUrl}/request-material/get-material-integration`,
            type: "get",
            data: function (params) {
				var query = {
					'name': params.term,
				}
				return query;
			},
			headers: {
				'Authorization': `Bearer ${token}`
			},
			processResults: function (data) {
				var dataIntegrasiMaterial = [];
				if (data.data) {
					for(var i = 0; i < data.data.length; i++){
						var newData = {
							id: data.data[i].description,
							text: data.data[i].description,
						}
						dataIntegrasiMaterial.push(newData);
					}
				}
				return {
					results: dataIntegrasiMaterial
				};
            }, error: function (jqXHR, textStatus, errorThrown) {
                gantt.alert(`Status: ${textStatus}`);
                gantt.alert(`Error thrown: ${errorThrown}`);
                gantt.alert(`Error accessing URL: ${adwIntegrationUrl}/request-material/get-material-integration`);
            }
		}
    });

    $("#form-assign-material").on('submit', function (e) {
        e.preventDefault();

        $('#btn-assign-material').html('Assign...');
        $('#btn-assign-material').prop("disabled", true);

        // /request-material/add
        let desc_req_material = $("#select-material-integration").val();
        let required_date = $("#required-date-req-material").val();
        let plan_date = $("#required-date-plan-material").val();
        let uom = $("#uom-req-material").val();
        let price = $("#price-req-material").val();
        let qty_planning = $("#qty-req-material").val();
        let material_id = null;

        let payload = {
            description: desc_req_material,
            fom_date: required_date,
            required_date: required_date,
            proyek_id: proyekId,
            uom: uom,
            qty: formatReplaceTitikRibuan(qty_planning),
            price: formatReplaceTitikRibuan(price)
        }
        $.ajax({
            data: JSON.stringify(payload),
            url: `${base_url}request-material/add`,
            type: "POST",
            processData: false,
            contentType: false,
            success: function (data) {
                if (data && data.code === 200) {
                    material_id = data.data.id;
                    resetFormAssignMaterial();

                    let payloadAssign = {
                        proyek_id: proyekId,
                        activity_id: activityId,
                        material_id: material_id,
                        qty_planning: qty_planning,
                        plan_date: plan_date
                    }
                    $.ajax({
                        data: JSON.stringify(payloadAssign),
                        url: `${base_url}assign-material/add`,
                        type: "POST",
                        processData: false,
                        contentType: false,
                        success: function (data) {
                            if (data && data.code === 200) {
                                actionHappen = true;
                                gantt.alert("Material Assign Success!");
                                tableMaterial.draw();
                                resetFormAssignMaterial();
                            }
                            else {
                                gantt.alert({ type: "error", text: data.message });
                                $('#btn-assign-material').html('Assign');
                                $('#btn-assign-material').prop("disabled", false);
                            }
                        },
                        error: function (data) {
                            gantt.alert("Material Assign Failed, try again later!");
                            resetFormAssignMaterial();
                        }
                    });
                }
                else {
                    gantt.alert({ type: "error", text: data.message });
                    $('#btn-assign-material').html('Assign');
                    $('#btn-assign-material').prop("disabled", false);
                }
            },
            error: function (data) {
                gantt.alert("Material Request Failed, try again later!");
                resetFormAssignMaterial();
            }
        });

    });

    // delete from row
    $("#table-material").on("click", ".btn-material-delete", function () {
        let id = $(this).data('id');
        var box = gantt.confirm({
            text: "Material resource will be deleted from activity, continue?",
            ok: "Delete",
            cancel: "Cancel",
            callback: function (result) {
                if (result) {
                    deleteMaterialAssign(id);
                }
            }
        });
    });
});