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

const {getTypeUser, getMenu} = useSettingStore();
const {listMenu, listTypeUser, 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 != "") {
    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
      );
      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?.[1]?.update || 0,
        accessRead: role_menu.access?.[2]?.read || 0,
        accessDelete: role_menu.access?.[3]?.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)
  );
  // 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: `${index + 1}`,
        idTipeUser: type_user.value._id,
        menu: i.display,
        accessAdd: 0,
        accessUpdate: 0,
        accessRead: 0,
        accessDelete: 0
      });
    });
  }
}

const onChange = (newValue, oldValue, el$) => {
}
const onSubmit = async () => {
  console.log("ini disimpan:", dataDetail.value?.form$.data);
};
onMounted(async () => {
  data.value = await dataMenu();
  checkMenu()
  console.log('aaaaa', data.value);
});


// 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) => {
  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',
      },
    },
    id_menu: {
      type: 'text',
      default: menu._id,
      builder: {
        type: 'text',
      },
    },
    idTipeUser: {
      type: 'hidden',
      default: menu.idTipeUser,
      builder: {
        type: 'text',
      },
    },
  }
  console.log(multiElement)

  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]
  ]
  // console.log(result)

  return result
}

// 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)
//   );
//   // 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: `${index + 1}`,
//         menu: i.display,
//         accessAdd: 0,
//         accessUpdate: 0,
//         accessRead: 0,
//         accessDelete: 0
//       });
//     });
//   }
// }
</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>
