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

export function useList() {
  const [count, setCount] = useState(0);
  const [{page, pageSize}, {onPageChange}] = usePage(pageContext);
  const [{name, code}, dispatch] = useContext(context);
  const {data, isFetching, refetch} = useQuery(
    [name, code, page, pageSize, getDepartmentList.name],
    async function() {
      const data = await getDepartmentList({
        departmentName: name,
        code,
        page: page.toString(),
        limit: pageSize.toString(),
      });

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

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

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

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

export function useHandle(refetch: () => void) {
  const [modalVisible, {setTrue, setFalse}] = useBoolean();
  const [pendingId, setPendingId] = useState<null | string>(null);
  const {mutate} = useMutation(
    deleteDepartment,
    {
      onSuccess(data) {
        setPendingId(null);

        if (data.msg === '200') {
          message.success('删除成功');
          refetch();
        }
      },
    },
  );
  const [editState, setEditState] = useState('');

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

  function onDelete(id: string) {
    return function() {
      deleteConfirm(
        '部门',
        function() {
          setPendingId(id);
          mutate(id.toString());
        },
      );
    };
  }

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

  const columns: ColumnsType<DepartmentListData> = [
    {title: '部门编号', dataIndex: 'code', key: 'code'},
    {title: '部门名称', dataIndex: 'departmentName', key: 'departmentName', width: '45%'},
    {title: '创建时间', dataIndex: 'createTime', key: 'createTime'},
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 200,
      render(_, {id}) {
        return (
          <>
            <Button
              type='link'
              disabled={pendingId === id}
              onClick={onEdit(id)}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              onClick={onDelete(id)}
              loading={pendingId === id}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

  return [{modalVisible, columns, editState}, {setTrue, setFalse, onAdd}] as const;
}
