import {useContext, usePage} from '@hooks';
import {context, pageContext} from '../context';
import {useMutation, useQuery} from '@tanstack/react-query';
import {deleteRole, getRoleList} from '@apis';
import {useEffect, useState} from 'react';
import {ColumnsType} from 'antd/es/table';
import {RoleListData} from '@models';
import {Button, message} from 'antd';
import {useBoolean} from 'ahooks';
import {deleteConfirm} from '@utils';

export function useList() {
  const [{page, pageSize}] = usePage(pageContext);
  const [count, setCount] = useState(0);
  const [{name}, dispatch] = useContext(context);

  const {data, isFetching, refetch} = useQuery(
    [getRoleList.name, page, pageSize, name],
    async function() {
      const data = await getRoleList({
        roleName: name,
        page: page.toString(),
        limit: pageSize.toString(),
      });

      if (data.msg === '200') {
        setCount(data.data.total);
        return data.data.list;
      }

      return [] as RoleListData[];
    },
    {
      initialData: [],
    },
  );

  useEffect(function() {
    dispatch({type: 'CHANGE_SEARCH_STATE', payload: isFetching});
  }, [dispatch, isFetching]);

  return [{data, isFetching, count}, refetch] as const;
}

function useDelete(refetch: () => void) {
  const [pendingId, setPendingId] = useState<string | null>(null);
  const {mutate} = useMutation(
    deleteRole,
    {
      onSuccess({msg}) {
        setPendingId(null);

        if (msg === '200') {
          refetch();
          message.success('删除成功');
        }
      },
    },
  );

  function onDelete(id: string) {
    return function() {
      deleteConfirm(
        '角色',
        function() {
          mutate(id);
          setPendingId(id);
        },
      );
    };
  }

  return [pendingId, onDelete] as const;
}

export function useHandle(data: RoleListData[], refetch: () => void) {
  const [deleteId, onDelete] = useDelete(refetch);
  const [visible, {setFalse, setTrue}] = useBoolean();
  const [editId, setEditId] = useState('');

  function onAdd() {
    setTrue();
    setEditId('');
  }

  function onEdit(id: string) {
    return function() {
      setTrue();
      setEditId(id);
    };
  }

  const [roleId, setRoleId] = useState('');
  const [roleVisible, {setTrue: roleSetTrue, setFalse: onRoleClose}] = useBoolean();

  function onSetRole(id: string) {
    return function() {
      setRoleId(id);
      roleSetTrue();
    };
  }

  const [pdaId, setPdaId] = useState('');
  const [pdaVisible, {setTrue: pdaSetTrue, setFalse: onPdaClose}] = useBoolean();
  function onSetPda(id: string) {
    return function() {
      setPdaId(id);
      pdaSetTrue();
    };
  }

  const columns: ColumnsType<RoleListData> = [
    {title: '角色编号', dataIndex: 'roleCode', key: 'roleCode'},
    {title: '角色名', dataIndex: 'roleName', key: 'roleName'},
    {title: '创建时间', dataIndex: 'createTime', key: 'createTime'},
    {title: '备注', dataIndex: 'remarks', key: 'remarks'},
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 400,
      render(_, {id}) {
        return (
          <>
            <Button
              type='link'
              disabled={deleteId === String(id)}
              onClick={onEdit(String(id))}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              onClick={onDelete(String(id))}
              loading={deleteId === String(id)}
            >
              删除
            </Button>
            <Button
              type='text'
              disabled={deleteId === String(id)}
              onClick={onSetRole(String(id))}
            >
              菜单权限
            </Button>
            <Button
              type='text'
              disabled={deleteId === String(id)}
              onClick={onSetPda(String(id))}
            >
              PDA菜单权限
            </Button>
          </>
        );
      },
    },
  ];

  return [
    {columns, visible, editId, roleVisible, roleId, pdaVisible, pdaId},
    {onAdd, onClose: setFalse, onRoleClose, onPdaClose},
  ] as const;
}
