import { initParams } from "@/utils/init";
import { TABLE } from "@/api/business/purchase/contract";

export default function useTable() {
  // 新 增
  const add = ({ _this, prop }) => {
    const { tableColumns } = _this.tabColumns.find(
      (element) => element.key === prop
    );
    _this.params[prop].push(initParams(tableColumns));
  };
  // 提 交
  const submit = async ({ _this, prop, scope }, done = () => {}) => {
    const { row } = scope;
    const { ADD, EDIT } = TABLE;
    try {
      // try
      _this.loading = true;
      const { contractId } = row;
      const { id } = _this.params;
      if (contractId) {
        await EDIT(row, prop);
      } else {
        await ADD({ ...row, contractId: id }, prop);
      }
      await done();
    } catch (err) {
      // catch
      console.error(err);
    } finally {
      // finally
      _this.loading = false;
    }
  };
  // 删 除
  const remove = ({ _this, prop, scope }, done = () => {}) => {
    const {
      row: { id },
      $index,
    } = scope;
    const { ROMVE } = TABLE;
    if (id) {
      try {
        // try
        _this.loading = true;
        const { code } = ROMVE(id, prop);
        if (code === 200) done();
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        _this.loading = false;
      }
    } else {
      _this.params[prop].splice($index, 1);
    }
  };

  return { add, submit, remove };
}