/**
 *  *************************************************************
 *  ****************  大模型数据 Reducer定义   ********************
 *  *************************************************************
 */
import { produce } from 'immer';
import { iDocumentState } from '../../document.type';
import * as docBigModelActions from './docBigModel.actions';

// DocBigModel Reducers
export const docBigModelReducers = {
  // 更新大模型数据
  updateBigModelDataReducer(
    state: iDocumentState,
    action: ReturnType<typeof docBigModelActions.updateDocBigModelDataAction>,
  ) {
    const { docId, data } = action.payload;
    const docBigModelData = data!;
    Object.keys(docBigModelData).forEach((key) => {
      if (!state.docBigModelDataMap[docId]) {
        // @ts-expect-error 待修复
        state.docBigModelDataMap[docId] = {};
      }
      state.docBigModelDataMap[docId][key] = docBigModelData[key];
    });
  },
  replaceSpeakerSummaryByIdReducer(
    state: iDocumentState,
    action: ReturnType<
      typeof docBigModelActions.replaceSpeakerSummaryByIdAction
    >,
  ) {
    const { docId, data } = action.payload;
    const { id, summary = {} } = data || {};

    const nextState = produce(state, (draft) => {
      if (
        draft.docBigModelDataMap[docId] &&
        draft.docBigModelDataMap[docId]?.speakSummary
      ) {
        draft.docBigModelDataMap[docId].speakSummary?.forEach((item) => {
          if (item.id === id) {
            Object.keys(summary).forEach((key) => {
              item[key] = summary[key];
            });
          }
        });
      }
    });

    return nextState;
  },
  replaceSpeakerSummaryBySpeakerReducer(
    state: iDocumentState,
    action: ReturnType<
      typeof docBigModelActions.replaceSpeakerSummaryBySpeakerAction
    >,
  ) {
    const { docId, data } = action.payload;
    const { speaker, summary = {} } = data || {};
    if (
      state.docBigModelDataMap[docId] &&
      state.docBigModelDataMap[docId]?.speakSummary
    ) {
      state.docBigModelDataMap[docId].speakSummary?.forEach((item) => {
        if (item.speaker === speaker) {
          Object.keys(summary).forEach((key) => {
            item[key] = summary[key];
          });
        }
      });
    }
  },
  // 清除所有文档大模型数据
  clearBigModelDataReducer(state: iDocumentState) {
    state.docBigModelDataMap = {};
  },
};
