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

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

  const {isFetching, data, refetch} = useQuery(
    [getStorageList.name, page, pageSize, name, code, isNotDisable, type],
    async function() {
      const data = await getStorageList({
        storageLocationName: name,
        storageLocationType: type,
        storageLocationCode: code,
        isNotDisable,
        page: String(page),
        limit: String(pageSize),
      });

      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 [{isFetching, data, count}, {refetch}] as const;
}

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

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

  const {mutate} = useMutation(
    deleteStorage,
    {
      onSuccess(data) {
        setPendingId('');

        if (data.msg === '200') {
          message.success('删除成功');
          reftch();
        }
      },
    },
  );
  function onDelete(id: string) {
    return function() {
      deleteConfirm(
        '库位',
        function() {
          mutate(id);
          setPendingId(id);
        },
      );
    };
  }

  const columns: ColumnsType<StorageListData> = [
    {title: '库位编号', dataIndex: 'storageLocationCode', key: 'storageLocationCode'},
    {title: '库位名称', dataIndex: 'storageLocationName', key: 'storageLocationName'},
    {title: '所在仓库', dataIndex: 'warehouseWhere', key: 'warehouseWhere'},
    {title: '库位类型', dataIndex: 'storageLocationType', key: 'storageLocationType'},
    {title: '库位容量', dataIndex: 'storageLocationCapacity', key: 'storageLocationCapacity'},
    {
      title: '是否禁用',
      dataIndex: 'isNotDisable',
      key: 'isNotDisable',
      render(_, {isNotDisable}) {
        return isNotDisable === '1'
          ? <span style={{color: 'var(--primary-color)'}}>启用</span>
          : <span style={{color: 'var(--error-color)'}}>禁用</span>;
      },
    },
    {title: '创建时间', dataIndex: 'createTime', key: 'createTime'},
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 200,
      render(_, {id}) {
        return (
          <>
            <Button
              type='link'
              onClick={onEdit(id)}
              disabled={id === pendingId}
            >
              修改
            </Button>
            <Button
              type='text'
              danger
              loading={id === pendingId}
              onClick={onDelete(id)}
            >
              删除
            </Button>

          </>
        );
      },
    },
  ];

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

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