import {editRolePDAMenu, getAllPDAMenu, getRoleList} from '@apis';
import {useContextSection, usePage} from '@hooks';
import {RoleListData} from '@models';
import {context, pageContext} from '@pages/role/context';
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
import {message} from 'antd';
import {FormEvent, useEffect, useState} from 'react';

export function useMenuList() {
  const {data} = useQuery(
    [getAllPDAMenu.name],
    async function() {
      const data = await getAllPDAMenu();

      if (data.msg === '200') {
        if (!data.data.list.length) throw new Error('未获取到菜单信息');

        return data.data.list;
      }

      throw new Error(data.errMsg);
    },
    {suspense: true},
  );

  return data;
}

export function useTransfer(id: string) {
  const [selected, setSelected] = useState<string[]>([]);

  function onChange(targetKeys: string[]) {
    setSelected(targetKeys);
  }

  const client = useQueryClient();
  const [{page, pageSize}] = usePage(pageContext);
  const name = useContextSection(context, state => state[0].name);
  useEffect(function() {
    if (!id) return;

    const data = client.getQueryData<RoleListData[]>(
      [getRoleList.name, page, pageSize, name],
    ) ?? [];
    const temp = data.find(val => String(val.id) === id);
    if (!temp) return;

    temp.menuPda
      ? setSelected(temp.menuPda.split(','))
      : setSelected([]);
  }, [client, id, name, page, pageSize]);

  return [selected, onChange] as const;
}

function useEditMenu(refetch: () => void, close: () => void) {
  return useMutation(
    editRolePDAMenu,
    {
      onSuccess({msg}) {
        if (msg === '200') {
          refetch();
          close();
          message.success('设置成功');
        }
      },
    },
  );
}

export function useSubmit(
  {id, onFetch, selected, onClose}:
  {id: string, onFetch: () => void, selected: string[], onClose: () => void},
) {
  const {isLoading, mutate} = useEditMenu(onFetch, onClose);

  function onSubmit(e: FormEvent) {
    e.preventDefault();
    mutate({
      id,
      menuPda: selected.join(','),
    });
  }

  return [isLoading, onSubmit] as const;
}
