import { reactive, shallowRef, toRaw, ref } from 'vue';
import { DEFAULT_PAGE_SIZE } from '@/types/common/constants';
import { Role, RolePageRequest } from '@/types/role/type';
import { cloneDeep } from 'lodash-es';
import { getRolesPage, getRoles } from '@/api/system/role';
import { useTargetTenantIdSetting } from '@/utils/useTargetTenantIdSetting';

const { getValue } = useTargetTenantIdSetting();

const defaultRolePageRequest: RolePageRequest = {
  pageNumber: 1,
  pageSize: DEFAULT_PAGE_SIZE,
  queryParam: {
    roleName: '',
  }
}

export default function useRolesQuery() {
  const requestParams = reactive<RolePageRequest>(cloneDeep(defaultRolePageRequest));
  const roleList = shallowRef<Role[]>([]);
  const total = ref(0);
  const loading = ref(false);

  const setRequestParams = (params: Partial<RolePageRequest>) => {
    Object.assign(requestParams, params);
  }

  const resetRequestParams = () => {
    Object.assign(requestParams, defaultRolePageRequest)
  }


  const queryRolesPage = async () => {
    try {
      //  当右上角“选择租户”切换租户时，查询当前租户下的拥有和创建的角色
      const targetTenantId = getValue();
      if (targetTenantId != null) {
        requestParams.queryParam!.tenantId = +targetTenantId;
      }

      loading.value = true;
      const result = await getRolesPage(toRaw(requestParams));
      roleList.value = result.records;
      total.value = result.totalRow;
    } catch (e) {
      console.error(e);
    } finally {
      loading.value = false;
    }
  };

  const queryRoles = async () => {
    try {
      loading.value = true;
      roleList.value = await getRoles();
    } catch (e) {
      console.error(e);
    } finally {
      loading.value = false;
    }
  };

  return {
    requestParams,
    roleList,
    total,
    loading,
    setRequestParams,
    resetRequestParams,
    queryRolesPage,
    queryRoles,
  };
}