<script setup lang="ts">
import {useSettingStore} from "@/stores/api/setting/setting";

const {getTypeUser, getMenu, postRoleUserMenu} = useSettingStore();
const {listMenu, listTypeUser,typeUser, roleMenuById,} = storeToRefs(useSettingStore());

const data = ref<any>([]);
const menuItem = ref<any>([]);
const type_user = ref<any>([]);
const dataDetail = ref(null)

const dataMenu = async () => {
  await Promise.all([
    getMenu(),
    getTypeUser()
  ])
  // filtering role akses menu terhadap tipe user
  if (roleMenuById.value.data != null && roleMenuById.value.data != "") {
    console.log('lidt menu',listMenu.value)
    return roleMenuById.value.data.map((role_menu: any) => {
      menuItem.value = listMenu.value.find(
          (menu: any) =>
              menu._id == role_menu.menu_id
      );
      type_user.value = listTypeUser.value.find(
          (type_user: any) => type_user._id == role_menu.type_user_id
      );
      console.log('menu item', menuItem.value);
      return {
        _id: role_menu._id,
        idTipeUser: type_user.value._id,
        menu: menuItem?.value.display || "-",
        type_user: type_user?.value.display || "-",
        accessAdd: role_menu.access?.[0]?.add || 0,
        accessUpdate: role_menu.access?.[0]?.update || 0,
        accessRead: role_menu.access?.[0]?.read || 0,
        accessDelete: role_menu.access?.[0]?.delete || 0,
      };
    });
  } else {
    checkMenu()
  }
};

const checkMenu = () => {
  // Filter the listMenu based on roleMenuById
  var arr = listMenu.value.filter((i: any) =>
      !roleMenuById.value.data ||
      !roleMenuById.value.data.map((r: any) => r.menu_id).includes(i._id)
  );
  console.log(' menu arr ',arr);
  console.log('list menu arr ',listMenu.value);
  // Check if arr is not empty or roleMenuById.value.data is null
  if (arr.length !== 0 || !roleMenuById.value.data) {
    arr.forEach((i: any, index: number) => {
      data.value.push({
        _id: `${i._id}`,
        idTipeUser: type_user.value._id,
        menu: i.display,
        accessAdd: 0,
        accessUpdate: 0,
        accessRead: 0,
        accessDelete: 0
      });
    });
  }
}

// const onSubmit = async () => {
//   // try {
//   const formData = dataDetail.value?.form$.data
// console.log('form ',formData)
// console.log(' data value',data.value)
//   // Struktur data untuk dikirim ke backend
//   const payload = {
//     menus: data.value.map(menu => ({
//       type_user_id: formData.idTipeUser, // ID tipe user dari hidden field
//       menu_id: menu._id,
//       // menu_name: formData[`name_menu_${menu._id}`], // Nama menu dari static element
//       access: [
//         {type: 'add', value: formData[`accessAdd_${menu._id}`] || '0'},
//         {type: 'update', value: formData[`accessUpdate_${menu._id}`] || '0'},
//         {type: 'read', value: formData[`accessRead_${menu._id}`] || '0'},
//         {type: 'delete', value: formData[`accessDelete_${menu._id}`] || '0'}
//       ]
//     }))
//   }
//
//   // console.log('Data yang dikirim:', payload)
//   await postRoleUserMenu(payload)
//   // Panggil action dari store untuk mengirim data ke backend
//   // const response = await saveRoleMenu(payload)
//
//   // Handle response dari backend
//   // if (response.success) {
//   //   alert('Data berhasil disimpan!')
//   //   // Refresh data jika perlu
//   //   data.value = await dataMenu()
//   // } else {
//   //   alert('Gagal menyimpan data: ' + response.message)
//   // }
//   // } catch (error) {
//   //   console.error('Error saat menyimpan data:', error)
//   //   alert('Terjadi kesalahan saat menyimpan data')
//   // }
// }
const onSubmit = async () => {
  const formData = dataDetail.value?.form$.data;

  // Jika data.value kosong, kita akan mengambil data dari form
  const menusToProcess = data.value!==undefined ? data.value : listMenu.value;
console.log(formData);
console.log(listTypeUser.value);
console.log(data.value);
console.log(menusToProcess);
  // Struktur data untuk dikirim ke backend
  const payload = {
    menus: menusToProcess.map(menu => {
      const menuId = menu._id || menu.id; // Gunakan _id atau id tergantung struktur data
      return {
        type_user_id: formData.idTipeUser||typeUser.value, // ID tipe user dari hidden field
        menu_id: menuId,
        access: [
          {type: 'add', value: formData[`accessAdd_${menuId}`] || '0'},
          {type: 'update', value: formData[`accessUpdate_${menuId}`] || '0'},
          {type: 'read', value: formData[`accessRead_${menuId}`] || '0'},
          {type: 'delete', value: formData[`accessDelete_${menuId}`] || '0'}
        ]
      };
    })
  };

  console.log('Payload yang dikirim:', payload);
  await postRoleUserMenu(payload);
};

onMounted(async () => {
  data.value = await dataMenu();
  console.log('aaaaa', data.value);
  console.log('user select', typeUser.value);
  console.log('listTypeUser', listTypeUser.value);
  checkMenu()
});


// Helper function to create checkbox config
const createCheckbox = (namePrefix: string, menu: any) => {
  const accessMap = {
    accessAdd: menu.accessAdd,
    accessUpdate: menu.accessUpdate,
    accessRead: menu.accessRead,
    accessDelete: menu.accessDelete
  };
  return {
    name: `${namePrefix}_${menu._id}`,
    type: 'checkbox',
    text: 'Ya',
    default: accessMap[namePrefix] !== undefined ? accessMap[namePrefix] : 0,
    'true-value': "1",
    'false-value': "0",
    builder: {
      type: 'checkbox',
      label: 'Checkbox'
    }
  };
};

// Helper function to create a menu row
let count = 0
const createMenuRow = (menu: any) => {
  console.log('create menu',menu);
  count += 1; // Use the current counter value and then increment it
  const multiElement = {
    nama_menu: {
      name: 'name_menu',
      type: 'static',
      content: menu.menu,
      builder: {
        type: 'p',
      },
    },
    [`idMenu_${menu._id}`]: {
      type: 'hidden',
      default: menu._id,
      builder: {
        type: 'text',
      },
    },
    idTipeUser: {
      type: 'text',
      default: menu.idTipeUser,
      builder: {
        type: 'text',
      },
    },
  }
  const result = [
    [`${count}`, 1, 1],
    [
      {
        name: 'container1',
        type: 'group',
        schema: {
          column: {
            name: 'column',
            type: 'group',
            schema: multiElement
          },
        },
        builder: {
          type: 'container2',
          label: '2 columns',
        },
      },
      1,
      1
    ],
    [createCheckbox('accessAdd', menu), 1, 1],
    [createCheckbox('accessUpdate', menu), 1, 1],
    [createCheckbox('accessRead', menu), 1, 1],
    [createCheckbox('accessDelete', menu), 1, 1]
  ]
  return result
}
</script>

<template>
  <div class="d-flex flex-column gap-1 mx-1 pa-7 pt-0 pb-0">
    <Vueform ref="dataDetail" validate-on="change|step" method="post" :endpoint="onSubmit">
      <!--      <v-text-field v-model="data[0].idTipeUser"></v-text-field>-->
      <GridElement
          name="gridTable"
          :widths="['80px', '','90px','90px','90px','90px']"
          :presets="['grid']"
          :cols="6"
          :rows="1+data.length"
          :grid="[
                    [
                      ['No', 1, 1, null, null],
                      ['Nama Menu', 1, 1, null, null],
                      ['Tambah', 1, 1, null, null],
                      ['Ubah', 1, 1, null, null],
                      ['Baca', 1, 1, null, null],
                      ['Hapus', 1, 1, null, null],
                    ],
                    ...data.map((menu:any) => createMenuRow(menu))
                  ]"
      />
      <ButtonElement
          class="mt-6"
          name="primaryButton"
          button-label="Simpan"
          :submits="true"
          align="right"
      />

    </Vueform>
  </div>
</template>
