<script setup lang="ts">
import { ref } from "vue";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import RoleModal from "./components/role-modal.vue";
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { httpSetRole } from "/@/api/system/account";
import { useAsync } from "/@/hooks/core/useAsync";
import { ModalTypes } from "./types";

const PageName = "accountRole";
const roleModalRef = ref<InstanceType<typeof RoleModal> | null>(null);
const instance = ref(null);

const searchCallback = params => ({
  result: { ...(params ? params : {}), level: "2" },
  deleteProp: []
});

const hooks: PageHooks = {
  pageSearchHook: () => usePageSearch(searchCallback, undefined, searchConfig)
};

const { run } = useAsync({
  success: () => instance.value.onSearch()
});

const events: PageEvents = {
  content: {
    create: () => roleModalRef.value.onDisplay(undefined, ModalTypes.create),
    preview: data => roleModalRef.value.onDisplay(data, ModalTypes.preview),
    update: data => roleModalRef.value.onDisplay(data, ModalTypes.update)
  }
};

function handleSave(data: any, type: ModalTypes) {
  const { roleid, id } = data;

  const params = {
    status: "1",
    user_id: id,
    role_id: roleid
  };

  switch (type) {
    case ModalTypes.update:
      run(httpSetRole(params));
      break;
  }
}
</script>

<template>
  <PageAuth :pageName="PageName">
    <PageContainer
      :hooks="hooks"
      :events="events"
      :contentConfig="contentConfig"
      :search-config="searchConfig"
      :get-content-ref="ref => (instance = ref)"
    />
    <RoleModal ref="roleModalRef" @finance-save="handleSave" />
  </PageAuth>
</template>
