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

const {getTypeUser, getMenu, postRoleUserMenu} = useSettingStore();
const {listMenu, listTypeUser, typeUser, roleMenuById, messages} = storeToRefs(useSettingStore());
const data = ref<any>([]);
const menuItem = ref<any>([]);
const type_user = ref<any>([]);
const dataDetail = ref(null)

const emit = defineEmits(['stateValue']);

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 || "-",
        menu_id: menuItem?.value._id,
        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)
  );
  // 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,
        menu_id: i._id,
        accessAdd: 0,
        accessUpdate: 0,
        accessRead: 0,
        accessDelete: 0
      });
    });
  }
}

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;
  // Struktur data untuk dikirim ke backend
  const payload = {
    menus: menusToProcess.map(menu => {
      const menuId = menu.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}
        ]
      };
    })
  };

  await postRoleUserMenu(payload);
  if (messages.value.type === 'success') {
    emit('stateValue', false)
    sweetalert(messages.value.title, '', messages.value.type);
  } else {
    sweetalert(messages.value.title, '', messages.value.type);
  }
};

onMounted(async () => {
  data.value = await dataMenu();
  checkMenu()
});

// function untu craete checkbox
const createCheckbox = (namePrefix: string, menu: any) => {
  const accessMap = {
    accessAdd: menu.accessAdd,
    accessUpdate: menu.accessUpdate,
    accessRead: menu.accessRead,
    accessDelete: menu.accessDelete
  };
  return {
    name: `${namePrefix}_${menu.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 untuk create row menu
let count = 0
const createMenuRow = (menu: any) => {
  count += 1;
  const multiElement = {
    nama_menu: {
      type: 'static', content: menu.menu,
      builder: {
        type: 'p',
      },
    },
    [`idMenu_${menu._id}`]: {
      type: 'hidden',
      default: menu._id,
      builder: {
        type: 'text',
      },
    },
    idTipeUser: {
      type: 'hidden',
      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">
      <GridElement
          name="gridTable"
          :widths="['80px', '','90px','90px','90px','90px']"
          :presets="['grid']"
          :cols="6"
          :rows="1+data.length"
          :grid="[
        [
          ['<strong>No</strong>', 1, 1, null, null],
          ['<strong>Nama Menu</strong>', 1, 1, null, null],
          ['<strong>Tambah</strong>', 1, 1, null, null],
          ['<strong>Ubah</strong>', 1, 1, null, null],
          ['<strong>Baca</strong>', 1, 1, null, null],
          ['<strong>Hapus</strong>', 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>
<style>
.my-swal {
  z-index: 2147483647 !important;
}
</style>
