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

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

  const {data, refetch, isFetching} = useQuery<GoodsListData[]>(
    [getGoodsList.name, number, page, pageSize],
    async function() {
      const data = await getGoodsList({
        page: String(page),
        limit: String(pageSize),
        itemNumber: number,
      });

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

        return data.data.list;
      }

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

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

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

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

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

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

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

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

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

  const columns: ColumnsType<GoodsListData> = [
    {title: '品号', dataIndex: 'itemNumber', key: 'itemNumber'},
    {title: '品名', dataIndex: 'name', key: 'name'},
    {title: '类型', dataIndex: 'type', key: 'type'},
    {title: '库位容纳小盒', dataIndex: 'minAccommodate', key: 'minAccommodate'},
    {title: '收容数', dataIndex: 'accommodateNum', key: 'accommodateNum'},
    {title: '库位最大容纳', dataIndex: 'maxAccommodate', key: 'maxAccommodate'},
    {title: '供应商/客户', dataIndex: 'supplier', key: 'supplier'},
    {title: '库位', dataIndex: 'storageLocationName', key: 'storageLocationName'},
    {title: '投入方式', dataIndex: 'inputType', key: 'inputType'},
    {title: '使用部门', dataIndex: 'userDepartmentName', key: 'userDepartmentName'},
    {title: '低储量', dataIndex: 'lowReserves', key: 'lowReserves'},
    {title: '高储量', dataIndex: 'highReserves', key: 'highReserves'},
    {title: '等级', dataIndex: 'grade', key: 'grade'},
    {title: '包装类别', dataIndex: 'packingType', key: 'packingType'},
    {title: '单位', dataIndex: 'unit', key: 'unit'},
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 200,
      fixed: 'right',
      render(_, {id}) {
        return (
          <>
            <Button
              type='link'
              disabled={pendingId === String(id)}
              onClick={onEdit(String(id))}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              onClick={onDelete(String(id))}
              loading={pendingId === String(id)}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

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