import {deleNotice} from '@apis';
import {Button} from 'antd';
import {ColumnsType} from 'antd/es/table';
import {NoticeListData} from '@models';
import {
  CODE_COL_WIDTH,
  COMPANY_COL_WIDTH,
  DOUBLE_BTN_WIDTH,
  ENTYR_NUMBER_COL_WIDTH,
  MATERIAL_CODE_COL_WIDTH,
  MATERIAL_NAME_COL_WIDTH,
  NORMAL_TABLE_WIDTH,
  SMALL_TABLE_WIDTH,
} from '@utils';
import {useSupertube, useTableDeleteEvent, useTableModalEvent} from '@hooks';

const tableColumns: ColumnsType<NoticeListData> = [
  {
    title: '生产订单号',
    dataIndex: 'productionCode',

    width: CODE_COL_WIDTH,
  },
  {title: '报工单编号', dataIndex: 'noticeCode', width: CODE_COL_WIDTH},
  {title: '物料编号', dataIndex: 'wllbCode', width: MATERIAL_CODE_COL_WIDTH},
  {
    title: '物料名称',
    dataIndex: 'materialName',
    width: MATERIAL_NAME_COL_WIDTH,
  },
  {title: '数量', dataIndex: 'num', width: SMALL_TABLE_WIDTH, align: 'right'},
  {title: '报工时间', dataIndex: 'noticeTime', width: NORMAL_TABLE_WIDTH},
  {title: '分录号', dataIndex: 'entryNumber', width: ENTYR_NUMBER_COL_WIDTH},
  {title: '所属公司', dataIndex: 'companyName', width: COMPANY_COL_WIDTH},
  {title: '公司编号', dataIndex: 'companyNumber', width: SMALL_TABLE_WIDTH},
  {title: '移动类型', dataIndex: 'moveType', width: NORMAL_TABLE_WIDTH},
  {title: '来源类型', dataIndex: 'sourceType', width: NORMAL_TABLE_WIDTH},
  {
    title: '状态',
    dataIndex: 'type',

    render(_, {type}) {
      return type === '0' ? '未入库' : '已入库';
    },
    width: SMALL_TABLE_WIDTH,
    align: 'center',
  },
];

export function useHandle(refetch: () => void) {
  const [deleteId, onDelete] = useTableDeleteEvent(deleNotice, refetch, {
    label: '半成品报工单',
  });
  const [{visible, editId}, {onClose, onEdit}] = useTableModalEvent();

  const isSuper = useSupertube();
  const columns: ColumnsType<NoticeListData> = [
    ...tableColumns,
    {
      title: '操作',
      dataIndex: 'id',

      width: isSuper ? DOUBLE_BTN_WIDTH : SMALL_TABLE_WIDTH,
      fixed: 'right',
      render(_, {id, type, noticeCode}) {
        return (
          <>
            <Button
              type='text'
              className='ant-text-btn-color-primary'
              disabled={type !== '0' || deleteId === id}
              onClick={onEdit(id)}
            >
              {type === '0' ? '入库' : '已入库'}
            </Button>
            {isSuper && (
              <Button
                type='text'
                danger
                loading={deleteId === id}
                onClick={onDelete(id, noticeCode)}
              >
                删除
              </Button>
            )}
          </>
        );
      },
    },
  ];

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