import { iDocBaseData } from '../../docBase/docBase.type';
import { eDocScene } from '../../document.baseType';
import { iDocumentState } from '../../document.type';
import * as docTagActions from './docTag.actions';

import * as docTagDataTransfer from './docTag.dataTransfer';

import { eDocSpeakerSplitStatus } from '../docTag.type';

// DocTag Effects
export const docTagEffects = {
  // 初始化Tag
  *initDocTagDataEffect(
    action: ReturnType<typeof docTagActions.initDocTagDataAction>,
    { put, call, select },
  ) {
    const { docId, docScene, data: tag } = action.payload;
    if ([eDocScene.transShare].includes(docScene)) {
      const defaultTagData = docTagDataTransfer.getDefaultDocTagData();

      // 从原文区获取发言人区分相关状态 Tag
      const { docResult }: { docResult: iDocBaseData } = yield select(
        (state: { documentModel: iDocumentState }) => ({
          docResult: state.documentModel.docBaseDataMap[docId],
        }),
      );
      const { identify, roleSplitNum, roleSplitTip } = docResult?.tag || {};
      defaultTagData.identify = identify;
      defaultTagData.roleSplitNum = roleSplitNum;
      defaultTagData.roleSplitTip = roleSplitTip;

      yield put(
        docTagActions.updateDocTagDataAction({
          docId,
          docScene,
          data: defaultTagData,
        }),
      );
      return defaultTagData;
    }
    // 转换过的数据
    const transferTagData = docTagDataTransfer.apiDocTagToLocalTransfer(tag!);
    console.log('transferTagData', tag);
    // 更新转换过的数据
    yield put(
      docTagActions.updateDocTagDataAction({
        docId,
        docScene,
        data: transferTagData,
      }),
    );

    /** 发言人处理 */
    // Tag 轮询，发言人区分中
    const { roleSplitTip } = transferTagData || {};
    if (roleSplitTip === eDocSpeakerSplitStatus.spliting) {
      yield put({
        type: 'fetchSpeakerSplitFinishTag',
        payload: action.payload,
      });
    }
  },
  // 更新 DocTag
  *updateDocTagEffect(
    action: ReturnType<typeof docTagActions.updateDocTagAndSyncTagAction>,
    { put, call },
  ) {
    // 更新 Tag 数据
    return yield put(
      docTagActions.updateDocTagPartialDataAction(action.payload),
    );
  },
};
