import { REFER } from "@/components/popover-select/api";
import { ADD, EDIT, ITEM, CODE } from "@/api/business/purchase/contract";

export default function useMethods() {
  const fetchCode = async ({ _this }) => {
    try {
      // try
      _this.loading = true;
      const code = await CODE();
      _this.params.code = code;
    } catch (err) {
      // catch
      console.error(err);
    } finally {
      // finally
      _this.loading = false;
    }
  };
  const fetchItem = async ({ _this, prop }) => {
    try {
      // try
      _this.loading = true;
      const { code, data } = await ITEM(prop);
      if (code === 200) {
        _this.params = data;
      }
    } catch (err) {
      // catch
      console.error(err);
    } finally {
      // finally
      _this.loading = false;
    }
  };
  const fetchRefer = async ({ _this, prop, type, source }) => {
    const { rateCode } = prop;
    if (type === "MATERIAL_PARAM") {
      try {
        // try
        _this.loading = true;
        const { code, rows } = await REFER({
          search: rateCode,
          type: "TAX_RATE_PARAM",
        });
        if (code === 200) {
          const [{ ntaxrate }] = rows;
          source.tax = ntaxrate === "0E-8" ? "0.00000000" : ntaxrate;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        _this.loading = false;
      }
    }
  };
  const open = ({ _this }) => {
    _this.visible = true;
    _this.tabName = _this.tabColumns[0].key;
  };
  const hide = ({ _this }) => {
    _this.visible = false;
  };
  const submit = ({ _this, prop, type }) => {
    _this.$refs[prop].validate(async (valid) => {
      if (valid) {
        try {
          // try
          _this.loading = true;
          const { buyer: createById, buyerName: createByName } = _this.params;
          const {
            user: { id: updateById, name: updateByName },
          } = _this.$store.state;
          const params = {
            createById,
            createByName,
            updateById,
            updateByName,
            ..._this.params,
          };
          const { msg, code } =
            type === "ADD" ? await ADD(params) : await EDIT(params);
          if (code === 200) {
            _this.hide();
            _this.$emit("success");
            _this.$notify.success(msg);
          }
        } catch (err) {
          // catch
          console.error(err);
        } finally {
          // finally
          _this.loading = false;
        }
      } else {
        return false;
      }
    });
  };
  return {
    open,
    hide,
    submit,
    fetchRefer,
    fetchCode,
    fetchItem,
  };
}