import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { FastModal, fastMessage } from 'components/ui';
import { Component } from 'components/types';
import { App } from 'utils/types';
import { isArray } from 'utils/isType';
import fetchData from 'utils/fetchData';
import { parseUrlTemplate } from 'utils/tool';
import { ActionProps } from './types';

const useAction = (props: ActionProps) => {
  const navigate = useNavigate();

  const {
    action,
    handle,
    data,
    loaderUuid,
  } = props;

  const [submitting, setSubmitting] = useState(false);

  const {
    label,
    result,
  } = action;

  // 关闭表单所在载体
  const handleCancel = () => {
    handle(Component.Business.ResultType.show, [loaderUuid], false);
  };

  // 获取单条详情数据
  const handleFetch = () => {
    const {
      dataSrc,
      ajaxKey,
      ajaxAliasKey,
      ajax: DetailAjax,
    } = action;
    if (dataSrc === Component.Business.FormDataSrcType.cache) {
      return Promise.resolve(data);
    }
    const params = {
      [ajaxAliasKey as string || ajaxKey as string]: data[ajaxKey as string],
    };
    return fetchData(DetailAjax, params).then((_data: App.Dict) => Promise.resolve(_data));
  };

  const handleResult = (_data?: App.Dict) => {
    const handleResultItem = (resultItem: Component.Business.Result) => {
      const { type, moduleIds } = resultItem;
      let payload = null;
      if (type === 'show') {
        payload = true;
      } else {
        payload = _data;
      }
      handle(type, moduleIds, payload);
    };
    if (isArray(result)) {
      (result as Component.Business.Result[]).forEach((
        resultItem: Component.Business.Result,
      ) => handleResultItem(resultItem));
    } else {
      handleResultItem(result as Component.Business.Result);
    }
  };

  // 确认行为
  const handleSubmit = () => {
    setSubmitting(true);
    const { ajax: submitAjax } = action;
    fetchData(submitAjax, data)
      .then(() => {
        fastMessage.success("操作成功");
        handleResult();
        handleCancel();
        setSubmitting(false);
      })
      .catch((e) => {
        setSubmitting(false);
      });
  };

  const handleConfirm = () => {
    const {
      logText,
      logKey,
      label,
      ajaxKey,
      ajaxAliasKey,
      ajax: ConfirmAjax,
    } = action;
    FastModal.confirm({
      title: label,
      content: `确认${logText || label}${logKey ? data[logKey] : ""}`,
      onOk: () => {
        const params = {
          [ajaxAliasKey as string || ajaxKey as string]: data[ajaxKey as string],
        };
        fetchData(ConfirmAjax, params).then((_data: App.Dict) => {
          handleResult(_data);
        });
      },
      okText: '确认',
      cancelText: '取消',
    });
  };

  const handleLink = () => {
    const { goto } = action;
    if (goto) {
      window.open(parseUrlTemplate(goto as string, data as App.Dict), '_blank');
    }
  };

  const handleRoute = () => {
    const { goto } = action;
    if (goto) navigate(parseUrlTemplate(goto as string, data as App.Dict));
  };

  return {
    submitting,
    handleSubmit,
    handleResult,
    handleConfirm,
    handleLink,
    handleRoute,
    handleFetch,
    handleCancel,
  };
};

export default useAction;
