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

import { iDocumentState } from '../document.type';
import { docTranslateActions } from './docTranslate.operator';

// DocTranslate Hooks
const useDocTranslateData = () => {
  const dispatch = useDispatch();
  // redux 取数
  const { docId, docScene, docTranslateDataMap } = useSelector(
    (state: { documentModel: iDocumentState }) => ({
      docScene: state.documentModel.docScene!,
      docId: state.documentModel.docId!,
      docTranslateDataMap: state.documentModel.docTranslateDataMap,
    }),
  );

  // 当前文档Tag数据
  const docTranslateData = useMemo(() => {
    if (!docId) return undefined;
    return docTranslateDataMap[docId];
  }, [docId, docTranslateDataMap]);

  // 更新翻译目标语言
  const updateDocTranslateTarget = useCallback(
    async (targetLang: number) => {
      return await dispatch(
        docTranslateActions.changeDocTranslateTargetAction({
          docId,
          docScene,
          data: targetLang,
        }),
      );
    },
    [docId, docScene, dispatch],
  );
  // 更新翻译展示模式
  const updateDocTranslateDisplayMode = useCallback(
    async (displayModel: number) => {
      return await dispatch(
        docTranslateActions.changeDocTranslateDisplayAction({
          docId,
          docScene,
          data: displayModel,
        }),
      );
    },
    [docId, docScene, dispatch],
  );

  // 更新翻译部分内容（原文修改后的翻译）
  const updateDocTranslatePartialData = useCallback(
    async (data: any) => {
      return await dispatch(
        docTranslateActions.updateDocTranslatePartialQueryDataAction({
          docId,
          docScene,
          data,
        }),
      );
    },
    [docId, docScene, dispatch],
  );

  return {
    // data
    docTranslateData,
    // data function
    updateDocTranslateTarget,
    updateDocTranslateDisplayMode,
    updateDocTranslatePartialData,
  };
};

export { useDocTranslateData };
