import { produce } from 'immer';
import { iDocumentState } from '../../document.type';

import * as docTagActions from './docTag.actions';

// DocTag Reducers
export const docTagReducers = {
  // 更新 DocTag 数据
  updateDocTagDataReducer(
    state: iDocumentState,
    action: ReturnType<typeof docTagActions.updateDocTagDataAction>,
  ) {
    const { docId, data } = action.payload;
    const docTagData = data!;

    // 计算新数据
    const newState = produce(state, (draftState) => {
      const originModelTagData = draftState.docTagDataMap[docId];
      if (!originModelTagData) {
        draftState.docTagDataMap[docId] = docTagData;
      } else {
        Object.keys(docTagData).forEach((key) => {
          // eslint-disable-next-line no-prototype-builtins
          if (docTagData.hasOwnProperty(key)) {
            delete originModelTagData[key];
            originModelTagData[key] = docTagData[key];
          }
        });
      }
    });
    console.log('newState:', newState);
    return newState;
  },
  // 部分Tag数据更新
  updateDocTagPartialDataReducer(
    state: iDocumentState,
    action: ReturnType<typeof docTagActions.updateDocTagPartialDataAction>,
  ) {
    const { docId, data } = action.payload;
    const partialDocTagData = data!;
    // 更新翻部分数据
    const newState = produce(state, (draftState) => {
      const originModelTagData = draftState.docTagDataMap[docId];
      if (!originModelTagData) return;
      Object.keys(partialDocTagData).forEach((key) => {
        // eslint-disable-next-line no-prototype-builtins
        if (partialDocTagData.hasOwnProperty(key)) {
          delete originModelTagData[key];
          originModelTagData[key] = partialDocTagData[key];
        }
      });
    });

    return newState;
  },
};
