/**
 * 表格行事件
 */

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 (record.level && record.level > 0) 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();
        if (controller.getGoodsTaxRateList && record.taxClassificationCode && !record.goodsTaxRateList ) {
          record.goodsTaxRateList = await controller.getGoodsTaxRateList(record.taxClassificationCode);
          // if (record.taxRate !== undefined && record.taxRate !== null && !record.goodsTaxRateList.includes(record.taxRate)) {
          //   record.taxRate = undefined;
          // }
        }
        await controller.pipeline(async s => { s.goodsListState.editGood || (await controller.setEditGood(record)) })();
      } else {
        if (controller.getGoodsTaxRateList && record.taxClassificationCode && !record.goodsTaxRateList ) {
          record.goodsTaxRateList = await controller.getGoodsTaxRateList(record.taxClassificationCode);
          // if (record.taxRate !== undefined && record.taxRate !== null && !record.goodsTaxRateList.includes(record.taxRate)) {
          //   record.taxRate = undefined;
          // }
        }
        await controller.setEditGood(record);
      }
    },
    [controller, model],
  );

  return {
    onClick,
  };
};
