import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { eDocScene, eDocShareError, iDocIDType } from './document.baseType';
import { iDocumentState } from './document.type';

import { documentActions } from './document.operator';

// 使用 Document 数据
const useDocumentData = () => {
  // 获取基础数据
  const documentData = useSelector(
    (state: { documentModel: iDocumentState }) => ({
      docId: state.documentModel.docId,
      docScene: state.documentModel.docScene,
      docFileType: state.documentModel.docFileType,
      docErrorCode: state.documentModel.docErrorCode,
    }),
  );

  const dispatch = useDispatch();

  // 更新 Document 基础数据
  const updateDocIdBeforeEntryDocument = useCallback(
    async (
      docId: iDocIDType,
      docScene?: eDocScene,
      docErrorCode?: eDocShareError,
    ) => {
      return await dispatch(
        documentActions.updateDocumentCurtDataAction(
          {
            docId,
            docScene,
            docErrorCode,
          },
          true,
        ),
      );
    },
    [dispatch],
  );
  // 清空当前数据
  const resetDocumentCurtData = useCallback(async () => {
    return await dispatch(
      documentActions.updateDocumentCurtDataAction(
        {
          docId: '',
          docScene: eDocScene.unknown,
          forceUpdate: true,
        },
        true,
      ),
    );
  }, [dispatch]);

  // 清除全部文档数据
  const clearDocumentData = useCallback(() => {
    dispatch<any>(documentActions.clearDocumentDataAction(true));
  }, [dispatch]);

  return {
    // data
    documentData,
    // data function
    updateDocIdBeforeEntryDocument,
    resetDocumentCurtData,
    clearDocumentData,
  };
};

export { useDocumentData };
