$(document).on('page:beforein', '.page[data-name="product_image"]', async function (e) {

  console.log('app product_image ready')

  var id = e.detail.route.params.id;

  console.log(id);

  let js = JSON.parse(localStorage.getItem('t05_data'));

  let dt= js.data.result.product_byid.data[id];  

  document.querySelector('#a8_id').value = id || '';

  //console.log(dt)

 if (dt.img) {

   $('input[name="product_image"]').closest('.custom-file-upload').find('label').css('background-image', `url('${dt.img}')`)

   $('input[name="product_image"]').closest('.custom-file-upload').find('label').css('background-size', 'contain')

   $('input[name="product_image"]').closest('.custom-file-upload').find('label').css('background-position', 'center')

    $('input[name="product_image"]').closest('.custom-file-upload').find('label').css('background-repeat', 'no-repeat')

 }  

});



$(document).on('change', 'input#fileuploadInput', function (e) {

  const file = e.target.files[0]

  const reader = new FileReader()

  reader.onload = function (e) {

    document.querySelector('.custom-file-upload label').style.backgroundImage = `url('${e.target.result}')`

    document.querySelector('.custom-file-upload label').style.backgroundSize = 'cover'

  }

  reader.readAsDataURL(file)

})



$(document).on('change', 'input[name="product_image"]', function (e) {

    const file = e.target.files[0];

    const reader = new FileReader();

    reader.onload = function (event) {

        console.log($('.custom-file-upload.profile'));

        $('.custom-file-upload.profile')

            .find('label')

            .css('background-image', `url('${event.target.result}')`)

            .css('background-size', 'cover');

    };

    if (file) {

        reader.readAsDataURL(file);

    }

});



$(document).on('click', '#save-profile-images', async function () {

  var view = app.views.current

  const id = $('#a8_id').val();

  const profile_image = $('input[name="product_image"]').prop('files')[0]

  let profileBase64 = null

  if (profile_image) {

    // Wrap the FileReader in a Promise to wait for it to complete

    profileBase64 = await new Promise((resolve, reject) => {

      const reader = new FileReader()

      reader.readAsDataURL(profile_image)

      reader.onload = () => resolve(reader.result)

      reader.onerror = () => reject(new Error('Failed to read image as base64'))

    })

    console.log(profileBase64)

  }    

  if(profileBase64){

    let image=profileBase64;  

    let req = {

      id,image

    }

    console.log(req)  

    try {

     app.preloader.show()

      let promises = [];

      if (req) {

          promises.push(product_image(req))

     }

     const responses = await Promise.all(promises)

     app.preloader.hide()

    } catch (error) {

     app.preloader.hide()

      app.dialog.alert(res.message, 'Upload Image Error');

    }     

  }       

});