import {useContext, usePage} from '@hooks';
import {useMutation, useQuery} from '@tanstack/react-query';
import {context, pageContext} from '../context';
import {deleteUser, getUserList} from '@apis';
import {UserListData} from '@models';
import {ColumnsType} from 'antd/es/table';
import {useEffect, useState} from 'react';
import {Button, Modal, message} from 'antd';
import {useBoolean} from 'ahooks';

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

  const {isFetching, data, refetch} = useQuery<UserListData[]>(
    [getUserList.name, page, pageSize, name, code],
    async function() {
      const data = await getUserList({
        limit: pageSize.toString(),
        page: page.toString(),
        userName: name,
        code,
      });

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

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

  useEffect(function() {
    disaptch({type: 'CHAGNE_SEARCH_STATE', payload: isFetching});
  }, [disaptch, isFetching]);

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

export function useHandle(onFetch: () => void) {
  const [visible, {setTrue, setFalse}] = useBoolean();

  const [pendingId, setPendingId] = useState('');
  const {mutate} = useMutation(
    deleteUser,
    {
      onSuccess(data) {
        setPendingId('');

        if (data.msg === '200') {
          onFetch();
          message.success('删除成功');
        }
      },
    },
  );
  function onDelte(id: string) {
    return function() {
      Modal.confirm({
        title: '删除用户',
        content: '你确定要删除当前用户吗？',
        onOk() {
          setPendingId(id);
          mutate(id);
        },
      });
    };
  }

  const [editId, setEditId] = useState('');

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

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

  const columns: ColumnsType<UserListData> = [
    {title: '用户编号', dataIndex: 'code', key: 'code', width: 150},
    {title: '用户名称', dataIndex: 'userName', key: 'userName', width: 250},
    {title: '真实姓名', dataIndex: 'realName', key: 'realName', width: 250},
    {title: '邮箱', dataIndex: 'email', key: 'email', width: 200},
    {title: '电话', dataIndex: 'landline', key: 'landline', width: 200},
    {title: '手机', dataIndex: 'phone', key: 'phone', width: 200},
    {title: '部门', dataIndex: 'department', key: 'department', width: 200},
    {title: '角色', dataIndex: 'role', key: 'role', width: 200},
    {title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 200},
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 200,
      fixed: 'right',
      render(_, {id}) {
        return (
          <>
            <Button
              type='link'
              disabled={String(id) === pendingId}
              onClick={onEdit(String(id))}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              loading={String(id) === pendingId}
              onClick={onDelte(String(id))}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

  return [{columns, visible, editId}, {onAdd, onClose: setFalse}] as const;
}
