<script setup>
import { VForm } from "vuetify/lib/components/VForm";

const props = defineProps({
  rolePermissions: {
    type: Object,
    required: true,
    default: () => ({
      name: "",
      alias: "",
      permissions: [],
    }),
  },
  roleId: {
    type: Number,
    required: true,
    default: 0,
  },
  isDialogVisible: {
    type: Boolean,
    required: true,
  },
});

const emit = defineEmits(["update:isDialogVisible", "update:rolePermissions"]);

const permissions = ref([]);
const role = ref("");
const alias = ref("");
const refPermissionForm = ref();
async function fetchData() {
  const res = await $api("/account-panel/permissions/subjects", {
    method: "get",
    headers: {
      "Content-Type": "application/json",
    },
  });
  permissions.value = res;
}

// if rolePermissions is not empty, then set permissions
watch(props, () => {
  if (props.rolePermissions?.permissions?.length) {
    role.value = props.rolePermissions.name;
    alias.value = props.rolePermissions.alias;
    permissions.value = permissions.value.map((permission) => {
      const rolePermission = props.rolePermissions.permissions.find(
        (item) => item.name === permission.name
      );
      if (rolePermission) {
        return {
          ...permission,
          ...rolePermission,
        };
      }
      return permission;
    });
  }
});

const onSubmit = async () => {
  // 初始化要提交的权限 ID 数组
  const selectedPermissionIds = [];

  // 遍历权限，检查并收集被选中的权限的 ID
  permissions.value.forEach((permission) => {
    if (permission.read) {
      selectedPermissionIds.push(permission.read_id);
    }
    if (permission.create) {
      selectedPermissionIds.push(permission.create_id);
    }
  });

  const rolePermissions = {
    name: role.value,
    alias: alias.value,
    permissionIds: selectedPermissionIds,
  };
  const apiEndpoint = props.roleId
    ? `/account-panel/roles/${props.roleId}/update-permission`
    : "/account-panel/roles";
  try {
    const response = await $api(apiEndpoint, {
      method: "post",
      body: rolePermissions,
    });

    emit("update:isDialogVisible", false);
    emit("role-updated");
  } catch (error) {
    console.error(error);
  }

  // 重置表单
  refPermissionForm.value?.reset();
};

const onReset = () => {
  emit("update:isDialogVisible", false);
  refPermissionForm.value?.reset();
};

fetchData();
</script>

<template>
  <VDialog
    :width="$vuetify.display.smAndDown ? 'auto' : 900"
    :model-value="props.isDialogVisible"
    @update:model-value="onReset"
  >
    <!-- 👉 Dialog close btn -->
    <DialogCloseBtn @click="onReset" />

    <VCard class="pa-sm-8 pa-5">
      <!-- 👉 Title -->
      <VCardItem class="text-center">
        <VCardTitle class="text-h3 mb-3">
          {{ props.rolePermissions.name ? "編輯" : "增加" }}角色
        </VCardTitle>
        <p class="text-base mb-0">設定角色權限</p>
      </VCardItem>

      <VCardText class="mt-6">
        <!-- 👉 Form -->
        <VForm ref="refPermissionForm">
          <!-- 👉 Role name -->
          <VRow>
            <!-- 👉 First Name -->
            <VCol cols="12" md="6"
              ><AppTextField
                v-model="role"
                label="角色名稱"
                placeholder="輸入角色名稱..."
            /></VCol>
            <VCol cols="12" md="6"
              ><AppTextField
                v-model="alias"
                label="角色別名"
                placeholder="輸入角色別名..." /></VCol
          ></VRow>

          <h6 class="text-h4 mt-8 mb-3">角色權限</h6>

          <!-- 👉 Role Permissions -->

          <VTable class="permission-table text-no-wrap">
            <!-- 👉 Other permission loop -->
            <template v-for="permission in permissions" :key="permission.name">
              <tr>
                <td>{{ permission.name }}</td>
                <td>
                  <div class="d-flex justify-end">
                    <VCheckbox
                      v-model="permission.read"
                      label="Read"
                      :name="permission.read_id"
                    />
                  </div>
                </td>
                <td>
                  <div class="d-flex justify-end">
                    <VCheckbox
                      v-model="permission.create"
                      label="Create"
                      :name="permission.create_id"
                    />
                  </div>
                </td>
              </tr>
            </template>
          </VTable>

          <!-- 👉 Actions button -->
          <div class="d-flex align-center justify-center gap-3 mt-6">
            <VBtn @click="onSubmit"> 提交 </VBtn>

            <VBtn color="secondary" variant="tonal" @click="onReset">
              取消
            </VBtn>
          </div>
        </VForm>
      </VCardText>
    </VCard>
  </VDialog>
</template>

<style lang="scss">
.permission-table {
  td {
    border-block-end: 1px solid
      rgba(var(--v-border-color), var(--v-border-opacity));
    padding-block: 0.5rem;

    .v-checkbox {
      min-inline-size: 4.75rem;
    }

    &:not(:first-child) {
      padding-inline: 0.5rem;
    }

    .v-label {
      white-space: nowrap;
    }
  }
}
</style>
