/**
 * 表格行事件
 */

import React from 'react';
import Invoice from '../../../../..';
import IGood from '../../../../../InvoiceController/InvoiceControllerState/GoodsListState/IGood';
import { LineAttributeType } from '../../../../../InvoiceController';

export default () => {
  /** 控制器 */
  const controller = Invoice.useInvoiceController();

  const model = controller.useMemo(s => s.model, []);

  const onClick = React.useCallback(
    async (record: IGood) => {
      if (model === 'prefab') return;
      if (model === 'readOnly') return;

      const editGood = controller.state.goodsListState.editGood;
      if (record.lineAttribute !== LineAttributeType.正常) return;

      if (editGood) {
        if (editGood.$index === record.$index) return;
        await controller.saveEditGood();
        await controller.wait();
        await controller.pipeline(async s => { s.goodsListState.editGood || (await controller.setEditGood(record)) })();
      } else {
        await controller.setEditGood(record);
      }
    },
    [controller, model],
  );

  return {
    onClick,
  };
};
