import {useContextSection} from '@hooks';
import {context} from './context';
import {FormEvent, useEffect} from 'react';
import {useMutation, useQueryClient} from '@tanstack/react-query';
import {editRoleMenu, getRoleList, getTreeMenu} from '@apis';
import {message} from 'antd';
import {RoleListData, TreeMenuListData} from '@models';
import {useMap} from 'ahooks';
import {pageContext, context as roleContext} from '@pages/role/context';

function useEditMenu(onClose: () => void, onFetch: () => void) {
  const {isLoading, mutate} = useMutation(
    editRoleMenu,
    {
      onSuccess({msg}) {
        if (msg === '200') {
          message.success('设置成功');
          onClose();
          onFetch();
        }
      },
    },
  );

  return [isLoading, mutate] as const;
}

function useTreeMap() {
  const client = useQueryClient();
  const [map, {set}] = useMap<string, string>();

  useEffect(
    function() {
      const treeData = client.getQueryData<TreeMenuListData[]>([getTreeMenu.name]);
      if (!treeData || treeData.length === 0) return;

      function deepTree(tree: TreeMenuListData[]) {
        tree.forEach(function({pId, key, children}) {
          // 一级菜单不参与寻找父级id
          pId !== '0' && set(key, pId);

          children.length && deepTree(children);
        });
      }

      deepTree(treeData);
    },
    [client, set],
  );

  return map;
}

export function useSubmit(
  {id, onClose, onFetch}:
  {id: string, onClose: () => void, onFetch: () => void},
) {
  const list = useContextSection(context, ([list]) => list);
  const [isLoading, mutate] = useEditMenu(onClose, onFetch);
  const treeMap = useTreeMap();

  function fixMenuTreeList(list: string) {
    const trees = list.split(','),
          // 方式有重复问题
          treeSet = new Set(trees);

    trees.forEach(function(val) {
      const mapPId = treeMap.get(val);

      mapPId && treeSet.add(mapPId);
    });

    return [...treeSet].join(',') + ',';
  }

  function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const listStr = list.join(',');
    const treeMenu = fixMenuTreeList(listStr);

    mutate({id, menu: treeMenu, menuBefore: listStr});
  }

  return [isLoading, onSubmit] as const;
}

export function useWatchId(id: string, visible: boolean) {
  const client = useQueryClient();
  const dispatch = useContextSection(context, ([,dispatch]) => dispatch);
  const {page, pageSize} = useContextSection(pageContext, state => state[0]);
  const name = useContextSection(roleContext, state => state[0].name);

  useEffect(function() {
    if (!visible) return;

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

    if (res) {
      const menuList = res?.menuBefore ? res.menuBefore.split(',') : [];

      dispatch(menuList);
    }
  }, [id, client, dispatch, visible, page, pageSize, name]);
}
