import {useContextSection, useQueryTableList} from '@hooks';
import {context, pageContext, searchContext} from '../context';

import {getDictionaryList} from '@apis';
import {DictionaryData, DictionaryParamsType} from '@models';
import {Button} from 'antd';
import {ColumnsType} from 'antd/es/table';
import {useState} from 'react';
import {useBoolean} from 'ahooks';

export function useList() {
  const params = useContextSection(
    context,
    function([{name, code}]) {
      return {name, code, type: ('物料字典' as DictionaryParamsType)};
    },
  );

  return useQueryTableList({
    queryFn: getDictionaryList,
    params,
    pageContext,
    searchContext,
  });
}

export function useEdit() {
  const [editId, setEditId] = useState('');
  const [visible, {setTrue, setFalse}] = useBoolean();

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

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

export function useHandle() {
  const [{visible, editId}, {onClose, onEdit}] = useEdit();

  const columns: ColumnsType<DictionaryData> = [
    {title: '物料名称', dataIndex: 'name', key: 'name'},
    {title: '物料编号', dataIndex: 'code', key: 'code'},
    {title: '物料类型', dataIndex: 'materialType', key: 'materialType'},
    {title: '存储容量', dataIndex: 'size', key: 'size'},
    {
      title: '是否混合存储',
      dataIndex: 'isNotDisable',
      key: 'isNotDisable',
      render(_, {isNotDisable}) {
        return isNotDisable === '1' ? '是' : '否';
      },
    },
    {
      title: '操作',
      dataIndex: 'tldId',
      key: 'tldId',
      width: 330,
      render(_, {tldId}) {
        return (
          <>
            <Button
              type='link'
              onClick={onEdit(tldId)}
            >
              修改
            </Button>
          </>
        );
      },
    },
  ];

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